Package org.butor.json.service

Source Code of org.butor.json.service.BaseServiceCaller

/*******************************************************************************
* Copyright 2013 butor.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.butor.json.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.Set;
import java.util.UUID;

import org.butor.json.JsonHelper;
import org.butor.json.JsonServiceRequest;
import org.butor.json.JsonStreamHandler;
import org.butor.json.StreamHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.api.client.http.AbstractHttpContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;

public abstract class BaseServiceCaller<T> implements ServiceCaller<T> {
  private Logger logger = LoggerFactory.getLogger(this.getClass());
  private JsonHelper _jsh = new JsonHelper();
  private String _namespace;
  private String _url;

  private int maxPayloadLengthToLog = -1;
  private Set<String> servicesToNotLogArgs = Collections.emptySet();

  public BaseServiceCaller(String namespace_, String url_) {
    _namespace = namespace_;
    _url = url_;
    logger.info(String.format("Created service caller: namespace=%s, url=%s",
        _namespace, _url));
  }
  public void setMaxPayloadLengthToLog(int maxPayloadLengthToLog) {
    this.maxPayloadLengthToLog = maxPayloadLengthToLog;
  }
  public String serialize(Object args_) {
    return _jsh.serialize(args_);
  }
  public JsonServiceRequest createRequest(String service_,
      Object serviceArgs_, String userId_, String sessionId_) {
    JsonServiceRequest req = new JsonServiceRequest();
    req.setSessionId(sessionId_);
    req.setReqId("R-" +UUID.randomUUID().toString());
    req.setUserId(userId_);
    req.setNamespace(_namespace);
    req.setService(service_);
    req.setServiceArgsJson(serviceArgs_ instanceof String ?
        (String)serviceArgs_ : serialize(serviceArgs_));

    return req;
  }
  @Override
  public void call(final JsonServiceRequest jsonServiceRequest_,
      final ResponseHandler<T> handler_) throws ServiceCallException {

    long time = System.currentTimeMillis();
    boolean success = false;
    final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

    try {
      HttpRequestFactory requestFactory = HTTP_TRANSPORT
          .createRequestFactory(new HttpRequestInitializer() {
            @Override
            public void initialize(HttpRequest request) {
            }
          });
      GenericUrl url = new GenericUrl(_url);

      HttpContent hc = new AbstractHttpContent("text/json") {
        String content = serialize(jsonServiceRequest_);
        @Override
        public long getLength() throws IOException {
          return content.getBytes("utf-8").length;
        }
        @Override
        public void writeTo(OutputStream out_) throws IOException {
          boolean logArgs = !servicesToNotLogArgs.contains(jsonServiceRequest_.getService());
          if (logArgs) {
            if (maxPayloadLengthToLog < 0 || content.length() <= maxPayloadLengthToLog) {
              logger.info("calling service: {}", content);
            } else {
              if (logger.isDebugEnabled()) {
                logger.info("calling service: {}", content);
              } else {
                String service = String.format("service: %s%s, reqId: %s, sessionId: %s, userId: %s",
                    _url, jsonServiceRequest_.getService(), jsonServiceRequest_.getReqId(),
                    jsonServiceRequest_.getSessionId(), jsonServiceRequest_.getUserId());

                int argsLen = content.length();
                String chunck = content.substring(0, maxPayloadLengthToLog);
                logger.info(String.format("calling %s, payload: %s... %d chars (truncated - full content in debug level)",
                  service, chunck, argsLen));
              }
            }
          } else {
            String service = String.format("service: %s%s, reqId: %s, sessionId: %s, userId: %s",
                _url, jsonServiceRequest_.getService(), jsonServiceRequest_.getReqId(),
                jsonServiceRequest_.getSessionId(), jsonServiceRequest_.getUserId());
            logger.info("calling {}, payload: /*censored*/",
                service);
          }
          out_.write(content.getBytes("utf-8"));
          out_.flush();
        }
      };

      HttpRequest request = requestFactory.buildPostRequest(url, hc);
      HttpResponse resp = request.execute();
      InputStream is = resp.getContent();
      String reqLogInfo = String.format("reqId: %s, sessionId: %s",
          jsonServiceRequest_.getReqId(), jsonServiceRequest_.getSessionId());
      StreamHandler jsh = getStreamHandler();
      jsh.parse(is, handler_, reqLogInfo);
      success = true;
    } catch (IOException e) {
      throw new ServiceCallException(e);
    } finally {
      String namespace = jsonServiceRequest_.getNamespace();
      String service = jsonServiceRequest_.getService();
      String reqId = jsonServiceRequest_.getReqId();
      String sessionId = jsonServiceRequest_.getSessionId();
      String userId = jsonServiceRequest_.getUserId();
      long elapsed = System.currentTimeMillis() - time;
      Object[] args = new Object[] { namespace, service, reqId, sessionId, userId, Boolean.valueOf(success), Long.valueOf(elapsed) };
      logger.info("Service: STATS namespace: {}, service: {}, reqId: {}, sessionId: {}, userId: {}, success: {}, elapsed: {} ms", args);
      // When HttpClient instance is no longer needed,
    }
  }
  public abstract StreamHandler getStreamHandler();

  public void setServicesToNotLogArgs(Set<String> servicesToNotLogArgs) {
    this.servicesToNotLogArgs = servicesToNotLogArgs;
    if (this.servicesToNotLogArgs == null) {
      this.servicesToNotLogArgs = Collections.emptySet();
    }
  }
}
TOP

Related Classes of org.butor.json.service.BaseServiceCaller

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.