Example usage for org.apache.http.protocol HttpContext setAttribute

List of usage examples for org.apache.http.protocol HttpContext setAttribute

Introduction

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

Prototype

void setAttribute(String str, Object obj);

Source Link

Usage

From source file:org.wso2.carbon.governance.registry.extensions.executors.APIDeleteExecutor.java

/**
 * Deletes API from the API Manager//  w  w  w. j  a  v  a2 s .c  om
 *
 * @param api API Generic artifact.
 * @return    True if successfully deleted.
 */
private boolean deleteFromAPIManager(GenericArtifact api) throws RegistryException {
    if (apimEndpoint == null || apimUsername == null || apimPassword == null) {
        throw new RuntimeException(ExecutorConstants.APIM_LOGIN_UNDEFINED);
    }

    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    Utils.authenticateAPIM(httpContext, apimEndpoint, apimUsername, apimPassword);
    String removeEndpoint = apimEndpoint + ExecutorConstants.APIM_REMOVE_URL;

    try {
        // create a post request to addAPI.
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(removeEndpoint);

        // Request parameters and other properties.
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair(ExecutorConstants.API_ACTION, ExecutorConstants.API_REMOVE_ACTION));
        params.add(new BasicNameValuePair(ExecutorConstants.API_NAME,
                api.getAttribute(ExecutorConstants.SERVICE_NAME)));
        params.add(new BasicNameValuePair(ExecutorConstants.API_PROVIDER, apimUsername));
        params.add(new BasicNameValuePair(ExecutorConstants.API_VERSION,
                api.getAttribute(ExecutorConstants.SERVICE_VERSION)));

        httppost.setEntity(new UrlEncodedFormEntity(params, ExecutorConstants.DEFAULT_CHAR_ENCODING));

        HttpResponse response = httpclient.execute(httppost, httpContext);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

    } catch (ClientProtocolException e) {
        throw new RegistryException(ExecutorConstants.APIM_POST_REQ_FAIL, e);
    } catch (UnsupportedEncodingException e) {
        throw new RegistryException(ExecutorConstants.ENCODING_FAIL, e);
    } catch (IOException e) {
        throw new RegistryException(ExecutorConstants.APIM_POST_REQ_FAIL, e);
    }

    return true;
}

From source file:org.jasig.portlet.proxy.service.web.RedirectTrackingResponseInterceptor.java

@Override
public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
    if (response.containsHeader("Location")) {
        Header[] locations = response.getHeaders("Location");
        if (locations.length > 0) {
            context.setAttribute(FINAL_URL_KEY, locations[0].getValue());
        }/*ww  w.  ja  va 2  s.c  o  m*/
    }
}

From source file:onl.area51.httpd.service.RequestScopeHandler.java

@Override
public void begin(HttpRequest req, HttpContext ctx) throws HttpException, IOException {
    Map<String, Object> dataStore = (Map<String, Object>) ctx.getAttribute(ATTR);
    if (dataStore == null) {
        dataStore = new HashMap<>();
        ctx.setAttribute(ATTR, dataStore);
        requestContext.associate(dataStore);
        requestContext.activate();/*from   w w  w .j a  va 2  s .  c  o  m*/
    }
}

From source file:org.sonatype.nexus.httpclient.NexusRedirectStrategyTest.java

@Test
public void doNotFollowRedirectsToDirIndex() throws ProtocolException {
    when(response.getStatusLine()).thenReturn(statusLine);

    final RedirectStrategy underTest = new NexusRedirectStrategy();
    HttpContext httpContext;

    // no location header
    request = new HttpGet("http://localhost/dir/fileA");
    httpContext = new BasicHttpContext();
    httpContext.setAttribute(NexusRedirectStrategy.CONTENT_RETRIEVAL_MARKER_KEY, Boolean.TRUE);
    when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_OK);
    assertThat(underTest.isRedirected(request, response, httpContext), is(false));

    // redirect to file
    request = new HttpGet("http://localhost/dir/fileA");
    httpContext = new BasicHttpContext();
    httpContext.setAttribute(NexusRedirectStrategy.CONTENT_RETRIEVAL_MARKER_KEY, Boolean.TRUE);
    when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_MOVED_TEMPORARILY);
    when(response.getFirstHeader("location"))
            .thenReturn(new BasicHeader("location", "http://localhost/dir/fileB"));
    assertThat(underTest.isRedirected(request, response, httpContext), is(true));

    // redirect to dir
    request = new HttpGet("http://localhost/dir");
    httpContext = new BasicHttpContext();
    httpContext.setAttribute(NexusRedirectStrategy.CONTENT_RETRIEVAL_MARKER_KEY, Boolean.TRUE);
    when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_MOVED_TEMPORARILY);
    when(response.getFirstHeader("location")).thenReturn(new BasicHeader("location", "http://localhost/dir/"));
    assertThat(underTest.isRedirected(request, response, httpContext), is(false));
}

From source file:guru.nidi.ramltester.httpcomponents.RamlHttpClient.java

private boolean alreadyTested(HttpContext context) {
    if (context.getAttribute(RAML_TESTED) != null) {
        return true;
    }/*from  w  ww .  j a  v a2s  .  com*/
    context.setAttribute(RAML_TESTED, true);
    return false;
}

From source file:org.exoplatform.social.client.core.net.SocialHttpClientImpl.java

private SocialHttpClientImpl(ClientConnectionManager ccm, HttpParams params) {
    //delegate = new DefaultHttpClient(ccm, params);

    delegate = new DefaultHttpClient(ccm, params) {

        @Override//w  w  w. java2s .  c o  m
        protected BasicHttpProcessor createHttpProcessor() {
            // Add interceptor to prevent making requests from main thread.
            BasicHttpProcessor processor = super.createHttpProcessor();
            return processor;
        }

        @Override
        protected HttpContext createHttpContext() {
            // Same as DefaultHttpClient.createHttpContext() minus the
            // cookie store.
            HttpContext context = new BasicHttpContext();
            context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, getAuthSchemes());
            context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, getCookieSpecs());
            context.setAttribute(ClientContext.CREDS_PROVIDER, getCredentialsProvider());
            return context;
        }
    };

}

From source file:org.sonatype.nexus.httpclient.internal.NexusRedirectStrategyTest.java

@Test
public void doNotFollowRedirectsToDirIndex() throws Exception {
    when(response.getStatusLine()).thenReturn(statusLine);

    final RedirectStrategy underTest = new NexusRedirectStrategy();
    HttpContext httpContext;

    // no location header
    request = new HttpGet("http://localhost/dir/fileA");
    httpContext = new BasicHttpContext();
    httpContext.setAttribute(CONTENT_RETRIEVAL_MARKER_KEY, Boolean.TRUE);
    when(statusLine.getStatusCode()).thenReturn(SC_OK);
    assertThat(underTest.isRedirected(request, response, httpContext), is(false));

    // redirect to file
    request = new HttpGet("http://localhost/dir/fileA");
    httpContext = new BasicHttpContext();
    httpContext.setAttribute(CONTENT_RETRIEVAL_MARKER_KEY, Boolean.TRUE);
    when(statusLine.getStatusCode()).thenReturn(SC_MOVED_TEMPORARILY);
    when(response.getFirstHeader(argThat(equalToIgnoringCase(LOCATION))))
            .thenReturn(new BasicHeader(LOCATION, "http://localhost/dir/fileB"));
    assertThat(underTest.isRedirected(request, response, httpContext), is(true));

    // redirect to dir
    request = new HttpGet("http://localhost/dir");
    httpContext = new BasicHttpContext();
    httpContext.setAttribute(CONTENT_RETRIEVAL_MARKER_KEY, Boolean.TRUE);
    when(statusLine.getStatusCode()).thenReturn(SC_MOVED_TEMPORARILY);
    when(response.getFirstHeader(argThat(equalToIgnoringCase(LOCATION))))
            .thenReturn(new BasicHeader(LOCATION, "http://localhost/dir/"));
    assertThat(underTest.isRedirected(request, response, httpContext), is(false));
}

From source file:org.pepstock.jem.node.https.Worker.java

@Override
public void run() {
    // creates a custom context
    HttpContext context = new BasicHttpContext(null);
    // adds the IP address of the client
    // necessary when the job ends and client is waiting the end of the job
    context.setAttribute(SubmitHandler.JOB_SUBMIT_IP_ADDRESS_KEY, clientAddress.getHostAddress());
    try {//from ww w . ja  va 2s  .com
        // till connection is open
        while (!Thread.interrupted() && httpConnection.isOpen()) {
            // starts the HTTP request
            httpService.handleRequest(httpConnection, context);
        }
    } catch (ConnectionClosedException ex) {
        // client close the connection
        LogAppl.getInstance().ignore(ex.getMessage(), ex);
        LogAppl.getInstance().emit(NodeMessage.JEMC023E,
                "Client closed connection (" + clientAddress.getHostAddress() + ")");
    } catch (IOException ex) {
        // any I/O error
        LogAppl.getInstance().ignore(ex.getMessage(), ex);
        LogAppl.getInstance().emit(NodeMessage.JEMC023E, "I/O error (" + clientAddress.getHostAddress() + ")");
    } catch (HttpException ex) {
        // Protocol exception
        LogAppl.getInstance().ignore(ex.getMessage(), ex);
        LogAppl.getInstance().emit(NodeMessage.JEMC023E,
                "Unrecoverable HTTP protocol violation (" + clientAddress.getHostAddress() + ")");
    } finally {
        // ALWAYS close connection
        try {
            httpConnection.shutdown();
        } catch (IOException e) {
            LogAppl.getInstance().ignore(e.getMessage(), e);
        }
    }
}

From source file:org.sonatype.nexus.repository.httpclient.HttpClientFactoryImpl.java

private void applyConfiguration(final Builder builder, final HttpClientConfig config) {
    // connection/socket timeouts
    int timeout = 1000;
    if (config.getConnection() != null && config.getConnection().getTimeout() != null) {
        timeout = config.getConnection().getTimeout();
    }//  ww  w.j  a v a2s  .com
    builder.getSocketConfigBuilder().setSoTimeout(timeout);
    builder.getRequestConfigBuilder().setConnectTimeout(timeout);
    builder.getRequestConfigBuilder().setSocketTimeout(timeout);

    // obey the given retries count and apply it to client.
    int retries = 0;
    if (config.getConnection() != null && config.getConnection().getRetries() != null) {
        retries = config.getConnection().getRetries();
    }
    builder.getHttpClientBuilder().setRetryHandler(new StandardHttpRequestRetryHandler(retries, false));

    applyAuthenticationConfig(builder, config.getAuthentication(), null);
    applyProxyConfig(builder, config);

    // Apply optional context-specific user-agent suffix
    if (config.getConnection() != null) {
        String userAgentSuffix = config.getConnection().getUserAgentCustomisation();
        String customizedUserAgent = null;
        if (!Strings.nullToEmpty(userAgentSuffix).isEmpty()) {
            customizedUserAgent = builder.getUserAgent() + " " + userAgentSuffix;
            builder.setUserAgent(customizedUserAgent);
        }
        String urlParameters = config.getConnection().getUrlParameters();
        if (Strings.nullToEmpty(urlParameters).isEmpty()) {
            urlParameters = null;
        }
        applyRequestExecutor(builder, customizedUserAgent, urlParameters);
    }
    if (config.getConnection() != null && Boolean.TRUE.equals(config.getConnection().getUseTrustStore())) {
        builder.getHttpClientBuilder().addInterceptorFirst(new HttpRequestInterceptor() {
            @Override
            public void process(final HttpRequest request, final HttpContext context) {
                context.setAttribute(SSLContextSelector.USE_TRUST_STORE, Boolean.TRUE);
            }
        });
    }
}

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 {//w w  w  .  j av a  2 s. c  o 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);
}