@Nullable
 private static JsonElement request(
     @NotNull String host,
     @Nullable String login,
     @Nullable String password,
     @NotNull String path,
     @Nullable String requestBody,
     boolean post) {
   HttpMethod method = null;
   try {
     method = doREST(host, login, password, path, requestBody, post);
     String resp = method.getResponseBodyAsString();
     if (method.getStatusCode() != 200) {
       String message =
           String.format(
               "Request not successful. Status-Code: %s, Message: %s.",
               method.getStatusCode(), method.getStatusText());
       LOG.warn(message);
       throw new HttpStatusException(method.getStatusCode(), method.getStatusText(), message);
     }
     if (resp == null) {
       String message = String.format("Unexpectedly empty response: %s.", resp);
       LOG.warn(message);
       throw new RuntimeException(message);
     }
     return parseResponse(resp);
   } catch (IOException e) {
     LOG.warn(String.format("Request failed: %s", e.getMessage()), e);
     throw Throwables.propagate(e);
   } finally {
     if (method != null) {
       method.releaseConnection();
     }
   }
 }
  @Monitor(
      server = LOGOIMAGE_SERVER,
      parserClass = ServiceUrlParserFactory.CLASS_PROPERTIES,
      filePath = "config/web_services.properties",
      serviceUrlKeys = "URL_GETLOGOIMAGE")
  private DetectResult monitorLogoImageServer() {
    DetectResult result = new DetectResult();

    HttpClient httpClient = null;
    HttpMethod method = null;
    try {
      String getLogImageUrl = WebServiceConfigurator.getUrlOfLogoImage();
      String url =
          MessageFormat.format(getLogImageUrl, "/tnimages/logo/cat-accomodation.png", "90", "90");
      method = new GetMethod(url);
      httpClient = new HttpClient();
      httpClient.executeMethod(method);
      String image = "";
      byte[] imageBytes = method.getResponseBody();
      if (method.getStatusCode() == 200) {
        if (imageBytes != null && imageBytes.length != 0) {
          image = Utility.byteArrayToBase64(imageBytes);
        }

        if (image != null && image.length() > 0) {
          result.isSuccess = true;
        } else {
          result.isSuccess = false;
          result.msg =
              image == null
                  ? "Image is null. Image url is " + url
                  : "result is empty. Image url is " + url;
        }
      } else {
        result.isSuccess = false;
        result.msg = "http status code is " + method.getStatusCode();
      }

    } catch (Exception ex) {
      logger.fatal("#monitorLogoImageServer", ex);
      result.isSuccess = false;
      result.msg =
          "Exception occurs when get logo image"
              + ". Exception msg->"
              + ExceptionUtil.collectExceptionMsg(ex);
    } finally {
      if (method != null) {
        try {
          method.releaseConnection();
        } catch (Exception ex) {
        }
      }
    }
    return result;
  }
Example #3
0
  public Response httpRequest(HttpMethod method, Boolean WithTokenHeader, String token)
      throws WeiboException {
    InetAddress ipaddr;
    int responseCode = -1;
    try {
      ipaddr = InetAddress.getLocalHost();
      List<Header> headers = new ArrayList<Header>();
      if (WithTokenHeader) {
        if (token == null) {
          throw new IllegalStateException("Oauth2 token is not set!");
        }
        headers.add(new Header("Authorization", "OAuth2 " + token));
        headers.add(new Header("API-RemoteIP", ipaddr.getHostAddress()));
        client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
        for (Header hd : headers) {
          log(hd.getName() + ": " + hd.getValue());
        }
      }

      method
          .getParams()
          .setParameter(
              HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
      client.executeMethod(method);
      Header[] resHeader = method.getResponseHeaders();
      responseCode = method.getStatusCode();
      log("Response:");
      log("https StatusCode:" + String.valueOf(responseCode));

      for (Header header : resHeader) {
        log(header.getName() + ":" + header.getValue());
      }
      Response response = new Response();
      response.setResponseAsString(method.getResponseBodyAsString());
      log(response.toString() + "\n");

      if (responseCode != OK) {
        try {
          throw new WeiboException(
              getCause(responseCode), response.asJSONObject(), method.getStatusCode());
        } catch (JSONException e) {
          e.printStackTrace();
        }
      }
      return response;

    } catch (IOException ioe) {
      throw new WeiboException(ioe.getMessage(), ioe, responseCode);
    } finally {
      method.releaseConnection();
    }
  }
Example #4
0
  public boolean checkWeibo() {
    //		if (null == account.getCookie()) {
    if (null == clientMap.get(account.getUsername())) {
      //			System.out.println("false");
      logger.info("false");
      return false;
    }
    try {
      resetMethod();
      httpMethod.setPath("/");
      try {
        httpClient.executeMethod(httpMethod);
      } catch (Exception e) {
        logger.error(e.getMessage());
        return false;
      }
      String response = "";
      if (httpMethod.getStatusCode() == 200) {

        //				logger.info("check httpclient 200");
        try {
          response = new String(httpMethod.getResponseBody(), "UTF-8");
        } catch (Exception e) {
          logger.error(e.getMessage());
        }
      } else {
        logger.info("check httpClient " + httpMethod.getStatusCode());
      }
      // HttpURLConnection connection =
      // resetGetConnection("http://weibo.com/");
      // connection.connect();
      // String response = IOUtils.toString(connection.getInputStream(),
      // "UTF-8");
      // connection.disconnect();
      //			System.out.println(response);
      boolean succ = response.indexOf("我的首页") > 0;
      //			System.out.println(succ);
      logger.info(succ);
      httpMethod.releaseConnection();
      return succ;
    } catch (Exception e1) {
      e1.printStackTrace();
    }
    return false;
  }
 void copyProxyReponse(HttpMethod proxyResponse, HttpServletResponse response) throws IOException {
   copyProxyHeaders(proxyResponse.getResponseHeaders(), response);
   response.setContentLength(getResponseContentLength(proxyResponse));
   copy(proxyResponse.getResponseBodyAsStream(), response.getOutputStream());
   if (proxyResponse.getStatusLine() != null) {
     int statCode = proxyResponse.getStatusCode();
     response.setStatus(statCode);
   }
 }
Example #6
0
  private Result excuteMethod(HttpMethod method, String cookie, Map<String, String> headers) {
    Result result = new Result();
    result.setSuccess(true);
    int responseCode = -1;
    try {
      // String cookie =
      // "240=240; CurLoginUserGUID=a44e6f49751b4d8b9659636ae20540d6;
      // strCertificate=410df02a24354be8bb194aeec0829589;";
      if (cookie != null) {
        method.addRequestHeader("Cookie", cookie);
      }
      if (headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
          method.addRequestHeader(entry.getKey(), entry.getValue());
        }
      }
      method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, httpRequestRetryHandler);
      org.apache.commons.httpclient.HttpClient client = this.createHttpClient();
      client.executeMethod(method);
      responseCode = method.getStatusCode();
      if (responseCode != HttpStatus.SC_OK) {
        result.setSuccess(false);
        result.setErrorCode(ErrorCodeEnum.NOT_FOUND_ERROR);
        result.setMessage("responseCode:" + responseCode);
        result.setResponseCode(responseCode);
      }
      InputStream is = method.getResponseBodyAsStream();
      try {
        result.setResultBytes(IOUtils.toByteArray(is));
      } finally {
        IOUtils.closeQuietly(is);
      }

    } catch (Exception e) {
      result.setSuccess(false);
      result.setErrorCode(ErrorCodeEnum.SYSTEM_ERROR);
      result.setMessage(e.getMessage());
      result.setCause(e);
    } finally {
      result.setMethodStatusCode(method.getStatusCode());
      method.releaseConnection();
    }
    return result;
  }
  @Test
  public void testRequiredRole() throws HttpException, IOException {
    HttpMethod method = doRequest("http://localhost:9191/secure/requireRole");

    int code = method.getStatusCode();
    Header location = method.getResponseHeader("Location");

    System.out.println("code:" + code);
    System.out.println("location:" + location.getValue());
    Assert.assertEquals(code, 302);
    Assert.assertEquals(location.getValue(), "http://localhost:9191/secure/errorPage");
  }
  @Test
  public void uploadCorruptPomTest() throws HttpException, IOException {

    File jarFile = this.getTestFile("bad-pom.jar");
    File badPomFile = this.getTestFile("pom.xml");

    HttpMethod resultMethod =
        getDeployUtils()
            .deployUsingPomWithRestReturnResult(
                this.getTestRepositoryId(), jarFile, badPomFile, "", "jar");

    Assert.assertEquals(400, resultMethod.getStatusCode(), "Expected a 400 error returned.");
  }
 private HTTPClientResponseResolver createResponseResolver(
     final HttpMethod httpMethod, final Status status, final Header[] headers) {
   try {
     when(httpMethod.getStatusLine())
         .thenReturn(
             new org.apache.commons.httpclient.StatusLine(
                 String.format("HTTP/1.1 %s %s\r\n", status.getCode(), status.getName())));
   } catch (HttpException e) {
     throw new RuntimeException(e);
   }
   when(httpMethod.getStatusCode()).thenReturn(status.getCode());
   when(httpMethod.getResponseHeaders()).thenReturn(headers);
   return new TestableHTTPClientResponseResolver(httpMethod);
 }
  @org.junit.Test
  public void test_crossdomain_url() {

    HttpMethod get = new GetMethod(SLING_URL + CROSSDOMAIN_URL);
    try {
      client.executeMethod(get);
    } catch (HttpException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    assertTrue((get.getStatusCode() != 403));
  }
Example #11
0
  protected <T> void processOnResponses(HttpMethod httpMethod, HttpInvocation<T> httpInvocation)
      throws Exception {
    int statusCode = httpMethod.getStatusCode();
    httpInvocation.onResponseStatus(statusCode);

    Header[] responseHeaders = httpMethod.getResponseHeaders();
    if (ArrayUtils.isNotEmpty(responseHeaders)) {
      for (Header header : responseHeaders) {
        httpInvocation.onResponseHeader(header.getName(), header.getValue());
      }
    }

    httpInvocation.onResponseBody(httpMethod.getResponseBodyAsStream());
  }
  /**
   * Get file from URL, directories are created and files overwritten.
   *
   * @deprecated use org.apache.commons.io.FileUtils.copyURLToFile(URL, File)
   * @param requestUrl
   * @param outputPathAndFileName
   * @return int request status code OR -1 if an exception occurred
   */
  public static int getToFile(String requestUrl, String outputPathAndFileName) {
    int resultStatus = -1;

    File outputFile = new File(outputPathAndFileName);
    String outputPath = outputFile.getAbsolutePath().replace(outputFile.getName(), "");
    File outputDir = new File(outputPath);
    if (!outputDir.exists()) {
      outputDir.mkdir();
    }

    HttpClient client = new HttpClient();

    //	client.getState().setCredentials(
    //			new AuthScope("localhost", 7080, null ),
    //			new UsernamePasswordCredentials("nation", "nationPW")
    //     );
    //	client.getParams().setAuthenticationPreemptive(true);

    HttpMethod method = new GetMethod(requestUrl);

    //	method.setDoAuthentication( true );
    //  client.getParams().setAuthenticationPreemptive(true);

    // Execute and print response
    try {

      OutputStream os = new FileOutputStream(outputFile);

      client.executeMethod(method);
      InputStream is = method.getResponseBodyAsStream();
      BufferedInputStream bis = new BufferedInputStream(is);

      byte[] bytes = new byte[8192]; // reading as chunk of 8192 bytes
      int count = bis.read(bytes);
      while (count != -1 && count <= 8192) {
        os.write(bytes, 0, count);
        count = bis.read(bytes);
      }
      bis.close();
      os.close();
      resultStatus = method.getStatusCode();

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      method.releaseConnection();
    }

    return resultStatus;
  }
 @Test
 public void testRunning() throws Exception {
   HttpClient client = new HttpClient();
   setupClientSsl();
   // test get
   HttpMethod get = new GetMethod("https://127.0.0.1:8443/etomcat_x509");
   client.executeMethod(get);
   byte[] responseBody = get.getResponseBody();
   String content = new String(responseBody, "UTF-8");
   Assert.assertEquals("Servlet get fail", SecuredService.GREETING, content);
   // test assess denied
   HttpMethod post = new PostMethod("https://127.0.0.1:8443/etomcat_x509");
   client.executeMethod(post);
   assertEquals("Method security fail get fail", 403, post.getStatusCode());
 }
 private HttpResponse getHttpResult(HttpMethod method, int retry)
     throws ConnectException, HttpHelperException {
   HttpResponse httpResponse = new HttpResponse();
   this.initMethod(method, retry);
   InputStream is = null;
   BufferedReader reader = null;
   HttpClient client = createHttpClient();
   try {
     client.executeMethod(method);
   } catch (HttpException e1) {
     throw new ConnectException(e1);
   } catch (IOException e1) {
     throw new HttpHelperException(e1);
   }
   try {
     is = method.getResponseBodyAsStream();
     reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
     StringBuilder sb = new StringBuilder();
     char[] ch = new char[3096];
     while (reader.read(ch) != -1) {
       sb.append(ch);
     }
     httpResponse.setStatusCode(method.getStatusCode());
     httpResponse.setStatusText(method.getStatusText());
     httpResponse.setResponseText(sb.toString());
     return httpResponse;
   } catch (Exception e) {
     throw new HttpHelperException(e);
   } finally {
     method.releaseConnection();
     try {
       if (reader != null) {
         reader.close();
       }
     } catch (IOException e) {
       throw new HttpHelperException(e);
     }
     try {
       if (is != null) {
         is.close();
       }
     } catch (IOException e) {
       throw new HttpHelperException(e);
     }
   }
 }
 @NotNull
 public String executeMethod(@NotNull HttpMethod method) throws Exception {
   LOG.debug("URI: " + method.getURI());
   int statusCode;
   String entityContent;
   try {
     statusCode = getHttpClient().executeMethod(method);
     LOG.debug("Status code: " + statusCode);
     // may be null if 204 No Content received
     final InputStream stream = method.getResponseBodyAsStream();
     entityContent = stream == null ? "" : StreamUtil.readText(stream, CharsetToolkit.UTF8);
     LOG.debug(entityContent);
   } finally {
     method.releaseConnection();
   }
   // besides SC_OK, can also be SC_NO_CONTENT in issue transition requests
   // see: JiraRestApi#setTaskStatus
   // if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_NO_CONTENT) {
   if (statusCode >= 200 && statusCode < 300) {
     return entityContent;
   } else if (method.getResponseHeader("Content-Type") != null) {
     Header header = method.getResponseHeader("Content-Type");
     if (header.getValue().startsWith("application/json")) {
       JsonObject object = GSON.fromJson(entityContent, JsonObject.class);
       if (object.has("errorMessages")) {
         String reason = StringUtil.join(object.getAsJsonArray("errorMessages"), " ");
         // something meaningful to user, e.g. invalid field name in JQL query
         LOG.warn(reason);
         throw new Exception("Request failed. Reason: " + reason);
       }
     }
   }
   if (method.getResponseHeader("X-Authentication-Denied-Reason") != null) {
     Header header = method.getResponseHeader("X-Authentication-Denied-Reason");
     // only in JIRA >= 5.x.x
     if (header.getValue().startsWith("CAPTCHA_CHALLENGE")) {
       throw new Exception("Login failed. Enter captcha in web-interface.");
     }
   }
   if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
     throw new Exception(LOGIN_FAILED_CHECK_YOUR_PERMISSIONS);
   }
   String statusText = HttpStatus.getStatusText(method.getStatusCode());
   throw new Exception(
       String.format("Request failed with HTTP error: %d %s", statusCode, statusText));
 }
 @Override
 public void updateTimeSpent(final LocalTask task, final String timeSpent, final String comment)
     throws Exception {
   checkVersion();
   final HttpMethod method =
       doREST(
           "/rest/issue/execute/"
               + task.getId()
               + "?command=work+Today+"
               + timeSpent.replaceAll(" ", "+")
               + "+"
               + comment,
           true);
   if (method.getStatusCode() != 200) {
     InputStream stream = method.getResponseBodyAsStream();
     String message = new SAXBuilder(false).build(stream).getRootElement().getText();
     throw new Exception(message);
   }
 }
  private String post(final HttpMethod method) throws IOException, ForbiddenException {
    method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    method.setRequestHeader("Accept-Encoding", "gzip");
    InputStream is = null;
    try {
      this.m_clientManager.executeMethod(method);
      final int statusCode = method.getStatusCode();
      final StatusLine statusLine = method.getStatusLine();
      final Header encoding = method.getResponseHeader("Content-Encoding");
      if (encoding != null && encoding.getValue().equals("gzip")) {
        m_log.debug("Unzipping body...");
        is = new GZIPInputStream(method.getResponseBodyAsStream());
      } else {
        is = method.getResponseBodyAsStream();
      }
      final String body = IOUtils.toString(is);
      if (StringUtils.isBlank(body)) {
        // Could easily be a post request, which would not have a body.
        m_log.debug("No response body.  Post request?");
      }
      if (statusCode == HttpStatus.SC_FORBIDDEN) {
        final String msg = "NO 200 OK: " + method.getURI() + "\n" + statusLine + "\n" + body;
        m_log.warn(msg);
        throw new ForbiddenException(msg);
      }

      if (statusCode != HttpStatus.SC_OK) {

        final String msg = "NO 200 OK: " + method.getURI() + "\n" + statusLine + "\n" + body;
        m_log.warn(msg);
        throw new IOException(msg);
      } else {
        m_log.debug("Got 200 response...");
      }

      return body;
    } finally {
      IOUtils.closeQuietly(is);
      method.releaseConnection();
    }
  }
  @org.junit.Test
  public void test_get_authenticated() {

    // Try to get a collection
    authPrefs.add(AuthPolicy.DIGEST);
    authPrefs.add(AuthPolicy.BASIC);
    defaultcreds = new UsernamePasswordCredentials("admin", "admin");

    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(AuthScope.ANY, defaultcreds);
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

    HttpMethod get = new GetMethod(SLING_URL + GET_URL);
    try {
      client.executeMethod(get);
    } catch (HttpException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    assertEquals(get.getStatusCode(), 404);
  }
  /**
   * Appends response form URL to a StringBuffer
   *
   * @param requestUrl
   * @param resultStringBuffer
   * @return int request status code OR -1 if an exception occurred
   */
  public static int getAsString(String requestUrl, StringBuffer resultStringBuffer) {
    HttpClient client = new HttpClient();

    //	client.getState().setCredentials(
    //			new AuthScope("localhost", 7080, null ),
    //			new UsernamePasswordCredentials("nation", "nationPW")
    //     );
    //	client.getParams().setAuthenticationPreemptive(true);

    HttpMethod method = new GetMethod(requestUrl);

    // method.setDoAuthentication( true );
    // client.getParams().setAuthenticationPreemptive(true);

    // Execute and print response
    try {
      client.executeMethod(method);
      InputStream is = method.getResponseBodyAsStream();
      BufferedInputStream bis = new BufferedInputStream(is);

      String datastr = null;
      byte[] bytes = new byte[8192]; // reading as chunk of 8192 bytes
      int count = bis.read(bytes);
      while (count != -1 && count <= 8192) {
        datastr = new String(bytes, 0, count);
        resultStringBuffer.append(datastr);
        count = bis.read(bytes);
      }
      bis.close();

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      method.releaseConnection();
    }

    return method.getStatusCode();
  }
  /**
   * Makes a rest request of any type at the specified urlSuffix. The urlSuffix should be of the
   * form /userService/users. If CS throws an exception it handled and transalated to a Openfire
   * exception if possible. This is done using the check fault method that tries to throw the best
   * maching exception.
   *
   * @param type Must be GET or DELETE
   * @param urlSuffix The url suffix of the rest request
   * @param xmlParams The xml with the request params, must be null if type is GET or DELETE only
   * @return The response as a xml doc.
   * @throws ConnectionException Thrown if there are issues perfoming the request.
   * @throws Exception Thrown if the response from Clearspace contains an exception.
   */
  public Element executeRequest(HttpType type, String urlSuffix, String xmlParams)
      throws ConnectionException, Exception {
    if (Log.isDebugEnabled()) {
      Log.debug("Outgoing REST call [" + type + "] to " + urlSuffix + ": " + xmlParams);
    }

    String wsUrl = getConnectionURI() + WEBSERVICES_PATH + urlSuffix;

    String secret = getSharedSecret();

    HttpClient client = new HttpClient();
    HttpMethod method;

    // Configures the authentication
    client.getParams().setAuthenticationPreemptive(true);
    Credentials credentials = new UsernamePasswordCredentials(OPENFIRE_USERNAME, secret);
    AuthScope scope = new AuthScope(host, port, AuthScope.ANY_REALM);
    client.getState().setCredentials(scope, credentials);

    // Creates the method
    switch (type) {
      case GET:
        method = new GetMethod(wsUrl);
        break;
      case POST:
        PostMethod pm = new PostMethod(wsUrl);
        StringRequestEntity requestEntity = new StringRequestEntity(xmlParams);
        pm.setRequestEntity(requestEntity);
        method = pm;
        break;
      case PUT:
        PutMethod pm1 = new PutMethod(wsUrl);
        StringRequestEntity requestEntity1 = new StringRequestEntity(xmlParams);
        pm1.setRequestEntity(requestEntity1);
        method = pm1;
        break;
      case DELETE:
        method = new DeleteMethod(wsUrl);
        break;
      default:
        throw new IllegalArgumentException();
    }

    method.setRequestHeader("Accept", "text/xml");
    method.setDoAuthentication(true);

    try {
      // Executes the request
      client.executeMethod(method);

      // Parses the result
      String body = method.getResponseBodyAsString();
      if (Log.isDebugEnabled()) {
        Log.debug("Outgoing REST call results: " + body);
      }

      // Checks the http status
      if (method.getStatusCode() != 200) {
        if (method.getStatusCode() == 401) {
          throw new ConnectionException(
              "Invalid password to connect to Clearspace.",
              ConnectionException.ErrorType.AUTHENTICATION);
        } else if (method.getStatusCode() == 404) {
          throw new ConnectionException(
              "Web service not found in Clearspace.", ConnectionException.ErrorType.PAGE_NOT_FOUND);
        } else if (method.getStatusCode() == 503) {
          throw new ConnectionException(
              "Web service not avaible in Clearspace.",
              ConnectionException.ErrorType.SERVICE_NOT_AVAIBLE);
        } else {
          throw new ConnectionException(
              "Error connecting to Clearspace, http status code: " + method.getStatusCode(),
              new HTTPConnectionException(method.getStatusCode()),
              ConnectionException.ErrorType.OTHER);
        }
      } else if (body.contains("Clearspace Upgrade Console")) {
        // TODO Change CS to send a more standard error message
        throw new ConnectionException(
            "Clearspace is in an update state.", ConnectionException.ErrorType.UPDATE_STATE);
      }

      Element response = localParser.get().parseDocument(body).getRootElement();

      // Check for exceptions
      checkFault(response);

      // Since there is no exception, returns the response
      return response;
    } catch (DocumentException e) {
      throw new ConnectionException(
          "Error parsing the response of Clearspace.", e, ConnectionException.ErrorType.OTHER);
    } catch (HttpException e) {
      throw new ConnectionException(
          "Error performing http request to Clearspace", e, ConnectionException.ErrorType.OTHER);
    } catch (UnknownHostException e) {
      throw new ConnectionException(
          "Unknown Host " + getConnectionURI() + " trying to connect to Clearspace",
          e,
          ConnectionException.ErrorType.UNKNOWN_HOST);
    } catch (IOException e) {
      throw new ConnectionException(
          "Error peforming http request to Clearspace.", e, ConnectionException.ErrorType.OTHER);
    } finally {
      method.releaseConnection();
    }
  }