Exemplo n.º 1
0
 public Res syncRequest(Req request, Class<Res> resClass) {
   if (HttpMethod.GET == request.getMethod()) {
     return this.handleGETRequest(request, resClass);
   } else if (HttpMethod.POST == request.getMethod()) {
     return this.handlePOSTRequest(request, resClass);
   }
   return null;
 }
Exemplo n.º 2
0
 private Res handleGETRequest(Req request, Class<Res> resClass) {
   Map<String, Object> paramsMap = request.getParams();
   String params = "";
   if (paramsMap != null) {
     params += "?";
     Iterator it = paramsMap.entrySet().iterator();
     while (it.hasNext()) {
       Map.Entry pairs = (Map.Entry) it.next();
       params += (pairs.getKey() + "=" + pairs.getValue());
       if (it.hasNext()) {
         params += "&";
       }
     }
   }
   String getUrl = request.getURL() + params;
   Log.d("[Request URL]", getUrl);
   HttpGet httpGet = new HttpGet(getUrl);
   Map<String, String> headersMap = request.getHeaders();
   if (headersMap != null) {
     Iterator<Map.Entry<String, String>> iterator = headersMap.entrySet().iterator();
     while (iterator.hasNext()) {
       Map.Entry<String, String> entry = iterator.next();
       httpGet.addHeader(entry.getKey(), entry.getValue());
     }
   }
   for (Header h : httpGet.getHeaders(HttpConstants.REQUEST_HEADER_DEVICE_ID)) {
     Log.d("[Request Header]", h.getName() + " --- " + h.getValue());
   }
   Res response = null;
   try {
     HttpResponse httpResponse = httpClient.execute(httpGet);
     response = (Res) resClass.newInstance().parseResult(httpResponse);
   } catch (Exception e) {
     e.printStackTrace();
   }
   return response;
 }
Exemplo n.º 3
0
  public final Res execute(final Req senseiReq) {
    SearchCounter.mark();
    Set<Integer> partitions = senseiReq == null ? null : senseiReq.getPartitions();
    if (partitions == null) {
      partitions = new HashSet<Integer>();
      int[] containsPart = _core.getPartitions();
      if (containsPart != null) {
        for (int part : containsPart) {
          partitions.add(part);
        }
      }
    }
    Res finalResult;
    if (partitions != null && partitions.size() > 0) {
      if (logger.isDebugEnabled()) {
        logger.debug("serving partitions: " + partitions.toString());
      }
      final ArrayList<Res> resultList = new ArrayList<Res>(partitions.size());
      Future<Res>[] futures = new Future[partitions.size() - 1];
      int i = 0;
      for (final int partition : partitions) {
        final long start = System.currentTimeMillis();
        final IndexReaderFactory<ZoieIndexReader<BoboIndexReader>> readerFactory =
            _core.getIndexReaderFactory(partition);

        if (i < partitions.size() - 1) // Search simultaneously.
        {
          try {
            futures[i] =
                (Future<Res>)
                    _executorService.submit(
                        new Callable<Res>() {
                          public Res call() throws Exception {
                            Timer timer = getTimer(partition);

                            Res res =
                                timer.time(
                                    new Callable<Res>() {

                                      @Override
                                      public Res call() throws Exception {
                                        return handleRequest(
                                            senseiReq,
                                            readerFactory,
                                            _core.getQueryBuilderFactory());
                                      }
                                    });

                            long end = System.currentTimeMillis();
                            res.setTime(end - start);
                            logger.info(
                                "searching partition: "
                                    + partition
                                    + " browse took: "
                                    + res.getTime());

                            return res;
                          }
                        });
          } catch (Exception e) {
            senseiReq.addError(new SenseiError(e.getMessage(), ErrorType.BoboExecutionError));
            logger.error(e.getMessage(), e);
          }
        } else // Reuse current thread.
        {
          try {
            Timer timer = getTimer(partition);
            Res res =
                timer.time(
                    new Callable<Res>() {

                      @Override
                      public Res call() throws Exception {
                        return handleRequest(
                            senseiReq, readerFactory, _core.getQueryBuilderFactory());
                      }
                    });

            resultList.add(res);
            long end = System.currentTimeMillis();
            res.setTime(end - start);
            logger.info("searching partition: " + partition + " browse took: " + res.getTime());
          } catch (Exception e) {
            logger.error(e.getMessage(), e);
            senseiReq.addError(new SenseiError(e.getMessage(), ErrorType.BoboExecutionError));

            resultList.add(getEmptyResultInstance(e));
          }
        }
        ++i;
      }

      for (i = 0; i < futures.length; ++i) {
        try {
          Res res = futures[i].get(_timeout, TimeUnit.MILLISECONDS);
          resultList.add(res);
        } catch (Exception e) {

          logger.error(e.getMessage(), e);
          if (e instanceof TimeoutException) {
            senseiReq.addError(new SenseiError(e.getMessage(), ErrorType.ExecutionTimeout));
          } else {
            senseiReq.addError(new SenseiError(e.getMessage(), ErrorType.BoboExecutionError));
          }
          resultList.add(getEmptyResultInstance(e));
        }
      }

      try {
        finalResult =
            MergeTimer.time(
                new Callable<Res>() {
                  public Res call() throws Exception {
                    return mergePartitionedResults(senseiReq, resultList);
                  }
                });
      } catch (Exception e) {
        logger.error(e.getMessage(), e);
        finalResult = getEmptyResultInstance(null);
        finalResult.addError(new SenseiError(e.getMessage(), ErrorType.MergePartitionError));
      }
    } else {
      if (logger.isInfoEnabled()) {
        logger.info("no partitions specified");
      }
      finalResult = getEmptyResultInstance(null);
      finalResult.addError(
          new SenseiError("no partitions specified", ErrorType.PartitionCallError));
    }
    if (logger.isInfoEnabled()) {
      logger.info(
          "searching partitions  "
              + String.valueOf(partitions)
              + " took: "
              + finalResult.getTime());
    }
    return finalResult;
  }
Exemplo n.º 4
0
  private Res handlePOSTRequest(Req request, Class<Res> resClass) {
    L.d(TAG, "Request URL: " + request.getURL());
    HttpPost httpPost = new HttpPost(request.getURL());
    // 添加请求头
    Map<String, String> headersMap = request.getHeaders();
    if (headersMap != null) {
      Iterator<Map.Entry<String, String>> iterator = headersMap.entrySet().iterator();
      while (iterator.hasNext()) {
        Map.Entry<String, String> entry = iterator.next();
        httpPost.addHeader(entry.getKey(), entry.getValue());
      }
    }
    L.d(TAG, "Request Header: " + new Gson().toJson(headersMap));
    // 判断是否存在上传文件,以不同方式添加请求参数
    if (request.existUploadFiles()) {
      Map<String, String> uploadFilesMap = request.getUploadFiles();
      Map<String, Object> paramsMap = request.getParams();
      /*MultipartEntityBuilder builder = MultipartEntityBuilder.create();
      builder.setMode( HttpMultipartMode.BROWSER_COMPATIBLE );
      //			builder.setCharset( Charset.forName( "UTF-8" ) );
      String data = new Gson().toJson( paramsMap );
      // 设置中文编码
      ContentType contentType = ContentType.create( "application/json" , HTTP.UTF_8 );
      StringBody strBody = new StringBody( data , contentType );
      builder.addPart( "data" , strBody );

      //			builder.addTextBody( "data" , data );
      //			builder.addTextBody( "data" , data , ContentType.APPLICATION_JSON.withCharset( "UTF-8" ) );
      Log.d( "[File Data]" , data );
      Iterator<Entry<String , String>> iterator = uploadFilesMap.entrySet().iterator();
      while( iterator.hasNext() )
      {
      	Map.Entry<String , String> entry = iterator.next();
      	String key = entry.getKey();
      	String filePath = entry.getValue();
      	if( !TextUtils.isEmpty( filePath ) )
      	{
      		byte[] fileByte = FileUtils.getBytesFromFile( new File( filePath ) );
      		builder.addBinaryBody( key , fileByte );
      	}
      }
      HttpEntity httpEntity = builder.build();*/
      MultipartEntity httpEntity = new MultipartEntity();
      StringBody sb =
          new StringBody(
              new Gson().toJson(paramsMap), ContentType.APPLICATION_JSON.withCharset("UTF-8"));
      httpEntity.addPart("data", sb);
      Iterator<Entry<String, String>> iterator = uploadFilesMap.entrySet().iterator();
      while (iterator.hasNext()) {
        Map.Entry<String, String> entry = iterator.next();
        String key = entry.getKey();
        String filePath = entry.getValue();
        if (!TextUtils.isEmpty(filePath)) {
          /*byte[] fileByte = FileUtils.getBytesFromFile( new File( filePath ) );
          builder.addBinaryBody( key , fileByte );*/
          ContentBody cbFile = new FileBody(new File(filePath));
          httpEntity.addPart(key, cbFile);
        }
      }
      httpPost.setEntity(httpEntity);
      /*if( paramsMap != null )
      {
      	MultipartEntity httpEntity = new MultipartEntity();
      	Iterator<Map.Entry<String , Object>> iterator = paramsMap.entrySet().iterator();
      	while( iterator.hasNext() )
      	{
      		Map.Entry<String , Object> entry = iterator.next();
      		L.d( TAG , "---- Params Key: " + entry.getKey() + " ----\n---- Params Value: " + entry.getValue() );
      		StringBody sb = new StringBody( new Gson().toJson( entry.getValue() ) , ContentType.APPLICATION_JSON.withCharset( "UTF-8" ) );
      		httpEntity.addPart( entry.getKey() , sb );
      	}
      	httpPost.setEntity( httpEntity );
      }*/
    } else {
      Map<String, Object> paramsMap = request.getParams();
      L.e(TAG, "[Request Params]: " + new Gson().toJson(paramsMap));
      if (paramsMap != null) {
        String bodyJsonString = new Gson().toJson(paramsMap);
        StringEntity entity = null;
        try {
          entity = new StringEntity(bodyJsonString, HTTP.UTF_8);
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        }
        httpPost.setEntity(entity);
      }
    }
    Res response = null;
    try {
      HttpResponse httpResponse = httpClient.execute(httpPost);
      try {
        response = (Res) resClass.newInstance().parseResult(httpResponse);
        if (response != null && response.isTokenError()) {
          EventBus.getDefault().post(new ErrorTokenEvent());
        }
      } catch (InstantiationException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return response;
  }
Exemplo n.º 5
0
 /** Creates request and response files on disk if applicable */
 protected void createFiles(Req request, Rsp response) throws ServiceException {
   try {
     if (response.isLogRequest()) {
       if (request.getXmlData() != null) {
         if (!ValidationUtils.isNullOrEmpty(request.getXmlData().getXml())) {
           String xml = request.getXmlData().getXml();
           ServiceRequest logRequest = new ServiceRequest();
           if (response.getLogType().equals(ELogStrategy.LOG_TO_FILE)
               || response.getLogType().equals(ELogStrategy.LOG_TO_BOTH)) {
             String fileName =
                 logXMLToDisk(
                     response.getLogType(),
                     response.getLogRoot(),
                     EMessagePart.REQUEST,
                     response.getUid(),
                     xml);
             logRequest.setFileName(fileName);
           }
         }
       }
     }
     if (response.isError()) {
       if (response.getXmlData() != null) {
         if (!ValidationUtils.isNullOrEmpty(response.getXmlData().getXml())) {
           String xml = response.getXmlData().getXml();
           ServiceError logError = new ServiceError();
           if (response.getLogType().equals(ELogStrategy.LOG_TO_FILE)
               || response.getLogType().equals(ELogStrategy.LOG_TO_BOTH)) {
             String fileName =
                 logXMLToDisk(
                     response.getLogType(),
                     response.getLogRoot(),
                     EMessagePart.ERROR,
                     response.getUid(),
                     xml);
             logError.setFileName(fileName);
           }
         }
       }
     } else {
       if (response.isLogResponse() && request.getTargetProcess().equals(EProcessType.ONLINE)) {
         if (response.getXmlData() != null) {
           if (!ValidationUtils.isNullOrEmpty(response.getXmlData().getXml())) {
             String xml = response.getXmlData().getXml();
             ServiceResponse logResponse = new ServiceResponse();
             if (response.getLogType().equals(ELogStrategy.LOG_TO_FILE)
                 || response.getLogType().equals(ELogStrategy.LOG_TO_BOTH)) {
               String fileName =
                   logXMLToDisk(
                       response.getLogType(),
                       response.getLogRoot(),
                       EMessagePart.RESPONSE,
                       response.getUid(),
                       xml);
               logResponse.setFileName(fileName);
             }
           }
         }
       }
     }
   } catch (Exception e) {
     throw new ServiceException(ErrorCodes.COR000, e, "Problem creating service log files");
   }
 }