Example usage for org.apache.commons.httpclient.params HttpConnectionParams setConnectionTimeout

List of usage examples for org.apache.commons.httpclient.params HttpConnectionParams setConnectionTimeout

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.params HttpConnectionParams setConnectionTimeout.

Prototype

public void setConnectionTimeout(int paramInt) 

Source Link

Usage

From source file:com.sittinglittleduck.DirBuster.EasySSLProtocolSocketFactoryUnitTest.java

@Test(expected = SocketTimeoutException.class)
@Ignore // TODO Won't work unless we figure out a way to slow down connect process artificially
public void shouldFailCreatingSocketWithInstantTimeout() throws Exception {
    // Given/*  w  w  w .j  a  v  a  2 s.c  o m*/
    HttpConnectionParams params = new HttpConnectionParams();
    params.setConnectionTimeout(1);
    // When
    socketFactory.createSocket("localhost", 18080, InetAddress.getLoopbackAddress(), 38080, params);
    // Then = SocketTimeoutException
}

From source file:com.sittinglittleduck.DirBuster.EasySSLProtocolSocketFactoryUnitTest.java

@Test
public void shouldSucceedCreatingSocketWithReasonableTimeout() throws Exception {
    // Given/*from ww  w .  j a  v  a2s. c om*/
    HttpConnectionParams params = new HttpConnectionParams();
    params.setConnectionTimeout(1000);
    // When
    Socket sslSocket = socketFactory.createSocket("localhost", 18080, InetAddress.getLoopbackAddress(), 48080,
            params);
    // Then
    assertThat(sslSocket, is(notNullValue()));
}

From source file:com.sittinglittleduck.DirBuster.EasySSLProtocolSocketFactoryUnitTest.java

@Test(expected = java.io.IOException.class)
public void shouldFailCreatingSocketForUnknownHost() throws Exception {
    // Given//w  w w  . jav  a2s .  c o m
    String unknownHost = "localhorst";
    InetAddress localAddress = InetAddress.getLoopbackAddress();
    int localPort = 28080;
    HttpConnectionParams params = new HttpConnectionParams();
    params.setConnectionTimeout(60000);
    // When
    socketFactory.createSocket(unknownHost, 18080, localAddress, localPort, params);
    // Then = IOException
}

From source file:de.ingrid.mdek.quartz.jobs.URLValidatorJob.java

@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {

    ExecutorService executorService = Executors.newFixedThreadPool(NUM_THREADS);
    JobDataMap mergedJobDataMap = jobExecutionContext.getMergedJobDataMap();
    Map<String, URLState> urlMap = (Map<String, URLState>) mergedJobDataMap.get(URL_MAP);
    List<URLValidator> validatorTasks = new ArrayList<URLValidator>(urlMap.size());

    Map<String, URLState> capabilitiesMap = (Map<String, URLState>) mergedJobDataMap.get(CAP_URL_MAP);
    List<CapabilitiesValidator> capabilitiesValidatorTasks = new ArrayList<CapabilitiesValidator>(
            capabilitiesMap.size());/*from   w  w  w  .  j ava 2 s  .  c  om*/

    HttpClientParams httpClientParams = new HttpClientParams();
    httpClientParams.setConnectionManagerTimeout(0);
    httpClientParams.setSoTimeout(SOCKET_TIMEOUT);
    HttpConnectionParams httpParams = new HttpConnectionParams();
    httpParams.setConnectionTimeout(CONNECTION_TIMEOUT);
    httpClientParams.setDefaults(httpParams);
    HttpClient httpClient = new HttpClient(httpClientParams, new MultiThreadedHttpConnectionManager());
    if (System.getProperty("http.proxyHost") != null && System.getProperty("http.proxyPort") != null) {
        httpClient.getHostConfiguration().setProxy(System.getProperty("http.proxyHost"),
                Integer.parseInt(System.getProperty("http.proxyPort")));
    }
    for (URLState urlState : urlMap.values()) {
        validatorTasks.add(new URLValidator(httpClient, urlState));
    }
    for (URLState urlState : capabilitiesMap.values()) {
        capabilitiesValidatorTasks.add(new CapabilitiesValidator(httpClient, urlState));
    }

    log.debug("Starting url validation...");
    long startTime = System.currentTimeMillis();
    List<Future<URLState>> resultFutureList = new ArrayList<Future<URLState>>();
    for (URLValidator validator : validatorTasks) {
        resultFutureList.add(executorService.submit(validator));
    }
    for (CapabilitiesValidator validator : capabilitiesValidatorTasks) {
        resultFutureList.add(executorService.submit(validator));
    }

    for (Future<URLState> future : resultFutureList) {
        try {
            if (!cancelJob) {
                future.get();

            } else {
                log.debug("forcing shutdown of executor service...");
                executorService.shutdownNow();
                break;
            }

        } catch (Exception ex) {
            log.debug("Exception while fetching result from future.", ex);
        }
    }
    long endTime = System.currentTimeMillis();
    log.debug("URL Validation took " + (endTime - startTime) + " ms.");

    executorService.shutdown();

    // Only store if job was not cancelled
    if (!cancelJob) {
        Map<String, List<URLObjectReference>> map = new HashMap<String, List<URLObjectReference>>();
        map.put(MdekKeys.URL_RESULT, (List<URLObjectReference>) mergedJobDataMap.get(URL_OBJECT_REFERENCES));
        map.put(MdekKeys.CAP_RESULT, (List<URLObjectReference>) mergedJobDataMap.get(CAPABILITIES_REFERENCES));
        jobExecutionContext.setResult(map);
    }
}

From source file:edu.internet2.middleware.shibboleth.idp.profile.saml2.SLOProfileHandler.java

/**
 * Creates Http connection.//from ww w  .  j a va  2s  .c om
 *
 * @param serviceLogoutInfo
 * @param endpoint
 * @return
 * @throws URIException
 * @throws GeneralSecurityException
 * @throws IOException
 */
private HttpConnection createHttpConnection(LogoutInformation serviceLogoutInfo, Endpoint endpoint)
        throws URIException, GeneralSecurityException, IOException {

    HttpClientBuilder httpClientBuilder = new HttpClientBuilder();
    httpClientBuilder.setContentCharSet("UTF-8");
    SecureProtocolSocketFactory sf = new EasySSLProtocolSocketFactory();
    httpClientBuilder.setHttpsProtocolSocketFactory(sf);

    //build http connection
    HttpClient httpClient = httpClientBuilder.buildClient();

    HostConfiguration hostConfig = new HostConfiguration();
    URI location = new URI(endpoint.getLocation());
    hostConfig.setHost(location);

    LogoutRequestConfiguration config = (LogoutRequestConfiguration) getProfileConfiguration(
            serviceLogoutInfo.getEntityID(), getProfileId());
    if (log.isDebugEnabled()) {
        log.debug("Creating new HTTP connection with the following timeouts:");
        log.debug("Maximum waiting time for the connection pool is {}",
                config.getBackChannelConnectionPoolTimeout());
        log.debug("Timeout for connection establishment is {}", config.getBackChannelConnectionTimeout());
        log.debug("Timeout for soap response is {}", config.getBackChannelResponseTimeout());
    }
    HttpConnection httpConn = null;
    try {
        httpConn = httpClient.getHttpConnectionManager().getConnectionWithTimeout(hostConfig,
                config.getBackChannelConnectionPoolTimeout());
    } catch (ConnectionPoolTimeoutException e) {
        return null;
    }

    HttpConnectionParams params = new HttpConnectionParams();
    params.setConnectionTimeout(config.getBackChannelConnectionTimeout());
    params.setSoTimeout(config.getBackChannelResponseTimeout());
    httpConn.setParams(params);

    return httpConn;
}

From source file:org.eclipse.mylyn.commons.tests.net.SslProtocolSocketFactoryTest.java

public void testTrustAllSslProtocolSocketFactory() throws Exception {
    SecureProtocolSocketFactory factory = new PollingSslProtocolSocketFactory();
    Socket s;//from   w  w w . j a va  2s.co  m

    s = factory.createSocket(proxyAddress.getHostName(), proxyAddress.getPort());
    assertNotNull(s);
    assertTrue(s.isConnected());
    s.close();

    InetAddress anyHost = new Socket().getLocalAddress();

    s = factory.createSocket(proxyAddress.getHostName(), proxyAddress.getPort(), anyHost, 0);
    assertNotNull(s);
    assertTrue(s.isConnected());
    s.close();

    HttpConnectionParams params = new HttpConnectionParams();
    s = factory.createSocket(proxyAddress.getHostName(), proxyAddress.getPort(), anyHost, 0, params);
    assertNotNull(s);
    assertTrue(s.isConnected());
    s.close();

    params.setConnectionTimeout(1000);
    s = factory.createSocket(proxyAddress.getHostName(), proxyAddress.getPort(), anyHost, 0, params);
    assertNotNull(s);
    assertTrue(s.isConnected());
    s.close();
}

From source file:org.olat.core.util.httpclient.HttpClientFactory.java

/**
 * A HttpClient with basic authentication and no host or port setting. Can only be used to retrieve absolute URLs
 * /*www .  j av  a 2 s  . c o m*/
 * @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;
}

From source file:org.opencms.applet.upload.FileUploadApplet.java

/**
 * Checks if the given client files exist on the server and internally stores duplications.<p>
 * /*  w  ww.  j av a2 s  .  co  m*/
 * Comparison is made by cutting the current directory of the file chooser from the path of the given files. 
 * The server files (VFS files) to compare to are found by the current session of the user which finds the correct site and 
 * the knowledge about the current directory. File translation rules are taken into account on the server. <p>
 * 
 * @param files the local files to check if they exist in the VFS 
 * 
 * @return one of {@link ModalDialog#ERROR_OPTION} , {@link ModalDialog#CANCEL_OPTION}, {@link ModalDialog#APPROVE_OPTION}. 
 */
int checkServerOverwrites(File[] files) {

    m_action = m_actionOverwriteCheck;
    repaint();
    int rtv = ModalDialog.ERROR_OPTION;
    // collect files
    List fileNames = new ArrayList();
    for (int i = 0; i < files.length; i++) {
        getRelativeFilePaths(files[i], fileNames);
    }

    StringBuffer uploadFiles = new StringBuffer();
    Iterator it = fileNames.iterator();
    // Http post header is limited, therefore only a ceratain amount of files may be checked 
    // for server overwrites. Solution is: multiple requests. 
    int count = 0;
    List duplications;
    // request to server
    HttpClient client = new HttpClient();
    this.m_overwrites = new ArrayList();
    try {
        while (it.hasNext()) {
            count++;
            uploadFiles.append(((String) it.next())).append('\n');

            if (((count % 40) == 0) || (!it.hasNext())) {
                // files to upload:
                PostMethod post = new PostMethod(m_targetUrl);
                Header postHeader = new Header("uploadFiles",
                        URLEncoder.encode(uploadFiles.toString(), "utf-8"));
                post.addRequestHeader(postHeader);
                // upload folder in vfs: 
                Header header2 = new Header("uploadFolder",
                        URLEncoder.encode(getParameter("filelist"), "utf-8"));
                post.addRequestHeader(header2);

                // the action constant
                post.setParameter("action", DIALOG_CHECK_OVERWRITE);

                // add jsessionid query string
                String sessionId = getParameter("sessionId");
                String query = ";" + C_JSESSIONID.toLowerCase() + "=" + sessionId;
                post.setQueryString(query);
                post.addRequestHeader(C_JSESSIONID, sessionId);

                HttpConnectionParams connectionParams = client.getHttpConnectionManager().getParams();
                connectionParams.setConnectionTimeout(5000);

                // add the session cookie
                client.getState();
                client.getHostConfiguration().getHost();

                HttpState initialState = new HttpState();
                URI uri = new URI(m_targetUrl, false);
                Cookie sessionCookie = new Cookie(uri.getHost(), C_JSESSIONID, sessionId, "/", null, false);
                initialState.addCookie(sessionCookie);
                client.setState(initialState);
                int status = client.executeMethod(post);

                if (status == HttpStatus.SC_OK) {
                    String response = post.getResponseBodyAsString();
                    duplications = parseDuplicateFiles(URLDecoder.decode(response, "utf-8"));
                    this.m_overwrites.addAll(duplications);

                } else {
                    // continue without overwrite check 
                    String error = m_errorLine1 + "\n" + post.getStatusLine();
                    System.err.println(error);
                }

                count = 0;
                uploadFiles = new StringBuffer();
            }

        }
        if (m_overwrites.size() > 0) {
            rtv = showDuplicationsDialog(m_overwrites);
        } else {
            rtv = ModalDialog.APPROVE_OPTION;
        }

    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace(System.err);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace(System.err);
    }

    return rtv;
}

From source file:org.opencms.applet.upload.FileUploadApplet.java

/**
 * Uploads the zipfile to the OpenCms.<p>
 * /*  ww w .j  a v  a 2s .  c o m*/
 * @param uploadFile the zipfile to upload
 */
private void uploadZipFile(File uploadFile) {

    m_action = m_actionOutputUpload;
    repaint();

    PostMethod post = new PostMethod(m_targetUrl);

    try {
        Part[] parts = new Part[5];
        parts[0] = new FilePart(uploadFile.getName(), uploadFile);
        parts[1] = new StringPart("action", "submitform");
        parts[2] = new StringPart("unzipfile", "true");
        parts[3] = new StringPart("uploadfolder", m_uploadFolder);
        parts[4] = new StringPart("clientfolder", m_fileSelector.getCurrentDirectory().getAbsolutePath());

        HttpMethodParams methodParams = post.getParams();
        methodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        MultipartRequestEntity request = new MultipartRequestEntity(parts, methodParams);
        post.setRequestEntity(request);

        // add jsessionid query string
        String sessionId = getParameter("sessionId");
        String query = ";" + C_JSESSIONID.toLowerCase() + "=" + sessionId;
        post.setQueryString(query);
        post.addRequestHeader(C_JSESSIONID, sessionId);

        HttpClient client = new HttpClient();
        HttpConnectionParams connectionParams = client.getHttpConnectionManager().getParams();
        connectionParams.setConnectionTimeout(5000);

        // add the session cookie
        client.getState();
        client.getHostConfiguration().getHost();

        HttpState initialState = new HttpState();
        URI uri = new URI(m_targetUrl, false);
        Cookie sessionCookie = new Cookie(uri.getHost(), C_JSESSIONID, sessionId, "/", null, false);
        initialState.addCookie(sessionCookie);
        client.setState(initialState);

        // no execute the file upload
        int status = client.executeMethod(post);

        if (status == HttpStatus.SC_OK) {
            //return to the specified url and frame target
            getAppletContext().showDocument(new URL(m_redirectUrl), m_redirectTargetFrame);
        } else {
            // create the error text
            String error = m_errorLine1 + "\n" + post.getStatusLine();
            //JOptionPane.showMessageDialog(this, error, "Error!", JOptionPane.ERROR_MESSAGE);
            getAppletContext().showDocument(new URL(m_errorUrl + "?action=showerror&uploaderror=" + error),
                    "explorer_files");
        }
    } catch (RuntimeException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        post.releaseConnection();
        // finally delete the zipFile on the harddisc
        uploadFile.delete();
    }
}

From source file:org.openo.nfvo.vnfmadapter.service.csm.connect.SslCertificateSocketTest.java

@Test
public void createSocketTest3() {
    SslCertificateSocket socket = new SslCertificateSocket();
    try {/*from  ww w . ja  v a 2  s. c  o  m*/
        HttpConnectionParams params = new HttpConnectionParams();
        params.setConnectionTimeout(0);
        socket.createSocket("http://127.0.0.1", 1234, null, 4321, params);
    } catch (IOException e) {
        e.printStackTrace();
    }
}