Example usage for org.apache.http.impl.client DefaultRedirectStrategy DefaultRedirectStrategy

List of usage examples for org.apache.http.impl.client DefaultRedirectStrategy DefaultRedirectStrategy

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultRedirectStrategy DefaultRedirectStrategy.

Prototype

public DefaultRedirectStrategy() 

Source Link

Usage

From source file:io.undertow.servlet.test.security.form.ServletFormAuthURLRewriteTestCase.java

@Test
public void testServletFormAuthWithOriginalRequestParams() throws IOException {
    TestHttpClient client = new TestHttpClient();
    client.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override//from   www  .ja  v  a2 s .com
        public boolean isRedirected(final HttpRequest request, final HttpResponse response,
                final HttpContext context) throws ProtocolException {
            if (response.getStatusLine().getStatusCode() == StatusCodes.FOUND) {
                return true;
            }
            return super.isRedirected(request, response, context);
        }
    });
    try {
        final String uri = DefaultServer.getDefaultServerURL()
                + "/servletContext/secured/echoParam?param=developer";
        HttpPost post = new HttpPost(uri);
        post.setEntity(new StringEntity("String Entity"));
        HttpResponse result = client.execute(post);
        assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        String response = HttpClientUtils.readResponse(result);
        Assert.assertTrue(response.startsWith("j_security_check"));

        BasicNameValuePair[] pairs = new BasicNameValuePair[] { new BasicNameValuePair("j_username", "user1"),
                new BasicNameValuePair("j_password", "password1") };
        final List<NameValuePair> data = new ArrayList<>();
        data.addAll(Arrays.asList(pairs));
        post = new HttpPost(DefaultServer.getDefaultServerURL() + "/servletContext/" + response);

        post.setEntity(new UrlEncodedFormEntity(data));

        result = client.execute(post);
        assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());

        response = HttpClientUtils.readResponse(result);
        assertEquals("developer", response);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:org.glowroot.tests.WebDriverSetup.java

private static Container createContainer(int uiPort, File testDir) throws Exception {
    File adminFile = new File(testDir, "admin.json");
    Files.asCharSink(adminFile, UTF_8).write("{\"web\":{\"port\":" + uiPort + "}}");
    Container container;//from w w  w .ja  v  a2s . c om
    if (Containers.useJavaagent()) {
        container = new JavaagentContainer(testDir, true, ImmutableList.of());
    } else {
        container = new LocalContainer(testDir, true, ImmutableMap.of());
    }
    // wait for UI to be available (UI starts asynchronously in order to not block startup)
    CloseableHttpClient httpClient = HttpClients.custom().setRedirectStrategy(new DefaultRedirectStrategy())
            .build();
    Stopwatch stopwatch = Stopwatch.createStarted();
    Exception lastException = null;
    while (stopwatch.elapsed(SECONDS) < 10) {
        HttpGet request = new HttpGet("http://localhost:" + uiPort);
        try (CloseableHttpResponse response = httpClient.execute(request);
                InputStream content = response.getEntity().getContent()) {
            ByteStreams.exhaust(content);
            lastException = null;
            break;
        } catch (Exception e) {
            lastException = e;
        }
    }
    httpClient.close();
    if (lastException != null) {
        throw new IllegalStateException("Timed out waiting for Glowroot UI", lastException);
    }
    return container;
}

From source file:lucee.commons.net.http.httpclient.HTTPEngine4Impl.java

private static HTTPResponse _invoke(URL url, HttpUriRequest request, String username, String password,
        long timeout, boolean redirect, String charset, String useragent, ProxyData proxy,
        lucee.commons.net.http.Header[] headers, Map<String, String> formfields) throws IOException {

    HttpClientBuilder builder = getHttpClientBuilder();

    // redirect/*  w w  w . ja v a 2  s .  com*/
    if (redirect)
        builder.setRedirectStrategy(new DefaultRedirectStrategy());
    else
        builder.disableRedirectHandling();

    HttpHost hh = new HttpHost(url.getHost(), url.getPort());
    setHeader(request, headers);
    if (CollectionUtil.isEmpty(formfields))
        setContentType(request, charset);
    setFormFields(request, formfields, charset);
    setUserAgent(request, useragent);
    if (timeout > 0)
        Http.setTimeout(builder, TimeSpanImpl.fromMillis(timeout));
    HttpContext context = setCredentials(builder, hh, username, password, false);
    setProxy(builder, request, proxy);
    CloseableHttpClient client = builder.build();
    if (context == null)
        context = new BasicHttpContext();
    return new HTTPResponse4Impl(url, context, request, client.execute(request, context));
}

From source file:io.milton.httpclient.Host.java

public Host(String server, String rootPath, Integer port, String user, String password,
        ProxyDetails proxyDetails, int timeoutMillis, Map<Folder, List<Resource>> cache,
        FileSyncer fileSyncer) {//w  w w  .j  a  v a  2s .  c o m
    //super((cache != null ? cache : new MemoryCache<Folder, List<Resource>>("resource-cache-default", 50, 20)));
    super((cache != null ? cache
            : new ConcurrentLinkedHashMap.Builder().maximumWeightedCapacity(1000).build()));
    if (server == null) {
        throw new IllegalArgumentException("host name cannot be null");
    }
    if (rootPath != null) {
        String rp = rootPath;
        if (rp.startsWith("/")) { // strip leading slash so can be concatenated
            rp = rp.substring(1);
        }
        this.rootPath = rp;
    } else {
        this.rootPath = null;
    }
    this.timeout = timeoutMillis;
    this.server = server;
    this.port = port;
    this.user = user;
    this.password = password;
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 10000);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

    // Create and initialize scheme registry 
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    // Create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
    cm.setMaxTotal(200);

    client = new MyDefaultHttpClient(cm, params);
    HttpRequestRetryHandler handler = new NoRetryHttpRequestRetryHandler();
    client.setHttpRequestRetryHandler(handler);
    client.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override
        public boolean isRedirected(final HttpRequest request, final HttpResponse response,
                final HttpContext context) throws ProtocolException {

            if (super.isRedirected(request, response, context)) {
                return true;
            }
            int statusCode = response.getStatusLine().getStatusCode();
            String method = request.getRequestLine().getMethod();
            Header locationHeader = response.getFirstHeader("location");
            switch (statusCode) {
            case HttpStatus.SC_MOVED_TEMPORARILY:
                return locationHeader != null && WEBDAV_REDIRECTABLE.contains(method);
            case HttpStatus.SC_MOVED_PERMANENTLY:
            case HttpStatus.SC_TEMPORARY_REDIRECT:
                return WEBDAV_REDIRECTABLE.contains(method);
            default:
                return false;
            }
        }
    });

    if (user != null) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(user, password));
        PreemptiveAuthInterceptor interceptor = new PreemptiveAuthInterceptor();
        client.addRequestInterceptor(interceptor, 0);
    }

    if (proxyDetails != null) {
        if (proxyDetails.isUseSystemProxy()) {
            System.setProperty("java.net.useSystemProxies", "true");
        } else {
            System.setProperty("java.net.useSystemProxies", "false");
            if (proxyDetails.getProxyHost() != null && proxyDetails.getProxyHost().length() > 0) {
                HttpHost proxy = new HttpHost(proxyDetails.getProxyHost(), proxyDetails.getProxyPort(), "http");
                client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
                if (proxyDetails.hasAuth()) {
                    client.getCredentialsProvider().setCredentials(
                            new AuthScope(proxyDetails.getProxyHost(), proxyDetails.getProxyPort()),
                            new UsernamePasswordCredentials(proxyDetails.getUserName(),
                                    proxyDetails.getPassword()));
                }
            }
        }
    }
    transferService = new TransferService(client, connectionListeners);
    transferService.setTimeout(timeoutMillis);
    this.fileSyncer = fileSyncer;
}

From source file:com.bigdata.rdf.sail.webapp.AbstractTestNanoSparqlClient.java

@Override
public void setUp() throws Exception {

    super.setUp();

    log.warn("Setting up test:" + getName());

    final Properties properties = getProperties();

    // guaranteed distinct namespace for the KB instance.
    namespace = getName() + UUID.randomUUID();

    final IIndexManager m_indexManager = getIndexManager();

    // Create the triple store instance.
    final AbstractTripleStore tripleStore = createTripleStore(m_indexManager, namespace, properties);

    if (tripleStore.isStatementIdentifiers()) {
        testMode = TestMode.sids;// w  w w.  jav a 2  s  .  c  o m
    } else if (tripleStore.isQuads()) {
        testMode = TestMode.quads;
    } else {
        testMode = TestMode.triples;
    }

    final Map<String, String> initParams = new LinkedHashMap<String, String>();
    {

        initParams.put(ConfigParams.NAMESPACE, namespace);

        initParams.put(ConfigParams.CREATE, "false");

    }
    // Start server for that kb instance.
    m_fixture = NanoSparqlServer.newInstance(0/* port */, m_indexManager, initParams);

    m_fixture.start();

    final int port = NanoSparqlServer.getLocalPort(m_fixture);

    // log.info("Getting host address");

    final String hostAddr = NicUtil.getIpAddress("default.nic", "default", true/* loopbackOk */);

    if (hostAddr == null) {

        fail("Could not identify network address for this host.");

    }

    m_rootURL = new URL("http", hostAddr, port, ""/* contextPath */
    ).toExternalForm();

    m_serviceURL = new URL("http", hostAddr, port, BigdataStatics.getContextPath()).toExternalForm();

    if (log.isInfoEnabled())
        log.info("Setup done: \nname=" + getName() + "\nnamespace=" + namespace + "\nrootURL=" + m_rootURL
                + "\nserviceURL=" + m_serviceURL);

    //        final HttpClient httpClient = new DefaultHttpClient();

    //        m_cm = httpClient.getConnectionManager();

    m_cm = DefaultClientConnectionManagerFactory.getInstance().newInstance();

    final DefaultHttpClient httpClient = new DefaultHttpClient(m_cm);
    m_httpClient = httpClient;

    /*
     * Ensure that the client follows redirects using a standard policy.
     * 
     * Note: This is necessary for tests of the webapp structure since the
     * container may respond with a redirect (302) to the location of the
     * webapp when the client requests the root URL.
     */
    httpClient.setRedirectStrategy(new DefaultRedirectStrategy());

    m_repo = new RemoteRepositoryManager(m_serviceURL, m_httpClient, m_indexManager.getExecutorService());

}

From source file:org.apache.manifoldcf.agents.output.solr.HttpPoster.java

/** Initialize the standard http poster.
*///ww w  .  j  a v  a  2s.c  om
public HttpPoster(String protocol, String server, int port, String webapp, String core, int connectionTimeout,
        int socketTimeout, String updatePath, String removePath, String statusPath, String realm, String userID,
        String password, String allowAttributeName, String denyAttributeName, String idAttributeName,
        String modifiedDateAttributeName, String createdDateAttributeName, String indexedDateAttributeName,
        String fileNameAttributeName, String mimeTypeAttributeName, String contentAttributeName,
        IKeystoreManager keystoreManager, Long maxDocumentLength, String commitWithin,
        boolean useExtractUpdateHandler) throws ManifoldCFException {
    // These are the paths to the handlers in Solr that deal with the actions we need to do
    this.postUpdateAction = updatePath;
    this.postRemoveAction = removePath;
    this.postStatusAction = statusPath;

    this.commitWithin = commitWithin;

    this.allowAttributeName = allowAttributeName;
    this.denyAttributeName = denyAttributeName;
    this.idAttributeName = idAttributeName;
    this.modifiedDateAttributeName = modifiedDateAttributeName;
    this.createdDateAttributeName = createdDateAttributeName;
    this.indexedDateAttributeName = indexedDateAttributeName;
    this.fileNameAttributeName = fileNameAttributeName;
    this.mimeTypeAttributeName = mimeTypeAttributeName;
    this.contentAttributeName = contentAttributeName;
    this.useExtractUpdateHandler = useExtractUpdateHandler;

    this.maxDocumentLength = maxDocumentLength;

    String location = "";
    if (webapp != null)
        location = "/" + webapp;
    if (core != null) {
        if (webapp == null)
            throw new ManifoldCFException("Webapp must be specified if core is specified.");
        location += "/" + core;
    }

    // Initialize standard solr-j.
    // First, we need an HttpClient where basic auth is properly set up.
    connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(1);

    SSLConnectionSocketFactory myFactory;
    if (keystoreManager != null) {
        myFactory = new SSLConnectionSocketFactory(keystoreManager.getSecureSocketFactory(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } else {
        // Use the "trust everything" one
        myFactory = new SSLConnectionSocketFactory(KeystoreManagerFactory.getTrustingSecureSocketFactory(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }

    RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
            .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).setExpectContinueEnabled(true)
            .setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(socketTimeout);

    HttpClientBuilder clientBuilder = HttpClients.custom().setConnectionManager(connectionManager)
            .setMaxConnTotal(1).disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build())
            .setRedirectStrategy(new DefaultRedirectStrategy()).setSSLSocketFactory(myFactory)
            .setRequestExecutor(new HttpRequestExecutor(socketTimeout)).setDefaultSocketConfig(
                    SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build());

    if (userID != null && userID.length() > 0 && password != null) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        Credentials credentials = new UsernamePasswordCredentials(userID, password);
        if (realm != null)
            credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, realm),
                    credentials);
        else
            credentialsProvider.setCredentials(AuthScope.ANY, credentials);

        clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }

    HttpClient localClient = clientBuilder.build();

    String httpSolrServerUrl = protocol + "://" + server + ":" + port + location;
    solrServer = new ModifiedHttpSolrServer(httpSolrServerUrl, localClient, new XMLResponseParser());
}

From source file:org.apache.manifoldcf.crawler.connectors.meridio.meridiowrapper.MeridioWrapper.java

/** The Meridio Wrapper constructor that calls the Meridio login method
*
*@param log                                     a handle to a Log4j logger
*@param meridioDmwsUrl          the URL to the Meridio Document Management Web Service
*@param meridioRmwsUrl          the URL to the Meridio Records Management Web Service
*@param dmwsProxyHost           the proxy for DMWS, or null if none
*@param dmwsProxyPort           the proxy port for DMWS, or -1 if default
*@param rmwsProxyHost           the proxy for RMWS, or null if none
*@param rmwsProxyPort           the proxy port for RMWS, or -1 if default
*@param userName                        the username of the user to log in as, must include the Windows, e.g. domain\\user
*@param password                        the password of the user who is logging in
*@param clientWorkstation       an identifier for the client workstation, could be the IP address, for auditing purposes
*@param protocolFactory         the protocol factory object to use for https communication
*@param engineConfigurationFile the engine configuration object to use to communicate with the web services
*
*@throws RemoteException        if an error is encountered logging into Meridio
*///from  ww  w . ja  v a2s.  co m
public MeridioWrapper(Logger log, URL meridioDmwsUrl, URL meridioRmwsUrl, URL meridioManifoldCFWSUrl,
        String dmwsProxyHost, String dmwsProxyPort, String rmwsProxyHost, String rmwsProxyPort,
        String mcwsProxyHost, String mcwsProxyPort, String userName, String password, String clientWorkstation,
        javax.net.ssl.SSLSocketFactory mySSLFactory, Class resourceClass, String engineConfigurationFile)
        throws RemoteException, NumberFormatException {
    // Initialize local instance variables
    oLog = log;
    this.engineConfiguration = new ResourceProvider(resourceClass, engineConfigurationFile);
    this.clientWorkstation = clientWorkstation;

    // Set up the pool.
    // We have a choice: We can either have one httpclient instance, which gets reinitialized for every service
    // it connects with (because each one has a potentially different proxy setup), OR we can have a different
    // httpclient for each service.  The latter approach is obviously the more efficient, so I've chosen to do it
    // that way.
    PoolingClientConnectionManager localConnectionManager = new PoolingClientConnectionManager();
    localConnectionManager.setMaxTotal(1);
    if (mySSLFactory != null) {
        SSLSocketFactory myFactory = new SSLSocketFactory(mySSLFactory, new BrowserCompatHostnameVerifier());
        Scheme myHttpsProtocol = new Scheme("https", 443, myFactory);
        localConnectionManager.getSchemeRegistry().register(myHttpsProtocol);
    }
    connectionManager = localConnectionManager;

    // Parse the user and password values
    int index = userName.indexOf("\\");
    String domainUser;
    String domain;
    if (index != -1) {
        domainUser = userName.substring(index + 1);
        domain = userName.substring(0, index);
        if (oLog != null && oLog.isDebugEnabled())
            oLog.debug("Meridio: User is '" + domainUser + "', domain is '" + domain + "'");
    } else {
        domain = null;
        domainUser = userName;
        if (oLog != null && oLog.isDebugEnabled())
            oLog.debug("Meridio: User is '" + domainUser + "'; there is no domain specified");
    }

    if (oLog != null && oLog.isDebugEnabled()) {
        if (password != null && password.length() > 0)
            oLog.debug("Meridio: Password exists");
        else
            oLog.debug("Meridio: Password is null");
    }

    // Initialize the three httpclient objects

    // dmws first
    BasicHttpParams dmwsParams = new BasicHttpParams();
    dmwsParams.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);
    dmwsParams.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
    dmwsParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
    dmwsParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 900000);
    dmwsParams.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
    DefaultHttpClient localDmwsHttpClient = new DefaultHttpClient(connectionManager, dmwsParams);
    // No retries
    localDmwsHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            return false;
        }

    });

    localDmwsHttpClient.setRedirectStrategy(new DefaultRedirectStrategy());
    if (domainUser != null) {
        localDmwsHttpClient.getCredentialsProvider().setCredentials(
                new AuthScope(meridioDmwsUrl.getHost(), meridioDmwsUrl.getPort()),
                new NTCredentials(domainUser, password, currentHost, domain));
    }
    // Initialize proxy
    if (dmwsProxyHost != null && dmwsProxyHost.length() > 0) {
        int port = (dmwsProxyPort == null || dmwsProxyPort.length() == 0) ? 8080
                : Integer.parseInt(dmwsProxyPort);
        // Configure proxy authentication
        if (domainUser != null && domainUser.length() > 0) {
            localDmwsHttpClient.getCredentialsProvider().setCredentials(new AuthScope(dmwsProxyHost, port),
                    new NTCredentials(domainUser, password, currentHost, domain));
        }

        HttpHost proxy = new HttpHost(dmwsProxyHost, port);
        localDmwsHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    dmwsHttpClient = localDmwsHttpClient;

    // rmws
    BasicHttpParams rmwsParams = new BasicHttpParams();
    rmwsParams.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);
    rmwsParams.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
    rmwsParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
    rmwsParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 900000);
    rmwsParams.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
    DefaultHttpClient localRmwsHttpClient = new DefaultHttpClient(connectionManager, rmwsParams);
    // No retries
    localRmwsHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            return false;
        }

    });

    localRmwsHttpClient.setRedirectStrategy(new DefaultRedirectStrategy());
    if (domainUser != null) {
        localRmwsHttpClient.getCredentialsProvider().setCredentials(
                new AuthScope(meridioRmwsUrl.getHost(), meridioRmwsUrl.getPort()),
                new NTCredentials(domainUser, password, currentHost, domain));
    }
    // Initialize proxy
    if (rmwsProxyHost != null && rmwsProxyHost.length() > 0) {
        int port = (rmwsProxyPort == null || rmwsProxyPort.length() == 0) ? 8080
                : Integer.parseInt(rmwsProxyPort);
        // Configure proxy authentication
        if (domainUser != null && domainUser.length() > 0) {
            localRmwsHttpClient.getCredentialsProvider().setCredentials(new AuthScope(rmwsProxyHost, port),
                    new NTCredentials(domainUser, password, currentHost, domain));
        }

        HttpHost proxy = new HttpHost(rmwsProxyHost, port);
        localRmwsHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    rmwsHttpClient = localRmwsHttpClient;

    // mcws
    if (meridioManifoldCFWSUrl != null) {
        BasicHttpParams mcwsParams = new BasicHttpParams();
        mcwsParams.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);
        mcwsParams.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
        mcwsParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
        mcwsParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 900000);
        mcwsParams.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        DefaultHttpClient localMcwsHttpClient = new DefaultHttpClient(connectionManager, mcwsParams);
        // No retries
        localMcwsHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
            public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                return false;
            }

        });

        localMcwsHttpClient.setRedirectStrategy(new DefaultRedirectStrategy());
        if (domainUser != null) {
            localMcwsHttpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(meridioManifoldCFWSUrl.getHost(), meridioManifoldCFWSUrl.getPort()),
                    new NTCredentials(domainUser, password, currentHost, domain));
        }
        // Initialize proxy
        if (mcwsProxyHost != null && mcwsProxyHost.length() > 0) {
            int port = (mcwsProxyPort == null || mcwsProxyPort.length() == 0) ? 8080
                    : Integer.parseInt(mcwsProxyPort);
            // Configure proxy authentication
            if (domainUser != null && domainUser.length() > 0) {
                localMcwsHttpClient.getCredentialsProvider().setCredentials(new AuthScope(mcwsProxyHost, port),
                        new NTCredentials(domainUser, password, currentHost, domain));
            }

            HttpHost proxy = new HttpHost(mcwsProxyHost, port);
            localMcwsHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
        mcwsHttpClient = localMcwsHttpClient;
    } else
        mcwsHttpClient = null;

    // Set up the stub handles
    /*=================================================================
    * Get a handle to the DMWS
    *================================================================*/
    MeridioDMLocator meridioDMLocator = new MeridioDMLocator(engineConfiguration);
    MeridioDMSoapStub meridioDMWebService = new MeridioDMSoapStub(meridioDmwsUrl, meridioDMLocator);

    meridioDMWebService.setPortName(meridioDMLocator.getMeridioDMSoapWSDDServiceName());
    meridioDMWebService.setUsername(userName);
    meridioDMWebService.setPassword(password);
    meridioDMWebService._setProperty(HTTPCLIENT_PROPERTY, dmwsHttpClient);

    meridioDMWebService_ = meridioDMWebService;

    /*=================================================================
    * Get a handle to the RMWS
    *================================================================*/
    MeridioRMLocator meridioRMLocator = new MeridioRMLocator(engineConfiguration);
    MeridioRMSoapStub meridioRMWebService = new MeridioRMSoapStub(meridioRmwsUrl, meridioRMLocator);

    meridioRMWebService.setPortName(meridioRMLocator.getMeridioRMSoapWSDDServiceName());
    meridioRMWebService.setUsername(userName);
    meridioRMWebService.setPassword(password);
    meridioRMWebService._setProperty(HTTPCLIENT_PROPERTY, rmwsHttpClient);

    meridioRMWebService_ = meridioRMWebService;

    /*=================================================================
    * Get a handle to the MeridioMetaCarta Web Service
    *================================================================*/
    if (meridioManifoldCFWSUrl != null) {
        MetaCartaLocator meridioMCWS = new MetaCartaLocator(engineConfiguration);
        Service McWsService = null;
        MetaCartaSoapStub meridioMetaCartaWebService = new MetaCartaSoapStub(meridioManifoldCFWSUrl,
                McWsService);

        meridioMetaCartaWebService.setPortName(meridioMCWS.getMetaCartaSoapWSDDServiceName());
        meridioMetaCartaWebService.setUsername(userName);
        meridioMetaCartaWebService.setPassword(password);
        meridioMetaCartaWebService._setProperty(HTTPCLIENT_PROPERTY, mcwsHttpClient);

        meridioMCWS_ = meridioMetaCartaWebService;
    }

    this.loginUnified();
}

From source file:org.apache.manifoldcf.meridio.MeridioWrapper.java

/** The Meridio Wrapper constructor that calls the Meridio login method
*
*@param log                                     a handle to a Log4j logger
*@param meridioDmwsUrl          the URL to the Meridio Document Management Web Service
*@param meridioRmwsUrl          the URL to the Meridio Records Management Web Service
*@param dmwsProxyHost           the proxy for DMWS, or null if none
*@param dmwsProxyPort           the proxy port for DMWS, or -1 if default
*@param rmwsProxyHost           the proxy for RMWS, or null if none
*@param rmwsProxyPort           the proxy port for RMWS, or -1 if default
*@param userName                        the username of the user to log in as, must include the Windows, e.g. domain\\user
*@param password                        the password of the user who is logging in
*@param clientWorkstation       an identifier for the client workstation, could be the IP address, for auditing purposes
*@param protocolFactory         the protocol factory object to use for https communication
*@param engineConfigurationFile the engine configuration object to use to communicate with the web services
*
*@throws RemoteException        if an error is encountered logging into Meridio
*//*from w w w  .j  a v  a2 s . c o  m*/
public MeridioWrapper(Logger log, URL meridioDmwsUrl, URL meridioRmwsUrl, URL meridioManifoldCFWSUrl,
        String dmwsProxyHost, String dmwsProxyPort, String rmwsProxyHost, String rmwsProxyPort,
        String mcwsProxyHost, String mcwsProxyPort, String userName, String password, String clientWorkstation,
        javax.net.ssl.SSLSocketFactory mySSLFactory, Class resourceClass, String engineConfigurationFile)
        throws RemoteException, NumberFormatException {
    // Initialize local instance variables
    oLog = log;
    this.engineConfiguration = new ResourceProvider(resourceClass, engineConfigurationFile);
    this.clientWorkstation = clientWorkstation;

    SSLConnectionSocketFactory myFactory = null;
    if (mySSLFactory != null) {
        myFactory = new SSLConnectionSocketFactory(mySSLFactory, new BrowserCompatHostnameVerifier());
    }

    // Set up the pool.
    // We have a choice: We can either have one httpclient instance, which gets reinitialized for every service
    // it connects with (because each one has a potentially different proxy setup), OR we can have a different
    // httpclient for each service.  The latter approach is obviously the more efficient, so I've chosen to do it
    // that way.

    // Parse the user and password values
    int index = userName.indexOf("\\");
    String domainUser;
    String domain;
    if (index != -1) {
        domainUser = userName.substring(index + 1);
        domain = userName.substring(0, index);
        if (oLog != null && oLog.isDebugEnabled())
            oLog.debug("Meridio: User is '" + domainUser + "', domain is '" + domain + "'");
    } else {
        domain = null;
        domainUser = userName;
        if (oLog != null && oLog.isDebugEnabled())
            oLog.debug("Meridio: User is '" + domainUser + "'; there is no domain specified");
    }

    if (oLog != null && oLog.isDebugEnabled()) {
        if (password != null && password.length() > 0)
            oLog.debug("Meridio: Password exists");
        else
            oLog.debug("Meridio: Password is null");
    }

    int socketTimeout = 900000;
    int connectionTimeout = 300000;

    dmwsConnectionManager = new PoolingHttpClientConnectionManager();
    rmwsConnectionManager = new PoolingHttpClientConnectionManager();
    mcwsConnectionManager = new PoolingHttpClientConnectionManager();

    // Initialize the three httpclient objects

    CredentialsProvider dmwsCredentialsProvider = new BasicCredentialsProvider();
    CredentialsProvider rmwsCredentialsProvider = new BasicCredentialsProvider();

    RequestConfig.Builder dmwsRequestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
            .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true)
            .setExpectContinueEnabled(false).setConnectTimeout(connectionTimeout)
            .setConnectionRequestTimeout(socketTimeout);
    RequestConfig.Builder rmwsRequestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
            .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).setExpectContinueEnabled(true)
            .setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(socketTimeout);

    // Set up credentials
    if (domainUser != null) {
        dmwsCredentialsProvider.setCredentials(
                new AuthScope(meridioDmwsUrl.getHost(), meridioDmwsUrl.getPort()),
                new NTCredentials(domainUser, password, currentHost, domain));
        rmwsCredentialsProvider.setCredentials(
                new AuthScope(meridioRmwsUrl.getHost(), meridioRmwsUrl.getPort()),
                new NTCredentials(domainUser, password, currentHost, domain));
    }

    // Initialize DMWS proxy
    if (dmwsProxyHost != null && dmwsProxyHost.length() > 0) {
        int port = (dmwsProxyPort == null || dmwsProxyPort.length() == 0) ? 8080
                : Integer.parseInt(dmwsProxyPort);
        // Configure proxy authentication
        if (domainUser != null && domainUser.length() > 0) {
            dmwsCredentialsProvider.setCredentials(new AuthScope(dmwsProxyHost, port),
                    new NTCredentials(domainUser, password, currentHost, domain));
        }

        HttpHost proxy = new HttpHost(dmwsProxyHost, port);
        dmwsRequestBuilder.setProxy(proxy);
    }

    // Initialize RMWS proxy
    if (rmwsProxyHost != null && rmwsProxyHost.length() > 0) {
        int port = (rmwsProxyPort == null || rmwsProxyPort.length() == 0) ? 8080
                : Integer.parseInt(rmwsProxyPort);
        // Configure proxy authentication
        if (domainUser != null && domainUser.length() > 0) {
            rmwsCredentialsProvider.setCredentials(new AuthScope(rmwsProxyHost, port),
                    new NTCredentials(domainUser, password, currentHost, domain));
        }

        HttpHost proxy = new HttpHost(rmwsProxyHost, port);
        rmwsRequestBuilder.setProxy(proxy);
    }

    dmwsHttpClient = HttpClients.custom().setConnectionManager(dmwsConnectionManager).setMaxConnTotal(1)
            .disableAutomaticRetries().setDefaultRequestConfig(dmwsRequestBuilder.build())
            .setDefaultSocketConfig(
                    SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
            .setDefaultCredentialsProvider(dmwsCredentialsProvider).setSSLSocketFactory(myFactory)
            .setRequestExecutor(new HttpRequestExecutor(socketTimeout))
            .setRedirectStrategy(new DefaultRedirectStrategy()).build();

    rmwsHttpClient = HttpClients.custom().setConnectionManager(rmwsConnectionManager).setMaxConnTotal(1)
            .disableAutomaticRetries().setDefaultRequestConfig(rmwsRequestBuilder.build())
            .setDefaultSocketConfig(
                    SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
            .setDefaultCredentialsProvider(rmwsCredentialsProvider).setSSLSocketFactory(myFactory)
            .setRequestExecutor(new HttpRequestExecutor(socketTimeout))
            .setRedirectStrategy(new DefaultRedirectStrategy()).build();

    if (meridioManifoldCFWSUrl != null) {
        CredentialsProvider mcwsCredentialsProvider = new BasicCredentialsProvider();

        RequestConfig.Builder mcwsRequestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
                .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true)
                .setExpectContinueEnabled(true).setConnectTimeout(connectionTimeout)
                .setConnectionRequestTimeout(socketTimeout);

        if (domainUser != null) {
            mcwsCredentialsProvider.setCredentials(
                    new AuthScope(meridioManifoldCFWSUrl.getHost(), meridioManifoldCFWSUrl.getPort()),
                    new NTCredentials(domainUser, password, currentHost, domain));
        }

        // Initialize MCWS proxy
        if (mcwsProxyHost != null && mcwsProxyHost.length() > 0) {
            int port = (mcwsProxyPort == null || mcwsProxyPort.length() == 0) ? 8080
                    : Integer.parseInt(mcwsProxyPort);
            // Configure proxy authentication
            if (domainUser != null && domainUser.length() > 0) {
                mcwsCredentialsProvider.setCredentials(new AuthScope(mcwsProxyHost, port),
                        new NTCredentials(domainUser, password, currentHost, domain));
            }

            HttpHost proxy = new HttpHost(mcwsProxyHost, port);
            mcwsRequestBuilder.setProxy(proxy);
        }

        mcwsHttpClient = HttpClients.custom().setConnectionManager(mcwsConnectionManager).setMaxConnTotal(1)
                .disableAutomaticRetries().setDefaultRequestConfig(mcwsRequestBuilder.build())
                .setDefaultSocketConfig(
                        SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
                .setDefaultCredentialsProvider(mcwsCredentialsProvider).setSSLSocketFactory(myFactory)
                .setRequestExecutor(new HttpRequestExecutor(socketTimeout))
                .setRedirectStrategy(new DefaultRedirectStrategy()).build();
    }

    // Set up the stub handles
    /*=================================================================
    * Get a handle to the DMWS
    *================================================================*/
    MeridioDMLocator meridioDMLocator = new MeridioDMLocator(engineConfiguration);
    MeridioDMSoapStub meridioDMWebService = new MeridioDMSoapStub(meridioDmwsUrl, meridioDMLocator);

    meridioDMWebService.setPortName(meridioDMLocator.getMeridioDMSoapWSDDServiceName());
    meridioDMWebService.setUsername(userName);
    meridioDMWebService.setPassword(password);
    meridioDMWebService._setProperty(HTTPCLIENT_PROPERTY, dmwsHttpClient);

    meridioDMWebService_ = meridioDMWebService;

    /*=================================================================
    * Get a handle to the RMWS
    *================================================================*/
    MeridioRMLocator meridioRMLocator = new MeridioRMLocator(engineConfiguration);
    MeridioRMSoapStub meridioRMWebService = new MeridioRMSoapStub(meridioRmwsUrl, meridioRMLocator);

    meridioRMWebService.setPortName(meridioRMLocator.getMeridioRMSoapWSDDServiceName());
    meridioRMWebService.setUsername(userName);
    meridioRMWebService.setPassword(password);
    meridioRMWebService._setProperty(HTTPCLIENT_PROPERTY, rmwsHttpClient);

    meridioRMWebService_ = meridioRMWebService;

    /*=================================================================
    * Get a handle to the MeridioMetaCarta Web Service
    *================================================================*/
    if (meridioManifoldCFWSUrl != null) {
        MetaCartaLocator meridioMCWS = new MetaCartaLocator(engineConfiguration);
        Service McWsService = null;
        MetaCartaSoapStub meridioMetaCartaWebService = new MetaCartaSoapStub(meridioManifoldCFWSUrl,
                McWsService);

        meridioMetaCartaWebService.setPortName(meridioMCWS.getMetaCartaSoapWSDDServiceName());
        meridioMetaCartaWebService.setUsername(userName);
        meridioMetaCartaWebService.setPassword(password);
        meridioMetaCartaWebService._setProperty(HTTPCLIENT_PROPERTY, mcwsHttpClient);

        meridioMCWS_ = meridioMetaCartaWebService;
    }

    this.loginUnified();
}

From source file:com.redhat.rcm.version.util.InputUtils.java

private static void setupClient() throws VManException {
    if (client == null) {
        SSLSocketFactory sslSocketFactory;
        try {/*from  ww  w .  j a v  a2s . c om*/
            sslSocketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, null, null, trustKs, null,
                    new TrustSelfSignedStrategy(), SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            //                sslSocketFactory =
            //                    new SSLSocketFactory( SSLSocketFactory.TLS, null, null, trustKs, null, null,
            //                                          SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER );
        } catch (final KeyManagementException e) {
            logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage());
            throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage());
        } catch (final UnrecoverableKeyException e) {
            logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage());
            throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage());
        } catch (final NoSuchAlgorithmException e) {
            logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage());
            throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage());
        } catch (final KeyStoreException e) {
            logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage());
            throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage());
        }

        final ThreadSafeClientConnManager ccm = new ThreadSafeClientConnManager();
        ccm.getSchemeRegistry().register(new Scheme("https", 443, sslSocketFactory));

        final DefaultHttpClient hc = new DefaultHttpClient(ccm);
        hc.setRedirectStrategy(new DefaultRedirectStrategy());

        final String proxyHost = System.getProperty("http.proxyHost");
        final int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort", "-1"));

        if (proxyHost != null && proxyPort > 0) {
            final HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            hc.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
        }

        client = hc;
    }
}

From source file:org.apache.manifoldcf.crawler.connectors.sharepoint.SharePointRepository.java

/** Set up a session */
protected void getSession() throws ManifoldCFException {
    if (proxy == null) {
        String serverVersion = params.getParameter(SharePointConfig.PARAM_SERVERVERSION);
        if (serverVersion == null)
            serverVersion = "4.0";
        supportsItemSecurity = !serverVersion.equals("2.0");
        dspStsWorks = serverVersion.equals("2.0") || serverVersion.equals("3.0");
        attachmentsSupported = !serverVersion.equals("2.0");

        String authorityType = params.getParameter(SharePointConfig.PARAM_AUTHORITYTYPE);
        if (authorityType == null)
            authorityType = "ActiveDirectory";

        activeDirectoryAuthority = authorityType.equals("ActiveDirectory");

        serverProtocol = params.getParameter(SharePointConfig.PARAM_SERVERPROTOCOL);
        if (serverProtocol == null)
            serverProtocol = "http";
        try {/*from w  ww .ja v  a 2s  . c  om*/
            String serverPort = params.getParameter(SharePointConfig.PARAM_SERVERPORT);
            if (serverPort == null || serverPort.length() == 0) {
                if (serverProtocol.equals("https"))
                    this.serverPort = 443;
                else
                    this.serverPort = 80;
            } else
                this.serverPort = Integer.parseInt(serverPort);
        } catch (NumberFormatException e) {
            throw new ManifoldCFException(e.getMessage(), e);
        }
        serverLocation = params.getParameter(SharePointConfig.PARAM_SERVERLOCATION);
        if (serverLocation == null)
            serverLocation = "";
        if (serverLocation.endsWith("/"))
            serverLocation = serverLocation.substring(0, serverLocation.length() - 1);
        if (serverLocation.length() > 0 && !serverLocation.startsWith("/"))
            serverLocation = "/" + serverLocation;
        encodedServerLocation = serverLocation;
        serverLocation = decodePath(serverLocation);

        userName = params.getParameter(SharePointConfig.PARAM_SERVERUSERNAME);
        password = params.getObfuscatedParameter(SharePointConfig.PARAM_SERVERPASSWORD);
        int index = userName.indexOf("\\");
        if (index != -1) {
            strippedUserName = userName.substring(index + 1);
            ntlmDomain = userName.substring(0, index);
        } else {
            strippedUserName = null;
            ntlmDomain = null;
        }

        String proxyHost = params.getParameter(SharePointConfig.PARAM_PROXYHOST);
        String proxyPortString = params.getParameter(SharePointConfig.PARAM_PROXYPORT);
        int proxyPort = 8080;
        if (proxyPortString != null && proxyPortString.length() > 0) {
            try {
                proxyPort = Integer.parseInt(proxyPortString);
            } catch (NumberFormatException e) {
                throw new ManifoldCFException(e.getMessage(), e);
            }
        }
        String proxyUsername = params.getParameter(SharePointConfig.PARAM_PROXYUSER);
        String proxyPassword = params.getParameter(SharePointConfig.PARAM_PROXYPASSWORD);
        String proxyDomain = params.getParameter(SharePointConfig.PARAM_PROXYDOMAIN);

        serverUrl = serverProtocol + "://" + serverName;
        if (serverProtocol.equals("https")) {
            if (serverPort != 443)
                serverUrl += ":" + Integer.toString(serverPort);
        } else {
            if (serverPort != 80)
                serverUrl += ":" + Integer.toString(serverPort);
        }

        fileBaseUrl = serverUrl + encodedServerLocation;

        // Set up ssl if indicated
        keystoreData = params.getParameter(SharePointConfig.PARAM_SERVERKEYSTORE);

        int connectionTimeout = 60000;
        int socketTimeout = 900000;

        connectionManager = new PoolingHttpClientConnectionManager();

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        SSLConnectionSocketFactory myFactory = null;
        if (keystoreData != null) {
            keystoreManager = KeystoreManagerFactory.make("", keystoreData);
            myFactory = new SSLConnectionSocketFactory(keystoreManager.getSecureSocketFactory(),
                    new BrowserCompatHostnameVerifier());
        }

        if (strippedUserName != null) {
            credentialsProvider.setCredentials(new AuthScope(serverName, serverPort),
                    new NTCredentials(strippedUserName, password, currentHost, ntlmDomain));
        }

        RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
                .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true)
                .setExpectContinueEnabled(false).setConnectTimeout(connectionTimeout)
                .setConnectionRequestTimeout(socketTimeout);

        // If there's a proxy, set that too.
        if (proxyHost != null && proxyHost.length() > 0) {

            // Configure proxy authentication
            if (proxyUsername != null && proxyUsername.length() > 0) {
                if (proxyPassword == null)
                    proxyPassword = "";
                if (proxyDomain == null)
                    proxyDomain = "";

                credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                        new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain));
            }

            HttpHost proxy = new HttpHost(proxyHost, proxyPort);

            requestBuilder.setProxy(proxy);
        }

        HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager)
                .setMaxConnTotal(1).disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build())
                .setDefaultSocketConfig(
                        SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
                .setDefaultCredentialsProvider(credentialsProvider);
        if (myFactory != null)
            builder.setSSLSocketFactory(myFactory);
        builder.setRequestExecutor(new HttpRequestExecutor(socketTimeout))
                .setRedirectStrategy(new DefaultRedirectStrategy());
        httpClient = builder.build();

        proxy = new SPSProxyHelper(serverUrl, encodedServerLocation, serverLocation, userName, password,
                org.apache.manifoldcf.connectorcommon.common.CommonsHTTPSender.class, "client-config.wsdd",
                httpClient);

    }
    sessionTimeout = System.currentTimeMillis() + sessionExpirationInterval;
}