List of usage examples for org.apache.commons.httpclient HttpMethod setPath
public abstract void setPath(String paramString);
From source file:org.alfresco.repo.transfer.HttpClientTransmitterImpl.java
public void commit(Transfer transfer) throws TransferException { TransferTarget target = transfer.getTransferTarget(); HttpMethod commitRequest = getPostMethod(); try {//from w w w. ja v a2 s .c o m HostConfiguration hostConfig = getHostConfig(target); HttpState httpState = getHttpState(target); commitRequest.setPath(target.getEndpointPath() + "/commit"); //Put the transferId on the query string commitRequest.setQueryString( new NameValuePair[] { new NameValuePair("transferId", transfer.getTransferId()) }); try { int responseStatus = httpClient.executeMethod(hostConfig, commitRequest, httpState); checkResponseStatus("commit", responseStatus, commitRequest); //If we get here then we've received a 200 response //We're expecting the transfer id encoded in a JSON object... } catch (RuntimeException e) { throw e; } catch (Exception e) { String error = "Failed to execute HTTP request to target"; log.error(error, e); throw new TransferException(MSG_HTTP_REQUEST_FAILED, new Object[] { "commit", target.toString(), e.toString() }, e); } } finally { commitRequest.releaseConnection(); } }
From source file:org.alfresco.repo.transfer.HttpClientTransmitterImpl.java
public void prepare(Transfer transfer) throws TransferException { TransferTarget target = transfer.getTransferTarget(); HttpMethod prepareRequest = getPostMethod(); try {//www .j a v a 2s . co m HostConfiguration hostConfig = getHostConfig(target); HttpState httpState = getHttpState(target); prepareRequest.setPath(target.getEndpointPath() + "/prepare"); //Put the transferId on the query string prepareRequest.setQueryString( new NameValuePair[] { new NameValuePair("transferId", transfer.getTransferId()) }); try { int responseStatus = httpClient.executeMethod(hostConfig, prepareRequest, httpState); checkResponseStatus("prepare", responseStatus, prepareRequest); //If we get here then we've received a 200 response //We're expecting the transfer id encoded in a JSON object... } catch (RuntimeException e) { throw e; } catch (Exception e) { String error = "Failed to execute HTTP request to target"; log.debug(error, e); throw new TransferException(MSG_HTTP_REQUEST_FAILED, new Object[] { "prepare", target.toString(), e.toString() }, e); } } finally { prepareRequest.releaseConnection(); } }
From source file:org.alfresco.repo.transfer.HttpClientTransmitterImpl.java
/** * *///from ww w . j a v a2s. c o m public TransferProgress getStatus(Transfer transfer) throws TransferException { TransferTarget target = transfer.getTransferTarget(); HttpMethod statusRequest = getPostMethod(); try { HostConfiguration hostConfig = getHostConfig(target); HttpState httpState = getHttpState(target); statusRequest.setPath(target.getEndpointPath() + "/status"); //Put the transferId on the query string statusRequest.setQueryString( new NameValuePair[] { new NameValuePair("transferId", transfer.getTransferId()) }); try { int responseStatus = httpClient.executeMethod(hostConfig, statusRequest, httpState); checkResponseStatus("status", responseStatus, statusRequest); //If we get here then we've received a 200 response String statusPayload = statusRequest.getResponseBodyAsString(); JSONObject statusObj = new JSONObject(statusPayload); //We're expecting the transfer progress encoded in a JSON object... int currentPosition = statusObj.getInt("currentPosition"); int endPosition = statusObj.getInt("endPosition"); String statusStr = statusObj.getString("status"); TransferProgress p = new TransferProgress(); if (statusObj.has("error")) { JSONObject errorJSON = statusObj.getJSONObject("error"); Throwable throwable = rehydrateError(errorJSON); p.setError(throwable); } p.setStatus(TransferProgress.Status.valueOf(statusStr)); p.setCurrentPosition(currentPosition); p.setEndPosition(endPosition); return p; } catch (RuntimeException e) { throw e; } catch (Exception e) { String error = "Failed to execute HTTP request to target"; log.debug(error, e); throw new TransferException(MSG_HTTP_REQUEST_FAILED, new Object[] { "status", target.toString(), e.toString() }, e); } } finally { statusRequest.releaseConnection(); } }
From source file:org.apache.ode.axis2.httpbinding.HttpMethodConverter.java
/** * create and initialize the http method. * Http Headers that may been passed in the params are not set in this method. * Headers will be automatically set by HttpClient. * See usages of HostParams.DEFAULT_HEADERS * See org.apache.commons.httpclient.HttpMethodDirector#executeMethod(org.apache.commons.httpclient.HttpMethod) *//*from www . j a v a 2 s . c om*/ protected HttpMethod prepareHttpMethod(BindingOperation opBinding, String verb, Map<String, Element> partValues, Map<String, Node> headers, final String rootUri, HttpParams params) throws UnsupportedEncodingException { if (log.isDebugEnabled()) log.debug("Preparing http request..."); // convenience variables... BindingInput bindingInput = opBinding.getBindingInput(); HTTPOperation httpOperation = (HTTPOperation) WsdlUtils.getOperationExtension(opBinding); MIMEContent content = WsdlUtils.getMimeContent(bindingInput.getExtensibilityElements()); String contentType = content == null ? null : content.getType(); boolean useUrlEncoded = WsdlUtils.useUrlEncoded(bindingInput) || PostMethod.FORM_URL_ENCODED_CONTENT_TYPE.equalsIgnoreCase(contentType); boolean useUrlReplacement = WsdlUtils.useUrlReplacement(bindingInput); // the http method to be built and returned HttpMethod method = null; // the 4 elements the http method may be made of String relativeUri = httpOperation.getLocationURI(); String queryPath = null; RequestEntity requestEntity; String encodedParams = null; // ODE supports uri template in both port and operation location. // so assemble the final url *before* replacement String completeUri = rootUri; if (StringUtils.isNotEmpty(relativeUri)) { completeUri = completeUri + (completeUri.endsWith("/") || relativeUri.startsWith("/") ? "" : "/") + relativeUri; } if (useUrlReplacement) { // insert part values in the url completeUri = new UrlReplacementTransformer().transform(completeUri, partValues); } else if (useUrlEncoded) { // encode part values encodedParams = new URLEncodedTransformer().transform(partValues); } // http-client api is not really neat // something similar to the following would save some if/else manipulations. // But we have to deal with it as-is. // // method = new Method(verb); // method.setRequestEnity(..) // etc... if ("GET".equalsIgnoreCase(verb) || "DELETE".equalsIgnoreCase(verb)) { if ("GET".equalsIgnoreCase(verb)) { method = new GetMethod(); } else if ("DELETE".equalsIgnoreCase(verb)) { method = new DeleteMethod(); } method.getParams().setDefaults(params); if (useUrlEncoded) { queryPath = encodedParams; } // Let http-client manage the redirection // see org.apache.commons.httpclient.params.HttpClientParams.MAX_REDIRECTS // default is 100 method.setFollowRedirects(true); } else if ("POST".equalsIgnoreCase(verb) || "PUT".equalsIgnoreCase(verb)) { if ("POST".equalsIgnoreCase(verb)) { method = new PostMethod(); } else if ("PUT".equalsIgnoreCase(verb)) { method = new PutMethod(); } method.getParams().setDefaults(params); // some body-building... final String contentCharset = method.getParams().getContentCharset(); if (log.isDebugEnabled()) log.debug("Content-Type [" + contentType + "] Charset [" + contentCharset + "]"); if (useUrlEncoded) { requestEntity = new StringRequestEntity(encodedParams, PostMethod.FORM_URL_ENCODED_CONTENT_TYPE, contentCharset); } else { // get the part to be put in the body Part part = opBinding.getOperation().getInput().getMessage().getPart(content.getPart()); Element partValue = partValues.get(part.getName()); if (part.getElementName() == null) { String errMsg = "XML Types are not supported. Parts must use elements."; if (log.isErrorEnabled()) log.error(errMsg); throw new RuntimeException(errMsg); } else if (HttpUtils.isXml(contentType)) { if (log.isDebugEnabled()) log.debug("Content-Type [" + contentType + "] equivalent to 'text/xml'"); // stringify the first element String xmlString = DOMUtils.domToString(DOMUtils.getFirstChildElement(partValue)); requestEntity = new StringRequestEntity(xmlString, contentType, contentCharset); } else { if (log.isDebugEnabled()) log.debug("Content-Type [" + contentType + "] NOT equivalent to 'text/xml'. The text content of part value will be sent as text"); // encoding conversion is managed by StringRequestEntity if necessary requestEntity = new StringRequestEntity(DOMUtils.getTextContent(partValue), contentType, contentCharset); } } // cast safely, PUT and POST are subclasses of EntityEnclosingMethod final EntityEnclosingMethod enclosingMethod = (EntityEnclosingMethod) method; enclosingMethod.setRequestEntity(requestEntity); enclosingMethod .setContentChunked(params.getBooleanParameter(Properties.PROP_HTTP_REQUEST_CHUNK, false)); } else { // should not happen because of HttpBindingValidator, but never say never throw new IllegalArgumentException("Unsupported HTTP method: " + verb); } method.setPath(completeUri); // assumes that the path is properly encoded (URL safe). method.setQueryString(queryPath); // set headers setHttpRequestHeaders(method, opBinding, partValues, headers, params); return method; }
From source file:org.cauldron.tasks.HttpCall.java
/** * Running an HttpTask retrieves the path contents according to the task * attributes. POST body comes from the input. *//* w w w . j a v a2 s . c o m*/ public Object run(Context context, Object input) throws TaskException { // For POST, body must be available as input. String body = null; if (!isGet) { body = (String) context.convert(input, String.class); if (body == null) throw new TaskException("HTTP POST input must be convertible to String"); } // Prepare request parameters. NameValuePair[] nvp = null; if (params != null && params.size() > 0) { nvp = new NameValuePair[params.size()]; int count = 0; for (Iterator entries = params.entrySet().iterator(); entries.hasNext();) { Map.Entry entry = (Map.Entry) entries.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); nvp[count++] = new NameValuePair(key, value); } } // Create the retrieval method and set parameters. // HttpMethod method; if (isGet) { GetMethod get = new GetMethod(); if (nvp != null) get.setQueryString(nvp); method = get; } else { PostMethod post = new PostMethod(); post.setRequestBody(body); if (nvp != null) post.addParameters(nvp); method = post; } // Make the call. method.setPath(path); HttpConnection connection = connectionManager.getConnection(config); try { connection.open(); method.execute(new HttpState(), connection); return method.getResponseBodyAsString(); } catch (HttpException e) { throw new TaskException(e); } catch (IOException e) { throw new TaskException(e); } finally { connection.close(); } }
From source file:org.codehaus.wadi.web.impl.CommonsHttpProxy.java
protected void doProxy(URI uri, WebInvocation context) throws ProxyingException { HttpServletRequest hreq = context.getHreq(); HttpServletResponse hres = context.getHres(); long startTime = System.currentTimeMillis(); String m = hreq.getMethod();/*from w w w . j av a 2s .c om*/ Class clazz = (Class) _methods.get(m); if (clazz == null) { throw new IrrecoverableException("unsupported http method: " + m); } HttpMethod hm = null; try { hm = (HttpMethod) clazz.newInstance(); } catch (Exception e) { throw new IrrecoverableException("could not create HttpMethod instance", e); // should never happen } String requestURI = getRequestURI(hreq); hm.setPath(requestURI); String queryString = hreq.getQueryString(); if (queryString != null) { hm.setQueryString(queryString); requestURI += queryString; } hm.setFollowRedirects(false); //hm.setURI(new URI(uri)); hm.setStrictMode(false); // check connection header String connectionHdr = hreq.getHeader("Connection"); // TODO - what if there are multiple values ? if (connectionHdr != null) { connectionHdr = connectionHdr.toLowerCase(); if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close")) connectionHdr = null; // TODO ?? } // copy headers boolean xForwardedFor = false; boolean hasContent = false; int contentLength = 0; Enumeration enm = hreq.getHeaderNames(); while (enm.hasMoreElements()) { // TODO could be better than this! - using javax.servlet ? String hdr = (String) enm.nextElement(); String lhdr = hdr.toLowerCase(); if (_DontProxyHeaders.contains(lhdr)) continue; if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0) continue; if ("content-length".equals(lhdr)) { try { contentLength = hreq.getIntHeader(hdr); hasContent = contentLength > 0; } catch (NumberFormatException e) { if (_log.isWarnEnabled()) _log.warn("bad Content-Length header value: " + hreq.getHeader(hdr), e); } } if ("content-type".equals(lhdr)) { hasContent = true; } Enumeration vals = hreq.getHeaders(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { hm.addRequestHeader(hdr, val); // if (_log.isInfoEnabled()) _log.info("Request " + hdr + ": " + val); xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); // why is this not in the outer loop ? } } } // cookies... // although we copy cookie headers into the request abover - commons-httpclient thinks it knows better and strips them out before sending. // we have to explicitly use their interface to add the cookies - painful... // DOH! - an org.apache.commons.httpclient.Cookie is NOT a // javax.servlet.http.Cookie - and it looks like the two don't // map onto each other without data loss... HttpState state = new HttpState(); javax.servlet.http.Cookie[] cookies = hreq.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { javax.servlet.http.Cookie c = cookies[i]; String domain = c.getDomain(); if (domain == null) { domain = hreq.getServerName(); // TODO - tmp test // _log.warn("defaulting cookie domain"); } // domain=null; String cpath = c.getPath(); if (cpath == null) { cpath = hreq.getContextPath(); // fix for Jetty // _log.warn("defaulting cookie path"); } //if (_log.isTraceEnabled()) _log.trace("PATH: value="+path+" length="+(path==null?0:path.length())); Cookie cookie = new Cookie(domain, c.getName(), c.getValue(), cpath, c.getMaxAge(), c.getSecure()); // TODO - sort out domain //if (_log.isTraceEnabled()) _log.trace("Cookie: "+cookie.getDomain()+","+ cookie.getName()+","+ cookie.getValue()+","+ cookie.getPath()+","+ cookie.getExpiryDate()+","+ cookie.getSecure()); state.addCookie(cookie); //if (_log.isTraceEnabled()) _log.trace("Cookie: "+cookie.toString()); } } // Proxy headers hm.addRequestHeader("Via", "1.1 " + hreq.getLocalName() + ":" + hreq.getLocalPort() + " \"WADI\""); if (!xForwardedFor) hm.addRequestHeader("X-Forwarded-For", hreq.getRemoteAddr()); // Max-Forwards... // a little bit of cache control // String cache_control = hreq.getHeader("Cache-Control"); // if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0)) // httpMethod.setUseCaches(false); // customize Connection // uc.setDoInput(true); int client2ServerTotal = 0; if (hasContent) { // uc.setDoOutput(true); try { if (hm instanceof EntityEnclosingMethod) ((EntityEnclosingMethod) hm).setRequestBody(hreq.getInputStream()); // TODO - do we need to close response stream at end... ? } catch (IOException e) { throw new IrrecoverableException("could not pss request input across proxy", e); } } try { HttpClient client = new HttpClient(); HostConfiguration hc = new HostConfiguration(); //String host=location.getAddress().getHostAddress(); // inefficient - but stops httpclient from rejecting half our cookies... String host = uri.getHost(); hc.setHost(host, uri.getPort()); client.executeMethod(hc, hm, state); } catch (IOException e) // TODO { _log.warn("problem proxying connection:", e); } InputStream fromServer = null; // handler status codes etc. int code = 502; // String message="Bad Gateway: could not read server response code or message"; code = hm.getStatusCode(); // IOException // message=hm.getStatusText(); // IOException hres.setStatus(code); // hres.setStatus(code, message); - deprecated... try { fromServer = hm.getResponseBodyAsStream(); // IOException } catch (IOException e) { _log.warn("problem acquiring http client output", e); } // clear response defaults. hres.setHeader("Date", null); hres.setHeader("Server", null); // set response headers // TODO - is it a bug in Jetty that I have to start my loop at 1 ? or that key[0]==null ? // Try this inside Tomcat... Header[] headers = hm.getResponseHeaders(); for (int i = 0; i < headers.length; i++) { String h = headers[i].toExternalForm(); int index = h.indexOf(':'); String key = h.substring(0, index).trim().toLowerCase(); String val = h.substring(index + 1, h.length()).trim(); if (val != null && !_DontProxyHeaders.contains(key)) { hres.addHeader(key, val); // if (_log.isInfoEnabled()) _log.info("Response: "+key+" - "+val); } } hres.addHeader("Via", "1.1 (WADI)"); // copy server->client int server2ClientTotal = 0; if (fromServer != null) { try { OutputStream toClient = hres.getOutputStream();// IOException server2ClientTotal += copy(fromServer, toClient, 8192);// IOException } catch (IOException e) { _log.warn("problem proxying server response back to client", e); } finally { try { fromServer.close(); } catch (IOException e) { // well - we did our best... _log.warn("problem closing server response stream", e); } } } long endTime = System.currentTimeMillis(); long elapsed = endTime - startTime; if (_log.isDebugEnabled()) { _log.debug("in:" + client2ServerTotal + ", out:" + server2ClientTotal + ", status:" + code + ", time:" + elapsed + ", uri:" + uri); } }
From source file:org.elasticsearch.hadoop.rest.commonshttp.CommonsHttpTransport.java
@Override public Response execute(Request request) throws IOException { HttpMethod http = null; switch (request.method()) { case DELETE://w w w. j a va 2 s. c o m http = new DeleteMethodWithBody(); break; case HEAD: http = new HeadMethod(); break; case GET: http = (request.body() == null ? new GetMethod() : new GetMethodWithBody()); break; case POST: http = new PostMethod(); break; case PUT: http = new PutMethod(); break; default: throw new EsHadoopTransportException("Unknown request method " + request.method()); } CharSequence uri = request.uri(); if (StringUtils.hasText(uri)) { http.setURI(new URI(escapeUri(uri.toString(), settings.getNetworkSSLEnabled()), false)); } // NB: initialize the path _after_ the URI otherwise the path gets reset to / http.setPath(prefixPath(request.path().toString())); try { // validate new URI uri = http.getURI().toString(); } catch (URIException uriex) { throw new EsHadoopTransportException("Invalid target URI " + request, uriex); } CharSequence params = request.params(); if (StringUtils.hasText(params)) { http.setQueryString(params.toString()); } ByteSequence ba = request.body(); if (ba != null && ba.length() > 0) { if (!(http instanceof EntityEnclosingMethod)) { throw new IllegalStateException(String.format("Method %s cannot contain body - implementation bug", request.method().name())); } EntityEnclosingMethod entityMethod = (EntityEnclosingMethod) http; entityMethod.setRequestEntity(new BytesArrayRequestEntity(ba)); entityMethod.setContentChunked(false); } // when tracing, log everything if (log.isTraceEnabled()) { log.trace(String.format("Tx %s[%s]@[%s][%s] w/ payload [%s]", proxyInfo, request.method().name(), httpInfo, request.path(), request.body())); } long start = System.currentTimeMillis(); try { client.executeMethod(http); } finally { stats.netTotalTime += (System.currentTimeMillis() - start); } if (log.isTraceEnabled()) { Socket sk = ReflectionUtils.invoke(GET_SOCKET, conn, (Object[]) null); String addr = sk.getLocalAddress().getHostAddress(); log.trace(String.format("Rx %s@[%s] [%s-%s] [%s]", proxyInfo, addr, http.getStatusCode(), HttpStatus.getStatusText(http.getStatusCode()), http.getResponseBodyAsString())); } // the request URI is not set (since it is retried across hosts), so use the http info instead for source return new SimpleResponse(http.getStatusCode(), new ResponseInputStream(http), httpInfo); }
From source file:org.openmicroscopy.shoola.svc.transport.HttpChannel.java
/** * Posts the request and catches the reply. * /*from w w w .j a va 2 s .c o m*/ * @param out The request to post. * @param in The reply to fill. * @throws TransportException If an error occurred while transferring data. * @throws IOException If an error occurred while unmarshalling the method. */ public void exchange(Request out, Reply in) throws TransportException, IOException { //Sanity checks. if (out == null) throw new NullPointerException("No request."); if (in == null) throw new NullPointerException("No reply."); //Build HTTP request, send it, and wait for response. //Then read the response into the Reply object. HttpClient comLink = getCommunicationLink(); HttpMethod method = null; try { method = out.marshal(); method.setPath(getRequestPath()); comLink.executeMethod(method); in.unmarshal(method, this); } finally { //Required by Http Client library. if (method != null) method.releaseConnection(); } }
From source file:org.osaf.caldav4j.methods.HttpClient.java
/** * Overwritten to Handle tickets.// w ww . j a v a 2s.c o m */ public int executeMethod(HostConfiguration hostConfiguration, HttpMethod method, HttpState state) throws IOException, HttpException { if (ticket != null) { if (ticketLocation == TicketLocation.HEADER) { method.addRequestHeader(CalDAVConstants.TICKET_HEADER, ticket); } //FIXME what if there are other query parameters! if (ticketLocation == TicketLocation.QUERY_PARAM) { method.setPath(method.getPath() + CalDAVConstants.URL_APPENDER + ticket); } } return super.executeMethod(hostConfiguration, method, state); }
From source file:org.socraticgrid.displaycalendarlib.CalendarInit.java
public int executeCalMethod(int expectedStatus, HttpMethod method, boolean deleteOnTearDown) throws IOException { String relativePath = method.getPath(); // prefix path with collection path method.setPath(collectionPath + relativePath); int response = executeHttpMethod(expectedStatus, httpClient, method); if (deleteOnTearDown) { deleteOnTearDownPaths.add(relativePath); }/*from w w w . jav a2 s.com*/ return response; }