Java Code Examples for org.apache.commons.httpclient.HttpClient

The following examples show how to use org.apache.commons.httpclient.HttpClient. These examples are extracted from open source projects. 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 Project: maven-framework-project   Source File: RestClient.java    License: MIT License 7 votes vote down vote up
public Book getBook(String bookName) throws Exception {

        String output = null;
        try{
            String url = "http://localhost:8080/bookservice/getbook/";

            url = url + URLEncoder.encode(bookName, "UTF-8");

            HttpClient client = new HttpClient();
            PostMethod mPost = new PostMethod(url);
            client.executeMethod( mPost );
            Header mtHeader = new Header();
            mtHeader.setName("content-type");
            mtHeader.setValue("application/x-www-form-urlencoded");
            mtHeader.setName("accept");
            mtHeader.setValue("application/xml");
            mPost.addRequestHeader(mtHeader);
            client.executeMethod(mPost);
            output = mPost.getResponseBodyAsString( );
            mPost.releaseConnection( );
            System.out.println("out : " + output);
        }catch(Exception e){
            throw new Exception("Exception in retriving group page info : " + e);
        }
        return null;
    }
 
Example 2
Source Project: olat   Source File: CoursesITCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateEmptyCourse() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final URI uri = UriBuilder.fromUri(getContextURI()).path("repo").path("courses").queryParam("shortTitle", "course3").queryParam("title", "course3 long name")
            .build();
    final PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true);

    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    final CourseVO course = parse(body, CourseVO.class);
    assertNotNull(course);
    assertEquals("course3", course.getTitle());
    // check repository entry
    final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(course.getRepoEntryKey());
    assertNotNull(re);
    assertNotNull(re.getOlatResource());
    assertNotNull(re.getOwnerGroup());
}
 
Example 3
Source Project: ci.maven   Source File: ServletTest.java    License: 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("Simple Servlet ran successfully"));
    } finally {
        method.releaseConnection();
    }  
}
 
Example 4
Source Project: olat   Source File: CourseGroupMgmtITCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCourseGroups() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final String request = "/repo/courses/" + course.getResourceableId() + "/groups";
    final GetMethod method = createGet(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(200, code);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final List<GroupVO> vos = parseGroupArray(body);
    assertNotNull(vos);
    assertEquals(2, vos.size());// g1 and g2
    assertTrue(vos.get(0).getKey().equals(g1.getKey()) || vos.get(0).getKey().equals(g2.getKey()));
    assertTrue(vos.get(1).getKey().equals(g1.getKey()) || vos.get(1).getKey().equals(g2.getKey()));
}
 
Example 5
Source Project: olat   Source File: CourseGroupMgmtITCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCourseGroups() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final String request = "/repo/courses/" + course.getResourceableId() + "/groups";
    final GetMethod method = createGet(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(200, code);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final List<GroupVO> vos = parseGroupArray(body);
    assertNotNull(vos);
    assertEquals(2, vos.size());// g1 and g2
    assertTrue(vos.get(0).getKey().equals(g1.getKey()) || vos.get(0).getKey().equals(g2.getKey()));
    assertTrue(vos.get(1).getKey().equals(g1.getKey()) || vos.get(1).getKey().equals(g2.getKey()));
}
 
Example 6
@Test(groups = "wso2.esb", description = "Sending HTTP1.1 message")
public void sendingHTTP11Message() throws Exception {
    PostMethod post = new PostMethod(getProxyServiceURLHttp("StockQuoteProxyTestHTTPVersion"));
    RequestEntity entity = new StringRequestEntity(getPayload(), "text/xml", "UTF-8");
    post.setRequestEntity(entity);
    post.setRequestHeader("SOAPAction", "urn:getQuote");
    HttpMethodParams params = new HttpMethodParams();
    params.setVersion(HttpVersion.HTTP_1_1);
    post.setParams(params);
    HttpClient httpClient = new HttpClient();
    String httpVersion = "";

    try {
        httpClient.executeMethod(post);
        post.getResponseBodyAsString();
        httpVersion = post.getStatusLine().getHttpVersion();
    } finally {
        post.releaseConnection();
    }
    Assert.assertEquals(httpVersion, HttpVersion.HTTP_1_1.toString(), "Http version mismatched");
}
 
Example 7
Source Project: development   Source File: RORClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void createClient_WithoutCredentials() throws Exception {
	// given
	System.setProperty(HTTPS_PROXY_HOST, HTTPS_PROXY_HOST_VALUE);
	System.setProperty(HTTPS_PROXY_PORT, HTTPS_PROXY_PORT_VALUE);

	// when
	HttpClient client = vdcClient.createHttpClient();

	// then
	assertEquals(HTTPS_PROXY_HOST_VALUE, client.getHostConfiguration()
			.getProxyHost());
	assertEquals(HTTPS_PROXY_PORT_VALUE,
			String.valueOf(client.getHostConfiguration().getProxyPort()));
	assertNull(client.getState().getProxyCredentials(AuthScope.ANY));

}
 
Example 8
@Test
public void testNormalFlow() throws HttpException, IOException, UnauthenticatedSessionException,
    AuthenticationException {
    IChatterData data = getMockedChatterData();

    ClientSecretAuthentication auth = new ClientSecretAuthentication(data, "");

    HttpClient mockHttpClient = mock(HttpClient.class);
    when(mockHttpClient.executeMethod(any(PostMethod.class))).thenAnswer(
        new ExecuteMethodAnswer("{\"access_token\" : \"abc\" }"));

    auth.setHttpClient(mockHttpClient);

    ChatterAuthToken token = auth.authenticate();
    assertEquals("abc", token.getAccessToken());
}
 
Example 9
public void testAsyncRequests_WaitUntilDone() throws Exception {
  long sleepTime = 2000;
  FakeableVmApiProxyDelegate fakeApiProxy = new FakeableVmApiProxyDelegate();
  ApiProxy.setDelegate(fakeApiProxy);
  HttpClient httpClient = new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
  GetMethod get = new GetMethod(createUrl("/sleep").toString());
  get.addRequestHeader("Use-Async-Sleep-Api", "true");
  get.addRequestHeader("Sleep-Time", Long.toString(sleepTime));
  long startTime = System.currentTimeMillis();
  int httpCode = httpClient.executeMethod(get);
  assertEquals(200, httpCode);
  Header vmApiWaitTime = get.getResponseHeader(VmRuntimeUtils.ASYNC_API_WAIT_HEADER);
  assertNotNull(vmApiWaitTime);
  assertTrue(Integer.parseInt(vmApiWaitTime.getValue()) > 0);
  long elapsed = System.currentTimeMillis() - startTime;
  assertTrue(elapsed >= sleepTime);
}
 
Example 10
Source Project: olat   Source File: GroupMgmtITCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetGroupInfos2() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final String request = "/groups/" + g2.getKey() + "/infos";
    final GetMethod method = createGet(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final GroupInfoVO vo = parse(body, GroupInfoVO.class);
    assertNotNull(vo);
    assertEquals(Boolean.FALSE, vo.getHasWiki());
    assertNull(vo.getNews());
    assertNotNull(vo.getForumKey());
}
 
Example 11
Source Project: HtmlExtractor   Source File: ExtractRegular.java    License: 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 12
Source Project: olat   Source File: CoursesITCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateEmptyCourse() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final URI uri = UriBuilder.fromUri(getContextURI()).path("repo").path("courses").queryParam("shortTitle", "course3").queryParam("title", "course3 long name")
            .build();
    final PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true);

    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    final CourseVO course = parse(body, CourseVO.class);
    assertNotNull(course);
    assertEquals("course3", course.getTitle());
    // check repository entry
    final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(course.getRepoEntryKey());
    assertNotNull(re);
    assertNotNull(re.getOlatResource());
    assertNotNull(re.getOwnerGroup());
}
 
Example 13
Source Project: javabase   Source File: OldHttpClientApi.java    License: Apache License 2.0 6 votes vote down vote up
public void  get() throws UnsupportedEncodingException {
    HttpClient client = new HttpClient();
    String APIKEY = "4b441cb500f431adc6cc0cb650b4a5d0";
    String INFO =new URLCodec().encode("who are you","utf-8");
    String requesturl = "http://www.tuling123.com/openapi/api?key=" + APIKEY + "&info=" + INFO;
    GetMethod getMethod = new GetMethod(requesturl);
    try {
        int stat = client.executeMethod(getMethod);
        if (stat != HttpStatus.SC_OK)
           log.error("get失败!");
        byte[] responseBody = getMethod.getResponseBody();
        String content=new String(responseBody ,"utf-8");
        log.info(content);
    }catch (Exception e){
       log.error(""+e.getLocalizedMessage());
    }finally {
        getMethod.releaseConnection();
    }
}
 
Example 14
Source Project: cloudstack   Source File: UriUtils.java    License: 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 15
Source Project: olat   Source File: GroupMgmtITCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAddParticipant() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/participants/" + part3.getKey();
    final HttpMethod method = createPut(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    method.releaseConnection();

    assertTrue(code == 200 || code == 201);

    final List<Identity> participants = securityManager.getIdentitiesOfSecurityGroup(g1.getPartipiciantGroup());
    boolean found = false;
    for (final Identity participant : participants) {
        if (participant.getKey().equals(part3.getKey())) {
            found = true;
        }
    }

    assertTrue(found);
}
 
Example 16
Source Project: olat   Source File: CatalogITCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteCatalogEntry() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry2.getKey().toString()).build();
    final DeleteMethod method = createDelete(uri, MediaType.APPLICATION_JSON, true);

    final int code = c.executeMethod(method);
    assertEquals(200, code);
    method.releaseConnection();

    final List<CatalogEntry> entries = catalogService.getChildrenOf(root1);
    for (final CatalogEntry entry : entries) {
        assertFalse(entry.getKey().equals(entry2.getKey()));
    }
}
 
Example 17
Source Project: boost   Source File: EndpointIT.java    License: Eclipse Public License 1.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(10000);

        assertTrue("Unexpected response body", response.contains("The population of NYC is 8550405"));
    } finally {
        method.releaseConnection();
    }
}
 
Example 18
Source Project: boost   Source File: EndpointIT.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testServlet() throws Exception {
    HttpClient client = new HttpClient();

    GetMethod method = new GetMethod(URL + "/hello");

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

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

        String response = method.getResponseBodyAsString(10000);

        assertTrue("Unexpected response body",
                response.contains("Hello World From Your Friends at Liberty Boost EE!"));
    } finally {
        method.releaseConnection();
    }
}
 
Example 19
Source Project: olat   Source File: GroupMgmtITCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateCourseGroup() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final GroupVO vo = new GroupVO();
    vo.setKey(g1.getKey());
    vo.setName("rest-g1-mod");
    vo.setDescription("rest-g1 description");
    vo.setMinParticipants(g1.getMinParticipants());
    vo.setMaxParticipants(g1.getMaxParticipants());
    vo.setType(g1.getType());

    final String stringuifiedAuth = stringuified(vo);
    final RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8");
    final String request = "/groups/" + g1.getKey();
    final PostMethod method = createPost(request, MediaType.APPLICATION_JSON, true);
    method.setRequestEntity(entity);
    final int code = c.executeMethod(method);
    assertTrue(code == 200 || code == 201);

    final BusinessGroup bg = businessGroupService.loadBusinessGroup(g1.getKey(), false);
    assertNotNull(bg);
    assertEquals(bg.getKey(), vo.getKey());
    assertEquals(bg.getName(), "rest-g1-mod");
    assertEquals(bg.getDescription(), "rest-g1 description");
}
 
Example 20
Source Project: olat   Source File: CatalogITCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAddOwner() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry1.getKey().toString()).path("owners").path(id1.getKey().toString()).build();
    final PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true);

    final int code = c.executeMethod(method);
    method.releaseConnection();
    assertEquals(200, code);

    final CatalogEntry entry = catalogService.loadCatalogEntry(entry1.getKey());
    final List<Identity> identities = securityManager.getIdentitiesOfSecurityGroup(entry.getOwnerGroup());
    boolean found = false;
    for (final Identity identity : identities) {
        if (identity.getKey().equals(id1.getKey())) {
            found = true;
        }
    }
    assertTrue(found);
}
 
Example 21
Source Project: office-365-connector-plugin   Source File: HttpWorker.java    License: Apache License 2.0 6 votes vote down vote up
private HttpClient getHttpClient() {
    HttpClient client = new HttpClient();
    Jenkins jenkins = Jenkins.getInstance();
    if (jenkins != null) {
        ProxyConfiguration proxy = jenkins.proxy;
        if (proxy != null) {
            client.getHostConfiguration().setProxy(proxy.name, proxy.port);
            String username = proxy.getUserName();
            String password = proxy.getPassword();
            // Consider it to be passed if username specified. Sufficient?
            if (StringUtils.isNotBlank(username)) {
                client.getState().setProxyCredentials(AuthScope.ANY,
                        new UsernamePasswordCredentials(username, password));
            }
        }
    }
    client.getParams().setConnectionManagerTimeout(timeout);
    client.getHttpConnectionManager().getParams().setSoTimeout(timeout);
    client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
    return client;
}
 
Example 22
Source Project: cloudstack   Source File: BigSwitchApiTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    HttpClientParams hmp = mock(HttpClientParams.class);
    when(_client.getParams()).thenReturn(hmp);
    _api = new BigSwitchBcfApi(){
        @Override
        protected HttpClient createHttpClient() {
            return _client;
        }

        @Override
        protected HttpMethod createMethod(String type, String uri, int port) {
            return _method;
        }
    };
    _api.setControllerAddress("10.10.0.10");
    _api.setControllerUsername("myname");
    _api.setControllerPassword("mypassword");
}
 
Example 23
Source Project: olat   Source File: CatalogITCase.java    License: 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 24
Source Project: olat   Source File: GroupMgmtITCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetGroups() throws IOException {
    final HttpClient c = loginWithCookie("rest-four", "A6B7C8");

    final String request = "/groups";
    final GetMethod method = createGet(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final List<GroupVO> groups = parseGroupArray(body);
    assertNotNull(groups);
    assertTrue(groups.size() >= 2);// g1, g2, g3 and g4 + from olat

    final Set<Long> keys = new HashSet<Long>();
    for (final GroupVO vo : groups) {
        keys.add(vo.getKey());
    }

    assertTrue(keys.contains(g1.getKey()));
    assertTrue(keys.contains(g2.getKey()));
    assertFalse(keys.contains(g3.getKey()));
    assertFalse(keys.contains(g4.getKey()));
}
 
Example 25
private void setProxy(HttpClient httpClient) {

    String proxyHost = AppSettings.get().get("http.proxy.host").trim();
    Integer proxyPort = Integer.parseInt(AppSettings.get().get("http.proxy.port").trim());
    HostConfiguration hostConfig = httpClient.getHostConfiguration();
    hostConfig.setProxy(proxyHost, proxyPort);
    if (!AppSettings.get().get("http.proxy.user").equals("")) {
      String user;
      String pwd;
      org.apache.commons.httpclient.UsernamePasswordCredentials credentials;
      org.apache.commons.httpclient.auth.AuthScope authscope;

      user = AppSettings.get().get("http.proxy.user").trim();
      pwd = AppSettings.get().get("http.proxy.password").trim();
      credentials = new org.apache.commons.httpclient.UsernamePasswordCredentials(user, pwd);
      authscope = new org.apache.commons.httpclient.auth.AuthScope(proxyHost, proxyPort);
      httpClient.getState().setProxyCredentials(authscope, credentials);
    }
  }
 
Example 26
Source Project: olat   Source File: HttpClientFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * A HttpClient with basic authentication and no host or port setting. Can only be used to retrieve absolute URLs
 * 
 * @param user
 *            can be NULL
 * @param password
 *            can be NULL
 * @return HttpClient
 */
public static HttpClient getHttpClientInstance(String user, String password) {
    HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    HttpConnectionParams params = connectionManager.getParams();
    // wait max 10 seconds to establish connection
    params.setConnectionTimeout(10000);
    // a read() call on the InputStream associated with this Socket
    // will block for only this amount
    params.setSoTimeout(10000);
    HttpClient c = new HttpClient(connectionManager);

    // use basic authentication if available
    if (user != null && user.length() > 0) {
        AuthScope authScope = new AuthScope(null, -1, null);
        Credentials credentials = new UsernamePasswordCredentials(user, password);
        c.getState().setCredentials(authScope, credentials);
    }
    return c;
}
 
Example 27
Source Project: microprofile-sandbox   Source File: EndpointIT.java    License: 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(10000);

        assertTrue("Unexpected response body",
                response.contains("Hello World From Your Friends at Liberty Boost EE!"));
    } finally {
        method.releaseConnection();
    }
}
 
Example 28
Source Project: scim2-compliance-test-suite   Source File: CSP.java    License: Apache License 2.0 5 votes vote down vote up
public String getAccessTokenUserPass() {
    if (!StringUtils.isEmpty(this.oAuth2AccessToken)) {
        return this.oAuth2AccessToken;
    }

    if (StringUtils.isEmpty(this.username) || StringUtils.isEmpty(this.password) && StringUtils.isEmpty(this.oAuth2AuthorizationServer)
            || StringUtils.isEmpty(this.oAuth2ClientId) || StringUtils.isEmpty(this.oAuth2ClientSecret)) {
        return "";
    }

    try {
        HttpClient client = new HttpClient();
        client.getParams().setAuthenticationPreemptive(true);

        // post development
        PostMethod method = new PostMethod(this.getOAuthAuthorizationServer());
        method.setRequestHeader(new Header("Content-type", "application/x-www-form-urlencoded"));

        method.addRequestHeader("Authorization", "Basic " + Base64.encodeBase64String((username + ":" + password).getBytes()));
        NameValuePair[] body = new NameValuePair[] { new NameValuePair("username", username), new NameValuePair("password", password),
                new NameValuePair("client_id", oAuth2ClientId), new NameValuePair("client_secret", oAuth2ClientSecret),
                new NameValuePair("grant_type", oAuth2GrantType) };
        method.setRequestBody(body);
        int responseCode = client.executeMethod(method);

        String responseBody = method.getResponseBodyAsString();
        if (responseCode != 200) {
            throw new RuntimeException("Failed to fetch access token form authorization server, " + this.getOAuthAuthorizationServer()
                    + ", got response code " + responseCode);
        }

        JSONObject accessResponse = new JSONObject(responseBody);
        accessResponse.getString("access_token");
        return (this.oAuth2AccessToken = accessResponse.getString("access_token"));
    } catch (Exception e) {
        throw new RuntimeException("Failed to read response from authorizationServer at " + this.getOAuthAuthorizationServer(), e);
    }
}
 
Example 29
Source Project: submarine   Source File: AbstractSubmarineServerTest.java    License: Apache License 2.0 5 votes vote down vote up
protected static DeleteMethod httpDelete(String path, String user, String pwd) throws IOException {
  LOG.info("Connecting to {}", URL + path);
  HttpClient httpClient = new HttpClient();
  DeleteMethod deleteMethod = new DeleteMethod(URL + path);
  deleteMethod.addRequestHeader("Origin", URL);
  if (userAndPasswordAreNotBlank(user, pwd)) {
    deleteMethod.setRequestHeader("Cookie", "JSESSIONID=" + getCookie(user, pwd));
  }
  httpClient.executeMethod(deleteMethod);
  LOG.info("{} - {}", deleteMethod.getStatusCode(), deleteMethod.getStatusText());
  return deleteMethod;
}
 
Example 30
Source Project: orion.server   Source File: CFActivator.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private HttpClient createHttpClient() {
	//see http://hc.apache.org/httpclient-3.x/threading.html
	MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
	HttpConnectionManagerParams params = connectionManager.getParams();
	params.setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION, PreferenceHelper.getInt(ServerConstants.HTTP_MAX_CONN_HOST_CONF_KEY, 50));
	params.setMaxTotalConnections(PreferenceHelper.getInt(ServerConstants.HTTP_MAX_CONN_TOTAL_CONF_KEY, 150));
	params.setConnectionTimeout(PreferenceHelper.getInt(ServerConstants.HTTP_CONN_TIMEOUT_CONF_KEY, 15000)); //15s
	params.setSoTimeout(PreferenceHelper.getInt(ServerConstants.HTTP_SO_TIMEOUT_CONF_KEY, 30000)); //30s
	connectionManager.setParams(params);

	HttpClientParams clientParams = new HttpClientParams();
	clientParams.setConnectionManagerTimeout(PreferenceHelper.getInt(ServerConstants.HTTP_CONN_MGR_TIMEOUT_CONF_KEY, 300000)); // 5 minutes

	return new HttpClient(clientParams, connectionManager);
}