List of usage examples for org.apache.http.client.methods HttpRequestBase reset
public void reset()
From source file:org.apache.openmeetings.service.calendar.caldav.handler.AbstractCalendarHandler.java
/** * Resets the Method for reusablility.//from www . j a v a2 s .co m * @param method Method to reset. */ void releaseConnection(HttpRequestBase method) { if (method != null) { method.reset(); } }
From source file:org.musicmount.io.server.dav.DAVResourceProvider.java
protected Sardine createSardine(final ServerFileSystem fileSystem) { /*/*from w ww . j a v a2 s .c om*/ * extract user/password */ String user = null; String password = null; if (fileSystem.getUserInfo() != null) { String[] userAndPassword = fileSystem.getUserInfo().split(":"); user = userAndPassword[0]; password = userAndPassword.length > 1 ? userAndPassword[1] : null; } /* * create customized sardine */ return new SardineImpl(user, password, null) { @Override protected Registry<ConnectionSocketFactory> createDefaultSchemeRegistry() { ConnectionSocketFactory socketFactory; if ("https".equalsIgnoreCase(fileSystem.getScheme())) { socketFactory = createDefaultSecureSocketFactory(); } else { socketFactory = createDefaultSocketFactory(); } return RegistryBuilder.<ConnectionSocketFactory>create() .register(fileSystem.getScheme(), socketFactory).build(); } @Override protected ConnectionSocketFactory createDefaultSecureSocketFactory() { try { // trust anybody... SSLContext context = SSLContext.getInstance("TLS"); X509TrustManager trustManager = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }; context.init(null, new TrustManager[] { trustManager }, null); return new SSLConnectionSocketFactory(context, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (NoSuchAlgorithmException | KeyManagementException e) { // should not happen... } return super.createDefaultSecureSocketFactory(); } @Override protected <T> T execute(HttpRequestBase request, ResponseHandler<T> responseHandler) throws IOException { /* * Sardine re-executes a PUT request after a org.apache.http.NoHttpResponseException without resetting it... */ if (request.isAborted()) { request.reset(); } return super.execute(request, responseHandler); } @Override public ContentLengthInputStream get(String url, Map<String, String> headers) throws IOException { /* * abort rather than consume entity for better performance */ final HttpGet get = new HttpGet(url); for (String header : headers.keySet()) { get.addHeader(header, headers.get(header)); } // Must use #execute without handler, otherwise the entity is consumed already after the handler exits. final HttpResponse response = this.execute(get); VoidResponseHandler handler = new VoidResponseHandler(); try { handler.handleResponse(response); // Will consume or abort the entity when the stream is closed. PositionInputStream positionInputStream = new PositionInputStream( response.getEntity().getContent()) { public void close() throws IOException { if (getPosition() == response.getEntity().getContentLength()) { EntityUtils.consume(response.getEntity()); } else { // partial read or unknown content length get.abort(); } } }; return new ContentLengthInputStream(positionInputStream, response.getEntity().getContentLength()); } catch (IOException ex) { get.abort(); throw ex; } } }; }
From source file:com.sangupta.jerry.http.HttpExecutor.java
/** * Execute the given web request and return the obtained raw web response. * //from w ww . ja va 2 s.co m * @param webRequest * the {@link WebRequest} to be executed * * @return the {@link WebRawResponse} obtained after execution * * @throws IOException * if something fails * * @throws ClientProtocolException * if something fails */ public WebRawResponse execute(WebRequest webRequest) throws ClientProtocolException, IOException { // sharing the context may lead to circular redirects in case // of redirections from two request objects towards a single // URI - like hitting http://google.com twice leads to circular // redirects in the second request HttpContext localHttpContext = new BasicHttpContext(); localHttpContext.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credentialsProvider); localHttpContext.setAttribute(HttpClientContext.AUTH_CACHE, this.authCache); localHttpContext.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); // localHttpContext.removeAttribute(DefaultRedirectStrategy.REDIRECT_LOCATIONS); HttpRequestBase httpRequest = webRequest.getHttpRequest(); httpRequest.reset(); return new WebRawResponse(this.client.execute(httpRequest, localHttpContext), localHttpContext); }
From source file:com.algolia.search.saas.APIClient.java
private JSONObject _requestByHost(HttpRequestBase req, String host, String url, String json, HashMap<String, String> errors) throws AlgoliaException { req.reset(); // set URL/*from ww w . ja v a2s . co m*/ try { req.setURI(new URI("https://" + host + url)); } catch (URISyntaxException e) { // never reached throw new IllegalStateException(e); } // set auth headers req.setHeader("X-Algolia-Application-Id", this.applicationID); if (forwardAdminAPIKey == null) { req.setHeader("X-Algolia-API-Key", this.apiKey); } else { req.setHeader("X-Algolia-API-Key", this.forwardAdminAPIKey); req.setHeader("X-Forwarded-For", this.forwardEndUserIP); req.setHeader("X-Forwarded-API-Key", this.forwardRateLimitAPIKey); } for (Entry<String, String> entry : headers.entrySet()) { req.setHeader(entry.getKey(), entry.getValue()); } // set user agent req.setHeader("User-Agent", "Algolia for Java " + version); // set JSON entity if (json != null) { if (!(req instanceof HttpEntityEnclosingRequestBase)) { throw new IllegalArgumentException("Method " + req.getMethod() + " cannot enclose entity"); } req.setHeader("Content-type", "application/json"); try { StringEntity se = new StringEntity(json, "UTF-8"); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); ((HttpEntityEnclosingRequestBase) req).setEntity(se); } catch (UnsupportedEncodingException e) { throw new AlgoliaException("Invalid JSON Object: " + json); // $COVERAGE-IGNORE$ } } RequestConfig config = RequestConfig.custom().setSocketTimeout(httpSocketTimeoutMS) .setConnectTimeout(httpConnectTimeoutMS).setConnectionRequestTimeout(httpConnectTimeoutMS).build(); req.setConfig(config); HttpResponse response; try { response = httpClient.execute(req); } catch (IOException e) { // on error continue on the next host errors.put(host, String.format("%s=%s", e.getClass().getName(), e.getMessage())); return null; } try { int code = response.getStatusLine().getStatusCode(); if (code / 100 == 4) { String message = ""; try { message = EntityUtils.toString(response.getEntity()); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (code == 400) { throw new AlgoliaException(code, message.length() > 0 ? message : "Bad request"); } else if (code == 403) { throw new AlgoliaException(code, message.length() > 0 ? message : "Invalid Application-ID or API-Key"); } else if (code == 404) { throw new AlgoliaException(code, message.length() > 0 ? message : "Resource does not exist"); } else { throw new AlgoliaException(code, message.length() > 0 ? message : "Error"); } } if (code / 100 != 2) { try { errors.put(host, EntityUtils.toString(response.getEntity())); } catch (IOException e) { errors.put(host, String.valueOf(code)); } // KO, continue return null; } try { InputStream istream = response.getEntity().getContent(); InputStreamReader is = new InputStreamReader(istream, "UTF-8"); JSONTokener tokener = new JSONTokener(is); JSONObject res = new JSONObject(tokener); is.close(); return res; } catch (IOException e) { return null; } catch (JSONException e) { throw new AlgoliaException("JSON decode error:" + e.getMessage()); } } finally { req.releaseConnection(); } }
From source file:com.jivesoftware.os.routing.bird.http.client.ApacheHttpClient441BackedHttpClient.java
private HttpStreamResponse executeStream(HttpRequestBase requestBase) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, IOException { applyHeadersCommonToAllRequests(requestBase); activeCount.incrementAndGet();/*from ww w . j a v a2 s . c o m*/ CloseableHttpResponse response = client.execute(requestBase); StatusLine statusLine = response.getStatusLine(); int status = statusLine.getStatusCode(); LOG.debug("Got status: {} {}", status, statusLine.getReasonPhrase()); if (status < 200 || status >= 300) { activeCount.decrementAndGet(); HttpClientUtils.closeQuietly(response); requestBase.reset(); throw new IOException("Bad status : " + statusLine); } return new HttpStreamResponse(statusLine.getStatusCode(), statusLine.getReasonPhrase(), response, response.getEntity().getContent(), requestBase, activeCount); }
From source file:org.eclipse.rdf4j.http.client.RDF4JProtocolSession.java
public void getStatements(Resource subj, IRI pred, Value obj, boolean includeInferred, RDFHandler handler, Resource... contexts) throws IOException, RDFHandlerException, RepositoryException, UnauthorizedException, QueryInterruptedException { checkRepositoryURL();/*from ww w. j a v a2 s . c om*/ try { final boolean useTransaction = transactionURL != null; String baseLocation = useTransaction ? transactionURL : Protocol.getStatementsLocation(getQueryURL()); URIBuilder url = new URIBuilder(baseLocation); if (subj != null) { url.setParameter(Protocol.SUBJECT_PARAM_NAME, Protocol.encodeValue(subj)); } if (pred != null) { url.setParameter(Protocol.PREDICATE_PARAM_NAME, Protocol.encodeValue(pred)); } if (obj != null) { url.setParameter(Protocol.OBJECT_PARAM_NAME, Protocol.encodeValue(obj)); } for (String encodedContext : Protocol.encodeContexts(contexts)) { url.addParameter(Protocol.CONTEXT_PARAM_NAME, encodedContext); } url.setParameter(Protocol.INCLUDE_INFERRED_PARAM_NAME, Boolean.toString(includeInferred)); if (useTransaction) { url.setParameter(Protocol.ACTION_PARAM_NAME, Action.GET.toString()); } HttpRequestBase method = useTransaction ? new HttpPut(url.build()) : new HttpGet(url.build()); try { getRDF(method, handler, true); } catch (MalformedQueryException e) { logger.warn("Server reported unexpected malfored query error", e); throw new RepositoryException(e.getMessage(), e); } finally { method.reset(); } } catch (URISyntaxException e) { throw new AssertionError(e); } }
From source file:org.eclipse.rdf4j.http.client.RDF4JProtocolSession.java
public long size(Resource... contexts) throws IOException, RepositoryException, UnauthorizedException { checkRepositoryURL();/*from w w w. j ava 2s . co m*/ try { final boolean useTransaction = transactionURL != null; String baseLocation = useTransaction ? appendAction(transactionURL, Action.SIZE) : Protocol.getSizeLocation(getQueryURL()); URIBuilder url = new URIBuilder(baseLocation); String[] encodedContexts = Protocol.encodeContexts(contexts); for (int i = 0; i < encodedContexts.length; i++) { url.addParameter(Protocol.CONTEXT_PARAM_NAME, encodedContexts[i]); } final HttpRequestBase method = useTransaction ? new HttpPut(url.build()) : new HttpGet(url.build()); try { String response = EntityUtils.toString(executeOK(method).getEntity()); try { return Long.parseLong(response); } catch (NumberFormatException e) { throw new RepositoryException("Server responded with invalid size value: " + response); } } finally { method.reset(); } } catch (URISyntaxException e) { throw new AssertionError(e); } catch (RepositoryException e) { throw e; } catch (RDF4JException e) { throw new RepositoryException(e); } }
From source file:com.jivesoftware.os.routing.bird.http.client.ApacheHttpClient441BackedHttpClient.java
private HttpResponse execute(HttpRequestBase requestBase) throws IOException, OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException { applyHeadersCommonToAllRequests(requestBase); byte[] responseBody; StatusLine statusLine = null;/* w ww . j a v a2 s . co m*/ if (LOG.isInfoEnabled()) { LOG.startTimer(TIMER_NAME); } activeCount.incrementAndGet(); CloseableHttpResponse response = null; try { response = client.execute(requestBase); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); InputStream responseBodyAsStream = response.getEntity().getContent(); if (responseBodyAsStream != null) { IOUtils.copy(responseBodyAsStream, outputStream); } responseBody = outputStream.toByteArray(); statusLine = response.getStatusLine(); return new HttpResponse(statusLine.getStatusCode(), statusLine.getReasonPhrase(), responseBody); } finally { if (response != null) { HttpClientUtils.closeQuietly(response); } requestBase.reset(); activeCount.decrementAndGet(); if (LOG.isInfoEnabled()) { long elapsedTime = LOG.stopTimer(TIMER_NAME); StringBuilder httpInfo = new StringBuilder(); if (statusLine != null) { httpInfo.append("Outbound ").append(statusLine.getProtocolVersion()).append(" Status ") .append(statusLine.getStatusCode()); } else { httpInfo.append("Exception sending request"); } httpInfo.append(" in ").append(elapsedTime).append(" ms ").append(requestBase.getMethod()) .append(" ").append(client).append(requestBase.getURI()); LOG.debug(httpInfo.toString()); } } }
From source file:ch.iterate.openstack.swift.Client.java
private <T> T execute(final HttpRequestBase method, ResponseHandler<T> handler) throws IOException { try {//from ww w.j a v a 2 s . c o m method.setHeader(Constants.X_AUTH_TOKEN, authenticationResponse.getAuthToken()); try { return client.execute(method, handler); } catch (AuthorizationException e) { method.abort(); authenticationResponse = this.authenticate(); method.reset(); // Add new auth token retrieved method.setHeader(Constants.X_AUTH_TOKEN, authenticationResponse.getAuthToken()); // Retry return client.execute(method, handler); } } catch (IOException e) { // In case of an IOException the connection will be released back to the connection manager automatically method.abort(); throw e; } finally { method.reset(); } }