Call REST entry point and handle errors

@param method
@param query
@param payload
@param needAuth
@return Full response as String
@throws IOException
511567
public String exec(String apiPath, String method, String query, Object payload, boolean needAuth)
			throws IOException {
		if (payload == null)
			payload = "";

		String responseText = null;

		boolean cached = false;
		if (cacheManager != null) {
			responseText = cacheManager.getCache(apiPath, method, query, payload);
			if (responseText != null)
				cached = true;
		}

		if (responseText == null)
			try {
				responseText = execInternal(method, query, payload, needAuth);
			} catch (OvhException e0) {
				throw e0;
			} catch (OvhServiceException e0) {
				throw e0;
			} catch (SocketTimeoutException e1) {
				log.error("calling {} {} Failed by timeout. (ConnectTimeout:{} ReadTimeout:{})", method, query,
						config.getConnectTimeout(), config.getReadTimeout());
				responseText = execInternal(method, query, payload, needAuth);
			} catch (IOException e2) {
				log.error("API OVH IOException", e2);
				throw e2;
			}
		if (cacheManager != null && !cached)
			cacheManager.setCache(apiPath, method, query, payload, responseText);

		if (mtdHandler != null) {
			for (String mtd : new String[] { method, "ALL" }) {
				TreeMap<String, OphApiHandler> handlers = null;
				OphApiHandler handler = null;
				handlers = mtdHandler.get(mtd);
				if (handlers == null)
					continue;
				handler = handlers.get(apiPath);
				if (handler == null)
					continue;
				try {
					handler.accept(method, method, payload, responseText);
				} catch (Exception e) {
					log.warn("Handler throw exeption on {} {} : {}", method, method, e);
				}
			}
		}
		return responseText;
	}
1239501
async def _makeHttpRequest(self, method, route, payload):
        

        url = self._constructUrl(route)
        log.debug('Full URL used is: %s', url)

        hawkExt = self.makeHawkExt()

        # Serialize payload if given
        if payload is not None:
            payload = utils.dumpJson(payload)

        # Do a loop of retries
        retry = -1  # we plus first in the loop, and attempt 1 is retry 0
        retries = self.options['maxRetries']
        while retry < retries:
            retry += 1
            # if this isn't the first retry then we sleep
            if retry > 0:
                snooze = float(retry * retry) / 10.0
                log.info('Sleeping %0.2f seconds for exponential backoff', snooze)
                await asyncio.sleep(utils.calculateSleepTime(retry))
            # Construct header
            if self._hasCredentials():
                sender = mohawk.Sender(
                    credentials={
                        'id': self.options['credentials']['clientId'],
                        'key': self.options['credentials']['accessToken'],
                        'algorithm': 'sha256',
                    },
                    ext=hawkExt if hawkExt else {},
                    url=url,
                    content=payload if payload else '',
                    content_type='application/json' if payload else '',
                    method=method,
                )

                headers = {'Authorization': sender.request_header}
            else:
                log.debug('Not using hawk!')
                headers = {}
            if payload:
                # Set header for JSON if payload is given, note that we serialize
                # outside this loop.
                headers['Content-Type'] = 'application/json'

            log.debug('Making attempt %d', retry)
            try:
                response = await asyncutils.makeSingleHttpRequest(
                    method, url, payload, headers, session=self.session
                )
            except aiohttp.ClientError as rerr:
                if retry < retries:
                    log.warn('Retrying because of: %s' % rerr)
                    continue
                # raise a connection exception
                raise exceptions.TaskclusterConnectionError(
                    "Failed to establish connection",
                    superExc=rerr
                )

            status = response.status
            if status == 204:
                return None

            # Catch retryable errors and go to the beginning of the loop
            # to do the retry
            if 500 <= status and status < 600 and retry < retries:
                log.warn('Retrying because of a %s status code' % status)
                continue

            # Throw errors for non-retryable errors
            if status < 200 or status >= 300:
                # Parse messages from errors
                data = {}
                try:
                    data = await response.json()
                except Exception:
                    pass  # Ignore JSON errors in error messages
                # Find error message
                message = "Unknown Server Error"
                if isinstance(data, dict):
                    message = data.get('message')
                else:
                    if status == 401:
                        message = "Authentication Error"
                    elif status == 500:
                        message = "Internal Server Error"
                    else:
                        message = "Unknown Server Error %s\n%s" % (str(status), str(data)[:1024])
                # Raise TaskclusterAuthFailure if this is an auth issue
                if status == 401:
                    raise exceptions.TaskclusterAuthFailure(
                        message,
                        status_code=status,
                        body=data,
                        superExc=None
                    )
                # Raise TaskclusterRestFailure for all other issues
                raise exceptions.TaskclusterRestFailure(
                    message,
                    status_code=status,
                    body=data,
                    superExc=None
                )

            # Try to load JSON
            try:
                await response.release()
                return await response.json()
            except (ValueError, aiohttp.client_exceptions.ContentTypeError):
                return {"response": response}

        # This code-path should be unreachable
        assert False, "Error from last retry should have been raised!"
839519
public JsonObject sendQuery(FutureAPIResponse response)
      throws ExecutionException, InterruptedException, IOException {
    int status = response.get().getStatus();
    String message = response.get().getMessage();

    if (status != HTTP_OK) {
      throw new IOException(status + " " + message);
    }
    return ((JsonObject) parser.parse(message));
  }
1372269
private Call<QueryResult> callQuery(final Query query) {
    Call<QueryResult> call;
    String db = query.getDatabase();
    if (db == null) {
        db = this.database;
    }
    if (query instanceof BoundParameterQuery) {
        BoundParameterQuery boundParameterQuery = (BoundParameterQuery) query;
        call = this.influxDBService.postQuery(db, query.getCommandWithUrlEncoded(),
                boundParameterQuery.getParameterJsonWithUrlEncoded());
    } else {
        if (query.requiresPost()) {
          call = this.influxDBService.postQuery(db, query.getCommandWithUrlEncoded());
        } else {
          call = this.influxDBService.query(db, query.getCommandWithUrlEncoded());
        }
    }
    return call;
  }
1295227
function(request, response, next){
		if (utils.Misc.isEmptyObject(request.query)) {
			var errApp = new Error(errors['130']);
			response.end(utils.Misc.createResponse(null, errApp, 130));
		}
		else {
			next();
		}
	}
1006768
public void doGeneric(String method, HttpServletRequest request, HttpServletResponse response) {
    try {
      ServletUtils.startTransaction(request.getHeader("User-Agent"));

      // Note that getServletPath does an un-escape so that the %24 of job id's are turned into $ characters.
      String uri = request.getServletPath();

      Properties headers = new Properties();
      Enumeration<String> en = request.getHeaderNames();
      while (en.hasMoreElements()) {
        String key = en.nextElement();
        String value = request.getHeader(key);
        headers.put(key, value);
      }

      final String contentType = request.getContentType();
      Properties parms = new Properties();
      String postBody = null;
      if (System.getProperty(H2O.OptArgs.SYSTEM_PROP_PREFIX + "debug.cors") != null) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
      }

      if (contentType != null && contentType.startsWith(MIME_JSON)) {
        StringBuffer jb = new StringBuffer();
        String line = null;
        try {
          BufferedReader reader = request.getReader();
          while ((line = reader.readLine()) != null)
            jb.append(line);
        } catch (Exception e) {
          throw new H2OIllegalArgumentException("Exception reading POST body JSON for URL: " + uri);
        }
        postBody = jb.toString();
      } else {
        // application/x-www-form-urlencoded
        Map<String, String[]> parameterMap;
        parameterMap = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
          String key = entry.getKey();
          String[] values = entry.getValue();

          if (values.length == 1) {
            parms.put(key, values[0]);
          } else if (values.length > 1) {
            StringBuilder sb = new StringBuilder();
            sb.append("[");
            boolean first = true;
            for (String value : values) {
              if (!first) sb.append(",");
              sb.append("\"").append(value).append("\"");
              first = false;
            }
            sb.append("]");
            parms.put(key, sb.toString());
          }
        }
      }

      // Make serve() call.
      NanoResponse resp = serve(uri, method, headers, parms, postBody);

      // Un-marshal Nano response back to Jetty.
      String choppedNanoStatus = resp.status.substring(0, 3);
      assert (choppedNanoStatus.length() == 3);
      int sc = Integer.parseInt(choppedNanoStatus);
      ServletUtils.setResponseStatus(response, sc);

      response.setContentType(resp.mimeType);

      Properties header = resp.header;
      Enumeration<Object> en2 = header.keys();
      while (en2.hasMoreElements()) {
        String key = (String) en2.nextElement();
        String value = header.getProperty(key);
        response.setHeader(key, value);
      }

      resp.writeTo(response.getOutputStream());

    } catch (IOException e) {
      e.printStackTrace();
      ServletUtils.setResponseStatus(response, 500);
      Log.err(e);
      // Trying to send an error message or stack trace will produce another IOException...
    } finally {
      ServletUtils.logRequest(method, request, response);
      // Handle shutdown if it was requested.
      if (H2O.getShutdownRequested()) {
        (new Thread() {
          public void run() {
            boolean [] confirmations = new boolean[H2O.CLOUD.size()];
            if (H2O.SELF.index() >= 0) {
              confirmations[H2O.SELF.index()] = true;
            }
            for(H2ONode n:H2O.CLOUD._memary) {
              if(n != H2O.SELF)
                new RPC<>(n, new UDPRebooted.ShutdownTsk(H2O.SELF,n.index(), 1000, confirmations, 0)).call();
            }
            try { Thread.sleep(2000); }
            catch (Exception ignore) {}
            int failedToShutdown = 0;
            // shutdown failed
            for(boolean b:confirmations)
              if(!b) failedToShutdown++;
            Log.info("Orderly shutdown: " + (failedToShutdown > 0? failedToShutdown + " nodes failed to shut down! ":"") + " Shutting down now.");
            H2O.closeAll();
            H2O.exit(failedToShutdown);
          }
        }).start();
      }
      ServletUtils.endTransaction();
    }
  }
1068726
public JsonObject sendQuery(Map<String, Object> query)
      throws ExecutionException, InterruptedException, IOException {
    return sendQuery(sendQueryAsFuture(query));
  }
1361963
protected Object httpRequest(HttpRequestMethod method, ApiParams apiParams) throws IOException {
        ApiAction action = apiParams.getApiCall();
        String url = apiUrl + "/" + action.toString().toLowerCase();
        String json = GSON.toJson(apiParams, apiParams.getType());
        Map<String, String> params = buildPayload(json);
        Object response = httpClient.executeHttpRequest(url, method, params, handler, customHeaders);
        recordRateLimitInfo(action, method, response);
        return response;
    }
1350646
def execute_query(self, payload):
        ''''''
        if vars(self).get('oauth'):
            if not self.oauth.token_is_valid(): # Refresh token if token has expired
                self.oauth.refresh_token()
            response = self.oauth.session.get(self.PRIVATE_URL, params= payload, header_auth=True)
        else:
            response = requests.get(self.PUBLIC_URL, params= payload)

        self._response = response # Saving last response object.
        return response
1124276
public void withHttpMethod(Http method) {
        Objects.requireNonNull(method, Required.METHOD.toString());
        this.method = method;
    }
618722
public void execute(final HttpQuery query) {
    http_query = query;
    final QueryStats query_stats = 
        new QueryStats(query.getRemoteAddress(), ts_query, query.getHeaders());
    ts_query.setQueryStats(query_stats);
    
    /**
     * Sends the serialized results to the caller. This should be the very
     * last callback executed.
     */
    class CompleteCB implements Callback<Object, ChannelBuffer> {
      @Override
      public Object call(final ChannelBuffer cb) throws Exception {
        query.sendReply(cb);
        return null;
      }
    }
    
    /**
     * After all of the queries have run and we have data (or not) then we
     * need to compile the iterators.
     * This class could probably be improved:
     * First we iterate over the results AND for each result, iterate over
     * the expressions, giving a time synced iterator to each expression that 
     * needs the result set.
     * THEN we iterate over the expressions again and build a DAG to determine
     * if any of the expressions require the output of an expression. If so
     * then we add the expressions to the proper parent and compile them in
     * order.
     * After all of that we're ready to start serializing and iterating
     * over the results.
     */
    class QueriesCB implements Callback<Object, ArrayList<DataPoints[]>> {
      public Object call(final ArrayList<DataPoints[]> query_results) 
        throws Exception {
        
        for (int i = 0; i < query_results.size(); i++) {
          final TSSubQuery sub = ts_query.getQueries().get(i);
          
          Iterator<Entry<String, TSSubQuery>> it = sub_queries.entrySet().iterator();
          while (it.hasNext()) {
            final Entry<String, TSSubQuery> entry = it.next();
            if (entry.getValue().equals(sub)) {
              sub_query_results.put(entry.getKey(), query_results.get(i));
              for (final ExpressionIterator ei : expressions.values()) {
                if (ei.getVariableNames().contains(entry.getKey())) {
                  final TimeSyncedIterator tsi = new TimeSyncedIterator(
                      entry.getKey(), sub.getFilterTagKs(), 
                      query_results.get(i));
                  final NumericFillPolicy fill = fills.get(entry.getKey());
                  if (fill != null) {
                    tsi.setFillPolicy(fill);
                  }
                  ei.addResults(entry.getKey(), tsi);
                  if (LOG.isDebugEnabled()) {
                    LOG.debug("Added results for " + entry.getKey() + 
                        " to " + ei.getId());
                  }
                }
              }
            }
          }
        }

        // handle nested expressions
        final DirectedAcyclicGraph<String, DefaultEdge> graph = 
            new DirectedAcyclicGraph<String, DefaultEdge>(DefaultEdge.class);

        for (final Entry<String, ExpressionIterator> eii : expressions.entrySet()) {
          if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Expression entry key is %s, value is %s", 
                eii.getKey(), eii.getValue().toString()));
            LOG.debug(String.format("Time to loop through the variable names "
                + "for %s", eii.getKey()));
          }

          if (!graph.containsVertex(eii.getKey())) {
            if (LOG.isDebugEnabled()) {
              LOG.debug("Adding vertex " + eii.getKey());
            }
            graph.addVertex(eii.getKey());
          }

          for (final String var : eii.getValue().getVariableNames()) {
            if (LOG.isDebugEnabled()) {
              LOG.debug(String.format("var is %s", var));
            }

            final ExpressionIterator ei = expressions.get(var);

            if (ei != null) {
              if (LOG.isDebugEnabled()) {
                LOG.debug(String.format("The expression iterator for %s is %s", 
                    var, ei.toString()));
              }

              // TODO - really ought to calculate this earlier
              if (eii.getKey().equals(var)) {
                throw new IllegalArgumentException(
                    "Self referencing expression found: " + eii.getKey());
              }

              if (LOG.isDebugEnabled()) {
                LOG.debug("Nested expression detected. " + eii.getKey() + 
                    " depends on " + var);
              }

              if (!graph.containsVertex(eii.getKey())) {
                if (LOG.isDebugEnabled()) {
                  LOG.debug("Added vertex " + eii.getKey());
                }
                graph.addVertex(eii.getKey());
              } else if (LOG.isDebugEnabled()) {
                LOG.debug("Already contains vertex " + eii.getKey());
              }

              if (!graph.containsVertex(var)) {
                if (LOG.isDebugEnabled()) {
                  LOG.debug("Added vertex " + var);
                }
                graph.addVertex(var);
              } else if (LOG.isDebugEnabled()) {
                LOG.debug("Already contains vertex " + var);
              }

              try {
                if (LOG.isDebugEnabled()) {
                  LOG.debug("Added Edge " + eii.getKey() + " - " + var);
                }
                graph.addDagEdge(eii.getKey(), var);
              } catch (CycleFoundException cfe) {
                throw new IllegalArgumentException("Circular reference found: " + 
                    eii.getKey(), cfe);
              }
            } else if (LOG.isDebugEnabled()) {
              LOG.debug(String.format("The expression iterator for %s is null", var));
            }
          }
        }

        // compile all of the expressions
        final long intersect_start = DateTime.currentTimeMillis();

        final Integer expressionLength = expressions.size();
        final ExpressionIterator[] compile_stack = 
            new ExpressionIterator[expressionLength];
        final TopologicalOrderIterator<String, DefaultEdge> it = 
            new TopologicalOrderIterator<String, DefaultEdge>(graph);

        if (LOG.isDebugEnabled()) {
          LOG.debug(String.format("Expressions Size is %d", expressionLength));
          LOG.debug(String.format("Topology Iterator %s", it.toString()));
        }

        int i = 0;
        while (it.hasNext()) {
          String next = it.next();
          if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Expression: %s", next));
          }
          ExpressionIterator ei = expressions.get(next);
          if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Expression Iterator: %s", ei.toString()));
          }
          if (ei == null) {
            LOG.error(String.format("The expression iterator for %s is null", next));
          }
          compile_stack[i] = ei;
          if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Added expression %s to compile_stack[%d]", 
                next, i));
          }
          i++;
        }

        if (i != expressionLength) {
          throw new IOException(String.format(" Internal Error: Fewer "
              + "expressions where added to the compile stack than "
              + "expressions.size (%d instead of %d)", i, expressionLength));
        }

        if (LOG.isDebugEnabled()) {
          LOG.debug(String.format("compile stack length: %d", compile_stack.length));
        }

        for (int x = compile_stack.length - 1; x >= 0; x--) {
          if (compile_stack[x] == null) {
            throw new NullPointerException(String.format("Item %d in "
                + "compile_stack[] is null", x));
          }
          // look for and add expressions
          for (final String var : compile_stack[x].getVariableNames()) {
            if (LOG.isDebugEnabled()) {
              LOG.debug(String.format("Looking for variable %s for %s", var, 
                  compile_stack[x].getId()));
            }
            ExpressionIterator source = expressions.get(var);
            if (source != null) {
              compile_stack[x].addResults(var, source.getCopy());
              if (LOG.isDebugEnabled()) {
                LOG.debug(String.format("Adding expression %s to %s", 
                    source.getId(), compile_stack[x].getId()));
              }
            }
          }
          compile_stack[x].compile();
          if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Successfully compiled %s", 
                compile_stack[x].getId()));
          }
        }

        if (LOG.isDebugEnabled()) {
          LOG.debug("Finished compilations in " +
              (DateTime.currentTimeMillis() - intersect_start) + " ms");
        }
        
        return serialize()
            .addCallback(new CompleteCB())
            .addErrback(new ErrorCB());
      }
    }
    
    /**
     * Callback executed after we have resolved the metric, tag names and tag
     * values to their respective UIDs. This callback then runs the actual 
     * queries and fetches their results.
     */
    class BuildCB implements Callback<Deferred<Object>, net.opentsdb.core.Query[]> {
      @Override
      public Deferred<Object> call(final net.opentsdb.core.Query[] queries) {
        final ArrayList<Deferred<DataPoints[]>> deferreds = 
            new ArrayList<Deferred<DataPoints[]>>(queries.length);
        
        for (final net.opentsdb.core.Query query : queries) {
          deferreds.add(query.runAsync());
        }
        return Deferred.groupInOrder(deferreds).addCallback(new QueriesCB())
            .addErrback(new ErrorCB());
      }
    }
    
    // TODO - only run the ones that will be involved in an output. Folks WILL
    // ask for stuff they don't need.... *sigh*
    ts_query.buildQueriesAsync(tsdb)
      .addCallback(new BuildCB())
      .addErrback(new ErrorCB());
  }
1226917
public void execute(final TSDB tsdb, HttpQuery query) throws IOException {
    final HttpMethod method = query.getAPIMethod();
    
    final String[] uri = query.explodeAPIPath();
    final String endpoint = uri.length > 1 ? uri[1] : "";
    if (endpoint != null && endpoint.toLowerCase().endsWith("bulk")) {
      executeBulk(tsdb, method, query);
      return;
    }
    
    final Annotation note;
    if (query.hasContent()) {
      note = query.serializer().parseAnnotationV1();
    } else {
      note = parseQS(query);
    }
    
    // GET
    if (method == HttpMethod.GET) {
      try {
        if ("annotations".toLowerCase().equals(uri[0])) {
          fetchMultipleAnnotations(tsdb, note, query);
        } else {
          fetchSingleAnnotation(tsdb, note, query);
        }
      } catch (BadRequestException e) {
        throw e;
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    // POST
    } else if (method == HttpMethod.POST || method == HttpMethod.PUT) {
      
      /**
       * Storage callback used to determine if the storage call was successful
       * or not. Also returns the updated object from storage.
       */
      class SyncCB implements Callback<Deferred<Annotation>, Boolean> {
        
        @Override
        public Deferred<Annotation> call(Boolean success) throws Exception {
          if (!success) {
            throw new BadRequestException(
                HttpResponseStatus.INTERNAL_SERVER_ERROR,
                "Failed to save the Annotation to storage", 
                "This may be caused by another process modifying storage data");
          }
          
          return Annotation.getAnnotation(tsdb, note.getTSUID(), 
              note.getStartTime());
        }
        
      }
      
      try {
        final Deferred<Annotation> process_meta = note.syncToStorage(tsdb, 
            method == HttpMethod.PUT).addCallbackDeferring(new SyncCB());
        final Annotation updated_meta = process_meta.joinUninterruptibly();
        tsdb.indexAnnotation(note);
        query.sendReply(query.serializer().formatAnnotationV1(updated_meta));
      } catch (IllegalStateException e) {
        query.sendStatusOnly(HttpResponseStatus.NOT_MODIFIED);
      } catch (IllegalArgumentException e) {
        throw new BadRequestException(e);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    // DELETE    
    } else if (method == HttpMethod.DELETE) {

      try {
        note.delete(tsdb).joinUninterruptibly();
        tsdb.deleteAnnotation(note);
      } catch (IllegalArgumentException e) {
        throw new BadRequestException(
            "Unable to delete Annotation information", e);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
      query.sendStatusOnly(HttpResponseStatus.NO_CONTENT);
      
    } else {
      throw new BadRequestException(HttpResponseStatus.METHOD_NOT_ALLOWED, 
          "Method not allowed", "The HTTP method [" + method.getName() +
          "] is not permitted for this endpoint");
    }
  }
683142
@RequestMapping(method = POST)
    public void handle(@Valid @RequestBody P payload) {
        logger.debug("{} handlers", handlers.size());
        for (H handler : handlers) {
            executor.execute(runnableHandler(handler, payload));
        }
    }
818728
public ApiResponse apiRequest(HttpMethod method,
            Map<String, Object> params, Object data, String... segments) {
        ApiResponse response = null;
        try {
            response = httpRequest(method, ApiResponse.class, params, data,
                    segments);
            log.info("Client.apiRequest(): Response: " + response);
        } catch (HttpClientErrorException e) {
            log.error("Client.apiRequest(): HTTP error: "
                    + e.getLocalizedMessage());
            response = parse(e.getResponseBodyAsString(), ApiResponse.class);
            if ((response != null) && !isEmpty(response.getError())) {
                log.error("Client.apiRequest(): Response error: "
                        + response.getError());
                if (!isEmpty(response.getException())) {
                    log.error("Client.apiRequest(): Response exception: "
                            + response.getException());
                }
            }
        }
        return response;
    }
584236
public HttpResponse invoke(String uri, String payload, HttpMethod method) {
        HttpResponse result = null;
        String url = directoryAddresses + uri;
        try {
            if (method == null || method == HttpMethod.GET) {
                result = HttpUtils.getJson(url);
            } else if (method == HttpMethod.POST) {
                result = HttpUtils.postJson(url, payload);
            } else if (method == HttpMethod.PUT) {
                result = HttpUtils.putJson(url, payload);
            } else if (method == HttpMethod.DELETE) {
                result = HttpUtils.deleteJson(url);
            }
        } catch (IOException e) {
            String errMsg = "Send HTTP Request to remote Directory Server failed";
            LOGGER.error(errMsg);
            LOGGER.debug(errMsg, e);
            ServiceDirectoryError sde = new ServiceDirectoryError(ErrorCode.HTTP_CLIENT_ERROR);
            throw new ServiceException(sde, errMsg, e);
        }

        if (result.getHttpCode() < 200 || result.getHttpCode() >= 300) {
            String errorBody = result.getRetBody();

            if(errorBody == null || errorBody.isEmpty()){
                LOGGER.error("Invoke remote directory server failed, status=" + result.getHttpCode()
                        + ", Error Message body is empty.");
                ServiceDirectoryError sde = new ServiceDirectoryError(
                        ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR);
                throw new ServiceException(sde, "Error Message body is empty.");
            }
            ServiceDirectoryError sde = null;
            try {
                sde = (ServiceDirectoryError) serializer
                        .deserialize(errorBody.getBytes(),
                                ServiceDirectoryError.class);
            } catch (IOException  e) {
                String errMsg = "Deserialize error body message failed";
                LOGGER.error(errMsg);
                LOGGER.debug(errMsg + ", messageBody=" + errorBody, e);
                ServiceDirectoryError sde1 = new ServiceDirectoryError(ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR);
                throw new ServiceException(sde1, errMsg, e);
            }

            if (sde != null) {
                throw new ServiceException(sde);
            }
        }
        return result;
    }
462856
public HttpResponse invoke(String uri, String payload, HttpMethod method, Map<String, String> headers) {
        HttpResponse result = null;
        String url = directoryAddresses + uri;
        try {
            if (method == HttpMethod.PUT) {
                result = HttpUtils.put(url, payload, headers);
            }
        } catch (IOException e) {
            String errMsg = "Send HTTP Request to remote Directory Server failed";
            LOGGER.error(errMsg);
            LOGGER.debug(errMsg, e);
            ServiceDirectoryError sde = new ServiceDirectoryError(ErrorCode.HTTP_CLIENT_ERROR);
            throw new ServiceException(sde, errMsg, e);
        }

        if (result.getHttpCode() < 200 || result.getHttpCode() >= 300) {
            String errorBody = result.getRetBody();

            if(errorBody == null || errorBody.isEmpty()){
                LOGGER.error("Invoke remote directory server failed, status=" + result.getHttpCode()
                        + ", Error Message body is empty.");
                ServiceDirectoryError sde = new ServiceDirectoryError(
                        ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR);
                throw new ServiceException(sde, "Error Message body is empty.");
            }
            ServiceDirectoryError sde = null;
            try {
                sde = (ServiceDirectoryError) serializer
                        .deserialize(errorBody.getBytes(),
                                ServiceDirectoryError.class);
            } catch (IOException  e) {
                String errMsg = "Deserialize error body message failed";
                LOGGER.error(errMsg);
                LOGGER.debug(errMsg + ", messageBody=" + errorBody, e);
                ServiceDirectoryError sde1 = new ServiceDirectoryError(ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR);
                throw new ServiceException(sde1, errMsg, e);
            }

            if (sde != null) {
                throw new ServiceException(sde);
            }
        }
        return result;
    }
262165
public void queryError(OutputStream os,
                         HeadersAmp headers,
                         String address,
                         long qId,
                         Throwable exn)
    throws IOException
  {
    init(os);

    OutH3 out = _out;

    if (out == null)
      return;

    if (log.isLoggable(_level)) {
      log.log(_level, "query-error " + exn
                 + " (in " + this + ")" + " {to:" + address + ", " + headers + "}");
      
      if (log.isLoggable(Level.FINEST)) {
        log.log(Level.FINEST, exn.toString(), exn);
      }
    }

    try {
      out.writeLong(MessageTypeHamp.QUERY_ERROR.ordinal());
      writeHeaders(out, headers);
      
      writeToAddress(out, address);
      out.writeLong(qId);

      ErrorAmp error = ErrorAmp.create(exn);

      out.writeString(error.getCode().toString());
      out.writeString(error.getMessage());
      out.writeObject(error.getDetail());

      // XXX: out.flushBuffer();
    } catch (Throwable e) {
      log.log(Level.WARNING, e.toString(), e);
      
      throw e;
    }
  }