List of usage examples for org.apache.http.protocol HttpContext setAttribute
void setAttribute(String str, Object obj);
From source file:org.sonatype.nexus.proxy.storage.remote.httpclient.HttpClientManagerTest.java
@Test public void doNotFollowRedirectsToDirIndex() throws ProtocolException { final RedirectStrategy underTest = httpClientManager.getProxyRepositoryRedirectStrategy(proxyRepository, globalRemoteStorageContext); HttpContext httpContext; // no location header request = new HttpGet("http://localhost/dir/fileA"); httpContext = new BasicHttpContext(); httpContext.setAttribute(HttpClientRemoteStorage.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(HttpClientRemoteStorage.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(HttpClientRemoteStorage.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:de.vanita5.twittnuker.util.net.TwidereHttpClientImpl.java
@Override public twitter4j.http.HttpResponse request(final twitter4j.http.HttpRequest req) throws TwitterException { final HostAddressResolver resolver = FactoryUtils.getHostAddressResolver(conf); final String urlString = req.getURL(); final URI urlOrig = ParseUtils.parseURI(urlString); final String host = urlOrig.getHost(), authority = urlOrig.getAuthority(); try {/* w w w . ja v a 2s . co m*/ HttpRequestBaseHC4 commonsRequest; final String resolvedHost = resolver != null ? resolver.resolve(host) : null; final String resolvedUrl = !isEmpty(resolvedHost) ? urlString.replace("://" + host, "://" + resolvedHost) : urlString; final RequestMethod method = req.getMethod(); if (method == RequestMethod.GET) { commonsRequest = new HttpGetHC4(resolvedUrl); } else if (method == RequestMethod.POST) { final HttpPostHC4 post = new HttpPostHC4(resolvedUrl); post.setEntity(getAsEntity(req.getParameters())); post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); commonsRequest = post; } else if (method == RequestMethod.DELETE) { commonsRequest = new HttpDeleteHC4(resolvedUrl); } else if (method == RequestMethod.HEAD) { commonsRequest = new HttpHeadHC4(resolvedUrl); } else if (method == RequestMethod.PUT) { final HttpPutHC4 put = new HttpPutHC4(resolvedUrl); put.setEntity(getAsEntity(req.getParameters())); commonsRequest = put; } else throw new TwitterException("Unsupported request method " + method); final HttpParams httpParams = commonsRequest.getParams(); HttpClientParams.setRedirecting(httpParams, false); final Map<String, String> headers = req.getRequestHeaders(); for (final String headerName : headers.keySet()) { commonsRequest.addHeader(headerName, headers.get(headerName)); } final Authorization authorization = req.getAuthorization(); final String authorizationHeader = authorization != null ? authorization.getAuthorizationHeader(req) : null; if (authorizationHeader != null) { commonsRequest.addHeader(HttpHeaders.AUTHORIZATION, authorizationHeader); } if (resolvedHost != null && !resolvedHost.isEmpty() && !resolvedHost.equals(host)) { commonsRequest.addHeader(HttpHeaders.HOST, authority); } final ApacheHttpClientHttpResponseImpl res; try { final HttpContext httpContext = new BasicHttpContextHC4(); httpContext.setAttribute(HostResolvedSSLConnectionSocketFactory.HTTP_CONTEXT_KEY_ORIGINAL_HOST, host); res = new ApacheHttpClientHttpResponseImpl(client.execute(commonsRequest, httpContext), conf); } catch (final IllegalStateException e) { throw new TwitterException("Please check your API settings.", e); } catch (final NullPointerException e) { // Bug http://code.google.com/p/android/issues/detail?id=5255 throw new TwitterException("Please check your APN settings, make sure not to use WAP APNs.", e); } catch (final OutOfMemoryError e) { // I don't know why OOM thown, but it should be catched. System.gc(); throw new TwitterException("Unknown error", e); } final int statusCode = res.getStatusCode(); if (statusCode < OK || statusCode > ACCEPTED) throw new TwitterException(res.asString(), req, res); return res; } catch (final IOException e) { // TODO if (resolver instanceof TwidereHostAddressResolver) { final TwidereHostAddressResolver twidereResolver = (TwidereHostAddressResolver) resolver; twidereResolver.removeCachedHost(host); } throw new TwitterException(e); } }
From source file:org.Cherry.Modules.Web.Engine.RequestInterceptor.java
private Boolean authenticate(final HttpRequest request, final HttpContext context) throws InvalidCredentialsException { context.setAttribute(CreateCookie, false); if (isOpenGateMessage(request)) { final User identity = getUser(request); if (null == authenticate(identity)) { context.setAttribute(CreateCookie, true); return true; }/* w w w .j a va 2s .c om*/ return false; } if (isCookiePathHit(request)) { final WeakReference<HeaderIterator> headerIterator = new WeakReference<HeaderIterator>( request.headerIterator(Cookie)); Header header; HeaderElement[] elements; String value; while (headerIterator.get().hasNext()) { header = headerIterator.get().nextHeader(); elements = header.getElements(); for (final HeaderElement element : elements) if (getSessionCookie().equalsIgnoreCase(element.getName())) { value = element.getValue(); if (!isTampered(value)) return true; else return false; } } return false; } throw new IllegalStateException("Unknown execution context!"); }
From source file:org.wso2.carbon.governance.registry.extensions.executors.apistore.ServiceToAPIExecutor.java
/** * Update the APIM DB for the published API. * * @param resource/*from w w w .j ava 2s. c o m*/ * @param serviceName */ private boolean publishDataToAPIM(Resource resource, String serviceName) throws GovernanceException { boolean valid = true; if (apimEndpoint == null || apimUsername == null || apimPassword == null || apimEnv == null) { throw new GovernanceException(ExecutorConstants.APIM_LOGIN_UNDEFINED); } CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); // APIUtils apiUtils = new APIUtils(); APIUtils.authenticateAPIM(httpContext, apimEndpoint, apimUsername, apimPassword); String addAPIendpoint = apimEndpoint + Constants.APIM_ENDPOINT; try { // create a post request to addAPI. HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(addAPIendpoint); // Request parameters and other properties. List<NameValuePair> params = new ArrayList<NameValuePair>(); String[] endPoints = artifact.getAttributes(Constants.ENDPOINTS_ENTRY); if (endPoints == null || endPoints.length == 0) { String msg = "Service Endpoint is a must attribute to create an API definition at the APIStore"; throw new GovernanceException(msg); } List<String> endPointsList = Arrays.asList(endPoints); if (endPointsList == null) { String msg = "Service Endpoint is a must attribute to create an API definition at the APIStore"; throw new GovernanceException(msg); } addParameters(params, resource, serviceName); LOG.info(new UrlEncodedFormEntity(params, Constants.UTF_8_ENCODE)); ResponseAPIM responseAPIM = APIUtils.callAPIMToPublishAPI(httpclient, httppost, params, httpContext); if (responseAPIM.getError().equalsIgnoreCase(Constants.TRUE_CONSTANT)) { LOG.error(responseAPIM.getMessage()); throw new GovernanceException("Error occurred while adding the api to API Manager."); } } catch (Exception e) { throw new GovernanceException(e.getMessage(), e); } return valid; }
From source file:com.couchbase.client.ViewNode.java
public boolean writeOp(HttpOperation op) { AsyncConnectionRequest connRequest = connMgr.requestConnection(); try {/* ww w . j a v a2 s. c o m*/ connRequest.waitFor(); } catch (InterruptedException e) { getLogger().warn("Interrupted while trying to get a connection."); connRequest.cancel(); return false; } NHttpClientConnection conn = connRequest.getConnection(); if (conn == null) { getLogger().debug("Failed to obtain connection on node " + this.addr); connRequest.cancel(); return false; } else { if (!user.equals("default")) { try { op.addAuthHeader(HttpUtil.buildAuthHeader(user, pass)); } catch (UnsupportedEncodingException ex) { getLogger().error("Could not create auth header for request, " + "could not encode credentials into base64. Canceling op." + op, ex); op.cancel(); connRequest.cancel(); } } HttpContext context = conn.getContext(); RequestHandle handle = new RequestHandle(connMgr, conn); context.setAttribute("request-handle", handle); context.setAttribute("operation", op); conn.requestOutput(); } return true; }
From source file:net.spy.memcached.CouchbaseNode.java
public void doWrites() { HttpOperation op;/* w ww.j av a 2 s. c o m*/ while ((op = writeQ.poll()) != null) { if (!op.isTimedOut() && !op.isCancelled()) { AsyncConnectionRequest connRequest = connMgr.requestConnection(); try { connRequest.waitFor(); } catch (InterruptedException e) { getLogger().warn("Interrupted while trying to get a connection." + " Cancelling op"); op.cancel(); return; } NHttpClientConnection conn = connRequest.getConnection(); if (conn == null) { getLogger().error("Failed to obtain connection. Cancelling op"); op.cancel(); } else { HttpContext context = conn.getContext(); RequestHandle handle = new RequestHandle(connMgr, conn); context.setAttribute("request-handle", handle); context.setAttribute("operation", op); conn.requestOutput(); } } } }
From source file:com.klarna.checkout.BasicConnector.java
/** * Applying the method on the specific resource. * * @param method HTTP method/*from w w w.ja v a 2 s . co m*/ * @param resource Resource implementation * @param options Connector Options * * @return A HttpResponse object * * @throws IOException In case of an I/O Error. */ @Override public HttpResponse apply(final String method, final IResource resource, final ConnectorOptions options) throws IOException { if (resource == null) { throw new IllegalArgumentException("IResource implementation may not be null."); } if (!method.equals("GET") && !method.equals("POST")) { throw new IllegalArgumentException("Unsupported HTTP Method. (" + method + ")"); } HttpUriRequest req = createRequest(method, resource, options); HttpContext ctex = new BasicHttpContext(); ctex.setAttribute("klarna_resource", resource); ctex.setAttribute("klarna_visited", new HashSet<URI>()); return getClient().execute(req, new Handler(resource), ctex); }
From source file:com.lillicoder.newsblurry.net.BaseTask.java
/** * Gets an {@link HttpContext} instance configured for making * web requests. The returned context will have a cookie store * attached for persisting cookies created during the request. * @return {@link HttpContext} for use with web requests. *//*from www .ja v a 2 s.co m*/ protected HttpContext getRequestContext() { HttpContext context = new BasicHttpContext(); CookieStore cookieStore = new PreferenceCookieStore(this.getContext()); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); return context; }
From source file:org.wso2.carbon.governance.registry.extensions.executors.APIPublishExecutor.java
/** * Publish the data to API Manager// w w w . j a va 2 s. c o m * * @param api API registry artifact. * @param xmlContent url Pattern value iterator. */ private void publishData(GenericArtifact api, OMElement xmlContent) 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 publishEndpoint = apimEndpoint + ExecutorConstants.APIM_PUBLISH_URL; // create a post request to addAPI. HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(publishEndpoint); // Request parameters and other properties. List<NameValuePair> params = getRequestParameters(api, xmlContent); if (api.getAttribute(ExecutorConstants.SERVICE_ENDPOINT_URL) != null && api.getAttribute(ExecutorConstants.SERVICE_ENDPOINT_URL).isEmpty()) { log.warn(ExecutorConstants.EMPTY_ENDPOINT); } try { 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); } }