List of usage examples for org.apache.commons.httpclient HttpMethodBase getName
@Override public abstract String getName();
From source file:com.eucalyptus.blockstorage.HttpTransfer.java
/** * Calculates and sets the Authorization header value for the request using the EucaRSA-V2 signing algorithm * Algorithm Overview://from ww w. j a v a2 s. c o m * * 1. Generate the canonical Request * a.) CanonicalRequest = * HTTPRequestMethod + '\n' + * CanonicalURI + '\n' + * CanonicalQueryString + '\n' + * CanonicalHeaders + '\n' + * SignedHeaders * b.) Where CanonicalURI = * c.) Where CanonicalQueryString = * d.) Where CanonicalHeaders = sorted (by lowercased header name) ';' delimited list of <lowercase(headername)>:<value> items * e.) Where SignedHeaders = sorted, ';' delimited list of headers in CanonicalHeaders * * 2. Signature = RSA(privkey, SHA256(CanonicalRequest)) * * 3. Add an Authorization HTTP header to the request that contains the following strings, separated by spaces: * EUCA2-RSA-SHA256 * The lower-case hexadecimal encoding of the component's X.509 certificate's md5 fingerprint * The SignedHeaders list calculated in Task 1 * The Base64 encoding of the Signature calculated in Task 2 * * @param httpBaseRequest -- the request, the 'Authorization' header will be added to the request */ public static void signEucaInternal(HttpMethodBase httpBaseRequest) { StringBuilder canonicalRequest = new StringBuilder(); String canonicalURI = null; String verb = httpBaseRequest.getName(); canonicalURI = httpBaseRequest.getPath(); String canonicalQuery = calcCanonicalQuery(httpBaseRequest); String[] processedHeaders = getCanonicalAndSignedHeaders(httpBaseRequest); String canonicalHeaders = processedHeaders[0]; String signedHeaders = processedHeaders[1]; canonicalRequest.append(verb).append('\n'); canonicalRequest.append(canonicalURI).append('\n'); canonicalRequest.append(canonicalQuery).append('\n'); canonicalRequest.append(canonicalHeaders).append('\n'); canonicalRequest.append(signedHeaders); StringBuilder authHeader = new StringBuilder(EUCA2_AUTH_ID); String signature = null; String fingerprint = null; try { Credentials ccCreds = SystemCredentials.lookup(Storage.class); PrivateKey ccPrivateKey = ccCreds.getPrivateKey(); fingerprint = ccCreds.getCertFingerprint(); Signature sign = Signature.getInstance("SHA256withRSA"); sign.initSign(ccPrivateKey); LOG.debug("Signing canonical request: " + canonicalRequest.toString()); sign.update(canonicalRequest.toString().getBytes()); byte[] sig = sign.sign(); signature = new String(Base64.encode(sig)); } catch (Exception ex) { LOG.error("Signing error while signing request", ex); } authHeader.append(" ").append(fingerprint.toLowerCase()).append(" ").append(signedHeaders.toString()) .append(" ").append(signature); httpBaseRequest.addRequestHeader(EUCA2_AUTH_HEADER_NAME, authHeader.toString()); }
From source file:com.googlecode.fascinator.common.BasicHttpClient.java
/** * Sends an HTTP request/*from w w w.j a v a2 s . co m*/ * * @param method an HTTP method * @param auth true to request with authentication, false to request without * @return HTTP status code * @throws IOException if an error occurred during the HTTP request */ public int executeMethod(HttpMethodBase method, boolean auth) throws IOException { log.trace("{} {}", method.getName(), method.getURI()); int status = getHttpClient(auth).executeMethod(method); log.trace("{} {}", status, HttpStatus.getStatusText(status)); return status; }
From source file:com.assemblade.client.AbstractClient.java
private void generateSignature(HttpMethodBase method) throws URIException { if (authentication != null) { String verb = method.getName(); String url = OAuthEncoder.encode(method.getURI().toString()); List<NameValuePair> queryStrings = new ArrayList<NameValuePair>(); queryStrings.add(new NameValuePair(OAuthConstants.CONSUMER_KEY, authentication.getToken())); queryStrings.add(new NameValuePair(OAuthConstants.NONCE, timestampService.getNonce())); queryStrings.add(new NameValuePair(OAuthConstants.SIGN_METHOD, signatureService.getSignatureMethod())); queryStrings.add(new NameValuePair(OAuthConstants.TIMESTAMP, timestampService.getTimestampInSeconds())); queryStrings.add(new NameValuePair(OAuthConstants.VERSION, "1.0")); method.setQueryString(queryStrings.toArray(new NameValuePair[] {})); String queryString = OAuthEncoder.encode(method.getQueryString()); String baseString = verb + "&" + url + "&" + queryString; String signature = signatureService.getSignature(baseString, authentication.getSecret(), ""); queryStrings.add(new NameValuePair(OAuthConstants.SIGNATURE, signature)); method.setQueryString(queryStrings.toArray(new NameValuePair[] {})); }/*from w w w.ja va 2 s .com*/ }
From source file:com.sittinglittleduck.DirBuster.Worker.java
private int makeRequest(HttpMethodBase httpMethod) throws HttpException, IOException, InterruptedException { if (Config.debug) { System.out.println("DEBUG Worker[" + threadId + "]: " + httpMethod.getName() + " : " + url.toString()); }//from w w w . j av a 2 s. c o m // set the custom HTTP headers Vector HTTPheaders = manager.getHTTPHeaders(); for (int a = 0; a < HTTPheaders.size(); a++) { HTTPHeader httpHeader = (HTTPHeader) HTTPheaders.elementAt(a); /* * Host header has to be set in a different way! */ if (httpHeader.getHeader().startsWith("Host")) { httpMethod.getParams().setVirtualHost(httpHeader.getValue()); } else { httpMethod.setRequestHeader(httpHeader.getHeader(), httpHeader.getValue()); } } httpMethod.setFollowRedirects(Config.followRedirects); /* * this code is used to limit the number of request/sec */ if (manager.isLimitRequests()) { while (manager.getTotalDone() / ((System.currentTimeMillis() - manager.getTimestarted()) / 1000.0) > manager .getLimitRequestsTo()) { Thread.sleep(100); } } /* * Send the request */ int code = httpclient.executeMethod(httpMethod); if (Config.debug) { System.out.println("DEBUG Worker[" + threadId + "]: " + code + " " + url.toString()); } return code; }
From source file:jeeves.utils.XmlRequest.java
private String getSentData(HttpMethodBase httpMethod) { StringBuilder sentData = new StringBuilder(httpMethod.getName()).append(" ").append(httpMethod.getPath()); if (httpMethod.getQueryString() != null) { sentData.append("?" + httpMethod.getQueryString()); }/*from w ww.ja va 2 s. com*/ sentData.append("\r\n"); for (Header h : httpMethod.getRequestHeaders()) { sentData.append(h); } sentData.append("\r\n"); if (httpMethod instanceof PostMethod) { sentData.append(postData); } return sentData.toString(); }
From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClient.java
private HttpStreamResponse executeMethodStream(HttpMethodBase method, int timeoutMillis) throws HttpClientException { try {/* www. j a v a2 s . c o m*/ return executeStreamWithTimeout(method, timeoutMillis); } catch (Exception e) { throw new HttpClientException("Error executing " + method.getName() + " request to: " + client.getHostConfiguration().getHostURL() + " path: " + method.getPath(), e); } }
From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClient.java
private HttpResponse executeMethod(HttpMethodBase method, Map<String, String> headers, int timeoutMillis) throws HttpClientException { setRequestHeaders(headers, method);//from w w w . ja v a 2 s . c om if (timeoutMillis > 0) { return executeWithTimeout(method, timeoutMillis); } try { return execute(method); } catch (Exception e) { throw new HttpClientException("Error executing " + method.getName() + " request to: " + client.getHostConfiguration().getHostURL() + " path: " + method.getPath(), e); } }
From source file:com.sun.syndication.propono.atom.client.OAuthStrategy.java
public void addAuthentication(HttpClient httpClient, HttpMethodBase method) throws ProponoException { if (state != State.ACCESS_TOKEN) { throw new ProponoException("ERROR: authentication strategy failed init"); }/*w ww . ja v a2 s .c om*/ // add OAuth name/values to request query string // wish we didn't have to parse them apart first, ugh List originalqlist = null; if (method.getQueryString() != null) { String qstring = method.getQueryString().trim(); qstring = qstring.startsWith("?") ? qstring.substring(1) : qstring; originalqlist = new ParameterParser().parse(qstring, '&'); } else { originalqlist = new ArrayList(); } // put query string into hashmap form to please OAuth.net classes Map params = new HashMap(); for (Iterator it = originalqlist.iterator(); it.hasNext();) { NameValuePair pair = (NameValuePair) it.next(); params.put(pair.getName(), pair.getValue()); } // add OAuth params to query string params.put("xoauth_requestor_id", username); params.put("oauth_consumer_key", consumerKey); params.put("oauth_signature_method", keyType); params.put("oauth_timestamp", Long.toString(timestamp)); params.put("oauth_nonce", nonce); params.put("oauth_token", accessToken); params.put("oauth_token_secret", tokenSecret); // sign complete URI String finalUri = null; OAuthServiceProvider provider = new OAuthServiceProvider(reqUrl, authzUrl, accessUrl); OAuthConsumer consumer = new OAuthConsumer(null, consumerKey, consumerSecret, provider); OAuthAccessor accessor = new OAuthAccessor(consumer); accessor.tokenSecret = tokenSecret; OAuthMessage message; try { message = new OAuthMessage(method.getName(), method.getURI().toString(), params.entrySet()); message.sign(accessor); finalUri = OAuth.addParameters(message.URL, message.getParameters()); } catch (Exception ex) { throw new ProponoException("ERROR: OAuth signing request", ex); } // pull query string off and put it back onto method method.setQueryString(finalUri.substring(finalUri.lastIndexOf("?"))); }
From source file:com.rometools.propono.atom.client.OAuthStrategy.java
@Override public void addAuthentication(final HttpClient httpClient, final HttpMethodBase method) throws ProponoException { if (state != State.ACCESS_TOKEN) { throw new ProponoException("ERROR: authentication strategy failed init"); }/*from w w w. j av a 2 s . c o m*/ // add OAuth name/values to request query string // wish we didn't have to parse them apart first, ugh List<NameValuePair> originalqlist = null; if (method.getQueryString() != null) { String qstring = method.getQueryString().trim(); qstring = qstring.startsWith("?") ? qstring.substring(1) : qstring; @SuppressWarnings("unchecked") final List<NameValuePair> parameters = new ParameterParser().parse(qstring, '&'); originalqlist = parameters; } else { originalqlist = new ArrayList<NameValuePair>(); } // put query string into hashmap form to please OAuth.net classes final Map<String, String> params = new HashMap<String, String>(); for (final Object element : originalqlist) { final NameValuePair pair = (NameValuePair) element; params.put(pair.getName(), pair.getValue()); } // add OAuth params to query string params.put("xoauth_requestor_id", username); params.put("oauth_consumer_key", consumerKey); params.put("oauth_signature_method", keyType); params.put("oauth_timestamp", Long.toString(timestamp)); params.put("oauth_nonce", nonce); params.put("oauth_token", accessToken); params.put("oauth_token_secret", tokenSecret); // sign complete URI String finalUri = null; final OAuthServiceProvider provider = new OAuthServiceProvider(reqUrl, authzUrl, accessUrl); final OAuthConsumer consumer = new OAuthConsumer(null, consumerKey, consumerSecret, provider); final OAuthAccessor accessor = new OAuthAccessor(consumer); accessor.tokenSecret = tokenSecret; OAuthMessage message; try { message = new OAuthMessage(method.getName(), method.getURI().toString(), params.entrySet()); message.sign(accessor); finalUri = OAuth.addParameters(message.URL, message.getParameters()); } catch (final Exception ex) { throw new ProponoException("ERROR: OAuth signing request", ex); } // pull query string off and put it back onto method method.setQueryString(finalUri.substring(finalUri.lastIndexOf("?"))); }
From source file:org.alfresco.repo.remoteconnector.LocalWebScriptConnectorServiceImpl.java
/** * Builds a new Request object, using HttpClient method descriptions *///from w w w .j a v a2s . c om public RemoteConnectorRequest buildRequest(String url, Class<? extends HttpMethodBase> method) { // Get the method name String methodName; try { HttpMethodBase httpMethod = method.getConstructor(String.class).newInstance(url); methodName = httpMethod.getName(); } catch (Exception e) { throw new AlfrescoRuntimeException("Error identifying method name", e); } // Build and return return buildRequest(url, methodName); }