private void addOptionalDateHeader(ClientRequest cr) { String date = getHeader(cr, "Date"); if (date == "") { date = new RFC1123DateConverter().format(new Date()); cr.getHeaders().add("Date", date); } }
/* * (non-Javadoc) * * @see * com.microsoft.windowsazure.services.core.IdempotentClientFilter#doHandle * (com.sun.jersey.api.client.ClientRequest) */ @Override public ClientResponse doHandle(ClientRequest cr) { MultivaluedMap<String, Object> headers = cr.getHeaders(); headers.add("DataServiceVersion", "3.0"); headers.add("MaxDataServiceVersion", "3.0"); headers.add("x-ms-version", "2.5"); return getNext().handle(cr); }
public ClientResponse handle(ClientRequest cr) { cr.getHeaders() .add( HttpHeaders.AUTHORIZATION, "Basic " + new String(Base64.encode(user + ":" + pass), Charset.forName("ASCII"))); ClientResponse resp = getNext().handle(cr); return resp; }
@Override public ClientResponse handle(ClientRequest clientRequest) throws ClientHandlerException { final MultivaluedMap<String, Object> headers = clientRequest.getHeaders(); List<Object> hcookies = headers.get(COOKIE_HEADER); if (hcookies == null) { hcookies = new ArrayList<Object>(); } hcookies.addAll(cookies); headers.put(COOKIE_HEADER, hcookies); return getNext().handle(clientRequest); }
@Override public ClientResponse handle(ClientRequest cr) throws ClientHandlerException { try { final Request request = buildRequest(cr); writeOutBoundHeaders(cr.getHeaders(), request); final ContentResponse response = request.send(); return new ClientResponse( response.getStatus(), getInBoundHeaders(response), new ByteArrayInputStream(response.getContent()), getMessageBodyWorkers()); } catch (InterruptedException | TimeoutException | ExecutionException | IOException e) { throw new ClientHandlerException(e); } }
/* * StringToSign = VERB + "\n" + * Content-Encoding + "\n" * Content-Language + "\n" * Content-Length + "\n" * Content-MD5 + "\n" + * Content-Type + "\n" + * Date + "\n" + * If-Modified-Since + "\n" * If-Match + "\n" * If-None-Match + "\n" * If-Unmodified-Since + "\n" * Range + "\n" * CanonicalizedHeaders + * CanonicalizedResource; */ public void sign(ClientRequest cr) { // gather signed material addOptionalDateHeader(cr); // build signed string String stringToSign = cr.getMethod() + "\n" + getHeader(cr, "Content-Encoding") + "\n" + getHeader(cr, "Content-Language") + "\n" + getHeader(cr, "Content-Length") + "\n" + getHeader(cr, "Content-MD5") + "\n" + getHeader(cr, "Content-Type") + "\n" + getHeader(cr, "Date") + "\n" + getHeader(cr, "If-Modified-Since") + "\n" + getHeader(cr, "If-Match") + "\n" + getHeader(cr, "If-None-Match") + "\n" + getHeader(cr, "If-Unmodified-Since") + "\n" + getHeader(cr, "Range") + "\n"; stringToSign += getCanonicalizedHeaders(cr); stringToSign += getCanonicalizedResource(cr); if (log.isDebugEnabled()) { log.debug(String.format("String to sign: \"%s\"", stringToSign)); } // System.out.println(String.format("String to sign: \"%s\"", stringToSign)); String signature = this.signer.sign(stringToSign); cr.getHeaders().putSingle("Authorization", "SharedKey " + this.accountName + ":" + signature); }
public void configureRequest( final RequestBuilder requestBuilder, final ClientRequest cr, final boolean needsBody) { final Map<String, Object> props = cr.getProperties(); // Set the read timeout final Integer readTimeout = (Integer) props.get(AhcConfig.PROPERTY_READ_TIMEOUT); if (readTimeout != null) { final PerRequestConfig c = new PerRequestConfig(); c.setRequestTimeoutInMs(readTimeout); requestBuilder.setPerRequestConfig(c); } if (cr.getEntity() != null && needsBody) { final RequestEntityWriter re = getRequestEntityWriter(cr); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { re.writeRequestEntity( new CommittingOutputStream(baos) { @Override protected void commit() throws IOException { configureHeaders(cr.getHeaders(), requestBuilder); } }); } catch (final IOException ex) { throw new ClientHandlerException(ex); } final byte[] content = baos.toByteArray(); requestBuilder.setBody( new Request.EntityWriter() { @Override public void writeEntity(final OutputStream out) throws IOException { out.write(content); } }); } else { configureHeaders(cr.getHeaders(), requestBuilder); } }
private ClientResponse _invoke(final ClientRequest ro) throws IOException { final HttpURLConnection uc; if (this.httpURLConnectionFactory == null) { uc = (HttpURLConnection) ro.getURI().toURL().openConnection(); } else { uc = this.httpURLConnectionFactory.getHttpURLConnection(ro.getURI().toURL()); } Integer readTimeout = (Integer) ro.getProperties().get(ClientConfig.PROPERTY_READ_TIMEOUT); if (readTimeout != null) { uc.setReadTimeout(readTimeout); } Integer connectTimeout = (Integer) ro.getProperties().get(ClientConfig.PROPERTY_CONNECT_TIMEOUT); if (connectTimeout != null) { uc.setConnectTimeout(connectTimeout); } Boolean followRedirects = (Boolean) ro.getProperties().get(ClientConfig.PROPERTY_FOLLOW_REDIRECTS); if (followRedirects != null) { uc.setInstanceFollowRedirects(followRedirects); } if (uc instanceof HttpsURLConnection) { HTTPSProperties httpsProperties = (HTTPSProperties) ro.getProperties().get(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES); if (httpsProperties != null) { httpsProperties.setConnection((HttpsURLConnection) uc); } } Boolean httpUrlConnectionSetMethodWorkaround = (Boolean) ro.getProperties().get(PROPERTY_HTTP_URL_CONNECTION_SET_METHOD_WORKAROUND); if (httpUrlConnectionSetMethodWorkaround != null && httpUrlConnectionSetMethodWorkaround == true) { setRequestMethodUsingWorkaroundForJREBug(uc, ro.getMethod()); } else { uc.setRequestMethod(ro.getMethod()); } // Write the request headers writeOutBoundHeaders(ro.getHeaders(), uc); // Write the entity (if any) Object entity = ro.getEntity(); if (entity != null) { uc.setDoOutput(true); if (ro.getMethod().equalsIgnoreCase("GET")) { final Logger logger = Logger.getLogger(URLConnectionClientHandler.class.getName()); if (logger.isLoggable(Level.INFO)) { logger.log( Level.INFO, "GET method with entity will be most likely replaced by POST, see http://java.net/jira/browse/JERSEY-1161"); } } writeRequestEntity( ro, new RequestEntityWriterListener() { public void onRequestEntitySize(long size) { if (size != -1 && size < Integer.MAX_VALUE) { // HttpURLConnection uses the int type for content length uc.setFixedLengthStreamingMode((int) size); } else { // TODO it appears HttpURLConnection has some bugs in // chunked encoding // uc.setChunkedStreamingMode(0); Integer chunkedEncodingSize = (Integer) ro.getProperties().get(ClientConfig.PROPERTY_CHUNKED_ENCODING_SIZE); if (chunkedEncodingSize != null) { uc.setChunkedStreamingMode(chunkedEncodingSize); } } } public OutputStream onGetOutputStream() throws IOException { return new CommittingOutputStream() { @Override protected OutputStream getOutputStream() throws IOException { return uc.getOutputStream(); } @Override public void commit() throws IOException { writeOutBoundHeaders(ro.getHeaders(), uc); } }; } }); } else { writeOutBoundHeaders(ro.getHeaders(), uc); } // Return the in-bound response return new URLConnectionResponse( uc.getResponseCode(), getInBoundHeaders(uc), getInputStream(uc), ro.getMethod(), uc); }
@Override public ClientResponse handle(ClientRequest clientRequest) throws ClientHandlerException { clientRequest.getHeaders().add("Connection", "close"); return getNext().handle(clientRequest); }
@Override public void executeMethod(final HttpMethod method, final ClientRequest cr) { final Map<String, Object> props = cr.getProperties(); method.setDoAuthentication(true); final HttpMethodParams methodParams = method.getParams(); // Set the handle cookies property if (!cr.getPropertyAsFeature(ApacheHttpClientConfig.PROPERTY_HANDLE_COOKIES)) { methodParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES); } // Set the interactive and credential provider properties if (cr.getPropertyAsFeature(ApacheHttpClientConfig.PROPERTY_INTERACTIVE)) { CredentialsProvider provider = (CredentialsProvider) props.get(ApacheHttpClientConfig.PROPERTY_CREDENTIALS_PROVIDER); if (provider == null) { provider = DEFAULT_CREDENTIALS_PROVIDER; } methodParams.setParameter(CredentialsProvider.PROVIDER, provider); } else { methodParams.setParameter(CredentialsProvider.PROVIDER, null); } // Set the read timeout final Integer readTimeout = (Integer) props.get(ApacheHttpClientConfig.PROPERTY_READ_TIMEOUT); if (readTimeout != null) { methodParams.setSoTimeout(readTimeout); } if (method instanceof EntityEnclosingMethod) { final EntityEnclosingMethod entMethod = (EntityEnclosingMethod) method; if (cr.getEntity() != null) { final RequestEntityWriter re = getRequestEntityWriter(cr); final Integer chunkedEncodingSize = (Integer) props.get(ApacheHttpClientConfig.PROPERTY_CHUNKED_ENCODING_SIZE); if (chunkedEncodingSize != null) { // There doesn't seems to be a way to set the chunk size. entMethod.setContentChunked(true); // It is not possible for a MessageBodyWriter to modify // the set of headers before writing out any bytes to // the OutputStream // This makes it impossible to use the multipart // writer that modifies the content type to add a boundary // parameter writeOutBoundHeaders(cr.getHeaders(), method); // Do not buffer the request entity when chunked encoding is // set entMethod.setRequestEntity( new RequestEntity() { @Override public boolean isRepeatable() { return false; } @Override public void writeRequest(OutputStream out) throws IOException { re.writeRequestEntity(out); } @Override public long getContentLength() { return re.getSize(); } @Override public String getContentType() { return re.getMediaType().toString(); } }); } else { entMethod.setContentChunked(false); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { re.writeRequestEntity( new CommittingOutputStream(baos) { @Override protected void commit() throws IOException { writeOutBoundHeaders(cr.getMetadata(), method); } }); } catch (IOException ex) { throw new ClientHandlerException(ex); } final byte[] content = baos.toByteArray(); entMethod.setRequestEntity( new RequestEntity() { @Override public boolean isRepeatable() { return true; } @Override public void writeRequest(OutputStream out) throws IOException { out.write(content); } @Override public long getContentLength() { return content.length; } @Override public String getContentType() { return re.getMediaType().toString(); } }); } } } else { writeOutBoundHeaders(cr.getHeaders(), method); // Follow redirects method.setFollowRedirects( cr.getPropertyAsFeature(ApacheHttpClientConfig.PROPERTY_FOLLOW_REDIRECTS)); } try { httpClient.executeMethod( getHostConfiguration(httpClient, props), method, getHttpState(props)); } catch (Exception e) { method.releaseConnection(); throw new ClientHandlerException(e); } }
@Override public ClientResponse handle(ClientRequest clientRequest) throws ClientHandlerException { int retryCount = 0; InputStream entityStream = null; if (clientRequest.getEntity() instanceof InputStream) entityStream = (InputStream) clientRequest.getEntity(); while (true) { try { // if using an InputStream, mark the stream so we can rewind it in case of an error if (entityStream != null && entityStream.markSupported()) entityStream.mark(config.getRetryBufferSize()); return getNext().handle(clientRequest); } catch (RuntimeException orig) { Throwable t = orig; // in this case, the exception was wrapped by Jersey if (t instanceof ClientHandlerException) t = t.getCause(); if (t instanceof AtmosException) { AtmosException ae = (AtmosException) t; // retry all 50x errors if (ae.getHttpCode() < 500) throw orig; // add small delay to Atmos code 1040 (server busy) if (ae.getErrorCode() == 1040) { try { Thread.sleep(ATMOS_1040_DELAY_MS); } catch (InterruptedException e) { log.warn("Interrupted while waiting after a 1040 response: " + e.getMessage()); } } // retry all IO exceptions unless wschecksum is enabled (can't overwrite data in this // case) } else if (!(t instanceof IOException) || clientRequest.getHeaders().getFirst(RestUtil.XHEADER_WSCHECKSUM) != null) throw orig; // only retry maxRetries times if (++retryCount > config.getMaxRetries()) throw orig; // attempt to reset InputStream if it has been read from if (entityStream != null) { if (!(entityStream instanceof MeasuredInputStream) || ((MeasuredInputStream) entityStream).getRead() > 0) { try { if (!entityStream.markSupported()) throw new IOException("Mark is not supported"); entityStream.reset(); } catch (IOException e) { log.warn("Could not reset entity stream for retry: " + e.getMessage()); throw orig; } } } log.info("Error received in response (" + t + "), retrying..."); // wait for retry delay if (config.getRetryDelayMillis() > 0) { try { Thread.sleep(config.getRetryDelayMillis()); } catch (InterruptedException e) { log.warn("Interrupted while waiting to retry: " + e.getMessage()); } } } } }