List of usage examples for org.apache.commons.httpclient HttpMethod getName
public abstract String getName();
From source file:com.twinsoft.convertigo.beans.connectors.HttpConnector.java
private byte[] executeMethod(HttpMethod method, final Context context) throws IOException, URIException, MalformedURLException, EngineException { Header[] requestHeaders, responseHeaders = null; byte[] result = null; String contents = null;//from w ww . ja va 2s. c om int statuscode = -1; if (!context.requestedObject.runningThread.bContinue) return null; Engine.logBeans .debug("(HttpConnector) Executing method - " + method.getName() + "(" + method.getPath() + ")"); try { requestHeaders = method.getRequestHeaders(); if (Engine.logBeans.isTraceEnabled()) Engine.logBeans .trace("(HttpConnector) Request headers :\n" + Arrays.asList(requestHeaders).toString()); statuscode = doExecuteMethod(method, context); Engine.logBeans.debug("(HttpConnector) Status: " + method.getStatusLine().toString()); responseHeaders = method.getResponseHeaders(); context.setResponseHeaders(responseHeaders); if (Engine.logBeans.isTraceEnabled()) Engine.logBeans .trace("(HttpConnector) Response headers:\n" + Arrays.asList(responseHeaders).toString()); if (statuscode != -1) { InputStream in = method.getResponseBodyAsStream(); if (in != null) { /** * Retrieve response charset if available in responseHeaders */ charset = null; boolean checkGZip = false; // add GZip support #320 for (int i = 0; i < responseHeaders.length && (charset == null || !checkGZip); i++) { Header head = responseHeaders[i]; if (HeaderName.ContentType.is(head)) { context.contentType = head.getValue(); HeaderElement[] els = head.getElements(); for (int j = 0; j < els.length && charset == null; j++) { NameValuePair nvp = els[j].getParameterByName("charset"); if (nvp != null) charset = nvp.getValue(); } } else if (HeaderName.ContentEncoding.is(head)) { checkGZip = true; HeaderElement[] els = head.getElements(); for (int j = 0; j < els.length; j++) if ("gzip".equals(els[j].getName())) { Engine.logBeans.debug("(HttpConnector) Decode GZip stream"); in = new GZIPInputStream(in); } } } if (context.contentType != null && context.contentType.startsWith("multipart/") && context.requestedObject instanceof AbstractHttpTransaction) { Engine.logBeans.debug("(HttpConnector) Decoding multipart contentType"); try { AbstractHttpTransaction transaction = (AbstractHttpTransaction) context.requestedObject; BigMimeMultipart mp = new BigMimeMultipart(new BufferedInputStream(in), context.contentType); ByteArrayOutputStream bos = new ByteArrayOutputStream(); mp.nextPart(bos); result = bos.toByteArray(); if (transaction.getAllowDownloadAttachment()) { Document doc = context.outputDocument; Element attInfo = null; File file = File.createTempFile("c8o_", ".part"); for (MimePart bp = mp.nextPart(file); bp != null; bp = mp.nextPart(file)) { try { file.deleteOnExit(); if (attInfo == null) { Engine.logBeans.debug("(HttpConnector) Saving attachment(s)"); attInfo = doc.createElement("AttachmentInfo"); doc.getDocumentElement().appendChild(attInfo); } Element att = doc.createElement("attachment"); attInfo.appendChild(att); String cid = bp.getContentID(); if (cid != null) { cid = cid.replaceFirst("^<?(.*?)>?$", "$1"); att.setAttribute("cid", "cid:" + cid); } Engine.logBeans.debug("(HttpConnector) Saving the attachment cid: " + cid + " in file: " + file.getAbsolutePath()); att.setAttribute("filepath", file.getAbsolutePath()); Enumeration<javax.mail.Header> headers = GenericUtils .cast(bp.getAllHeaders()); while (headers.hasMoreElements()) { javax.mail.Header header = headers.nextElement(); Element eHeader = doc.createElement("header"); att.appendChild(eHeader); eHeader.setAttribute("name", header.getName()); eHeader.setAttribute("value", header.getValue()); } } catch (Exception e1) { Engine.logBeans .error("(HttpConnector) Failed to retrieve the attachment in " + file.getAbsolutePath(), e1); } file = File.createTempFile("c8o_", ".part"); } file.delete(); in.close(); } } catch (Exception e) { Engine.logBeans.error("(HttpConnector) Failed to retrieve attachments", e); } } else { result = IOUtils.toByteArray(in); in.close(); } } if (Engine.logBeans.isTraceEnabled()) { contents = new String((result != null) ? result : new byte[] {}); Engine.logBeans.trace("(HttpConnector) Response content:\n" + contents); } String redirectUrl, newuri; GetMethod redirectMethod = null; // Handles REDIRECTION through Location header if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header location = method.getResponseHeader("Location"); if (location != null) { newuri = location.getValue(); if ((newuri == null) || (newuri.equals(""))) { newuri = "/"; } // ignore any data after the ";" character int split = newuri.indexOf(';'); if (split != -1) { newuri = newuri.substring(0, split); } redirectUrl = getAbsoluteUrl(method, newuri); Engine.logBeans.debug("(HttpConnector) Redirecting to : " + redirectUrl); redirectMethod = new GetMethod(redirectUrl); // set headers for (int i = 0; i < requestHeaders.length; i++) redirectMethod.setRequestHeader(requestHeaders[i]); referer = redirectUrl.startsWith("http") ? redirectUrl : (hostConfiguration.getHostURL() + redirectUrl); result = executeMethod(redirectMethod, context); // recurse } else { Engine.logBeans.debug("(HttpConnector) Invalid redirect!"); } } else { /* * String lwContents = contents.toLowerCase(); int index, i, * j, k, z; // Handles REDIRECTION through META Refresh if * (((index = lwContents.indexOf("http-equiv='refresh'")) != * -1) || ((index = * lwContents.indexOf("http-equiv=\"refresh\"")) != -1)) { * if ((i = lwContents.indexOf("content=", index + 20)) != * -1) { char c = lwContents.charAt(i+8); if ((j = * lwContents.indexOf("url=", i)) != -1) { if ((k = * lwContents.indexOf(c, j + 1)) != -1) { newuri = * lwContents.substring(j+4, k); redirectUrl = * getAbsoluteUrl(method,newuri); * Engine.logBeans.debug("(HttpConnector) Redirecting to : " * + redirectUrl); redirectMethod = new * GetMethod(redirectUrl); * * // set headers for (z=0; z<requestHeaders.length; z++) * redirectMethod.setRequestHeader(requestHeaders[z]); * * referer = redirectUrl; result = * executeMethod(redirectMethod, context); // recurse } } } * } // Handles FRAMESET else if * (lwContents.indexOf("frameset") != -1) { * Engine.logBeans.debug * ("(HttpConnector) Analyzing frameset..."); * StringTokenizer st = new StringTokenizer(lwContents); * StringEx newcontents = new StringEx(lwContents); while * (st.hasMoreTokens()) { String token = st.nextToken(); * String uri; if (token.startsWith("src=")) { if * ((token.indexOf("\"") != -1) || (token.indexOf("'") != * -1)) { token = token.substring(5); uri = * token.substring(0,token.length()-1); newuri = * getAbsoluteUrl(method,uri); * Engine.logBeans.trace("(HttpConnector) Replaced uri ("+ * uri +") with newuri("+ newuri +")"); * * newcontents.replaceAll(token,newuri); } } } * Engine.logBeans * .trace("(HttpConnector) New response content:\n"+ * newcontents); result = newcontents.toString().getBytes(); * } */ } } //Added by julienda - #3433 - 04/03/2013 AbstractHttpTransaction abstractHttpTransaction = (AbstractHttpTransaction) context.transaction; if (abstractHttpTransaction.getHttpInfo()) { Document doc = context.outputDocument; //Remove the node HTTPInfo if we have a redirect NodeList nodeList = XMLUtils.findElements(context.outputDocument.getDocumentElement(), abstractHttpTransaction.getHttpInfoTagName()); if (nodeList != null) { XMLUtils.removeNodeListContent(nodeList); } //Parent Element httpInfoElement = doc.createElement(abstractHttpTransaction.getHttpInfoTagName()); //Add requested URL Element urlElement = doc.createElement("url"); urlElement.setTextContent(method.getURI().toString()); httpInfoElement.appendChild(urlElement); //Add status code Element httpStatusElement = doc.createElement("status"); httpStatusElement.setAttribute("code", Integer.toString(statuscode)); httpStatusElement.setAttribute("text", method.getStatusText()); httpInfoElement.appendChild(httpStatusElement); //We add headers informations List<Header> headers = Arrays.asList(requestHeaders); if (!headers.isEmpty()) { Element httpHeadersElement = doc.createElement("headers"); for (int i = 0; i < headers.size(); i++) { Element elt = doc.createElement("header"); elt.setAttribute("name", headers.get(i).getName()); elt.setAttribute("value", headers.get(i).getValue()); httpHeadersElement.appendChild(elt); } httpInfoElement.appendChild(httpHeadersElement); } // we add response header information if (responseHeaders.length != 0) { Element httpHeadersElement = doc.createElement("responseHeaders"); for (int i = 0; i < responseHeaders.length; i++) { Element elt = doc.createElement("header"); elt.setAttribute("name", responseHeaders[i].getName()); elt.setAttribute("value", responseHeaders[i].getValue()); httpHeadersElement.appendChild(elt); } httpInfoElement.appendChild(httpHeadersElement); } doc.getDocumentElement().appendChild(httpInfoElement); } } finally { method.releaseConnection(); } return result; }
From source file:com.twinsoft.convertigo.beans.connectors.SiteClipperConnector.java
private void doProcessRequest(Shuttle shuttle) throws IOException, ServletException, EngineException { shuttle.statisticsTaskID = context.statistics.start(EngineStatistics.GET_DOCUMENT); try {/*from w w w .j av a 2 s .com*/ shuttle.sharedScope = context.getSharedScope(); String domain = shuttle.getRequest(QueryPart.host) + shuttle.getRequest(QueryPart.port); Engine.logSiteClipper.trace("(SiteClipperConnector) Prepare the request for the domain " + domain); if (!shouldRewrite(domain)) { Engine.logSiteClipper.info( "(SiteClipperConnector) The domain " + domain + " is not allowed with this connector"); shuttle.response.sendError(HttpServletResponse.SC_FORBIDDEN, "The domain " + domain + " is not allowed with this connector"); return; } String uri = shuttle.getRequest(QueryPart.uri); Engine.logSiteClipper.info("Preparing " + shuttle.request.getMethod() + " " + shuttle.getRequestUrl()); HttpMethod httpMethod = null; XulRecorder xulRecorder = context.getXulRecorder(); if (xulRecorder != null) { httpMethod = shuttle.httpMethod = xulRecorder.getRecord(shuttle.getRequestUrlAndQuery()); } if (httpMethod == null) { try { switch (shuttle.getRequestHttpMethodType()) { case GET: httpMethod = new GetMethod(uri); break; case POST: httpMethod = new PostMethod(uri); ((PostMethod) httpMethod) .setRequestEntity(new InputStreamRequestEntity(shuttle.request.getInputStream())); break; case PUT: httpMethod = new PutMethod(uri); ((PutMethod) httpMethod) .setRequestEntity(new InputStreamRequestEntity(shuttle.request.getInputStream())); break; case DELETE: httpMethod = new DeleteMethod(uri); break; case HEAD: httpMethod = new HeadMethod(uri); break; case OPTIONS: httpMethod = new OptionsMethod(uri); break; case TRACE: httpMethod = new TraceMethod(uri); break; default: throw new ServletException( "(SiteClipperConnector) unknown http method " + shuttle.request.getMethod()); } httpMethod.setFollowRedirects(false); } catch (Exception e) { throw new ServletException( "(SiteClipperConnector) unexpected exception will building the http method : " + e.getMessage()); } shuttle.httpMethod = httpMethod; SiteClipperScreenClass screenClass = getCurrentScreenClass(); Engine.logSiteClipper.info("Request screen class: " + screenClass.getName()); for (String name : Collections .list(GenericUtils.<Enumeration<String>>cast(shuttle.request.getHeaderNames()))) { if (requestHeadersToIgnore.contains(HeaderName.parse(name))) { Engine.logSiteClipper.trace("(SiteClipperConnector) Ignoring request header " + name); } else { String value = shuttle.request.getHeader(name); Engine.logSiteClipper .trace("(SiteClipperConnector) Copying request header " + name + "=" + value); shuttle.setRequestCustomHeader(name, value); } } Engine.logSiteClipper.debug("(SiteClipperConnector) applying request rules for the screenclass " + screenClass.getName()); for (IRequestRule rule : screenClass.getRequestRules()) { if (rule.isEnabled()) { Engine.logSiteClipper .trace("(SiteClipperConnector) applying request rule " + rule.getName()); rule.fireEvents(); boolean done = rule.applyOnRequest(shuttle); Engine.logSiteClipper.debug("(SiteClipperConnector) the request rule " + rule.getName() + " is " + (done ? "well" : "not") + " applied"); } else { Engine.logSiteClipper .trace("(SiteClipperConnector) skip the disabled request rule " + rule.getName()); } } for (Entry<String, String> header : shuttle.requestCustomHeaders.entrySet()) { Engine.logSiteClipper.trace("(SiteClipperConnector) Push request header " + header.getKey() + "=" + header.getValue()); httpMethod.addRequestHeader(header.getKey(), header.getValue()); } String queryString = shuttle.request.getQueryString(); if (queryString != null) { try { // Fake test in order to check query string validity new URI("http://localhost/index?" + queryString, true, httpMethod.getParams().getUriCharset()); } catch (URIException e) { // Bugfix #2103 StringBuffer newQuery = new StringBuffer(); for (String part : RegexpUtils.pattern_and.split(queryString)) { String[] pair = RegexpUtils.pattern_equals.split(part, 2); try { newQuery.append('&') .append(URLEncoder.encode(URLDecoder.decode(pair[0], "UTF-8"), "UTF-8")); if (pair.length > 1) { newQuery.append('=').append( URLEncoder.encode(URLDecoder.decode(pair[1], "UTF-8"), "UTF-8")); } } catch (UnsupportedEncodingException ee) { Engine.logSiteClipper .trace("(SiteClipperConnector) failed to encode query part : " + part); } } queryString = newQuery.length() > 0 ? newQuery.substring(1) : newQuery.toString(); Engine.logSiteClipper.trace("(SiteClipperConnector) re-encode query : " + queryString); } } Engine.logSiteClipper.debug("(SiteClipperConnector) Copying the query string : " + queryString); httpMethod.setQueryString(queryString); // if (context.httpState == null) { // Engine.logSiteClipper.debug("(SiteClipperConnector) Creating new HttpState for context id " + context.contextID); // context.httpState = new HttpState(); // } else { // Engine.logSiteClipper.debug("(SiteClipperConnector) Using HttpState of context id " + context.contextID); // } getHttpState(shuttle); HostConfiguration hostConfiguration = getHostConfiguration(shuttle); HttpMethodParams httpMethodParams = httpMethod.getParams(); httpMethodParams.setBooleanParameter("http.connection.stalecheck", true); httpMethodParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true)); Engine.logSiteClipper.info("Requesting " + httpMethod.getName() + " " + hostConfiguration.getHostURL() + httpMethod.getURI().toString()); HttpClient httpClient = context.getHttpClient3(shuttle.getHttpPool()); HttpUtils.logCurrentHttpConnection(httpClient, hostConfiguration, shuttle.getHttpPool()); httpClient.executeMethod(hostConfiguration, httpMethod, context.httpState); } else { Engine.logSiteClipper.info("Retrieve recorded response from Context"); } int status = httpMethod.getStatusCode(); shuttle.processState = ProcessState.response; Engine.logSiteClipper.info("Request terminated with status " + status); shuttle.response.setStatus(status); if (Engine.isStudioMode() && status == HttpServletResponse.SC_OK && shuttle.getResponseMimeType().startsWith("text/")) { fireDataChanged(new ConnectorEvent(this, shuttle.getResponseAsString())); } SiteClipperScreenClass screenClass = getCurrentScreenClass(); Engine.logSiteClipper.info("Response screen class: " + screenClass.getName()); if (Engine.isStudioMode()) { Engine.theApp.fireObjectDetected(new EngineEvent(screenClass)); } for (Header header : httpMethod.getResponseHeaders()) { String name = header.getName(); if (responseHeadersToIgnore.contains(HeaderName.parse(name))) { Engine.logSiteClipper.trace("(SiteClipperConnector) Ignoring response header " + name); } else { String value = header.getValue(); Engine.logSiteClipper .trace("(SiteClipperConnector) Copying response header " + name + "=" + value); shuttle.responseCustomHeaders.put(name, value); } } Engine.logSiteClipper.debug( "(SiteClipperConnector) applying response rules for the screenclass " + screenClass.getName()); for (IResponseRule rule : screenClass.getResponseRules()) { if (rule.isEnabled()) { Engine.logSiteClipper.trace("(SiteClipperConnector) applying response rule " + rule.getName()); rule.fireEvents(); boolean done = rule.applyOnResponse(shuttle); Engine.logSiteClipper.debug("(SiteClipperConnector) the response rule " + rule.getName() + " is " + (done ? "well" : "not") + " applied"); } else { Engine.logSiteClipper .trace("(SiteClipperConnector) skip the disabled response rule " + rule.getName()); } } for (Entry<String, String> header : shuttle.responseCustomHeaders.entrySet()) { Engine.logSiteClipper.trace( "(SiteClipperConnector) Push request header " + header.getKey() + "=" + header.getValue()); shuttle.response.addHeader(header.getKey(), header.getValue()); } if (shuttle.postInstructions != null) { JSONArray instructions = new JSONArray(); for (IClientInstruction instruction : shuttle.postInstructions) { try { instructions.put(instruction.getInstruction()); } catch (JSONException e) { Engine.logSiteClipper.error( "(SiteClipperConnector) Failed to add a post instruction due to a JSONException", e); } } String codeToInject = "<script>C8O_postInstructions = " + instructions.toString() + "</script>\n" + "<script src=\"" + shuttle.getRequest(QueryPart.full_convertigo_path) + "/scripts/jquery.min.js\"></script>\n" + "<script src=\"" + shuttle.getRequest(QueryPart.full_convertigo_path) + "/scripts/siteclipper.js\"></script>\n"; String content = shuttle.getResponseAsString(); Matcher matcher = HtmlLocation.head_top.matcher(content); String newContent = RegexpUtils.inject(matcher, codeToInject); if (newContent == null) { matcher = HtmlLocation.body_top.matcher(content); newContent = RegexpUtils.inject(matcher, codeToInject); } if (newContent != null) { shuttle.setResponseAsString(newContent); } else { Engine.logSiteClipper.info( "(SiteClipperConnector) Failed to find a head or body tag in the response content"); Engine.logSiteClipper.trace("(SiteClipperConnector) Response content : \"" + content + "\""); } } long nbBytes = 0L; if (shuttle.responseAsString != null && shuttle.responseAsString.hashCode() != shuttle.responseAsStringOriginal.hashCode()) { OutputStream os = shuttle.response.getOutputStream(); switch (shuttle.getResponseContentEncoding()) { case gzip: os = new GZIPOutputStream(os); break; case deflate: os = new DeflaterOutputStream(os, new Deflater(Deflater.DEFAULT_COMPRESSION | Deflater.DEFAULT_STRATEGY, true)); break; default: break; } nbBytes = shuttle.responseAsByte.length; IOUtils.write(shuttle.responseAsString, os, shuttle.getResponseCharset()); os.close(); } else { InputStream is = (shuttle.responseAsByte == null) ? httpMethod.getResponseBodyAsStream() : new ByteArrayInputStream(shuttle.responseAsByte); if (is != null) { nbBytes = 0; OutputStream os = shuttle.response.getOutputStream(); int read = is.read(); while (read >= 0) { os.write(read); os.flush(); read = is.read(); nbBytes++; } is.close(); // nbBytes = IOUtils.copyLarge(is, shuttle.response.getOutputStream()); Engine.logSiteClipper .trace("(SiteClipperConnector) Response body copyied (" + nbBytes + " bytes)"); } } shuttle.response.getOutputStream().close(); shuttle.score = getScore(nbBytes); Engine.logSiteClipper .debug("(SiteClipperConnector) Request terminated with a score of " + shuttle.score); } finally { long duration = context.statistics.stop(shuttle.statisticsTaskID); if (context.requestedObject != null) { try { Engine.theApp.billingManager.insertBilling(context, Long.valueOf(duration), Long.valueOf(shuttle.score)); } catch (Exception e) { Engine.logContext.warn("Unable to insert billing ticket (the billing is thus ignored): [" + e.getClass().getName() + "] " + e.getMessage()); } } } }
From source file:org.abstracthorizon.proximity.storage.remote.CommonsHttpClientRemotePeer.java
/** * Execute method./*from w w w . j a v a2s. c om*/ * * @param method the method * * @return the int */ protected int executeMethod(HttpMethod method) { if (getUserAgentString() != null) { method.setRequestHeader(new Header("user-agent", getUserAgentString())); } method.setRequestHeader(new Header("accept", "*/*")); method.setRequestHeader(new Header("accept-language", "en-us")); method.setRequestHeader(new Header("accept-encoding", "gzip, identity")); method.setRequestHeader(new Header("connection", "Keep-Alive")); method.setRequestHeader(new Header("cache-control", "no-cache")); // TODO: fix for #93 // method.setFollowRedirects(isFollowRedirection()); method.setFollowRedirects(true); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, httpRetryHandler); method.setQueryString(getQueryString()); int resultCode = 0; try { resultCode = getHttpClient().executeMethod(httpConfiguration, method); } catch (HttpException ex) { logger.error("Protocol error while executing " + method.getName() + " method", ex); } catch (IOException ex) { logger.error("Tranport error while executing " + method.getName() + " method", ex); } return resultCode; }
From source file:org.alfresco.jive.impl.JiveOpenClientImpl.java
/** * Debugging method for obtaining the state of a request as a String. * //from w w w . j a va2 s .c o m * @param method The method to retrieve the request state from <i>(may be null)</i>. * @return The request state as a human-readable string value <i>(will not be null)</i>. */ private String requestToString(final HttpMethod method, final String body) { StringBuffer result = new StringBuffer(128); if (method != null) { result.append("\n\tMethod: "); result.append(method.getName()); result.append("\n\tURL: "); try { result.append(String.valueOf(method.getURI())); } catch (final URIException ue) { result.append("unknown, due to: " + ue.getMessage()); } result.append("\n\tHeaders: "); for (final Header header : method.getRequestHeaders()) { result.append("\n\t\t"); result.append(header.getName()); result.append(" : "); result.append(header.getValue()); } result.append("\n\tAuthenticating? " + method.getDoAuthentication()); if (body != null) { result.append("\n\tBody: "); result.append(body); } } else { result.append("(null)"); } return (result.toString()); }
From source file:org.alfresco.wcm.client.impl.WebScriptCallerImpl.java
private void executeRequest(WebscriptResponseHandler handler, HttpMethod httpMethod, boolean ignoreUnauthorized) { long startTime = 0L; if (log.isDebugEnabled()) { startTime = System.currentTimeMillis(); }/*from w ww . ja v a 2 s.com*/ try { httpClient.executeMethod(httpMethod); if ((httpMethod.getStatusCode() == 401 || httpMethod.getStatusCode() == 403) && !ignoreUnauthorized) { discardResponse(httpMethod); this.getTicket(username, password); httpClient.executeMethod(httpMethod); } if (httpMethod.getStatusCode() == 200) { handler.handleResponse(httpMethod.getResponseBodyAsStream()); } else { // Must read the response, even though we don't use it discardResponse(httpMethod); } } catch (RuntimeException ex) { log.error("Rethrowing runtime exception.", ex); throw ex; } catch (Exception ex) { log.error("Failed to make request to Alfresco web script", ex); } finally { if (log.isDebugEnabled()) { log.debug(httpMethod.getName() + " request to " + httpMethod.getPath() + "?" + httpMethod.getQueryString() + " completed in " + (System.currentTimeMillis() - startTime) + "ms"); } httpMethod.releaseConnection(); } }
From source file:org.apache.abdera.ext.oauth.OAuthScheme.java
private String generateSignature(OAuthCredentials credentials, HttpMethod method, String nonce, long timestamp) throws AuthenticationException { try {//from w w w . j a v a 2 s.c om String baseString = method.getName().toUpperCase() + method.getURI().toString() + OAUTH_KEYS.OAUTH_CONSUMER_KEY.toLowerCase() + "=" + credentials.getConsumerKey() + OAUTH_KEYS.OAUTH_TOKEN.toLowerCase() + "=" + credentials.getToken() + OAUTH_KEYS.OAUTH_SIGNATURE_METHOD.toLowerCase() + "=" + credentials.getSignatureMethod() + OAUTH_KEYS.OAUTH_TIMESTAMP.toLowerCase() + "=" + timestamp + OAUTH_KEYS.OAUTH_NONCE.toLowerCase() + "=" + nonce + OAUTH_KEYS.OAUTH_VERSION.toLowerCase() + "=" + credentials.getVersion(); return sign(credentials.getSignatureMethod(), URLEncoder.encode(baseString, "UTF-8"), credentials.getCert()); } catch (URIException e) { throw new AuthenticationException(e.getMessage(), e); } catch (UnsupportedEncodingException e) { throw new AuthenticationException(e.getMessage(), e); } }
From source file:org.apache.camel.component.http.HttpProducer.java
public void process(Exchange exchange) throws Exception { // if we bridge endpoint then we need to skip matching headers with the HTTP_QUERY to avoid sending // duplicated headers to the receiver, so use this skipRequestHeaders as the list of headers to skip Map<String, Object> skipRequestHeaders = null; if (getEndpoint().isBridgeEndpoint()) { exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE); String queryString = exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class); if (queryString != null) { skipRequestHeaders = URISupport.parseQuery(queryString); }/*from w w w . j a v a 2 s. c om*/ // Need to remove the Host key as it should be not used exchange.getIn().getHeaders().remove("host"); } HttpMethod method = createMethod(exchange); Message in = exchange.getIn(); String httpProtocolVersion = in.getHeader(Exchange.HTTP_PROTOCOL_VERSION, String.class); if (httpProtocolVersion != null) { // set the HTTP protocol version HttpMethodParams params = method.getParams(); params.setVersion(HttpVersion.parse(httpProtocolVersion)); } HeaderFilterStrategy strategy = getEndpoint().getHeaderFilterStrategy(); // propagate headers as HTTP headers for (Map.Entry<String, Object> entry : in.getHeaders().entrySet()) { String key = entry.getKey(); Object headerValue = in.getHeader(key); if (headerValue != null) { // use an iterator as there can be multiple values. (must not use a delimiter, and allow empty values) final Iterator<?> it = ObjectHelper.createIterator(headerValue, null, true); // the value to add as request header final List<String> values = new ArrayList<String>(); // if its a multi value then check each value if we can add it and for multi values they // should be combined into a single value while (it.hasNext()) { String value = exchange.getContext().getTypeConverter().convertTo(String.class, it.next()); // we should not add headers for the parameters in the uri if we bridge the endpoint // as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) { continue; } if (value != null && strategy != null && !strategy.applyFilterToCamelHeaders(key, value, exchange)) { values.add(value); } } // add the value(s) as a http request header if (values.size() > 0) { // use the default toString of a ArrayList to create in the form [xxx, yyy] // if multi valued, for a single value, then just output the value as is String s = values.size() > 1 ? values.toString() : values.get(0); method.addRequestHeader(key, s); } } } // lets store the result in the output message. try { if (LOG.isDebugEnabled()) { LOG.debug("Executing http {} method: {}", method.getName(), method.getURI().toString()); } int responseCode = executeMethod(method); LOG.debug("Http responseCode: {}", responseCode); if (!throwException) { // if we do not use failed exception then populate response for all response codes populateResponse(exchange, method, in, strategy, responseCode); } else { if (responseCode >= 100 && responseCode < 300) { // only populate response for OK response populateResponse(exchange, method, in, strategy, responseCode); } else { // operation failed so populate exception to throw throw populateHttpOperationFailedException(exchange, method, responseCode); } } } finally { method.releaseConnection(); } }
From source file:org.apache.cloudstack.network.element.SspClient.java
private String executeMethod(HttpMethod method) { String apiCallPath = null;/*from ww w . j a va 2s . c om*/ try { apiCallPath = method.getName() + " " + method.getURI().toString(); } catch (URIException e) { s_logger.error("method getURI failed", e); } String response = null; try { client.executeMethod(method); response = method.getResponseBodyAsString(); } catch (HttpException e) { s_logger.error("ssp api call failed " + apiCallPath, e); return null; } catch (IOException e) { s_logger.error("ssp api call failed " + apiCallPath, e); return null; } finally { method.releaseConnection(); } if (method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { if (!login()) { return null; } try { client.executeMethod(method); response = method.getResponseBodyAsString(); } catch (HttpException e) { s_logger.error("ssp api call failed " + apiCallPath, e); return null; } catch (IOException e) { s_logger.error("ssp api call failed " + apiCallPath, e); return null; } finally { method.releaseConnection(); } } s_logger.info("ssp api call:" + apiCallPath + " user=" + username + " status=" + method.getStatusLine()); if (method instanceof EntityEnclosingMethod) { EntityEnclosingMethod emethod = (EntityEnclosingMethod) method; RequestEntity reqEntity = emethod.getRequestEntity(); if (reqEntity instanceof StringRequestEntity) { StringRequestEntity strReqEntity = (StringRequestEntity) reqEntity; s_logger.debug("ssp api request body:" + strReqEntity.getContent()); } else { s_logger.debug("ssp api request body:" + emethod.getRequestEntity()); } } s_logger.debug("ssp api response body:" + response); return response; }
From source file:org.apache.cocoon.generation.WebServiceProxyGenerator.java
/** * Forwards the request and returns the response. * /* w w w . j a v a 2s . c o m*/ * The rest is probably out of date: * Will use a UrlGetMethod to benefit the cacheing mechanism * and intermediate proxy servers. * It is potentially possible that the size of the request * may grow beyond a certain limit for GET and it will require POST instead. * * @return byte[] XML response */ public byte[] fetch() throws ProcessingException { HttpMethod method = null; // check which method (GET or POST) to use. if (this.configuredHttpMethod.equalsIgnoreCase(METHOD_POST)) { method = new PostMethod(this.source); } else { method = new GetMethod(this.source); } if (this.getLogger().isDebugEnabled()) { this.getLogger().debug("request HTTP method: " + method.getName()); } // this should probably be exposed as a sitemap option method.setFollowRedirects(true); // copy request parameters and merge with URL parameters Request request = ObjectModelHelper.getRequest(objectModel); ArrayList paramList = new ArrayList(); Enumeration enumeration = request.getParameterNames(); while (enumeration.hasMoreElements()) { String pname = (String) enumeration.nextElement(); String[] paramsForName = request.getParameterValues(pname); for (int i = 0; i < paramsForName.length; i++) { NameValuePair pair = new NameValuePair(pname, paramsForName[i]); paramList.add(pair); } } if (paramList.size() > 0) { NameValuePair[] allSubmitParams = new NameValuePair[paramList.size()]; paramList.toArray(allSubmitParams); String urlQryString = method.getQueryString(); // use HttpClient encoding routines method.setQueryString(allSubmitParams); String submitQryString = method.getQueryString(); // set final web service query string // sometimes the querystring is null here... if (null == urlQryString) { method.setQueryString(submitQryString); } else { method.setQueryString(urlQryString + "&" + submitQryString); } } // if there are submit parameters byte[] response = null; try { int httpStatus = httpClient.executeMethod(method); if (httpStatus < 400) { if (this.getLogger().isDebugEnabled()) { this.getLogger().debug("Return code when accessing the remote Url: " + httpStatus); } } else { throw new ProcessingException("The remote returned error " + httpStatus + " when attempting to access remote URL:" + method.getURI()); } } catch (URIException e) { throw new ProcessingException("There is a problem with the URI: " + this.source, e); } catch (IOException e) { try { throw new ProcessingException( "Exception when attempting to access the remote URL: " + method.getURI(), e); } catch (URIException ue) { throw new ProcessingException("There is a problem with the URI: " + this.source, ue); } } finally { /* It is important to always read the entire response and release the * connection regardless of whether the server returned an error or not. * {@link http://jakarta.apache.org/commons/httpclient/tutorial.html} */ response = method.getResponseBody(); method.releaseConnection(); } return response; }
From source file:org.apache.hadoop.hbase.stargate.client.Client.java
/** * Execute a transaction method given a complete URI. * @param method the transaction method// ww w .j a v a2s .c o m * @param headers HTTP header values to send * @param uri the URI * @return the HTTP response code * @throws IOException */ @SuppressWarnings("deprecation") public int executeURI(HttpMethod method, Header[] headers, String uri) throws IOException { method.setURI(new URI(uri)); if (headers != null) { for (Header header : headers) { method.addRequestHeader(header); } } long startTime = System.currentTimeMillis(); int code = httpClient.executeMethod(method); long endTime = System.currentTimeMillis(); if (LOG.isDebugEnabled()) { LOG.debug(method.getName() + " " + uri + ": " + code + " " + method.getStatusText() + " in " + (endTime - startTime) + " ms"); } return code; }