Example usage for org.apache.http.protocol BasicHttpContext BasicHttpContext

List of usage examples for org.apache.http.protocol BasicHttpContext BasicHttpContext

Introduction

In this page you can find the example usage for org.apache.http.protocol BasicHttpContext BasicHttpContext.

Prototype

public BasicHttpContext() 

Source Link

Usage

From source file:org.muckebox.android.net.DownloadServer.java

private void initHttpServer() {
    mHttpProcessor = new BasicHttpProcessor();
    mHttpContext = new BasicHttpContext();
    mHttpService = new HttpService(mHttpProcessor, new DefaultConnectionReuseStrategy(),
            new DefaultHttpResponseFactory());

    mHttpProcessor.addInterceptor(new ResponseContent());
    mHttpProcessor.addInterceptor(new ResponseConnControl());

    mRegistry = new HttpRequestHandlerRegistry();

    mRegistry.register("*", new FileHandler());

    mHttpService.setHandlerResolver(mRegistry);
}

From source file:com.kolich.http.common.HttpClient4ClosureBase.java

public final T request(final HttpRequestBase request, final HttpContext context) {
    return doit(request, (context == null) ? new BasicHttpContext() : context);
}

From source file:at.ac.tuwien.big.testsuite.impl.validator.WaiValidator.java

@Override
public ValidationResult validate(File fileToValidate, String exerciseId) throws Exception {
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    HttpPost request = new HttpPost("http://localhost:8080/" + contextPath + "/checker/index.php");
    List<ValidationResultEntry> validationResultEntries = new ArrayList<>();

    try {//from   www.  j a v a  2  s.co m
        MultipartEntity multipartEntity = new MultipartEntity();
        multipartEntity.addPart("uri", new StringBody(""));
        multipartEntity.addPart("MAX_FILE_SIZE", new StringBody("52428800"));
        multipartEntity.addPart("uploadfile", new FileBody(fileToValidate, "text/html"));
        multipartEntity.addPart("validate_file", new StringBody("Check It"));
        multipartEntity.addPart("pastehtml", new StringBody(""));
        multipartEntity.addPart("radio_gid[]", new StringBody("8"));
        multipartEntity.addPart("checkbox_gid[]", new StringBody("8"));
        multipartEntity.addPart("rpt_format", new StringBody("1"));

        request.setEntity(multipartEntity);
        Document doc = httpClient.execute(request, new DomResponseHandler(httpClient, request), httpContext);
        Element errorsContainer = DomUtils.byId(doc.getDocumentElement(), "AC_errors");

        String title = "";
        StringBuilder descriptionSb = new StringBuilder();
        boolean descriptionStarted = false;

        for (Element e : DomUtils.asList(errorsContainer.getChildNodes())) {
            if ("h3".equals(e.getTagName())) {
                if (descriptionStarted) {
                    validationResultEntries.add(new DefaultValidationResultEntry(title,
                            descriptionSb.toString(), ValidationResultEntryType.ERROR));
                }

                title = e.getTextContent();
                descriptionSb.setLength(0);
                descriptionStarted = false;
            } else if ("div".equals(e.getTagName()) && e.getAttribute("class").contains("gd_one_check")) {
                if (descriptionStarted) {
                    descriptionSb.append('\n');
                }

                if (extractDescription(e, descriptionSb)) {
                    descriptionStarted = true;
                }
            }
        }

        if (descriptionStarted) {
            validationResultEntries.add(new DefaultValidationResultEntry(title, descriptionSb.toString(),
                    ValidationResultEntryType.ERROR));
        }
    } finally {
        request.releaseConnection();
    }

    return new DefaultValidationResult("WAI Validation", fileToValidate.getName(),
            new DefaultValidationResultType("WAI"), validationResultEntries);
}

From source file:org.wso2.carbon.apimgt.impl.publishers.WSO2APIPublisher.java

@Override
public boolean deleteFromStore(APIIdentifier apiId, APIStore store) throws APIManagementException {
    boolean deleted = false;
    if (store.getEndpoint() == null || store.getUsername() == null || store.getPassword() == null) {
        String msg = "External APIStore endpoint URL or credentials are not defined. "
                + "Cannot proceed with publishing API to the APIStore - " + store.getDisplayName();
        throw new APIManagementException(msg);
    } else {/*from   w w w . j a v  a  2 s. c  o  m*/
        CookieStore cookieStore = new BasicCookieStore();
        HttpContext httpContext = new BasicHttpContext();
        httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        boolean authenticated = authenticateAPIM(store, httpContext);
        if (authenticated) {
            deleted = deleteWSO2Store(apiId, store.getUsername(), store.getEndpoint(), httpContext,
                    store.getDisplayName());
            logoutFromExternalStore(store, httpContext);
        }
        return deleted;
    }
}

From source file:gsn.http.rest.RestRemoteWrapper.java

public DataField[] connectToRemote() throws IOException, ClassNotFoundException {
    // Create the GET request
    HttpGet httpget = new HttpGet(initParams.getRemoteContactPointEncoded(lastReceivedTimestamp));
    // Create local execution context
    HttpContext localContext = new BasicHttpContext();
    ///*from  w  w w  .jav  a 2s  . c om*/
    structure = null;
    int tries = 0;
    AuthState authState = null;
    //
    if (inputStream != null) {
        try {
            if (response != null && response.getEntity() != null) {
                response.getEntity().consumeContent();
            }
            inputStream.close();
            inputStream = null;
        } catch (Exception e) {
            logger.debug(e.getMessage(), e);
        }
    }
    //
    while (tries < 2) {
        tries++;
        try {
            // Execute the GET request
            response = httpclient.execute(httpget, localContext);
            //
            int sc = response.getStatusLine().getStatusCode();
            //
            if (sc == HttpStatus.SC_OK) {
                logger.debug(new StringBuilder().append("Wants to consume the structure packet from ")
                        .append(initParams.getRemoteContactPoint()).toString());
                inputStream = XSTREAM.createObjectInputStream(response.getEntity().getContent());
                structure = (DataField[]) inputStream.readObject();
                logger.warn("Connection established for: " + initParams.getRemoteContactPoint());
                break;
            } else {
                if (sc == HttpStatus.SC_UNAUTHORIZED)
                    authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); // Target host authentication required
                else if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED)
                    authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); // Proxy authentication required
                else {
                    logger.error(new StringBuilder().append("Unexpected GET status code returned: ").append(sc)
                            .append("\nreason: ").append(response.getStatusLine().getReasonPhrase())
                            .toString());
                }
                if (authState != null) {
                    if (initParams.getUsername() == null || (tries > 1 && initParams.getUsername() != null)) {
                        logger.error("A valid username/password required to connect to the remote host: "
                                + initParams.getRemoteContactPoint());
                    } else {

                        AuthScope authScope = authState.getAuthScope();
                        logger.warn(new StringBuilder().append("Setting Credentials for host: ")
                                .append(authScope.getHost()).append(":").append(authScope.getPort())
                                .toString());
                        Credentials creds = new UsernamePasswordCredentials(initParams.getUsername(),
                                initParams.getPassword());
                        httpclient.getCredentialsProvider().setCredentials(authScope, creds);
                    }
                }
            }
        } catch (RuntimeException ex) {
            // In case of an unexpected exception you may want to abort
            // the HTTP request in order to shut down the underlying
            // connection and release it back to the connection manager.
            logger.warn("Aborting the HTTP GET request.");
            httpget.abort();
            throw ex;
        } finally {
            if (structure == null) {
                if (response != null && response.getEntity() != null) {
                    response.getEntity().consumeContent();
                }
            }
        }
    }

    if (structure == null)
        throw new RuntimeException("Cannot connect to the remote host: " + initParams.getRemoteContactPoint());

    return structure;
}

From source file:com.ryan.ryanreader.cache.CacheDownload.java

private void downloadPost(final HttpClient httpClient) {

    final HttpPost httpPost = new HttpPost(initiator.url);

    try {/*  w  w w .  ja  v a2  s .  c o m*/
        httpPost.setEntity(new UrlEncodedFormEntity(initiator.postFields, HTTP.UTF_8));
    } catch (UnsupportedEncodingException e) {
        BugReportActivity.handleGlobalError(initiator.context, e);
        return;
    }

    final HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, initiator.getCookies());

    final HttpResponse response;
    final StatusLine status;

    try {
        response = httpClient.execute(httpPost, localContext);
        status = response.getStatusLine();

    } catch (Throwable t) {
        t.printStackTrace();
        notifyAllOnFailure(RequestFailureType.CONNECTION, t, null, "Unable to open a connection");
        return;
    }

    if (status.getStatusCode() != 200) {
        notifyAllOnFailure(RequestFailureType.REQUEST, null, status,
                String.format("HTTP error %d (%s)", status.getStatusCode(), status.getReasonPhrase()));
        return;
    }

    final HttpEntity entity = response.getEntity();

    if (entity == null) {
        notifyAllOnFailure(RequestFailureType.CONNECTION, null, status,
                "Did not receive a valid HTTP response");
        return;
    }

    final InputStream is;

    try {
        is = entity.getContent();
    } catch (Throwable t) {
        t.printStackTrace();
        notifyAllOnFailure(RequestFailureType.CONNECTION, t, status, "Could not open an input stream");
        return;
    }

    if (initiator.isJson) {

        final BufferedInputStream bis = new BufferedInputStream(is, 8 * 1024);

        final JsonValue value;

        try {
            value = new JsonValue(bis);
            value.buildInNewThread();

        } catch (Throwable t) {
            t.printStackTrace();
            notifyAllOnFailure(RequestFailureType.PARSE, t, null, "Error parsing the JSON stream");
            return;
        }

        synchronized (this) {
            this.value = value;
            notifyAllOnJsonParseStarted(value, RRTime.utcCurrentTimeMillis(), session);
        }

        try {
            value.join();

        } catch (Throwable t) {
            t.printStackTrace();
            notifyAllOnFailure(RequestFailureType.PARSE, t, null, "Error parsing the JSON stream");
            return;
        }

        success = true;

    } else {
        throw new RuntimeException("POST requests must be for JSON values");
    }

}

From source file:org.callimachusproject.client.HttpClientFactoryTest.java

@Test
public void testTargetHost() throws Exception {
    HttpContext localContext = new BasicHttpContext();
    responses.add(new BasicHttpResponse(_200));
    client.execute(new HttpGet("http://example.com/200"), new ResponseHandler<Void>() {
        public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode());
            return null;
        }/*from www .  ja va 2  s . co  m*/
    }, localContext);
    HttpHost host = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    assertEquals(ORIGIN, host.toString());
}

From source file:com.lazerycode.selenium.filedownloader.FileDownloader.java

/**
 * Perform the file/image download./*  w w w.  ja  v  a2s .c o  m*/
 *
 * @param element
 * @param attribute
 * @return
 * @throws IOException
 * @throws NullPointerException
 */
private String downloader(WebElement element, String attribute, String Filename)
        throws IOException, NullPointerException, URISyntaxException {
    String fileToDownloadLocation = element.getAttribute(attribute);
    if (fileToDownloadLocation.trim().equals(""))
        throw new NullPointerException("The element you have specified does not link to anything!");

    URL fileToDownload = new URL(fileToDownloadLocation);
    //changed by Raul
    File downloadedFile = new File(Filename);
    //+ " fileToDownload.getFile().replaceFirst("/|\\\\", "").replace("?", ""));

    if (downloadedFile.canWrite() == false)
        downloadedFile.setWritable(true);

    HttpClient client = new DefaultHttpClient();
    BasicHttpContext localContext = new BasicHttpContext();

    //LOG.info("Mimic WebDriver cookie state: " + this.mimicWebDriverCookieState);
    if (this.mimicWebDriverCookieState) {
        localContext.setAttribute(ClientContext.COOKIE_STORE,
                mimicCookieState(this.driver.manage().getCookies()));
    }

    HttpGet httpget = new HttpGet(fileToDownload.toURI());
    HttpParams httpRequestParameters = httpget.getParams();
    httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, this.followRedirects);
    httpget.setParams(httpRequestParameters);

    // LOG.info("Sending GET request for: " + httpget.getURI());
    HttpResponse response = client.execute(httpget, localContext);
    this.httpStatusOfLastDownloadAttempt = response.getStatusLine().getStatusCode();
    //LOG.info("HTTP GET request status: " + this.httpStatusOfLastDownloadAttempt);
    //LOG.info("Downloading file: " + downloadedFile.getName());
    FileUtils.copyInputStreamToFile(response.getEntity().getContent(), downloadedFile);
    response.getEntity().getContent().close();

    String downloadedFileAbsolutePath = downloadedFile.getAbsolutePath();
    // LOG.info("File downloaded to '" + downloadedFileAbsolutePath + "'");

    return downloadedFileAbsolutePath;
}

From source file:org.apache.geode.tools.pulse.PulseDataExportTest.java

private HttpContext buildAuthenticatedHttpContext() throws Throwable {
    HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

    return localContext;
}

From source file:com.lurencun.cfuture09.androidkit.http.async.AsyncHttp.java

public AsyncHttp() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams, Version.ANDROIDKIT_NAME);

    // ??//www.j a  v  a 2 s  .c  o m
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }

            for (Entry<String, String> entry : clientHeaderMap.entrySet()) {
                request.addHeader(entry.getKey(), entry.getValue());
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool(new AKThreadFactory());

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
}