private String doCall(String uri) throws IOException {
    System.out.println("We're calling the uri");
    HttpClient httpClient = new HttpClient();
    httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    HttpMethod getMethod = new GetMethod(uri);

    try {
      int response = httpClient.executeMethod(getMethod);

      if (response != 200) {
        throw new IOException("HTTP problem, httpcode: " + response);
      }

      InputStream stream = getMethod.getResponseBodyAsStream();
      String responseText = responseToString(stream);
      return responseText;

    } catch (HttpException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return null;
  }
 @Nullable
 public Task findTask(String id) throws Exception {
   HttpMethod method = doREST("/rest/issue/byid/" + id, false);
   InputStream stream = method.getResponseBodyAsStream();
   Element element = new SAXBuilder(false).build(stream).getRootElement();
   return element.getName().equals("issue") ? createIssue(element) : null;
 }
예제 #3
0
  @Override
  public void loadResultFile(int fileId, FilePath file) {
    InputStream responseBodyAsStream = null;
    try {
      URL url = new URL(String.format(this.serviceExchangeURL, this.sessionId, fileId));

      HttpClient client = new HttpClient();
      HttpMethod get = new GetMethod(url.toExternalForm());
      client.executeMethod(get);
      responseBodyAsStream = get.getResponseBodyAsStream();

      file.copyFrom(responseBodyAsStream);
    } catch (MalformedURLException e) {
      LOGGER.log(
          Level.SEVERE,
          "Cannot access to exchange service on SCTM. Check the service URL and if SCTM up and running.!",
          e);
    } catch (HttpException e) {
      // handle lost session here
    } catch (IOException e) {
      LOGGER.log(Level.SEVERE, "Cannot load result file from SCTM.", e);
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      try {
        if (responseBodyAsStream != null) responseBodyAsStream.close();
      } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Cannot close file stream.", e);
      }
    }
  }
예제 #4
0
  private String sendApp(HttpMethod httpMethod) {

    String response = null;
    int resultCode = HttpStatus.SC_OK;

    try {

      httpMethod.setRequestHeader(CONTENT_TYPE_NAME, CONTENT_TYPE_VALUE_XML_APP);

      resultCode = httpClient.executeMethod(httpMethod);
      if (HttpStatus.SC_OK == resultCode) {
        byte[] resBody = httpMethod.getResponseBody();
        if (null != resBody && resBody.length > 0) {
          response = new String(resBody, UTF_8);
        }
      } else {
        response = "ResultCode = " + resultCode;
      }
    } catch (Exception ex) {
      response = ex.toString();
    } finally {
      if (null != httpMethod) {
        httpMethod.releaseConnection();
      }
    }
    return response;
  }
  private String signedRequest(
      final Map<String, String> paramMap,
      final Map<String, String> cookieMap,
      final Map<String, String> headerMap,
      final String apiPath)
      throws IOException, ForbiddenException {
    final String sessionId = cookieMap.get(SessionAttributeKeys.SESSION_ID);
    if (StringUtils.isBlank(sessionId)) {
      m_log.error(SessionAttributeKeys.SESSION_ID + " not in cookies: " + cookieMap);
      throw new IOException("Missing session ID");
    }

    final String userId = cookieMap.get(SessionAttributeKeys.USER_ID);
    if (StringUtils.isBlank(userId)) {
      m_log.debug("No user ID!!");
      // throw new IOException("Blank user ID");
    } else {
      paramMap.put("userId", userId);
    }

    m_log.debug("Sending session ID as cookie: " + sessionId);

    final String baseUrl = createBaseUrl(apiPath);
    final String finalUrl = sign(baseUrl, paramMap, cookieMap);

    final HttpMethod method = new PostMethod(finalUrl);
    method.setRequestHeader("Cookie", SessionAttributeKeys.SESSION_ID + "=" + sessionId);
    if (headerMap.containsKey("Referer")) {
      method.setRequestHeader("Referer", headerMap.get("Referer"));
    }

    m_log.debug("Sending request to: {}", finalUrl);
    return post(method);
  }
예제 #6
0
  /**
   * 发送http请求,并返回响应的xml报文 <功能详细描述>
   *
   * @param url http请求url
   * @param xml 请求xml报文
   * @return
   */
  private String send(HttpMethod httpMethod) {
    // 获取响应报文
    String response = null;
    int resultCode = HttpStatus.SC_OK;
    try {
      // 设置header信息,传输XML格式的
      httpMethod.setRequestHeader(CONTENT_TYPE_NAME, CONTENT_TYPE_VALUE_XML_UTF_8);

      // 处理响应结果码
      resultCode = httpClient.executeMethod(httpMethod);
      if (HttpStatus.SC_OK == resultCode) {
        byte[] resBody = httpMethod.getResponseBody();
        if (null != resBody && resBody.length > 0) {
          response = new String(resBody, UTF_8);
        }
      } else {
        response = resultCode + "";
        LogUtil.error("Http response: " + httpMethod.getResponseBodyAsString());
      }
    } catch (Exception ex) {
      response = ex.toString();
      LogUtil.error("send http request error!", ex);
    } finally {
      if (null != httpMethod) {
        httpMethod.releaseConnection();
      }
    }
    return response;
  }
  public void test_getContentsFolder() {

    try {
      Thread.sleep(2000);
    } catch (InterruptedException e1) {

      e1.printStackTrace();
    }

    // Get the content
    HttpMethod get_col_contents =
        new GetMethod(
            SLING_URL + COLLECTION_URL + slug + "/" + CONTENTS_FOLDER + "/" + "sling:resourceType");
    try {
      client.executeMethod(get_col_contents);
    } catch (HttpException e) {

      e.printStackTrace();
    } catch (IOException e) {

      e.printStackTrace();
    }
    // handle response.
    String response_body = "";
    try {
      response_body = get_col_contents.getResponseBodyAsString();
    } catch (IOException e) {

      e.printStackTrace();
    }

    assertEquals(response_body, CONTENTS_RESOURCE_TYPE);
  }
예제 #8
0
  @Test
  public void testFullFileDecryption() throws IOException, URISyntaxException {
    final URL testResourceUrl = new URL(VAULT_BASE_URI.toURL(), "fullFileDecryptionTestFile.txt");
    final HttpClient client = new HttpClient();

    // prepare 64MiB test data:
    final byte[] plaintextData = new byte[16777216 * Integer.BYTES];
    final ByteBuffer bbIn = ByteBuffer.wrap(plaintextData);
    for (int i = 0; i < 16777216; i++) {
      bbIn.putInt(i);
    }
    final InputStream plaintextDataInputStream = new ByteArrayInputStream(plaintextData);

    // put request:
    final EntityEnclosingMethod putMethod = new PutMethod(testResourceUrl.toString());
    putMethod.setRequestEntity(new ByteArrayRequestEntity(plaintextData));
    final int putResponse = client.executeMethod(putMethod);
    putMethod.releaseConnection();
    Assert.assertEquals(201, putResponse);

    // get request:
    final HttpMethod getMethod = new GetMethod(testResourceUrl.toString());
    final int statusCode = client.executeMethod(getMethod);
    Assert.assertEquals(200, statusCode);
    // final byte[] received = new byte[plaintextData.length];
    // IOUtils.read(getMethod.getResponseBodyAsStream(), received);
    // Assert.assertArrayEquals(plaintextData, received);
    Assert.assertTrue(
        IOUtils.contentEquals(plaintextDataInputStream, getMethod.getResponseBodyAsStream()));
    getMethod.releaseConnection();
  }
예제 #9
0
  @Test
  public void testUnsatisfiableRangeRequest() throws IOException, URISyntaxException {
    final URL testResourceUrl =
        new URL(VAULT_BASE_URI.toURL(), "unsatisfiableRangeRequestTestFile.txt");
    final HttpClient client = new HttpClient();

    // prepare file content:
    final byte[] fileContent = "This is some test file content.".getBytes();

    // put request:
    final EntityEnclosingMethod putMethod = new PutMethod(testResourceUrl.toString());
    putMethod.setRequestEntity(new ByteArrayRequestEntity(fileContent));
    final int putResponse = client.executeMethod(putMethod);
    putMethod.releaseConnection();
    Assert.assertEquals(201, putResponse);

    // get request:
    final HttpMethod getMethod = new GetMethod(testResourceUrl.toString());
    getMethod.addRequestHeader("Range", "chunks=1-2");
    final int getResponse = client.executeMethod(getMethod);
    final byte[] response = new byte[fileContent.length];
    IOUtils.read(getMethod.getResponseBodyAsStream(), response);
    getMethod.releaseConnection();
    Assert.assertEquals(416, getResponse);
    Assert.assertArrayEquals(fileContent, response);
  }
예제 #10
0
  private HttpMethod createProxyRequest(String targetUrl, HttpServletRequest request)
      throws IOException {
    URI targetUri;
    try {
      targetUri = new URI(uriEncode(targetUrl));
    } catch (URISyntaxException e) {
      throw new RuntimeException(e);
    }

    HttpMethod commonsHttpMethod =
        httpMethodProvider.getMethod(request.getMethod(), targetUri.toString());

    commonsHttpMethod.setFollowRedirects(false);

    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
      String headerName = headerNames.nextElement();
      Enumeration<String> headerVals = request.getHeaders(headerName);
      while (headerVals.hasMoreElements()) {
        String headerValue = headerVals.nextElement();
        headerValue = headerFilter.processRequestHeader(headerName, headerValue);
        if (headerValue != null) {
          commonsHttpMethod.addRequestHeader(new Header(headerName, headerValue));
        }
      }
    }

    return commonsHttpMethod;
  }
예제 #11
0
  public void execute() {

    client = new HttpClient();
    //		if (requestType.equals("GET")) {
    // Instantiate a GET HTTP method
    //	        HttpMethod method = new GetMethod(apiUrl);

    //	        if (!authentication.equals("")) {
    //	        	method.setRequestHeader("Authorization", "basic " + authentication);
    //	        }
    try {

      int statusCode = client.executeMethod(method);

      System.out.println("QueryString>>> " + apiUrl);
      System.out.println("Status Text>>>" + HttpStatus.getStatusText(statusCode));

      // Get data as a String
      System.out.println(method.getResponseBodyAsString());

      // OR as a byte array
      byte[] res = method.getResponseBody();

      // write to file
      FileOutputStream fos = new FileOutputStream("donepage.html");
      fos.write(res);

      // release connection
      method.releaseConnection();
    } catch (IOException e) {
      e.printStackTrace();
    }
    // }
  }
예제 #12
0
  /**
   * Extracts the response from the method as a InputStream.
   *
   * @param method the method that was executed
   * @return the response either as a stream, or as a deserialized java object
   * @throws IOException can be thrown
   */
  protected static Object extractResponseBody(HttpMethod method, Exchange exchange)
      throws IOException, ClassNotFoundException {
    InputStream is = method.getResponseBodyAsStream();
    if (is == null) {
      return null;
    }

    Header header = method.getResponseHeader(Exchange.CONTENT_ENCODING);
    String contentEncoding = header != null ? header.getValue() : null;

    if (!exchange.getProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.FALSE, Boolean.class)) {
      is = GZIPHelper.uncompressGzip(contentEncoding, is);
    }

    // Honor the character encoding
    String contentType = null;
    header = method.getResponseHeader("content-type");
    if (header != null) {
      contentType = header.getValue();
      // find the charset and set it to the Exchange
      HttpHelper.setCharsetFromContentType(contentType, exchange);
    }
    InputStream response = doExtractResponseBodyAsStream(is, exchange);
    // if content type is a serialized java object then de-serialize it back to a Java object
    if (contentType != null
        && contentType.equals(HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT)) {
      return HttpHelper.deserializeJavaObjectFromStream(response);
    } else {
      return response;
    }
  }
  public Object deserializeUrl(String url) {

    HttpMethod httpMethod = new GetMethod(url);
    HttpClient httpClient = new HttpClient();
    int code = 0;
    int tries = 0;
    String stringResponse = null;
    try {
      code = httpClient.executeMethod(httpMethod);
      if (code < 200 || code >= 300) throw new IOException("a cow");

      stringResponse = httpMethod.getResponseBodyAsString();
    } catch (IOException ioEx) {
      Log.v(_tag, ioEx.toString());
      tries++;
    }
    httpMethod.releaseConnection();

    if (stringResponse == null) return null;
    int start = stringResponse.indexOf("File1=") + 6;
    if (start == -1) return null;
    stringResponse = stringResponse.substring(start, stringResponse.indexOf("\n", start));

    return stringResponse;
  }
 /**
  * If a 'Proxy-Connection' header has been added to the request, it'll be of a 'keep-alive' type.
  * Until we support 'keep-alives', override the Proxy-Connection setting and instead pass a
  * 'close' (Otherwise every request has to timeout before we notice end-of-document).
  *
  * @param method Method to find proxy-connection header in.
  */
 public void handleAddProxyConnectionHeader(HttpMethod method) {
   Header h = method.getRequestHeader("Proxy-Connection");
   if (h != null) {
     h.setValue("close");
     method.setRequestHeader(h);
   }
 }
예제 #15
0
  protected Response request(HttpMethod method) throws IOException {
    int statusCode;
    String body;

    try {
      statusCode = client.executeMethod(method);
      if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
          || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
        method.releaseConnection();

        HttpMethod postMethod = redirectMethod((PostMethod) method);
        statusCode = client.executeMethod(postMethod);
        method = postMethod;
      }
      if (statusCode == HttpStatus.SC_NO_CONTENT) {
        body = "";
      } else {
        body = new String(method.getResponseBody(), "utf-8");
      }
      logger.debug("Remote Control replied with '" + statusCode + " / '" + body + "'");
      return new Response(statusCode, body, method.getResponseHeaders());
    } finally {
      method.releaseConnection();
    }
  }
예제 #16
0
 public String getHtmlByCode(String code) {
   StringBuffer content = new StringBuffer();
   HttpMethod getMethod = null;
   init();
   try {
     getMethod = new GetMethod(this.getUrl());
     client.executeMethod(getMethod);
     InputStream in = getMethod.getResponseBodyAsStream();
     BufferedReader br = new BufferedReader(new InputStreamReader(in, code), 1024);
     String line = "";
     while ((line = br.readLine()) != null) {
       content.append(line);
     }
     if (br != null) {
       br.close();
       br = null;
     }
     if (in != null) {
       in.close();
       in = null;
     }
   } catch (Exception e) {
     e.printStackTrace();
     release();
   } finally {
     getMethod.releaseConnection();
   }
   return content.toString();
 }
예제 #17
0
  public Object doTransform(Object src, String encoding) throws TransformerException {
    Object msg;
    HttpMethod httpMethod = (HttpMethod) src;
    Header contentType = httpMethod.getResponseHeader(HttpConstants.HEADER_CONTENT_TYPE);
    try {
      if (contentType != null && !contentType.getValue().startsWith("text/")) {
        msg = httpMethod.getResponseBody();
      } else {
        msg = httpMethod.getResponseBodyAsString();
      }
    } catch (IOException e) {
      throw new TransformerException(this, e);
    }
    // Standard headers
    Map headerProps = new HashMap();
    Header[] headers = httpMethod.getRequestHeaders();
    String name;
    for (int i = 0; i < headers.length; i++) {
      name = headers[i].getName();
      if (name.startsWith("X-" + MuleProperties.PROPERTY_PREFIX)) {
        name = name.substring(2);
      }
      headerProps.put(headers[i].getName(), headers[i].getValue());
    }
    // Set Mule Properties

    return new MuleMessage(msg, headerProps);
  }
  public void test_getTagsFolder() {

    try {
      Thread.sleep(2000);
    } catch (InterruptedException e1) {

      e1.printStackTrace();
    }

    String response_body = "";
    HttpMethod get_col_tags =
        new GetMethod(
            SLING_URL + COLLECTION_URL + slug + "/" + TAGS_FOLDER + "/" + "sling:resourceType");
    try {
      client.executeMethod(get_col_tags);
    } catch (HttpException e) {

      e.printStackTrace();
    } catch (IOException e) {

      e.printStackTrace();
    }

    try {
      response_body = get_col_tags.getResponseBodyAsString();
    } catch (IOException e) {

      e.printStackTrace();
    }

    assertEquals(response_body, TAGS_RESOURCE_TYPE);
    get_col_tags.releaseConnection();
  }
  @Test
  public void testServletAsAnonymous() throws Exception {

    HttpClient httpClient = new HttpClient();

    HttpMethod getMethod = null;
    try {
      // ------------ Test anonymous user not allowed ----------------
      getMethod =
          new GetMethod(
              "http://localhost:18080/authentication/token?applicationName=myFavoriteApp&deviceId=dead-beaf-cafe-babe&permission=rw");
      int status = httpClient.executeMethod(getMethod);
      assertEquals(401, status);

      // ------------ Test anonymous user allowed ----------------
      harness.deployContrib(
          "org.nuxeo.ecm.platform.login.token.test",
          "OSGI-INF/test-token-authentication-allow-anonymous-token-contrib.xml");

      status = httpClient.executeMethod(getMethod);
      assertEquals(201, status);
      String token = getMethod.getResponseBodyAsString();
      assertNotNull(token);
      assertNotNull(tokenAuthenticationService.getUserName(token));
      assertEquals(1, tokenAuthenticationService.getTokenBindings("Guest").size());

      harness.undeployContrib(
          "org.nuxeo.ecm.platform.login.token.test",
          "OSGI-INF/test-token-authentication-allow-anonymous-token-contrib.xml");
    } finally {
      getMethod.releaseConnection();
    }
  }
예제 #20
0
 @Override
 public void run() {
   byte[] buffer = new byte[4096];
   while (!this.stats.isComplete()) {
     HttpMethod httpmethod;
     if (this.content == null) {
       GetMethod httpget = new GetMethod(target.toASCIIString());
       httpmethod = httpget;
     } else {
       PostMethod httppost = new PostMethod(target.toASCIIString());
       httppost.setRequestEntity(new ByteArrayRequestEntity(content));
       httpmethod = httppost;
     }
     long contentLen = 0;
     try {
       httpclient.executeMethod(httpmethod);
       InputStream instream = httpmethod.getResponseBodyAsStream();
       if (instream != null) {
         int l = 0;
         while ((l = instream.read(buffer)) != -1) {
           contentLen += l;
         }
       }
       this.stats.success(contentLen);
     } catch (IOException ex) {
       this.stats.failure(contentLen);
     } finally {
       httpmethod.releaseConnection();
     }
   }
 }
예제 #21
0
 String getContent(HttpMethod httpMethod) {
   StringBuilder contentBuilder = new StringBuilder();
   if (isZipContent(httpMethod)) {
     InputStream is = null;
     GZIPInputStream gzin = null;
     InputStreamReader isr = null;
     BufferedReader br = null;
     try {
       is = httpMethod.getResponseBodyAsStream();
       gzin = new GZIPInputStream(is);
       isr =
           new InputStreamReader(
               gzin,
               ((HttpMethodBase) httpMethod).getResponseCharSet()); // ���ö�ȡ���ı����ʽ���Զ������
       br = new BufferedReader(isr);
       char[] buffer = new char[4096];
       int readlen = -1;
       while ((readlen = br.read(buffer, 0, 4096)) != -1) {
         contentBuilder.append(buffer, 0, readlen);
       }
     } catch (Exception e) {
       log.error("Unzip fail", e);
     } finally {
       try {
         br.close();
       } catch (Exception e1) {
         // ignore
       }
       try {
         isr.close();
       } catch (Exception e1) {
         // ignore
       }
       try {
         gzin.close();
       } catch (Exception e1) {
         // ignore
       }
       try {
         is.close();
       } catch (Exception e1) {
         // ignore
       }
     }
   } else {
     String content = null;
     try {
       content = httpMethod.getResponseBodyAsString();
     } catch (Exception e) {
       log.error("Fetch config error:", e);
     }
     if (null == content) {
       return null;
     }
     contentBuilder.append(content);
   }
   return contentBuilder.toString();
 }
예제 #22
0
 boolean isZipContent(HttpMethod httpMethod) {
   if (null != httpMethod.getResponseHeader(Constants.CONTENT_ENCODING)) {
     String acceptEncoding = httpMethod.getResponseHeader(Constants.CONTENT_ENCODING).getValue();
     if (acceptEncoding.toLowerCase().indexOf("gzip") > -1) {
       return true;
     }
   }
   return false;
 }
예제 #23
0
 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);
   }
 }
예제 #24
0
  /**
   * Gets the result of the execution of a get request. the attempt will be repeated until obtain
   * the exepected result
   *
   * @param path the path on which the request should be executed
   * @param expression the result that should be returned by the GET request, which allows to know
   *     if that request is completely processed or not
   * @throws Exception if something's going wrong...
   */
  public void retryGetRequestUntilObtainExpectedResponse(
      @NonNull String path, @NonNull String expression) throws Exception {
    String fullpath = path;
    if (path.startsWith("/")) fullpath = baseUrl + path;
    log.debug("Sending GET request to " + fullpath + " with several attemps");

    final int maxAttempts = Integer.parseInt(ExecutionContext.get(RestConstants.MAX_ATTEMPTS_KEY));
    final int timeToWait = Integer.parseInt(ExecutionContext.get(RestConstants.TIME_TO_WAIT_KEY));

    final HttpMethod method = new GetMethod(fullpath);
    try {
      for (final Map.Entry<String, String> header : requestHeaders.entrySet())
        method.setRequestHeader(header.getKey(), header.getValue());

      String responseAsString = null;
      String toCheck = null;
      String expected = expression;
      String prop = null;
      final int idx = expression.indexOf("=");
      if (idx > 0) {
        prop = expression.substring(0, idx);
        expected = expression.substring(idx + 1);
      }
      int statusCode;
      int attempts = 0;
      boolean success = false;
      do {
        // waiting timeToWait seconds
        Thread.sleep(timeToWait * 1000);
        statusCode = httpClient.executeMethod(method);
        attempts++;
        if (statusCode == HttpStatus.SC_OK) {
          responseAsString = method.getResponseBodyAsString();
          toCheck = responseAsString;
          if (prop != null) toCheck = JSONHelper.getPropertyValue(responseAsString, prop);
          if (toCheck.contains(expected)) {
            success = true;
            log.debug("The result is available! ");
          } else
            log.warn("The result is not yet available! | Waiting " + timeToWait + " seconds ...");
        } else
          log.warn(
              "unsuccessful GET request : "
                  + method.getStatusLine()
                  + " | Waiting "
                  + timeToWait
                  + " seconds ...");
      } while (!success && maxAttempts > attempts);
      response = new ResponseWrapper(responseAsString, statusCode);
    } catch (final Exception e) {
      log.error(e.getMessage(), e);
      throw e;
    } finally {
      method.releaseConnection();
    }
  }
 @Test
 public void testRunning() throws Exception {
   HttpClient client = new HttpClient();
   HttpMethod get = new GetMethod("http://127.0.0.1:8080/etomcat_test");
   client.executeMethod(get);
   byte[] responseBody = get.getResponseBody();
   String content = new String(responseBody, "UTF-8");
   Assert.assertEquals(
       "Servlet get fail", EmbeddedAnnotationSpringContext.class.getSimpleName(), content);
 }
예제 #26
0
  /**
   * Creates the HttpMethod to use to call the remote server, either its GET or POST.
   *
   * @param exchange the exchange
   * @return the created method as either GET or POST
   * @throws CamelExchangeException is thrown if error creating RequestEntity
   */
  @SuppressWarnings("deprecation")
  protected HttpMethod createMethod(Exchange exchange) throws Exception {
    // creating the url to use takes 2-steps
    String url = HttpHelper.createURL(exchange, getEndpoint());
    URI uri = HttpHelper.createURI(exchange, url, getEndpoint());
    // get the url and query string from the uri
    url = uri.toASCIIString();
    String queryString = uri.getRawQuery();

    // execute any custom url rewrite
    String rewriteUrl = HttpHelper.urlRewrite(exchange, url, getEndpoint(), this);
    if (rewriteUrl != null) {
      // update url and query string from the rewritten url
      url = rewriteUrl;
      uri = new URI(url);
      // use raw query to have uri decimal encoded which http client requires
      queryString = uri.getRawQuery();
    }

    // remove query string as http client does not accept that
    if (url.indexOf('?') != -1) {
      url = url.substring(0, url.indexOf('?'));
    }

    // create http holder objects for the request
    RequestEntity requestEntity = createRequestEntity(exchange);
    HttpMethods methodToUse =
        HttpHelper.createMethod(exchange, getEndpoint(), requestEntity != null);
    HttpMethod method = methodToUse.createMethod(url);
    if (queryString != null) {
      // need to encode query string
      queryString = UnsafeUriCharactersEncoder.encode(queryString);
      method.setQueryString(queryString);
    }

    LOG.trace("Using URL: {} with method: {}", url, method);

    if (methodToUse.isEntityEnclosing()) {
      ((EntityEnclosingMethod) method).setRequestEntity(requestEntity);
      if (requestEntity != null && requestEntity.getContentType() == null) {
        LOG.debug("No Content-Type provided for URL: {} with exchange: {}", url, exchange);
      }
    }

    // there must be a host on the method
    if (method.getHostConfiguration().getHost() == null) {
      throw new IllegalArgumentException(
          "Invalid uri: "
              + url
              + ". If you are forwarding/bridging http endpoints, then enable the bridgeEndpoint option on the endpoint: "
              + getEndpoint());
    }

    return method;
  }
  @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;
  }
예제 #28
0
 protected void doAuthorization(
     HttpClient httpclient, HttpMethod method, Map<String, Object> params) {
   if (type == null) {
     return;
   }
   String u = (String) params.get("Username");
   String p = (String) params.get("Password");
   if (u == null || p == null) {
     u = this.username;
     p = this.password;
   }
   if (u == null) {
     throw new IllegalArgumentException("Could not find username");
   }
   if (p == null) {
     throw new IllegalArgumentException("Could not find password");
   }
   if (type == AuthenticationType.BASIC) {
     httpclient
         .getState()
         .setCredentials(
             new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
             new UsernamePasswordCredentials(u, p));
     method.setDoAuthentication(true);
   } else if (type == AuthenticationType.FORM_BASED) {
     String authUrlStr = (String) params.get("AuthUrl");
     if (authUrlStr == null) {
       authUrlStr = authUrl;
     }
     if (authUrlStr == null) {
       throw new IllegalArgumentException("Could not find authentication url");
     }
     try {
       httpclient.executeMethod(method);
     } catch (IOException e) {
       throw new RuntimeException("Could not execute request for form-based authentication", e);
     } finally {
       method.releaseConnection();
     }
     PostMethod authMethod = new PostMethod(authUrlStr);
     NameValuePair[] data = {
       new NameValuePair("j_username", u), new NameValuePair("j_password", p)
     };
     authMethod.setRequestBody(data);
     try {
       httpclient.executeMethod(authMethod);
     } catch (IOException e) {
       throw new RuntimeException("Could not initialize form-based authentication", e);
     } finally {
       authMethod.releaseConnection();
     }
   } else {
     throw new RuntimeException("Unknown AuthenticationType " + type);
   }
 }
예제 #29
0
  private static String getTinyUrl(String fullUrl) throws HttpException, IOException {
    HttpClient httpclient = new HttpClient();

    // Prepare a request object
    HttpMethod method = new GetMethod("http://tinyurl.com/api-create.php");
    method.setQueryString(new NameValuePair[] {new NameValuePair("url", fullUrl)});
    httpclient.executeMethod(method);
    String tinyUrl = method.getResponseBodyAsString();
    method.releaseConnection();
    return tinyUrl;
  }
 private void checkVersion() throws Exception {
   HttpMethod method = doREST("/rest/workflow/version", false);
   InputStream stream = method.getResponseBodyAsStream();
   Element element = new SAXBuilder(false).build(stream).getRootElement();
   final boolean timeTrackingAvailable =
       element.getName().equals("version")
           && VersionComparatorUtil.compare(element.getChildText("version"), "4.1") >= 0;
   if (!timeTrackingAvailable) {
     throw new Exception("This version of Youtrack the time tracking is not supported");
   }
 }