@Mock
 public void $init(
     CloudProvider provider,
     HttpClientBuilder clientBuilder,
     HttpUriRequest request,
     ResponseHandler handler) {
   String requestUri = request.getURI().toString();
   if (request.getMethod().equals("GET")
       && requestUri.equals(
           String.format(VM_RESOURCES, ENDPOINT, ACCOUNT_NO, DATACENTER_ID, VM_1_ID))) {
     requestResourceType = 1;
   }
   if (request.getMethod().equals("GET")
       && requestUri.equals(
           String.format(VM_NETWORK_ADAPTERS, ENDPOINT, ACCOUNT_NO, DATACENTER_ID, VM_1_ID))) {
     requestResourceType = 2;
   }
   if (request.getMethod().equals("GET")
       && requestUri.equals(String.format(HARDWARE_PROFILES, ENDPOINT, ACCOUNT_NO))) {
     requestResourceType = 3;
   }
   if (request.getMethod().equals("GET")
       && requestUri.equals(String.format(LIST_VM_RESOURCES, ENDPOINT, ACCOUNT_NO))) {
     requestResourceType = 4;
   }
   responseHandler = handler;
 }
 @Mock
 public void $init(
     CloudProvider provider,
     HttpClientBuilder clientBuilder,
     HttpUriRequest request,
     ResponseHandler handler) {
   String requestUri = request.getURI().toString();
   if (request.getMethod().equals("GET")
       && requestUri.equals(
           String.format(VM_RESOURCES, ENDPOINT, ACCOUNT_NO, DATACENTER_ID, VM_1_ID))) {
     requestResourceType = 11;
   } else if (request.getMethod().equals("PUT")
       && requestUri.equals(
           String.format(VM_RESOURCES, ENDPOINT, ACCOUNT_NO, DATACENTER_ID, VM_1_ID))) {
     requestResourceType = 12;
     WAPVirtualMachineModel wapVirtualMachineModel = createWAPVirtualMachineModel();
     wapVirtualMachineModel.setOperation(operation);
     assertPut(
         request,
         String.format(VM_RESOURCES, ENDPOINT, ACCOUNT_NO, DATACENTER_ID, VM_1_ID),
         new Header[0],
         wapVirtualMachineModel);
   } else {
     super.$init(provider, clientBuilder, request, handler);
   }
 }
 @Mock
 public void $init(
     CloudProvider provider,
     HttpClientBuilder clientBuilder,
     HttpUriRequest request,
     ResponseHandler handler) {
   String requestUri = request.getURI().toString();
   if (request.getMethod().equals("GET")
       && requestUri.equals(String.format(VMTEMPLATES_RESOURCES, ENDPOINT, ACCOUNT_NO))) {
     requestResourceType = 1;
   }
   if (request.getMethod().equals("GET")
       && requestUri.equals(String.format(HARDWARE_PROFILES, ENDPOINT, ACCOUNT_NO))) {
     requestResourceType = 2;
   }
 }
  String createCanonicalRequest(HttpUriRequest request) {
    StringBuilder result = new StringBuilder();
    result.append(request.getMethod()).append('\n');
    String path = request.getURI().getPath();
    if (path.isEmpty()) {
      path = "/";
    }
    result.append(path).append('\n');
    String queryString = request.getURI().getQuery();
    queryString = queryString != null ? queryString : "";
    addCanonicalQueryString(queryString, result).append('\n');
    addCanonicalHeaders(request, result).append('\n');

    HttpEntity entity = null;
    try {
      if (request instanceof HttpEntityEnclosingRequestBase) {
        entity = ((HttpEntityEnclosingRequestBase) request).getEntity();
      } else {
        entity = new StringEntity("");
      }
      InputStream content = entity.getContent();
      addHashedPayload(content, result);
    } catch (IOException e) {
      throw new RuntimeException("Could not create hash for entity " + entity, e);
    }
    return result.toString();
  }
  @Test
  public void shouldHandleMultipleInvocationsOfExecute() throws Exception {
    Robolectric.addPendingHttpResponse(200, "a happy response body");
    Robolectric.addPendingHttpResponse(201, "another happy response body");

    requestDirector.execute(null, new HttpGet("http://example.com"), null);
    requestDirector.execute(null, new HttpGet("www.example.com"), null);

    HttpUriRequest request1 = (HttpUriRequest) Robolectric.getSentHttpRequest(0);
    assertThat(request1.getMethod(), equalTo(HttpGet.METHOD_NAME));
    assertThat(request1.getURI(), equalTo(URI.create("http://example.com")));

    HttpUriRequest request2 = (HttpUriRequest) Robolectric.getSentHttpRequest(1);
    assertThat(request2.getMethod(), equalTo(HttpGet.METHOD_NAME));
    assertThat(request2.getURI(), equalTo(URI.create("www.example.com")));
  }
Example #6
0
  @Override
  public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
    boolean retry = true;

    Boolean b = (Boolean) context.getAttribute(ExecutionContext.HTTP_REQ_SENT);
    boolean sent = (b != null && b.booleanValue());

    if (executionCount > maxRetries) {
      // 尝试次数超过用户定义的测试,默认5次
      retry = false;
    } else if (exceptionBlacklist.contains(exception.getClass())) {
      // 线程被用户中断,则不继续尝试
      retry = false;
    } else if (exceptionWhitelist.contains(exception.getClass())) {
      retry = true;
    } else if (!sent) {
      retry = true;
    }

    if (retry) {
      HttpUriRequest currentReq =
          (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
      retry = currentReq != null && !"POST".equals(currentReq.getMethod());
    }

    if (retry) {
      // 休眠1秒钟后再继续尝试
      SystemClock.sleep(RETRY_SLEEP_TIME_MILLIS);
    } else {
      exception.printStackTrace();
    }

    return retry;
  }
  public JestResult execute(Action clientRequest) throws IOException {

    String elasticSearchRestUrl = getRequestURL(getElasticSearchServer(), clientRequest.getURI());

    HttpUriRequest request =
        constructHttpMethod(
            clientRequest.getRestMethodName(), elasticSearchRestUrl, clientRequest.getData());

    // add headers added to action
    if (!clientRequest.getHeaders().isEmpty()) {
      for (Entry<String, Object> header : clientRequest.getHeaders().entrySet()) {
        request.addHeader(header.getKey(), header.getValue() + "");
      }
    }

    HttpResponse response = httpClient.execute(request);

    // If head method returns no content, it is added according to response code thanks to
    // https://github.com/hlassiege
    if (request.getMethod().equalsIgnoreCase("HEAD")) {
      if (response.getEntity() == null) {
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
          response.setEntity(new StringEntity("{\"ok\" : true, \"found\" : true}"));
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
          response.setEntity(new StringEntity("{\"ok\" : false, \"found\" : false}"));
        }
      }
    }
    return deserializeResponse(response, clientRequest.getName(), clientRequest.getPathToResult());
  }
 /**
  * Executes the HTTP request.
  *
  * <p>In case of any exception thrown by HttpClient, it will release the connection. In other
  * cases it is the duty of caller to do it, or process the input stream.
  *
  * @param repository to execute the HTTP method for
  * @param request resource store request that triggered the HTTP request
  * @param httpRequest HTTP request to be executed
  * @param baseUrl The BaseURL used to construct final httpRequest
  * @return response of making the request
  * @throws RemoteStorageException If an error occurred during execution of HTTP request
  */
 @VisibleForTesting
 HttpResponse executeRequest(
     final ProxyRepository repository,
     final ResourceStoreRequest request,
     final HttpUriRequest httpRequest,
     final String baseUrl,
     final boolean contentRequest)
     throws RemoteStorageException {
   final Timer timer = timer(repository, httpRequest, baseUrl);
   final TimerContext timerContext = timer.time();
   Stopwatch stopwatch = null;
   if (outboundRequestLog.isDebugEnabled()) {
     stopwatch = new Stopwatch().start();
   }
   try {
     return doExecuteRequest(repository, request, httpRequest, contentRequest);
   } finally {
     timerContext.stop();
     if (stopwatch != null) {
       outboundRequestLog.debug(
           "[{}] {} {} - {}",
           repository.getId(),
           httpRequest.getMethod(),
           httpRequest.getURI(),
           stopwatch);
     }
   }
 }
 private void attachSignature(
     final HttpUriRequest request, final List<NameValuePair> params, final byte[] content) {
   final RequestDigestBuffer digest =
       RequestDigestBuffer.newBuilder(config)
           .withMethod(request.getMethod())
           .withPath(request.getURI().getPath())
           .withQueryParams(params)
           .withTimestamp(Instant.now(Clock.systemUTC()).toEpochMilli())
           .build();
   final byte[] signature = digest.doFinal(content);
   for (final Header h : digest.requestHeaders(signature)) {
     request.addHeader(h);
   }
 }
  private ManticoreHttpResponse httpExecute(HttpUriRequest request) {
    int statusCode = 200;
    String ret = "";
    try {
      Logger.verbose(
          LOG_TAG,
          String.format("Executing %s %s", request.getMethod(), request.getURI().toString()));
      ret = _http.execute(request, _handler, _context);
    } catch (HttpResponseException httpEx) {
      // Bad status code
      statusCode = httpEx.getStatusCode();
      ret = httpEx.getLocalizedMessage();
      Logger.warn(
          LOG_TAG,
          String.format("Error executing %s %s", request.getMethod(), request.getURI().toString()),
          httpEx);
    } catch (IOException ioEx) {
      Logger.error(LOG_TAG, "Error loading page " + request.getURI().toString(), ioEx);
      return null;
    }

    return new ManticoreHttpResponse(statusCode, ret, _handler.getHeaders());
  }
  private <T> T executeRequest(final HttpUriRequest request, final ResponseHandler<T> handler)
      throws IOException {
    final CloseableHttpClient client = createClientInstance();
    try {
      final CloseableHttpResponse response = client.execute(request);
      //  Wrap the response in a buffer to facilitate error handlers re-playing the content if the
      // response
      //  size is smaller than the max allowable buffer
      if (response.getEntity().getContentLength() >= 0
          && response.getEntity().getContentLength() < config.getMaxBufferSize()) {
        EntityUtils.updateEntity(response, new BufferedHttpEntity(response.getEntity()));
      }

      //  Explicit check for the authorization status of the API key
      if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
        throw new HyppoAuthException(config);
      }

      try {
        log.debug(
            "{} - {} : {}",
            request.getMethod(),
            request.getURI().getPath(),
            response.getStatusLine().getStatusCode());
        return handler.handleResponse(response);
      } finally {
        IOUtils.closeQuietly(response);
      }
    } catch (Exception e) {
      log.error(
          "{} - {} : FAILED - {}", request.getMethod(), request.getURI().getPath(), e.toString());
      throw e;
    } finally {
      IOUtils.closeQuietly(client);
    }
  }
  @Test
  public void shouldProxyTheRequestMethodUriBodyAndContentType()
      throws ServletException, IOException, URISyntaxException {
    CloseableHttpClient mockHttpClient =
        mock(CloseableHttpClient.class, Mockito.RETURNS_DEEP_STUBS);

    AbstractLightblueProxyServlet servlet =
        getTestServlet(mockHttpClient, null, "http://myservice.com", null);

    HttpServletRequest stubRequest =
        new StubHttpServletRequest(
            "http://my.site.com/app/get/the/thing?foo=bar",
            "GET",
            "{test:0}",
            "application/json",
            "/get/*");

    HttpServletResponse mockResponse = mock(HttpServletResponse.class);
    ServletOutputStream outputStream = new FakeServletOutputStream(new ByteArrayOutputStream());
    when(mockResponse.getOutputStream()).thenReturn(outputStream);

    servlet.service(stubRequest, mockResponse);

    ArgumentCaptor<HttpUriRequest> requestCaptor = ArgumentCaptor.forClass(HttpUriRequest.class);

    verify(mockHttpClient).execute(requestCaptor.capture());

    HttpUriRequest request = requestCaptor.getValue();

    assertEquals("GET", request.getMethod());
    assertEquals(new URI("http://myservice.com/the/thing?foo=bar"), request.getURI());
    assertThat(request, instanceOf(HttpEntityEnclosingRequest.class));
    assertEquals(1, request.getHeaders("content-type").length);
    assertEquals("application/json", request.getHeaders("content-type")[0].getValue());

    HttpEntityEnclosingRequest entityEnclosingRequest = (HttpEntityEnclosingRequest) request;
    ByteArrayOutputStream entityOutStream = new ByteArrayOutputStream();
    entityEnclosingRequest.getEntity().writeTo(entityOutStream);

    byte[] expectedEntityBytes = new byte[stubRequest.getContentLength()];
    stubRequest.getInputStream().read(expectedEntityBytes, 0, stubRequest.getContentLength());

    assertEquals(new String(expectedEntityBytes), entityOutStream.toString());
  }
Example #13
0
 protected void logRequest(HttpUriRequest httpUriRequest) {
   LOGGER.info(String.format("%s %s", httpUriRequest.getMethod(), httpUriRequest.getURI()));
 }
    @Override
    protected List<SmartDevice> doInBackground(final Void... params) {
      mLogger.entering(getClass().getName(), "doInBackground", params);

      List<SmartDevice> devices = new ArrayList<SmartDevice>();

      DConnectMessage message = null;

      try {
        URIBuilder builder = new URIBuilder();
        builder.setProfile(ServiceDiscoveryProfileConstants.PROFILE_NAME);

        SharedPreferences prefs =
            PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        if (prefs.getBoolean(getString(R.string.key_settings_dconn_ssl), false)) {
          builder.setScheme("https");
        } else {
          builder.setScheme("http");
        }

        builder.setHost(
            prefs.getString(
                getString(R.string.key_settings_dconn_host), getString(R.string.default_host)));

        builder.setPort(
            Integer.parseInt(
                prefs.getString(
                    getString(R.string.key_settings_dconn_port),
                    getString(R.string.default_port))));

        builder.addParameter(DConnectMessage.EXTRA_ACCESS_TOKEN, getAccessToken());

        HttpUriRequest request = new HttpGet(builder.build());
        request.addHeader(DConnectMessage.HEADER_GOTAPI_ORIGIN, getPackageName());
        mLogger.info(request.getMethod() + " " + request.getURI());
        HttpResponse response = mDConnectClient.execute(request);
        message = (new HttpMessageFactory()).newDConnectMessage(response);
      } catch (URISyntaxException e) {
        e.printStackTrace();

        mLogger.exiting(getClass().getName(), "doInBackground", devices);
        return devices;
      } catch (IOException e) {
        e.printStackTrace();

        mLogger.exiting(getClass().getName(), "doInBackground", devices);
        return devices;
      }

      if (message == null) {
        mLogger.exiting(getClass().getName(), "doInBackground", devices);
        return devices;
      }

      int result = message.getInt(DConnectMessage.EXTRA_RESULT);
      if (result == DConnectMessage.RESULT_ERROR) {
        mLogger.exiting(getClass().getName(), "doInBackground", devices);
        return devices;
      }

      List<Object> services = message.getList(ServiceDiscoveryProfileConstants.PARAM_SERVICES);
      if (services != null) {
        for (Object object : services) {
          @SuppressWarnings("unchecked")
          Map<String, Object> service = (Map<String, Object>) object;
          SmartDevice device =
              new SmartDevice(
                  service.get(ServiceDiscoveryProfileConstants.PARAM_ID).toString(),
                  service.get(ServiceDiscoveryProfileConstants.PARAM_NAME).toString());
          devices.add(device);
          mLogger.info("Found smart device: " + device.getId());
        }
      }

      mLogger.exiting(getClass().getName(), "doInBackground", devices);
      return devices;
    }
  private ListResult<T> doListTypeRequest(
      HttpUriRequest request, ActionType type, boolean isJSONResponse) throws SocializeException {
    List<T> results = null;
    List<ActionError> errors = null;
    HttpEntity entity = null;

    ListResult<T> result = null;

    if (!clientFactory.isDestroyed()) {

      try {
        HttpClient client = clientFactory.getClient();

        if (logger != null && logger.isDebugEnabled()) {
          logger.debug("Request: " + request.getMethod() + " " + request.getRequestLine().getUri());
        }

        HttpResponse response = executeRequest(client, request);

        if (logger != null && logger.isDebugEnabled()) {
          logger.debug("Response: " + response.getStatusLine().getStatusCode());
        }

        entity = response.getEntity();

        if (httpUtils.isHttpError(response)) {

          if (sessionPersister != null && httpUtils.isAuthError(response)) {
            sessionPersister.delete(context);
          }

          String msg = ioUtils.readSafe(entity.getContent());
          throw new SocializeApiError(httpUtils, response.getStatusLine().getStatusCode(), msg);
        } else {

          result = new ListResult<T>();

          if (isJSONResponse) {
            // Read the json just for logging
            String json = ioUtils.readSafe(entity.getContent());

            if (logger != null && logger.isDebugEnabled()) {
              logger.debug("JSON Response: " + json);
            }

            if (!StringUtils.isEmpty(json)) {
              JSONObject object = jsonParser.parseObject(json);

              if (object.has(JSON_ATTR_ERRORS) && !object.isNull(JSON_ATTR_ERRORS)) {

                JSONArray errorList = object.getJSONArray(JSON_ATTR_ERRORS);

                int length = errorList.length();

                errors = new ArrayList<ActionError>(length);

                for (int i = 0; i < length; i++) {
                  JSONObject jsonObject = errorList.getJSONObject(i);
                  ActionError error = errorFactory.fromJSON(jsonObject);
                  errors.add(error);
                }

                result.setErrors(errors);
              }

              if (object.has(JSON_ATTR_ITEMS) && !object.isNull(JSON_ATTR_ITEMS)) {
                JSONArray list = object.getJSONArray(JSON_ATTR_ITEMS);

                int length = list.length();

                results = new ArrayList<T>(length);

                for (int i = 0; i < length; i++) {
                  results.add(fromJSON(list.getJSONObject(i), type));
                }

                result.setItems(results);
              }

              if (object.has(JSON_ATTR_COUNT) && !object.isNull(JSON_ATTR_COUNT)) {
                result.setTotalCount(object.getInt(JSON_ATTR_COUNT));
              }
            }
          }
        }
      } catch (Throwable e) {
        throw SocializeException.wrap(e);
      } finally {
        closeEntity(entity);
      }

      return result;
    } else {
      if (logger != null) {
        logger.warn("Attempt to access HttpClientFactory that was already destroyed");
      }

      return null;
    }
  }
Example #16
0
  /**
   * Executes the HTTP request.
   *
   * <p>In case of any exception thrown by HttpClient, it will release the connection. In other
   * cases it is the duty of caller to do it, or process the input stream.
   *
   * @param repository to execute the HTTP method fpr
   * @param request resource store request that triggered the HTTP request
   * @param httpRequest HTTP request to be executed
   * @return response of making the request
   * @throws RemoteStorageException If an error occurred during execution of HTTP request
   */
  private HttpResponse executeRequest(
      final ProxyRepository repository,
      final ResourceStoreRequest request,
      final HttpUriRequest httpRequest)
      throws RemoteStorageException {
    final URI methodUri = httpRequest.getURI();

    if (getLogger().isDebugEnabled()) {
      getLogger()
          .debug(
              "Invoking HTTP "
                  + httpRequest.getMethod()
                  + " method against remote location "
                  + methodUri);
    }

    final RemoteStorageContext ctx = getRemoteStorageContext(repository);

    final HttpClient httpClient = HttpClientUtil.getHttpClient(CTX_KEY, ctx);

    httpRequest.setHeader("user-agent", formatUserAgentString(ctx, repository));
    httpRequest.setHeader("accept", "*/*");
    httpRequest.setHeader("accept-language", "en-us");
    httpRequest.setHeader("accept-encoding", "gzip,deflate,identity");
    httpRequest.setHeader("cache-control", "no-cache");

    // HTTP keep alive should not be used, except when NTLM is used
    final Boolean isNtlmUsed = HttpClientUtil.isNTLMAuthenticationUsed(CTX_KEY, ctx);
    if (isNtlmUsed == null || !isNtlmUsed) {
      httpRequest.setHeader("Connection", "close");
      httpRequest.setHeader("Proxy-Connection", "close");
    }

    HttpResponse httpResponse = null;
    try {
      httpResponse = httpClient.execute(httpRequest);
      final int statusCode = httpResponse.getStatusLine().getStatusCode();

      final Header httpServerHeader = httpResponse.getFirstHeader("server");
      checkForRemotePeerAmazonS3Storage(
          repository, httpServerHeader == null ? null : httpServerHeader.getValue());

      Header proxyReturnedErrorHeader = httpResponse.getFirstHeader(NEXUS_MISSING_ARTIFACT_HEADER);
      boolean proxyReturnedError =
          proxyReturnedErrorHeader != null && Boolean.valueOf(proxyReturnedErrorHeader.getValue());

      if (statusCode == HttpStatus.SC_FORBIDDEN) {
        throw new RemoteAccessDeniedException(
            repository, methodUri.toASCIIString(), httpResponse.getStatusLine().getReasonPhrase());
      } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
        throw new RemoteAuthenticationNeededException(
            repository, httpResponse.getStatusLine().getReasonPhrase());
      } else if (statusCode == HttpStatus.SC_OK && proxyReturnedError) {
        throw new RemoteStorageException(
            "Invalid artifact found, most likely a proxy redirected to an HTML error page.");
      }

      return httpResponse;
    } catch (RemoteStorageException ex) {
      release(httpResponse);
      throw ex;
    } catch (ClientProtocolException ex) {
      release(httpResponse);
      throw new RemoteStorageException(
          "Protocol error while executing "
              + httpRequest.getMethod()
              + " method. [repositoryId=\""
              + repository.getId()
              + "\", requestPath=\""
              + request.getRequestPath()
              + "\", remoteUrl=\""
              + methodUri.toASCIIString()
              + "\"]",
          ex);
    } catch (IOException ex) {
      release(httpResponse);
      throw new RemoteStorageException(
          "Transport error while executing "
              + httpRequest.getMethod()
              + " method [repositoryId=\""
              + repository.getId()
              + "\", requestPath=\""
              + request.getRequestPath()
              + "\", remoteUrl=\""
              + methodUri.toASCIIString()
              + "\"]",
          ex);
    }
  }
  private HttpResponse doExecuteRequest(
      final ProxyRepository repository,
      final ResourceStoreRequest request,
      final HttpUriRequest httpRequest,
      final boolean contentRequest)
      throws RemoteStorageException {
    final URI methodUri = httpRequest.getURI();

    if (log.isDebugEnabled()) {
      log.debug(
          "Invoking HTTP {} method against remote location {}", httpRequest.getMethod(), methodUri);
    }

    final RemoteStorageContext ctx = getRemoteStorageContext(repository);

    final HttpClient httpClient = (HttpClient) ctx.getContextObject(CTX_KEY_CLIENT);

    httpRequest.setHeader("Accept", "*/*");
    httpRequest.setHeader("Accept-Language", "en-us");
    httpRequest.setHeader("Accept-Encoding", "gzip,deflate,identity");
    httpRequest.setHeader("Cache-Control", "no-cache");

    HttpResponse httpResponse = null;
    try {
      final BasicHttpContext httpContext = new BasicHttpContext();
      httpContext.setAttribute(Hc4Provider.HTTP_CTX_KEY_REPOSITORY, repository);
      if (contentRequest) {
        httpContext.setAttribute(CONTENT_RETRIEVAL_MARKER_KEY, Boolean.TRUE);
      }

      httpResponse = httpClient.execute(httpRequest, httpContext);
      final int statusCode = httpResponse.getStatusLine().getStatusCode();

      final Header httpServerHeader = httpResponse.getFirstHeader("server");
      checkForRemotePeerAmazonS3Storage(
          repository, httpServerHeader == null ? null : httpServerHeader.getValue());

      Header proxyReturnedErrorHeader = httpResponse.getFirstHeader(NEXUS_MISSING_ARTIFACT_HEADER);
      boolean proxyReturnedError =
          proxyReturnedErrorHeader != null && Boolean.valueOf(proxyReturnedErrorHeader.getValue());

      if (statusCode == HttpStatus.SC_FORBIDDEN) {
        throw new RemoteAccessDeniedException(
            repository, methodUri.toASCIIString(), httpResponse.getStatusLine().getReasonPhrase());
      } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
        throw new RemoteAuthenticationNeededException(
            repository, httpResponse.getStatusLine().getReasonPhrase());
      } else if (statusCode == HttpStatus.SC_OK && proxyReturnedError) {
        throw new RemoteStorageException(
            "Invalid artifact found, most likely a proxy redirected to an HTML error page.");
      }

      return httpResponse;
    } catch (RemoteStorageException ex) {
      release(httpResponse);
      throw ex;
    } catch (ClientProtocolException ex) {
      release(httpResponse);
      throw new RemoteStorageException(
          "Protocol error while executing "
              + httpRequest.getMethod()
              + " method. [repositoryId=\""
              + repository.getId()
              + "\", requestPath=\""
              + request.getRequestPath()
              + "\", remoteUrl=\""
              + methodUri.toASCIIString()
              + "\"]",
          ex);
    } catch (ConnectionPoolTimeoutException ex) {
      release(httpResponse);
      throw new RemoteStorageTransportOverloadedException(
          repository,
          "Connection pool timeout error while executing "
              + httpRequest.getMethod()
              + " method [repositoryId=\""
              + repository.getId()
              + "\", requestPath=\""
              + request.getRequestPath()
              + "\", remoteUrl=\""
              + methodUri.toASCIIString()
              + "\"]",
          ex);
    } catch (IOException ex) {
      release(httpResponse);
      throw new RemoteStorageException(
          "Transport error while executing "
              + httpRequest.getMethod()
              + " method [repositoryId=\""
              + repository.getId()
              + "\", requestPath=\""
              + request.getRequestPath()
              + "\", remoteUrl=\""
              + methodUri.toASCIIString()
              + "\"]",
          ex);
    }
  }
 private Timer timer(
     final ProxyRepository repository, final HttpUriRequest httpRequest, final String baseUrl) {
   return metricsRegistry.newTimer(
       HttpClientRemoteStorage.class, baseUrl, httpRequest.getMethod());
 }
Example #19
0
 public String toString() {
   if (request == null) {
     return "Request";
   }
   return request.getMethod() + " request to " + request.getURI();
 }
Example #20
0
  private HttpResponse phaRequestPart1(
      String reqMeth,
      String reletivePath,
      Object queryString,
      String phaToken,
      String phaTokenSecret,
      Object requestBody, // String or byte[]
      String contentType,
      Map<String, Object> options)
      throws IndivoClientException {

    String consumerToken = null;
    String consumerSecret = null;
    String foreignURL = null;
    Object indivoInstallation = options.get("indivoInstallation");
    if (indivoInstallation != null) {
      if (!(indivoInstallation instanceof String[])) {
        throw new IndivoClientException(
            "indivoInstallation option must be of type String[] with lenght == 3.  Was: "
                + indivoInstallation.getClass().getName());
      }
      String[] indivoInstallation0 = (String[]) indivoInstallation;
      if (indivoInstallation0.length != 3) {
        throw new IndivoClientException(
            "indivoInstallation option must be a String array with length 3. Length is: "
                + indivoInstallation0.length);
      }
      foreignURL = indivoInstallation0[0];
      consumerToken = indivoInstallation0[1];
      consumerSecret = indivoInstallation0[2];
    }

    logger.info(
        "consumerToken, consumerSecret, foreignURL: "
            + consumerToken
            + ", "
            + consumerSecret
            + ", "
            + foreignURL);
    String displayQS = "null";
    if (queryString != null) {
      displayQS = queryString.getClass().getName() + " " + queryString;
    }
    ;

    logger.info(
        "reletivePath, queryString, requestXmlOrParams: "
            + reletivePath
            + ",  "
            + displayQS
            + '\n'
            + requestBody
            + "\n\n");
    String queryString0;
    if (queryString == null
        || ((queryString instanceof String) && ((String) queryString).length() == 0)) {
      queryString0 = "";
    } else if (queryString instanceof String) {
      String qsString = (String) queryString;
      if (qsString.indexOf('=') < 1) {
        throw new IndivoClientException(
            "unexpected queryString, did not have any key/value delimiter of '=': " + queryString);
      }
      queryString0 = qsString;
      logger.info("queryString0 = qsString = " + qsString);
    } else if (queryString instanceof Map) {
      StringBuffer qsBuff = new StringBuffer();
      Map qsMap = (Map) queryString;
      Iterator iter = qsMap.keySet().iterator();
      while (iter.hasNext()) {
        if (qsBuff.length() > 0) {
          qsBuff.append('&');
        }

        Object keyObj = iter.next();
        if (!(keyObj instanceof String)) {
          throw new IndivoClientException(
              "queryString map key of unexpected type: "
                  + keyObj.getClass().getName()
                  + " -- "
                  + keyObj);
        }
        String key = (String) keyObj;

        Object valueObj = qsMap.get(key);
        try {
          if (valueObj instanceof String) {
            qsBuff.append(
                URLEncoder.encode(key, "UTF-8")
                    + '='
                    + URLEncoder.encode((String) valueObj, "UTF-8"));
          } else if (valueObj instanceof String[]) {
            String[] valueArr = (String[]) valueObj;
            for (int ii = 0; ii < valueArr.length; ii++) {
              qsBuff.append(
                  URLEncoder.encode(key, "UTF-8") + '=' + URLEncoder.encode(valueArr[ii], "UTF-8"));
            }
          } else {
            throw new IndivoClientException(
                "queryString map value of unexpected type: "
                    + valueObj.getClass().getName()
                    + " -- "
                    + valueObj);
          }
        } catch (java.io.UnsupportedEncodingException uee) {
          throw new IndivoClientException(uee);
        }
      }
      queryString0 = qsBuff.toString();
    } else {
      throw new IndivoClientException(
          "queryString not String or Map, type is: " + queryString.getClass().getName());
    }

    String baseURL0 = defaultBaseURL;
    if (foreignURL != null) {
      baseURL0 = foreignURL;
    }

    String consumerKey0 = defaultConsumerKey;
    String consumerSecret0 = defaultConsumerSecret;
    if (consumerToken != null) {
      consumerKey0 = consumerToken;
      consumerSecret0 = consumerSecret;
    }

    logger.info(
        " -- baseURL0: "
            + baseURL0
            + " -- reletivePath: "
            + reletivePath
            + " -- queryString: "
            + queryString0);

    String phaURLString = baseURL0 + reletivePath;
    if (queryString0.length() > 0) {
      phaURLString += "?" + queryString0;
    }

    /* FIXME temp for test*/
    // System.out.println(phaURLString); if (requestBody != null) { System.out.println(requestBody);
    // }

    if (requestBody != null) {
      if (requestBody instanceof String) {
        if (((String) requestBody).length() > 0) {
          if (contentType == null || contentType.length() == 0) {
            throw new IndivoClientException("contentType must be provided for request body");
          }
        }
      } else if ((requestBody instanceof Byte[] && ((Byte[]) requestBody).length > 0)
          || (requestBody instanceof byte[] && ((byte[]) requestBody).length > 0)) {
        if (contentType == null || contentType.length() == 0) {
          throw new IndivoClientException("contentType must be provided for request body");
        }
      } else {
        throw new IndivoClientException(
            "requestBody must be either String or Byte[] or byte[], was: "
                + requestBody.getClass().getName());
      }
    } else if (contentType != null && contentType.length() > 0) {
      throw new IndivoClientException("content type provided without requestBody: " + contentType);
    }

    HttpUriRequest hcRequest = null;

    // String requestXmlOrParams0 = null;
    if (requestBody == null) {
      requestBody = "";
    }

    logger.info("reqMeth: " + reqMeth);
    try {
      if (reqMeth.equals("PUT") || reqMeth.equals("POST")) {
        if (reqMeth.equals("PUT")) {
          hcRequest = new HttpPut(phaURLString);
        } else {
          hcRequest = new HttpPost(phaURLString);
        }

        byte[] requestBodyB = null;
        if (requestBody instanceof String) {
          String requestBodyStr = (String) requestBody;
          if (requestBodyStr.startsWith("<?xml")) {
            String[] parsedProlog = getEncoding(requestBodyStr);
            if (parsedProlog.length == 3 && (!parsedProlog[1].toUpperCase().equals("UTF-8"))) {
              requestBodyStr = parsedProlog[0] + "UTF-8" + parsedProlog[1];
              logger.info("changing prolog from: " + parsedProlog[1] + " to: " + "UTF-8");
              requestBodyStr = parsedProlog[0] + "UTF-8" + parsedProlog[2];
            }
          }

          // System.out.println("requestBodyStr: " + requestBodyStr);
          requestBodyB = requestBodyStr.getBytes("UTF-8");
        } else if (requestBody instanceof byte[]) {
          requestBodyB = (byte[]) requestBody;
        } else { // requestBody instanceof Byte[]
          requestBodyB = new byte[((Byte[]) requestBody).length];
          for (int ii = 0; ii < ((Byte[]) requestBody).length; ii++) {
            requestBodyB[ii] = ((Byte[]) requestBody)[ii];
          }
        }
        ByteArrayEntity bae = new ByteArrayEntity(requestBodyB);
        bae.setContentType(contentType);
        ((HttpEntityEnclosingRequestBase) hcRequest).setEntity(bae);
        //                hcRequest.addHeader("Content-Type",contentType);
      } else if (reqMeth.equals("GET")) {
        hcRequest = new HttpGet(phaURLString);
      } else if (reqMeth.equals("DELETE")) {
        hcRequest = new HttpDelete(phaURLString);
      }
    } catch (java.io.UnsupportedEncodingException uee) {
      throw new IndivoClientException(uee);
    }

    // in case of form-url-encoded, will signpost know to look at Content-Type header and entity??

    logger.info("pre signWithSignpost");
    signWithSignpost(hcRequest, consumerKey0, consumerSecret0, phaToken, phaTokenSecret);
    logger.info("post signWithSignpost");

    hcRequest.addHeader("Accept", "text/plain,application/xml"); // don't be mistaken for a browser
    logger.info("post signWithSignpost 1");

    AbstractHttpClient httpClient = new DefaultHttpClient();
    HttpParams httpParams0 = httpClient.getParams();
    logger.info("post signWithSignpost 2");

    Object connectionTimeout = options.get("connectionTimeout");
    Object socketTimeout = options.get("socketTimeout");
    logger.info("post signWithSignpost 3");
    if (connectionTimeout == null) {
      connectionTimeout = defaultHttpTimeout;
    }
    if (socketTimeout == null) {
      socketTimeout = defaultHttpTimeout;
    }
    logger.info("post signWithSignpost 4");

    if (!((socketTimeout instanceof Integer) && (connectionTimeout instanceof Integer))) {
      throw new IndivoClientException(
          "socketTimeout and connectionTimeout options must be ingeters. "
              + "sockenTimeout was "
              + socketTimeout.getClass().getName()
              + ", and connectionTimeout was "
              + connectionTimeout.getClass().getName());
    }
    logger.info("about to set CONNECTION_TIMEOUT");

    httpParams0 =
        httpParams0.setIntParameter(
            CoreConnectionPNames.CONNECTION_TIMEOUT, (Integer) connectionTimeout);
    httpParams0 =
        httpParams0.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, (Integer) socketTimeout);
    httpClient.setParams(httpParams0);

    HttpResponse httpResponse = null;
    //        StatusLine statusLine = null;
    //        InputStream istrm = null;
    org.apache.http.Header[] allheaders = hcRequest.getAllHeaders();
    StringBuffer allheadersSB = new StringBuffer("\nall request headers:");
    for (int ii = 0; ii < allheaders.length; ii++) {
      allheadersSB.append("\n" + allheaders[ii].getName() + " : " + allheaders[ii].getValue());
    }
    logger.info("request: " + hcRequest.getMethod() + " " + hcRequest.getURI() + allheadersSB);
    try {
      httpResponse = httpClient.execute(hcRequest);
    } catch (java.net.ConnectException conE) {
      conE.printStackTrace();
      logger.warn("connectionTimeout, socketTimeout: " + connectionTimeout + ", " + socketTimeout);
      throw new IndivoClientConnectException(
          "connectionTimeout, socketTimeout: " + connectionTimeout + ", " + socketTimeout, conE);
    } catch (Exception excp) {
      excp.printStackTrace();
      logger.warn("phaRequestPart1 exception");
      throw new IndivoClientException(
          "connectionTimeout, socketTimeout: " + connectionTimeout + ", " + socketTimeout, excp);
    }

    return httpResponse;
  }
 protected HttpResponse execute(final HttpUriRequest method) throws IOException {
   logger.debug("Executing: " + method.getMethod() + " to " + method.getURI());
   return client.execute(method);
 }