org.apache.commons.httpclient.HostConfiguration Java Examples

The following examples show how to use org.apache.commons.httpclient.HostConfiguration. 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: HttpClientFactory.java    From alfresco-core with GNU Lesser General Public License v3.0 7 votes vote down vote up
public SecureHttpMethodResponse(HttpMethod method, HostConfiguration hostConfig, 
        EncryptionUtils encryptionUtils) throws AuthenticationException, IOException
{
    super(method);
    this.hostConfig = hostConfig;
    this.encryptionUtils = encryptionUtils;

    if(method.getStatusCode() == HttpStatus.SC_OK)
    {
        this.decryptedBody = encryptionUtils.decryptResponseBody(method);
        // authenticate the response
        if(!authenticate())
        {
            throw new AuthenticationException(method);
        }
    }
}
 
Example #2
Source File: ErrorReportSender.java    From otroslogviewer with Apache License 2.0 6 votes vote down vote up
public String sendReport(Map<String, String> values) throws IOException {
  HttpClient httpClient = new HttpClient();

  HostConfiguration hostConfiguration = new HostConfiguration();
  if (!StringUtils.isBlank(proxy)) {
    hostConfiguration.setProxy(proxy, proxyPort);
    if (StringUtils.isNotBlank(user) && StringUtils.isNotBlank(password)) {
      httpClient.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
    }
  }
  httpClient.setHostConfiguration(hostConfiguration);
  PostMethod method = new PostMethod(getSendUrl());

  addHttpPostParams(values, method);

  int executeMethod = httpClient.executeMethod(method);
  LOGGER.info("HTTP result of report send POST: " + executeMethod);
  return IOUtils.toString(method.getResponseBodyAsStream());
}
 
Example #3
Source File: HttpHostFactory.java    From http4e with Apache License 2.0 6 votes vote down vote up
/**
 * Get a Protocol for the given parameters. The default implementation
 * selects a protocol based only on the scheme. Subclasses can do fancier
 * things, such as select SSL parameters based on the host or port. This
 * method must not return null.
 */
protected Protocol getProtocol(HostConfiguration old, String scheme, String host, int port)
{
    final Protocol oldProtocol = old.getProtocol();
    if (oldProtocol != null) {
        final String oldScheme = oldProtocol.getScheme();
        if (oldScheme == scheme || (oldScheme != null && oldScheme.equalsIgnoreCase(scheme))) {
            // The old protocol has the desired scheme.
            return oldProtocol; // Retain it.
        }
    }
    Protocol newProtocol = (scheme != null && scheme.toLowerCase().endsWith("s")) ? httpsProtocol
            : httpProtocol;
    if (newProtocol == null) {
        newProtocol = Protocol.getProtocol(scheme);
    }
    return newProtocol;
}
 
Example #4
Source File: HTTPNotificationStrategy.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
public HTTPNotificationStrategy(PushNotificationConfig config) {
    this.config = config;
    if (this.config == null) {
        throw new InvalidConfigurationException("Properties Cannot be found");
    }
    endpoint = config.getProperties().get(URL_PROPERTY);
    if (endpoint == null || endpoint.isEmpty()) {
        throw new InvalidConfigurationException("Property - 'url' cannot be found");
    }
    try {
        this.uri = endpoint;
        URL url = new URL(endpoint);
        hostConfiguration = new HostConfiguration();
        hostConfiguration.setHost(url.getHost(), url.getPort(), url.getProtocol());
        this.authorizationHeaderValue = config.getProperties().get(AUTHORIZATION_HEADER_PROPERTY);
        executorService = Executors.newFixedThreadPool(1);
        httpClient = new HttpClient();
    } catch (MalformedURLException e) {
        throw new InvalidConfigurationException("Property - 'url' is malformed.", e);
    }
}
 
Example #5
Source File: HttpPerformer.java    From http4e with Apache License 2.0 6 votes vote down vote up
private void doSSL( HttpClient client, HostConfiguration hostConf, String host, int port){
   if (hostConf.getProtocol().isSecure()) {

      // System.setProperty("javax.net.ssl.trustStore", sslKeystore);
      // Protocol sslPprotocol = new Protocol("https", new
      // org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory(),
      // 443);
      // client.getHostConfiguration().setHost(host, 443, sslPprotocol);

      try {
         ProtocolSocketFactory factory = new InsecureSSLProtocolSocketFactory();
         Protocol https = new Protocol("https", factory, port);
         Protocol.registerProtocol("https", https);
         client.getHostConfiguration().setHost(host, port, https);

      } catch (GeneralSecurityException e) {
         throw new CoreException(CoreException.SSL, e);
      }
   }
}
 
Example #6
Source File: DefaultDiamondSubscriber.java    From diamond with Apache License 2.0 6 votes vote down vote up
protected void initHttpClient() {
    if (MockServer.isTestMode()) {
        return;
    }
    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setHost(diamondConfigure.getDomainNameList().get(this.domainNamePos.get()),
        diamondConfigure.getPort());

    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    connectionManager.closeIdleConnections(diamondConfigure.getPollingIntervalTime() * 4000);

    HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    params.setStaleCheckingEnabled(diamondConfigure.isConnectionStaleCheckingEnabled());
    params.setMaxConnectionsPerHost(hostConfiguration, diamondConfigure.getMaxHostConnections());
    params.setMaxTotalConnections(diamondConfigure.getMaxTotalConnections());
    params.setConnectionTimeout(diamondConfigure.getConnectionTimeout());
    // 设置读超时为1分钟,
    // [email protected]
    params.setSoTimeout(60 * 1000);

    connectionManager.setParams(params);
    httpClient = new HttpClient(connectionManager);
    httpClient.setHostConfiguration(hostConfiguration);
}
 
Example #7
Source File: ProxySelector.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static Object[] configureProxy(final HostConfiguration conf,
                                       final URI uri,
                                       final String proxyServer,
                                       final String proxyPortStr,
                                       final String nonProxyHosts)
{
  if (null!=proxyServer && 0<proxyServer.length()) {
    if (!isNonProxyHost(nonProxyHosts, uri)) {
      try {
        int proxyPort = null!=proxyPortStr && 0<proxyPortStr.length()
          ? Integer.parseInt(proxyPortStr) : 80;
        conf.setProxy(proxyServer, proxyPort);
        return new Object[]{proxyServer, new Integer(proxyPort)};
      } catch (NumberFormatException e) {
        throw new RuntimeException("Invalid proxy: " +proxyServer +":"
                                   +proxyPortStr);
      }
    }
  }
  return null;
}
 
Example #8
Source File: HttpConnectionManagerParams.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Gets the maximum number of connections to be used for a particular host config.  If
 * the value has not been specified for the given host the default value will be
 * returned.
 * 
 * @param hostConfiguration The host config.
 * @return The maximum number of connections to be used for the given host config.
 * 
 * @see #MAX_HOST_CONNECTIONS
 */
public int getMaxConnectionsPerHost(HostConfiguration hostConfiguration) {
    
    Map m = (Map) getParameter(MAX_HOST_CONNECTIONS);
    if (m == null) {
        // MAX_HOST_CONNECTIONS have not been configured, using the default value
        return MultiThreadedHttpConnectionManager.DEFAULT_MAX_HOST_CONNECTIONS;
    } else {
        Integer max = (Integer) m.get(hostConfiguration);
        if (max == null && hostConfiguration != HostConfiguration.ANY_HOST_CONFIGURATION) {
            // the value has not been configured specifically for this host config,
            // use the default value
            return getMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION);
        } else {
            return (
                    max == null 
                    ? MultiThreadedHttpConnectionManager.DEFAULT_MAX_HOST_CONNECTIONS 
                    : max.intValue()
                );
        }
    }
}
 
Example #9
Source File: DefaultDiamondSubscriber.java    From diamond with Apache License 2.0 6 votes vote down vote up
protected void initHttpClient() {
    if (MockServer.isTestMode()) {
        return;
    }
    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setHost(diamondConfigure.getDomainNameList().get(this.domainNamePos.get()),
        diamondConfigure.getPort());

    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    connectionManager.closeIdleConnections(diamondConfigure.getPollingIntervalTime() * 4000);

    HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    params.setStaleCheckingEnabled(diamondConfigure.isConnectionStaleCheckingEnabled());
    params.setMaxConnectionsPerHost(hostConfiguration, diamondConfigure.getMaxHostConnections());
    params.setMaxTotalConnections(diamondConfigure.getMaxTotalConnections());
    params.setConnectionTimeout(diamondConfigure.getConnectionTimeout());
    // 设置读超时为1分钟,
    // [email protected]
    params.setSoTimeout(60 * 1000);

    connectionManager.setParams(params);
    httpClient = new HttpClient(connectionManager);
    httpClient.setHostConfiguration(hostConfiguration);
}
 
Example #10
Source File: HttpRequestSender.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #11
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 #12
Source File: HttpClientTransmitterImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void testSuccessfulVerifyTargetOverHttps() throws Exception
{
    
    //Stub HttpClient so that executeMethod returns a 200 response
    when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class), 
            any(HttpState.class))).thenReturn(200);

    target.setEndpointProtocol(HTTPS_PROTOCOL);
    target.setEndpointPort(HTTPS_PORT);
    
    //Call verifyTarget
    transmitter.verifyTarget(target);
    
    ArgumentCaptor<HostConfiguration> hostConfig = ArgumentCaptor.forClass(HostConfiguration.class);
    ArgumentCaptor<HttpMethod> httpMethod = ArgumentCaptor.forClass(HttpMethod.class);
    ArgumentCaptor<HttpState> httpState = ArgumentCaptor.forClass(HttpState.class);
    
    verify(mockedHttpClient).executeMethod(hostConfig.capture(), httpMethod.capture(), httpState.capture());
    
    assertEquals("port", HTTPS_PORT, hostConfig.getValue().getPort());
    assertTrue("socket factory", 
            hostConfig.getValue().getProtocol().getSocketFactory() instanceof SecureProtocolSocketFactory);
    assertEquals("protocol", HTTPS_PROTOCOL.toLowerCase(), 
            hostConfig.getValue().getProtocol().getScheme().toLowerCase());
}
 
Example #13
Source File: HttpClientTransmitterImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Test create target.
 * 
 * @throws Exception
 */
public void testSuccessfulVerifyTargetOverHttp() throws Exception
{
    //Stub HttpClient so that executeMethod returns a 200 response
    when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class), 
            any(HttpState.class))).thenReturn(200);
    
    //Call verifyTarget
    transmitter.verifyTarget(target);
    
    ArgumentCaptor<HostConfiguration> hostConfig = ArgumentCaptor.forClass(HostConfiguration.class);
    ArgumentCaptor<HttpMethod> httpMethod = ArgumentCaptor.forClass(HttpMethod.class);
    ArgumentCaptor<HttpState> httpState = ArgumentCaptor.forClass(HttpState.class);
    
    verify(mockedHttpClient).executeMethod(hostConfig.capture(), httpMethod.capture(), httpState.capture());
    
    assertTrue("post method", httpMethod.getValue() instanceof PostMethod);
    assertEquals("host name", TARGET_HOST, hostConfig.getValue().getHost());
    assertEquals("port", HTTP_PORT, hostConfig.getValue().getPort());
    assertEquals("protocol", HTTP_PROTOCOL.toLowerCase(), 
            hostConfig.getValue().getProtocol().getScheme().toLowerCase());
    assertEquals("path", TRANSFER_SERVICE_PATH + "/test", httpMethod.getValue().getPath());
}
 
Example #14
Source File: HttpClientExecuteInterceptor.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeMethod(final EnhancedInstance objInst, final Method method, final Object[] allArguments,
    final Class<?>[] argumentsTypes, final MethodInterceptResult result) throws Throwable {

    final HttpClient client = (HttpClient) objInst;

    HostConfiguration hostConfiguration = (HostConfiguration) allArguments[0];
    if (hostConfiguration == null) {
        hostConfiguration = client.getHostConfiguration();
    }

    final HttpMethod httpMethod = (HttpMethod) allArguments[1];
    final String remotePeer = httpMethod.getURI().getHost() + ":" + httpMethod.getURI().getPort();

    final URI uri = httpMethod.getURI();
    final String requestURI = getRequestURI(uri);

    final ContextCarrier contextCarrier = new ContextCarrier();
    final AbstractSpan span = ContextManager.createExitSpan(requestURI, contextCarrier, remotePeer);

    span.setComponent(ComponentsDefine.HTTPCLIENT);
    Tags.URL.set(span, uri.toString());
    Tags.HTTP.METHOD.set(span, httpMethod.getName());
    SpanLayer.asHttp(span);

    for (CarrierItem next = contextCarrier.items(); next.hasNext(); ) {
        next = next.next();
        httpMethod.addRequestHeader(next.getHeadKey(), next.getHeadValue());
    }
}
 
Example #15
Source File: HttpClientTransmitterImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @param target TransferTarget
 * @return HostConfiguration
 */
private HostConfiguration getHostConfig(TransferTarget target)
{
    String requiredProtocol = target.getEndpointProtocol();
    if (requiredProtocol == null)
    {
        throw new TransferException(MSG_UNSUPPORTED_PROTOCOL, new Object[] {requiredProtocol});
    }

    Protocol protocol = protocolMap.get(requiredProtocol.toLowerCase().trim());
    if (protocol == null) 
    {
        log.error("Unsupported protocol: " + target.getEndpointProtocol());
        throw new TransferException(MSG_UNSUPPORTED_PROTOCOL, new Object[] {requiredProtocol});
    }

    HostConfiguration hostConfig = new HostConfiguration();
    hostConfig.setHost(target.getEndpointHost(), target.getEndpointPort(), protocol);
    
    // Use the appropriate Proxy Host if required
    if (httpProxyHost != null && HTTP_SCHEME_NAME.equals(protocol.getScheme()) && HttpClientHelper.requiresProxy(target.getEndpointHost()))
    {
        hostConfig.setProxyHost(httpProxyHost);

        if (log.isDebugEnabled())
        {
            log.debug("Using HTTP proxy host for: " + target.getEndpointHost());
        }
    }
    else if (httpsProxyHost != null && HTTPS_SCHEME_NAME.equals(protocol.getScheme()) && HttpClientHelper.requiresProxy(target.getEndpointHost()))
    {
        hostConfig.setProxyHost(httpsProxyHost);

        if (log.isDebugEnabled())
        {
            log.debug("Using HTTPS proxy host for: " + target.getEndpointHost());
        }
    } 
    return hostConfig;
}
 
Example #16
Source File: ApacheHttpClient3xAspect.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@OnBefore
public static @Nullable TraceEntry onBefore(ThreadContext context,
        @SuppressWarnings("unused") @BindParameter @Nullable HostConfiguration hostConfiguration,
        @BindParameter @Nullable HttpMethod methodObj) {
    if (methodObj == null) {
        return null;
    }
    String method = methodObj.getName();
    if (method == null) {
        method = "";
    } else {
        method += " ";
    }
    String uri;
    try {
        URI uriObj = methodObj.getURI();
        if (uriObj == null) {
            uri = "";
        } else {
            uri = uriObj.getURI();
            if (uri == null) {
                uri = "";
            }
        }
    } catch (URIException e) {
        uri = "";
    }
    return context.startServiceCallEntry("HTTP", method + Uris.stripQueryString(uri),
            MessageSupplier.create("http client request: {}{}", method, uri),
            timerName);
}
 
Example #17
Source File: SingleHttpConnectionManager.java    From webarchive-commons with Apache License 2.0 5 votes vote down vote up
public HttpConnection getConnectionWithTimeout(
    HostConfiguration hostConfiguration, long timeout) {

    HttpConnection conn = new HttpConnection(hostConfiguration);
    conn.setHttpConnectionManager(this);
    conn.getParams().setDefaults(this.getParams());
    return conn;
}
 
Example #18
Source File: Confluence.java    From maven-confluence-plugin with Apache License 2.0 5 votes vote down vote up
protected Confluence(String endpoint, ConfluenceProxy proxyInfo ) throws URISyntaxException, MalformedURLException {
       this(new XmlRpcClient());
if (endpoint.endsWith("/")) {
           endpoint = endpoint.substring(0, endpoint.length() - 1);
       }

       endpoint = ConfluenceService.Protocol.XMLRPC.addTo(endpoint);
   
       final java.net.URI serviceURI = new java.net.URI(endpoint);

       XmlRpcClientConfigImpl clientConfig = new XmlRpcClientConfigImpl();
       clientConfig.setServerURL(serviceURI.toURL() );

       clientConfig.setEnabledForExtensions(true); // add this to support attachment upload

       client.setConfig( clientConfig );

       if( isProxyEnabled(proxyInfo, serviceURI) ) {
           
           final XmlRpcCommonsTransportFactory transportFactory = new XmlRpcCommonsTransportFactory( client );

           final HttpClient httpClient = new HttpClient();
           final HostConfiguration hostConfiguration = httpClient.getHostConfiguration();
           hostConfiguration.setProxy( proxyInfo.host, proxyInfo.port );
           hostConfiguration.setHost(serviceURI.getHost(), serviceURI.getPort(), serviceURI.toURL().getProtocol());

           if( !isNullOrEmpty(proxyInfo.userName) && !isNullOrEmpty(proxyInfo.password) ) {
               Credentials cred = new UsernamePasswordCredentials(proxyInfo.userName,proxyInfo.password);
               httpClient.getState().setProxyCredentials(AuthScope.ANY, cred);
           }

           transportFactory.setHttpClient( httpClient );
           client.setTransportFactory( transportFactory );
       }
   }
 
Example #19
Source File: PaymentServiceProviderBeanTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    psp = new PaymentServiceProviderBean();

    HttpMethodFactory.setTestMode(true);
    PostMethodStub.reset();

    httpClientMock = mock(HttpClient.class);
    HostConfiguration hostConfigurationMock = mock(HostConfiguration.class);
    when(httpClientMock.getHostConfiguration()).thenReturn(
            hostConfigurationMock);

    psp.client = httpClientMock;

}
 
Example #20
Source File: ApacheHttp31SLRFactory.java    From webarchive-commons with Apache License 2.0 5 votes vote down vote up
public ApacheHttp31SLRFactory() {
  	connectionManager = new MultiThreadedHttpConnectionManager();
  	//connectionManager = new ThreadLocalHttpConnectionManager();
  	hostConfiguration = new HostConfiguration();
HttpClientParams params = new HttpClientParams();
  	http = new HttpClient(params,connectionManager);
  	http.setHostConfiguration(hostConfiguration);
  }
 
Example #21
Source File: HTTPMessageExecutor.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
public HTTPMessageExecutor(NotificationContext notificationContext, String authorizationHeader, String url
        , HostConfiguration hostConfiguration, HttpClient httpClient) {
    this.url = url;
    this.authorizationHeader = authorizationHeader;
    Gson gson = new Gson();
    this.payload = gson.toJson(notificationContext);
    this.hostConfiguration = hostConfiguration;
    this.httpClient = httpClient;
}
 
Example #22
Source File: TraceeHttpClientDecorator.java    From tracee with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public int executeMethod(HostConfiguration hostconfig, HttpMethod method, HttpState state) throws IOException, HttpException {
	preRequest(method);
	try {
		int result = delegate.executeMethod(hostconfig, method, state);
		postResponse(method);
		return result;
	} finally {
		cancel();
	}
}
 
Example #23
Source File: ServerAddressProcessor.java    From diamond with Apache License 2.0 5 votes vote down vote up
private void initHttpClient() {
    HostConfiguration hostConfiguration = new HostConfiguration();

    SimpleHttpConnectionManager connectionManager = new SimpleHttpConnectionManager();
    connectionManager.closeIdleConnections(5000L);

    HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    params.setStaleCheckingEnabled(diamondConfigure.isConnectionStaleCheckingEnabled());
    params.setConnectionTimeout(diamondConfigure.getConnectionTimeout());
    connectionManager.setParams(params);

    configHttpClient = new HttpClient(connectionManager);
    configHttpClient.setHostConfiguration(hostConfiguration);
}
 
Example #24
Source File: HttpClientTransmitterImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testHttpsVerifyTargetWithCustomSocketFactory() throws Exception
{
    //Override the default SSL socket factory with our own custom one...
    CustomSocketFactory socketFactory = new CustomSocketFactory();
    transmitter.setHttpsSocketFactory(socketFactory);
    
    target.setEndpointProtocol(HTTPS_PROTOCOL);
    target.setEndpointPort(HTTPS_PORT);
    
    //Stub HttpClient so that executeMethod returns a 200 response
    when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class), 
            any(HttpState.class))).thenReturn(200);

    //Call verifyTarget
    transmitter.verifyTarget(target);
    
    ArgumentCaptor<HostConfiguration> hostConfig = ArgumentCaptor.forClass(HostConfiguration.class);
    ArgumentCaptor<HttpMethod> httpMethod = ArgumentCaptor.forClass(HttpMethod.class);
    ArgumentCaptor<HttpState> httpState = ArgumentCaptor.forClass(HttpState.class);
    
    verify(mockedHttpClient).executeMethod(hostConfig.capture(), httpMethod.capture(), httpState.capture());
    
    assertEquals("port", HTTPS_PORT, hostConfig.getValue().getPort());
    //test that the socket factory passed to HttpClient is our custom one (intentional use of '==')
    assertTrue("socket factory", hostConfig.getValue().getProtocol().getSocketFactory() == socketFactory);
    assertEquals("protocol", HTTPS_PROTOCOL.toLowerCase(), 
            hostConfig.getValue().getProtocol().getScheme().toLowerCase());
}
 
Example #25
Source File: HttpClientTransmitterImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testUnauthorisedVerifyTarget() throws Exception
{
    //Stub HttpClient so that executeMethod returns a 401 response
    when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class), 
            any(HttpState.class))).thenReturn(401);
    
    try
    {
        transmitter.verifyTarget(target);
    }
    catch (TransferException ex)
    {
        //expected
    }
}
 
Example #26
Source File: HttpClientTransmitterImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testGetStatusErrorRehydration() throws Exception
{
    final ExceptionJsonSerializer errorSerializer = new ExceptionJsonSerializer();
    final TransferException expectedException = new TransferException("my message id", new Object[] {"param1", "param2"}); 
    when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class), 
            any(HttpState.class))).thenReturn(200);
    doAnswer(new Answer<String>() {
        @Override
        public String answer(InvocationOnMock invocation) throws Throwable
        {
            JSONObject progressObject = new JSONObject();
            progressObject.put("transferId", "mytransferid");
            progressObject.put("status", Status.ERROR);
            progressObject.put("currentPosition", 1);
            progressObject.put("endPosition", 10);
            JSONObject errorObject = errorSerializer.serialize(expectedException);
            progressObject.put("error", errorObject);
            return progressObject.toString();
        }
    }).when(mockedHttpMethodFactory.latestPostMethod).getResponseBodyAsString();
    
    Transfer transfer = new Transfer();
    transfer.setTransferId("mytransferid");
    transfer.setTransferTarget(target);
    TransferProgress progress = transmitter.getStatus(transfer);
    assertTrue(progress.getError() != null);
    assertEquals(expectedException.getClass(), progress.getError().getClass());
    TransferException receivedException = (TransferException)progress.getError();
    assertEquals(expectedException.getMsgId(), receivedException.getMsgId());
    assertTrue(Arrays.deepEquals(expectedException.getMsgParams(), receivedException.getMsgParams()));
}
 
Example #27
Source File: BitlyUrlShortenerImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public BitlyUrlShortenerImpl()
{
    httpClient = new HttpClient();
    httpClient.setHttpConnectionManager(new MultiThreadedHttpConnectionManager());
    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setHost("api-ssl.bitly.com", 443, Protocol.getProtocol("https"));
    httpClient.setHostConfiguration(hostConfiguration);
}
 
Example #28
Source File: HttpClientTransmitterImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testBeginFailure() throws Exception
{
    final ExceptionJsonSerializer errorSerializer = new ExceptionJsonSerializer();
    final TransferException expectedException = new TransferException("my message id", new Object[] {"param1", "param2"}); 
    when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class), 
            any(HttpState.class))).thenReturn(500);
    doAnswer(new Answer<String>() {
        @Override
        public String answer(InvocationOnMock invocation) throws Throwable
        {
            JSONObject errorObject = errorSerializer.serialize(expectedException);
            return errorObject.toString();
        }
    }).when(mockedHttpMethodFactory.latestPostMethod).getResponseBodyAsString();
    
    try
    {
        transmitter.begin(target, "1234", new TransferVersionImpl("2", "2", "2", "Dummy"));
        fail();
    }
    catch(TransferException ex)
    {
        assertEquals(expectedException.getClass(), ex.getClass());
        assertEquals(expectedException.getMsgId(), ex.getMsgId());
        assertTrue(Arrays.deepEquals(expectedException.getMsgParams(), ex.getMsgParams()));
    }
}
 
Example #29
Source File: CFActivator.java    From orion.server with 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);
}
 
Example #30
Source File: HttpClientBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Builds an HTTP client with the given settings. Settings are NOT reset to their default values after a client has
 * been created.
 * 
 * @return the created client.
 */
public HttpClient buildClient() {
    if (httpsProtocolSocketFactory != null) {
        Protocol.registerProtocol("https", new Protocol("https", httpsProtocolSocketFactory, 443));
    }

    HttpClientParams clientParams = new HttpClientParams();
    clientParams.setAuthenticationPreemptive(isPreemptiveAuthentication());
    clientParams.setContentCharset(getContentCharSet());
    clientParams.setParameter(HttpClientParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(
            connectionRetryAttempts, false));

    HttpConnectionManagerParams connMgrParams = new HttpConnectionManagerParams();
    connMgrParams.setConnectionTimeout(getConnectionTimeout());
    connMgrParams.setDefaultMaxConnectionsPerHost(getMaxConnectionsPerHost());
    connMgrParams.setMaxTotalConnections(getMaxTotalConnections());
    connMgrParams.setReceiveBufferSize(getReceiveBufferSize());
    connMgrParams.setSendBufferSize(getSendBufferSize());
    connMgrParams.setTcpNoDelay(isTcpNoDelay());

    MultiThreadedHttpConnectionManager connMgr = new MultiThreadedHttpConnectionManager();
    connMgr.setParams(connMgrParams);

    HttpClient httpClient = new HttpClient(clientParams, connMgr);

    if (proxyHost != null) {
        HostConfiguration hostConfig = new HostConfiguration();
        hostConfig.setProxy(proxyHost, proxyPort);
        httpClient.setHostConfiguration(hostConfig);

        if (proxyUsername != null) {
            AuthScope proxyAuthScope = new AuthScope(proxyHost, proxyPort);
            UsernamePasswordCredentials proxyCredentials = new UsernamePasswordCredentials(proxyUsername,
                    proxyPassword);
            httpClient.getState().setProxyCredentials(proxyAuthScope, proxyCredentials);
        }
    }

    return httpClient;
}