Java Code Examples for org.apache.commons.httpclient.methods.GetMethod#releaseConnection()

The following examples show how to use org.apache.commons.httpclient.methods.GetMethod#releaseConnection() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpClientIT.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Test
public void hostConfig() {
    HttpClient client = new HttpClient();
    client.getParams().setConnectionManagerTimeout(CONNECTION_TIMEOUT);
    client.getParams().setSoTimeout(SO_TIMEOUT);

    HostConfiguration config = new HostConfiguration();
    config.setHost("weather.naver.com", 80, "http");
    GetMethod method = new GetMethod("/rgn/cityWetrMain.nhn");

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    method.setQueryString(new NameValuePair[] { new NameValuePair("key2", "value2") });

    try {
        // Execute the method.
        client.executeMethod(config, method);
    } catch (Exception ignored) {
    } finally {
        method.releaseConnection();
    }

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
}
 
Example 2
Source File: CatalogITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetOwner() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    // admin is owner
    URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry1.getKey().toString()).path("owners").path(admin.getKey().toString()).build();
    GetMethod method = createGet(uri, MediaType.APPLICATION_JSON, true);

    int code = c.executeMethod(method);
    assertEquals(200, code);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final UserVO vo = parse(body, UserVO.class);
    assertNotNull(vo);

    // id1 is not owner
    uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry1.getKey().toString()).path("owners").path(id1.getKey().toString()).build();
    method = createGet(uri, MediaType.APPLICATION_JSON, true);

    code = c.executeMethod(method);
    assertEquals(404, code);
}
 
Example 3
Source File: YarnRestJobStatusProvider.java    From samza with Apache License 2.0 6 votes vote down vote up
/**
 * Issues a HTTP Get request to the provided url and returns the response
 * @param requestUrl the request url
 * @return the response
 * @throws IOException if there are problems with the http get request.
 */
byte[] httpGet(String requestUrl)
    throws IOException {
  GetMethod getMethod = new GetMethod(requestUrl);
  try {
    int responseCode = this.httpClient.executeMethod(getMethod);
    LOGGER.debug("Received response code: {} for the get request on the url: {}", responseCode, requestUrl);
    byte[] response = getMethod.getResponseBody();
    if (responseCode != HttpStatus.SC_OK) {
      throw new SamzaException(
          String.format("Received response code: %s for get request on: %s, with message: %s.", responseCode,
              requestUrl, StringUtils.newStringUtf8(response)));
    }
    return response;
  } finally {
    getMethod.releaseConnection();
  }
}
 
Example 4
Source File: UriUtils.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public static List<String> getMetalinkChecksums(String url) {
    HttpClient httpClient = getHttpClient();
    GetMethod getMethod = new GetMethod(url);
    try {
        if (httpClient.executeMethod(getMethod) == HttpStatus.SC_OK) {
            InputStream is = getMethod.getResponseBodyAsStream();
            Map<String, List<String>> checksums = getMultipleValuesFromXML(is, new String[] {"hash"});
            if (checksums.containsKey("hash")) {
                List<String> listChksum = new ArrayList<>();
                for (String chk : checksums.get("hash")) {
                    listChksum.add(chk.replaceAll("\n", "").replaceAll(" ", "").trim());
                }
                return listChksum;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        getMethod.releaseConnection();
    }
    return null;
}
 
Example 5
Source File: EndpointTest.java    From ci.maven with Apache License 2.0 6 votes vote down vote up
@Test
public void testServlet() throws Exception {
    HttpClient client = new HttpClient();

    GetMethod method = new GetMethod(URL);

    try {
        int statusCode = client.executeMethod(method);

        assertEquals("HTTP GET failed", HttpStatus.SC_OK, statusCode);

        String response = method.getResponseBodyAsString();

        assertTrue("Unexpected response body", response.contains("Hello! How are you today?"));
    } finally {
        method.releaseConnection();
    }  
}
 
Example 6
Source File: JobsClient.java    From samza with Apache License 2.0 6 votes vote down vote up
/**
 * This method initiates http get request on the request url and returns the
 * response returned from the http get.
 * @param requestUrl url on which the http get request has to be performed.
 * @return the http get response.
 * @throws IOException if there are problems with the http get request.
 */
private byte[] httpGet(String requestUrl) throws IOException {
  GetMethod getMethod = new GetMethod(requestUrl);
  try {
    int responseCode = httpClient.executeMethod(getMethod);
    LOG.debug("Received response code: {} for the get request on the url: {}", responseCode, requestUrl);
    byte[] response = getMethod.getResponseBody();
    if (responseCode != HttpStatus.SC_OK) {
      throw new SamzaException(String.format("Received response code: %s for get request on: %s, with message: %s.",
                                             responseCode, requestUrl, StringUtils.newStringUtf8(response)));
    }
    return response;
  } finally {
    getMethod.releaseConnection();
  }
}
 
Example 7
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testFindUsersByProperty() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final GetMethod method = createGet("/users", MediaType.APPLICATION_JSON, true);
    method.setQueryString(new NameValuePair[] { new NameValuePair("telMobile", "39847592"), new NameValuePair("gender", "Female"),
            new NameValuePair("birthDay", "12/12/2009") });
    method.addRequestHeader("Accept-Language", "en");
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final List<UserVO> vos = parseUserArray(body);

    assertNotNull(vos);
    assertFalse(vos.isEmpty());
}
 
Example 8
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testFindUsersByLogin() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final GetMethod method = createGet("/users", MediaType.APPLICATION_JSON, true);
    method.setQueryString(new NameValuePair[] { new NameValuePair("login", "administrator"), new NameValuePair("authProvider", "OLAT") });
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final List<UserVO> vos = parseUserArray(body);
    final String[] authProviders = new String[] { "OLAT" };
    final List<Identity> identities = securityManager.getIdentitiesByPowerSearch("administrator", null, true, null, null, authProviders, null, null, null, null,
            Identity.STATUS_VISIBLE_LIMIT);

    assertNotNull(vos);
    assertFalse(vos.isEmpty());
    assertEquals(vos.size(), identities.size());
    boolean onlyLikeAdmin = true;
    for (final UserVO vo : vos) {
        if (!vo.getLogin().startsWith("administrator")) {
            onlyLikeAdmin = false;
        }
    }
    assertTrue(onlyLikeAdmin);
}
 
Example 9
Source File: ExtractRegular.java    From HtmlExtractor with Apache License 2.0 6 votes vote down vote up
/**
 * 从配置管理WEB服务器下载规则(json表示)
 *
 * @param url 配置管理WEB服务器下载规则的地址
 * @return json字符串
 */
private String downJson(String url) {
    // 构造HttpClient的实例
    HttpClient httpClient = new HttpClient();
    // 创建GET方法的实例
    GetMethod method = new GetMethod(url);
    try {
        // 执行GetMethod
        int statusCode = httpClient.executeMethod(method);
        LOGGER.info("响应代码:" + statusCode);
        if (statusCode != HttpStatus.SC_OK) {
            LOGGER.error("请求失败: " + method.getStatusLine());
        }
        // 读取内容
        String responseBody = new String(method.getResponseBody(), "utf-8");
        return responseBody;
    } catch (IOException e) {
        LOGGER.error("检查请求的路径:" + url, e);
    } finally {
        // 释放连接
        method.releaseConnection();
    }
    return "";
}
 
Example 10
Source File: UserAuthenticationMgmtITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAuthentications() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final GetMethod method = createGet("/users/administrator/auth", MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    final List<AuthenticationVO> vos = parseAuthenticationArray(body);
    assertNotNull(vos);
    assertFalse(vos.isEmpty());
    method.releaseConnection();
}
 
Example 11
Source File: CatalogITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetRoots() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").build();
    final GetMethod method = createGet(uri, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(200, code);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final List<CatalogEntryVO> vos = parseEntryArray(body);
    assertNotNull(vos);
    assertEquals(1, vos.size());// Root-1
}
 
Example 12
Source File: SchemaUtils.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
/**
 * Given host, port and schema name, send a http GET request to download the {@link Schema}.
 *
 * @return schema on success.
 * <P><code>null</code> on failure.
 */
public static @Nullable
Schema getSchema(@Nonnull String host, int port, @Nonnull String schemaName) {
  Preconditions.checkNotNull(host);
  Preconditions.checkNotNull(schemaName);

  try {
    URL url = new URL("http", host, port, "/schemas/" + schemaName);
    GetMethod httpGet = new GetMethod(url.toString());
    try {
      int responseCode = HTTP_CLIENT.executeMethod(httpGet);
      String response = httpGet.getResponseBodyAsString();
      if (responseCode >= 400) {
        // File not find error code.
        if (responseCode == 404) {
          LOGGER.info("Cannot find schema: {} from host: {}, port: {}", schemaName, host, port);
        } else {
          LOGGER.warn("Got error response code: {}, response: {}", responseCode, response);
        }
        return null;
      }
      return Schema.fromString(response);
    } finally {
      httpGet.releaseConnection();
    }
  } catch (Exception e) {
    LOGGER.error("Caught exception while getting the schema: {} from host: {}, port: {}", schemaName, host, port, e);
    return null;
  }
}
 
Example 13
Source File: ExchangeSessionFactory.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Send a request to Exchange server to check current settings.
 *
 * @throws IOException if unable to access Exchange server
 */
public static void checkConfig() throws IOException {
    String url = Settings.getProperty("davmail.url");
    if (url == null || (!url.startsWith("http://") && !url.startsWith("https://"))) {
        throw new DavMailException("LOG_INVALID_URL", url);
    }
    HttpClient httpClient = DavGatewayHttpClientFacade.getInstance(url);
    GetMethod testMethod = new GetMethod(url);
    try {
        // get webMail root url (will not follow redirects)
        int status = DavGatewayHttpClientFacade.executeTestMethod(httpClient, testMethod);
        ExchangeSession.LOGGER.debug("Test configuration status: " + status);
        if (status != HttpStatus.SC_OK && status != HttpStatus.SC_UNAUTHORIZED
                && !DavGatewayHttpClientFacade.isRedirect(status)) {
            throw new DavMailException("EXCEPTION_CONNECTION_FAILED", url, status);
        }
        // session opened, future failure will mean network down
        configChecked = true;
        // Reset so next time an problem occurs message will be sent once
        errorSent = false;
    } catch (Exception exc) {
        handleNetworkDown(exc);
    } finally {
        testMethod.releaseConnection();
    }

}
 
Example 14
Source File: OlatJerseyTestCase.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Login the HttpClient based on the session cookie
 * 
 * @param username
 * @param password
 * @param c
 * @throws HttpException
 * @throws IOException
 */
public void loginWithCookie(final String username, final String password, final HttpClient c) throws HttpException, IOException {
    final URI uri = UriBuilder.fromUri(getContextURI()).path("auth").path(username).queryParam("password", password).build();
    final GetMethod method = new GetMethod(uri.toString());
    method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    final int response = c.executeMethod(method);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    assertTrue(response == 200);
    assertTrue(body != null && body.length() > "<hello></hello>".length());
}
 
Example 15
Source File: BaseHttp.java    From JgFramework with Apache License 2.0 5 votes vote down vote up
/**
 * 模拟get
 *
 * @param args
 * @param retry
 *            重试第几次了
 * @return
 * @throws HttpException
 */
private static String doGet(HashMap<String, Object> args, int retry) throws HttpException {
    int maxRedirect = (Integer) args.get("maxRedirect");
    String result = null;
    if (retry > maxRedirect) {
        return result;
    }
    String url = (String) args.get("url");
    HashMap<String, String> header = (HashMap<String, String>) args.get("header");
    BaseCookie[] cookie = (BaseCookie[]) args.get("cookie");
    String charset = (String) args.get("charset");
    Integer timeout = (Integer) args.get("timeout");
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(url);
    BaseHttp.init(client, method, header, cookie, charset, timeout);
    try {
        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            result = getResponse(method, charset);
        } else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY || statusCode == HttpStatus.SC_SEE_OTHER
                || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
            // 301, 302, 303, 307 跳转
            Header locationHeader = method.getResponseHeader("location");
            String location = null;
            if (locationHeader != null) {
                location = locationHeader.getValue();
                retry++;
                args.put("url", location);
                result = BaseHttp.doGet(args, retry);
            }
        }
    } catch (IOException e) {
        throw new HttpException("执行HTTP Get请求" + url + "时,发生异常! => " + e.getMessage());
    } finally {
        method.releaseConnection();
    }
    return result;
}
 
Example 16
Source File: CatalogITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetRoots() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").build();
    final GetMethod method = createGet(uri, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(200, code);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final List<CatalogEntryVO> vos = parseEntryArray(body);
    assertNotNull(vos);
    assertEquals(1, vos.size());// Root-1
}
 
Example 17
Source File: TestRailClient.java    From testrail-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
public boolean serverReachable() throws IOException {
    boolean result = false;
    HttpClient httpclient = new HttpClient();
    GetMethod get = new GetMethod(host);
    try {
        httpclient.executeMethod(get);
        result = true;
    } catch (java.net.UnknownHostException e) {
        // nop - we default to result == false
    } finally {
        get.releaseConnection();
    }
    return result;
}
 
Example 18
Source File: RepositoryEntriesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetEntry() throws HttpException, IOException {
    final RepositoryEntry re = createRepository("Test GET repo entry", 83911l);

    final HttpClient c = loginWithCookie("administrator", "olat");

    final GetMethod method = createGet("repo/entries/" + re.getKey(), MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(200, code);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();

    final RepositoryEntryVO entryVo = parse(body, RepositoryEntryVO.class);
    assertNotNull(entryVo);
}
 
Example 19
Source File: ZeppelinRestApiTest.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetNoteJob() throws Exception {
  LOG.info("testGetNoteJob");

  Note note = null;
  try {
    // Create note to run test.
    note = TestUtils.getInstance(Notebook.class).createNote("note1_testGetNoteJob", anonymous);
    assertNotNull("can't create new note", note);
    note.setName("note for run test");
    Paragraph paragraph = note.addNewParagraph(AuthenticationInfo.ANONYMOUS);

    Map config = paragraph.getConfig();
    config.put("enabled", true);
    paragraph.setConfig(config);

    paragraph.setText("%sh sleep 1");
    paragraph.setAuthenticationInfo(anonymous);
    TestUtils.getInstance(Notebook.class).saveNote(note, anonymous);
    String noteId = note.getId();

    note.runAll(anonymous, true, false, new HashMap<>());
    // assume that status of the paragraph is running
    GetMethod get = httpGet("/notebook/job/" + noteId);
    assertThat("test get note job: ", get, isAllowed());
    String responseBody = get.getResponseBodyAsString();
    get.releaseConnection();

    LOG.info("test get note job: \n" + responseBody);
    Map<String, Object> resp = gson.fromJson(responseBody,
            new TypeToken<Map<String, Object>>() {}.getType());

    List<Map<String, Object>> paragraphs = (List<Map<String, Object>>) resp.get("body");
    assertEquals(1, paragraphs.size());
    assertTrue(paragraphs.get(0).containsKey("progress"));
    int progress = Integer.parseInt((String) paragraphs.get(0).get("progress"));
    assertTrue(progress >= 0 && progress <= 100);

    // wait until job is finished or timeout.
    int timeout = 1;
    while (!paragraph.isTerminated()) {
      Thread.sleep(100);
      if (timeout++ > 10) {
        LOG.info("testGetNoteJob timeout job.");
        break;
      }
    }
  } finally {
    //cleanup
    if (null != note) {
      TestUtils.getInstance(Notebook.class).removeNote(note, anonymous);
    }
  }
}
 
Example 20
Source File: InterpreterRestApiTest.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
@Test
public void testCreatedInterpreterDependencies() throws IOException {
  // when: Create 2 interpreter settings `md1` and `md2` which have different dep.
  String md1Name = "md1";
  String md2Name = "md2";

  String md1Dep = "org.apache.drill.exec:drill-jdbc:jar:1.7.0";
  String md2Dep = "org.apache.drill.exec:drill-jdbc:jar:1.6.0";

  String reqBody1 = "{\"name\":\"" + md1Name + "\",\"group\":\"md\"," +
          "\"properties\":{\"propname\": {\"value\": \"propvalue\", \"name\": \"propname\", " +
          "\"type\": \"textarea\"}}," +
          "\"interpreterGroup\":[{\"class\":\"org.apache.zeppelin.markdown.Markdown\"," +
          "\"name\":\"md\"}]," +
          "\"dependencies\":[ {\n" +
          "      \"groupArtifactVersion\": \"" + md1Dep + "\",\n" +
          "      \"exclusions\":[]\n" +
          "    }]," +
          "\"option\": { \"remote\": true, \"session\": false }}";
  PostMethod post = httpPost("/interpreter/setting", reqBody1);
  assertThat("test create method:", post, isAllowed());
  post.releaseConnection();

  String reqBody2 = "{\"name\":\"" + md2Name + "\",\"group\":\"md\"," +
          "\"properties\": {\"propname\": {\"value\": \"propvalue\", \"name\": \"propname\", " +
          "\"type\": \"textarea\"}}," +
          "\"interpreterGroup\":[{\"class\":\"org.apache.zeppelin.markdown.Markdown\"," +
          "\"name\":\"md\"}]," +
          "\"dependencies\":[ {\n" +
          "      \"groupArtifactVersion\": \"" + md2Dep + "\",\n" +
          "      \"exclusions\":[]\n" +
          "    }]," +
          "\"option\": { \"remote\": true, \"session\": false }}";
  post = httpPost("/interpreter/setting", reqBody2);
  assertThat("test create method:", post, isAllowed());
  post.releaseConnection();

  // 1. Call settings API
  GetMethod get = httpGet("/interpreter/setting");
  String rawResponse = get.getResponseBodyAsString();
  get.releaseConnection();

  // 2. Parsing to List<InterpreterSettings>
  JsonObject responseJson = gson.fromJson(rawResponse, JsonElement.class).getAsJsonObject();
  JsonArray bodyArr = responseJson.getAsJsonArray("body");
  List<InterpreterSetting> settings = new Gson().fromJson(bodyArr,
      new TypeToken<ArrayList<InterpreterSetting>>() {
      }.getType());

  // 3. Filter interpreters out we have just created
  InterpreterSetting md1 = null;
  InterpreterSetting md2 = null;
  for (InterpreterSetting setting : settings) {
    if (md1Name.equals(setting.getName())) {
      md1 = setting;
    } else if (md2Name.equals(setting.getName())) {
      md2 = setting;
    }
  }

  // then: should get created interpreters which have different dependencies

  // 4. Validate each md interpreter has its own dependencies
  assertEquals(1, md1.getDependencies().size());
  assertEquals(1, md2.getDependencies().size());
  assertEquals(md1Dep, md1.getDependencies().get(0).getGroupArtifactVersion());
  assertEquals(md2Dep, md2.getDependencies().get(0).getGroupArtifactVersion());
}