List of usage examples for org.apache.commons.httpclient Header Header
public Header(String paramString1, String paramString2)
From source file:com.tasktop.c2c.server.ssh.server.commands.AbstractInteractiveProxyCommand.java
protected void performCommand(Environment env, ProjectService service, String projectId, String path, String requestPath, RequestHeadersSupport headers) throws CommandException { String internalProxyUri = service.computeInternalProxyBaseUri(false); if (internalProxyUri == null) { throw new IllegalStateException(); }//from w w w . ja v a2 s . c o m URI targetUri; try { if (!internalProxyUri.endsWith("/")) { internalProxyUri += "/"; } internalProxyUri += getName() + '/' + path; targetUri = new URI(internalProxyUri); } catch (URISyntaxException e) { throw new RuntimeException(e); } String host = targetUri.getHost(); int port = targetUri.getPort(); if (port < 0) { port = 80; } if (targetUri.getScheme() == null || !targetUri.getScheme().equalsIgnoreCase("http")) { throw new IllegalStateException("scheme " + targetUri.getScheme() + " is not supported"); } HeaderGroup headerGroup = computeHeaders(targetUri); for (Entry<String, List<String>> headerEntry : headers.getRequestHeaders().entrySet()) { for (String value : headerEntry.getValue()) { headerGroup.addHeader(new Header(headerEntry.getKey(), value)); } } getLogger().info("Proxying " + getName() + " to " + targetUri); try { Socket socket = socketFactory.openConnection(host, port); try { // initiate an HTTP request with Transfer-Encoding: chunked OutputStream proxyOut = socket.getOutputStream(); emitHttpRequestLine(proxyOut, targetUri); emitHeaders(proxyOut, headerGroup); proxyOut.flush(); List<Callable<Void>> tasks = new ArrayList<Callable<Void>>(3); FlushingChunkedOutputStream chunkedRequestOut = new FlushingChunkedOutputStream(proxyOut); tasks.add(new InputPipe(in, chunkedRequestOut, bufferSize, Thread.currentThread()).flush(true)); // start these pipes ExecutorService executor = Executors.newFixedThreadPool(tasks.size()); try { for (Callable<Void> task : tasks) { executor.submit(task); } InputStream proxyInput = socket.getInputStream(); try { readHttpResponse(proxyInput); MultiplexingInputStream input = new MultiplexingInputStream( new ChunkedInputStream(proxyInput)); for (;;) { PacketType packetType = input.getPacketType(); if (packetType == null) { break; } int length = input.getPacketLength(); processData(input, packetType, length); } } finally { try { executor.shutdown(); executor.awaitTermination(1000L, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // ignore } } } finally { executor.shutdownNow(); try { executor.awaitTermination(3000L, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // ignore } Thread.interrupted(); try { // attempt to close the chunked output, since this will make us a well-behaved client // by sending the closing chunk. chunkedRequestOut.close(); } catch (Throwable t) { // ignore } } } finally { socket.close(); } } catch (ConnectException e) { getLogger().error(e.getMessage(), e); throw new CommandException(-1, "Service temporarily unavailable"); } catch (IOException e) { getLogger().warn(e.getMessage(), e); throw new CommandException(-1, e.getMessage()); } }
From source file:com.panet.imeta.cluster.SlaveServer.java
public String sendXML(String xml, String service) throws Exception { // The content // /*from w w w . j av a2 s . c om*/ byte[] content = xml.getBytes(Const.XML_ENCODING); // Prepare HTTP put // String urlString = constructUrl(service); log.logDebug(toString(), Messages.getString("SlaveServer.DEBUG_ConnectingTo", urlString)); //$NON-NLS-1$ PutMethod put = new PutMethod(urlString); // Request content will be retrieved directly from the input stream // RequestEntity entity = new ByteArrayRequestEntity(content); put.setRequestEntity(entity); put.setDoAuthentication(true); put.addRequestHeader(new Header("Content-Type", "text/xml;charset=" + Const.XML_ENCODING)); // post.setContentChunked(true); // Get HTTP client // HttpClient client = new HttpClient(); addCredentials(client); // Execute request // try { int result = client.executeMethod(put); // The status code log.logDebug(toString(), Messages.getString("SlaveServer.DEBUG_ResponseStatus", Integer.toString(result))); //$NON-NLS-1$ // the response InputStream inputStream = new BufferedInputStream(put.getResponseBodyAsStream(), 1000); StringBuffer bodyBuffer = new StringBuffer(); int c; while ((c = inputStream.read()) != -1) bodyBuffer.append((char) c); inputStream.close(); String bodyTmp = bodyBuffer.toString(); switch (result) { case 401: // Security problem: authentication required // Non-internationalized message String message = "Authentication failed" + Const.DOSCR + Const.DOSCR + bodyTmp; //$NON-NLS-1$ WebResult webResult = new WebResult(WebResult.STRING_ERROR, message); bodyBuffer.setLength(0); bodyBuffer.append(webResult.getXML()); break; } String body = bodyBuffer.toString(); // String body = post.getResponseBodyAsString(); log.logDebug(toString(), Messages.getString("SlaveServer.DEBUG_ResponseBody", body)); //$NON-NLS-1$ return body; } finally { // Release current connection to the connection pool once you are done put.releaseConnection(); log.logDetailed(toString(), Messages.getString("SlaveServer.DETAILED_SentXmlToService", service, hostname)); //$NON-NLS-1$ } }
From source file:com.sa.npopa.samples.hbase.rest.client.Client.java
/** * Send a PUT request//from ww w. j av a 2 s . com * @param cluster the cluster definition * @param path the path or URI * @param contentType the content MIME type * @param content the content bytes * @return a Response object with response detail * @throws IOException */ public Response put(Cluster cluster, String path, String contentType, byte[] content) throws IOException { Header[] headers = new Header[1]; headers[0] = new Header("Content-Type", contentType); return put(cluster, path, headers, content); }
From source file:com.cloud.network.bigswitch.BigSwitchApiTest.java
@Test public void testExecuteUpdateObjectOK() throws BigSwitchBcfApiException, IOException { NetworkData network = new NetworkData(); _method = mock(PutMethod.class); when(_method.getResponseHeader("X-BSN-BVS-HASH-MATCH")) .thenReturn(new Header("X-BSN-BVS-HASH-MATCH", UUID.randomUUID().toString())); when(_method.getStatusCode()).thenReturn(HttpStatus.SC_OK); String hash = _api.executeUpdateObject(network, "/", Collections.<String, String>emptyMap()); verify(_method, times(1)).releaseConnection(); verify(_client, times(1)).executeMethod(_method); assertNotEquals(hash, ""); assertNotEquals(hash, BigSwitchBcfApi.HASH_CONFLICT); assertNotEquals(hash, BigSwitchBcfApi.HASH_IGNORE); }
From source file:com.mirth.connect.connectors.http.HttpMessageDispatcher.java
private HttpMethod buildHttpRequest(String address, MessageObject mo) throws Exception { String method = connector.getDispatcherMethod(); String content = replacer.replaceValues(connector.getDispatcherContent(), mo); String contentType = connector.getDispatcherContentType(); String charset = connector.getDispatcherCharset(); boolean isMultipart = connector.isDispatcherMultipart(); Map<String, String> headers = replacer.replaceValuesInMap(connector.getDispatcherHeaders(), mo); Map<String, String> parameters = replacer.replaceValuesInMap(connector.getDispatcherParameters(), mo); HttpMethod httpMethod = null;//from w ww . j a v a 2 s. c om // populate the query parameters NameValuePair[] queryParameters = new NameValuePair[parameters.size()]; int index = 0; for (Entry<String, String> parameterEntry : parameters.entrySet()) { queryParameters[index] = new NameValuePair(parameterEntry.getKey(), parameterEntry.getValue()); index++; logger.debug("setting query parameter: [" + parameterEntry.getKey() + ", " + parameterEntry.getValue() + "]"); } // create the method if ("GET".equalsIgnoreCase(method)) { httpMethod = new GetMethod(address); httpMethod.setQueryString(queryParameters); } else if ("POST".equalsIgnoreCase(method)) { PostMethod postMethod = new PostMethod(address); if (isMultipart) { logger.debug("setting multipart file content"); File tempFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp"); FileUtils.writeStringToFile(tempFile, content, charset); Part[] parts = new Part[] { new FilePart(tempFile.getName(), tempFile, contentType, charset) }; postMethod.setQueryString(queryParameters); postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); } else if (StringUtils.equals(contentType, "application/x-www-form-urlencoded")) { postMethod.setRequestBody(queryParameters); } else { postMethod.setQueryString(queryParameters); postMethod.setRequestEntity(new StringRequestEntity(content, contentType, charset)); } httpMethod = postMethod; } else if ("PUT".equalsIgnoreCase(method)) { PutMethod putMethod = new PutMethod(address); putMethod.setRequestEntity(new StringRequestEntity(content, contentType, charset)); putMethod.setQueryString(queryParameters); httpMethod = putMethod; } else if ("DELETE".equalsIgnoreCase(method)) { httpMethod = new DeleteMethod(address); httpMethod.setQueryString(queryParameters); } // set the headers for (Entry<String, String> headerEntry : headers.entrySet()) { httpMethod.setRequestHeader(new Header(headerEntry.getKey(), headerEntry.getValue())); logger.debug("setting method header: [" + headerEntry.getKey() + ", " + headerEntry.getValue() + "]"); } return httpMethod; }
From source file:freeciv.servlet.ProxyServlet.java
/** * Retreives all of the headers from the servlet request and sets them on * the proxy request/*from ww w . j av a 2s. c o m*/ * * @param httpServletRequest The request object representing the client's * request to the servlet engine * @param httpMethodProxyRequest The request that we are about to send to * the proxy host */ @SuppressWarnings("unchecked") private void setProxyRequestHeaders(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) { // Get an Enumeration of all of the header names sent by the client Enumeration enumerationOfHeaderNames = httpServletRequest.getHeaderNames(); while (enumerationOfHeaderNames.hasMoreElements()) { String stringHeaderName = (String) enumerationOfHeaderNames.nextElement(); if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME)) continue; // As per the Java Servlet API 2.5 documentation: // Some headers, such as Accept-Language can be sent by clients // as several headers each with a different value rather than // sending the header as a comma separated list. // Thus, we get an Enumeration of the header values sent by the client Enumeration enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName); while (enumerationOfHeaderValues.hasMoreElements()) { String stringHeaderValue = (String) enumerationOfHeaderValues.nextElement(); // In case the proxy host is running multiple virtual servers, // rewrite the Host header to ensure that we get content from // the correct virtual server if (stringHeaderName.equalsIgnoreCase(STRING_HOST_HEADER_NAME)) { stringHeaderValue = getProxyHostAndPort(); } Header header = new Header(stringHeaderName, stringHeaderValue); // Set the same header on the proxy request httpMethodProxyRequest.setRequestHeader(header); } } }
From source file:com.xmlcalabash.library.HttpRequest.java
public void gorun() throws SaxonApiException { super.gorun(); XdmNode requestDoc = source.read(stepContext); XdmNode start = S9apiUtils.getDocumentElement(requestDoc); if (!c_request.equals(start.getNodeName())) { throw XProcException.stepError(40); }// w w w . j a v a 2s .co m // Check for valid attributes XdmSequenceIterator iter = start.axisIterator(Axis.ATTRIBUTE); boolean ok = true; while (iter.hasNext()) { XdmNode attr = (XdmNode) iter.next(); QName name = attr.getNodeName(); if (_method.equals(name) || _href.equals(name) || _detailed.equals(name) || _status_only.equals(name) || _username.equals(name) || _password.equals(name) || _auth_method.equals(name) || _send_authorization.equals(name) || _override_content_type.equals(name)) { // nop } else { if (XMLConstants.DEFAULT_NS_PREFIX.equals(name.getNamespaceURI())) { throw new XProcException(step.getNode(), "Unsupported attribute on c:request for p:http-request: " + name); } } } String send = step.getExtensionAttribute(cx_send_binary); encodeBinary = !"true".equals(send); method = start.getAttributeValue(_method); statusOnly = "true".equals(start.getAttributeValue(_status_only)); detailed = "true".equals(start.getAttributeValue(_detailed)); overrideContentType = start.getAttributeValue(_override_content_type); if (method == null) { throw XProcException.stepError(6); } if (statusOnly && !detailed) { throw XProcException.stepError(4); } if (start.getAttributeValue(_href) == null) { throw new XProcException(step.getNode(), "The 'href' attribute must be specified on c:request for p:http-request"); } requestURI = start.getBaseURI().resolve(start.getAttributeValue(_href)); if ("file".equals(requestURI.getScheme())) { doFile(); return; } // What about cookies String saveCookieKey = step.getExtensionAttribute(cx_save_cookies); String useCookieKeys = step.getExtensionAttribute(cx_use_cookies); String cookieKey = step.getExtensionAttribute(cx_cookies); if (saveCookieKey == null) { saveCookieKey = cookieKey; } if (useCookieKeys == null) { useCookieKeys = cookieKey; } client = new HttpClient(); client.getParams().setCookiePolicy(CookiePolicy.RFC_2109); client.getParams().setParameter("http.protocol.single-cookie-header", true); HttpState state = client.getState(); if (useCookieKeys != null) { for (String key : useCookieKeys.split("\\s+")) { for (Cookie cookie : runtime.getCookies(key)) { state.addCookie(cookie); } } } String timeOutStr = step.getExtensionAttribute(cx_timeout); if (timeOutStr != null) { HttpMethodParams params = client.getParams(); params.setSoTimeout(Integer.parseInt(timeOutStr)); } ProxySelector proxySelector = ProxySelector.getDefault(); List<Proxy> plist = proxySelector.select(requestURI); // I have no idea what I'm expected to do if I get more than one... if (plist.size() > 0) { Proxy proxy = plist.get(0); switch (proxy.type()) { case DIRECT: // nop; break; case HTTP: // This can't cause a ClassCastException, right? InetSocketAddress addr = (InetSocketAddress) proxy.address(); String host = addr.getHostName(); int port = addr.getPort(); client.getHostConfiguration().setProxy(host, port); break; default: // FIXME: send out a log message break; } } if (start.getAttributeValue(_username) != null) { String user = start.getAttributeValue(_username); String pass = start.getAttributeValue(_password); String meth = start.getAttributeValue(_auth_method); if (meth == null || !("basic".equals(meth.toLowerCase()) || "digest".equals(meth.toLowerCase()))) { throw XProcException.stepError(3, "Unsupported auth-method: " + meth); } String host = requestURI.getHost(); int port = requestURI.getPort(); AuthScope scope = new AuthScope(host, port); UsernamePasswordCredentials cred = new UsernamePasswordCredentials(user, pass); client.getState().setCredentials(scope, cred); if ("basic".equals(meth.toLowerCase())) { client.getParams().setAuthenticationPreemptive(true); } } iter = start.axisIterator(Axis.CHILD); XdmNode body = null; while (iter.hasNext()) { XdmNode event = (XdmNode) iter.next(); // FIXME: What about non-whitespace text nodes? if (event.getNodeKind() == XdmNodeKind.ELEMENT) { if (body != null) { throw new UnsupportedOperationException("Elements follow c:multipart or c:body"); } if (XProcConstants.c_header.equals(event.getNodeName())) { String name = event.getAttributeValue(_name); if (name == null) { continue; // this can't happen, right? } if (name.toLowerCase().equals("content-type")) { // We'll deal with the content-type header later headerContentType = event.getAttributeValue(_value).toLowerCase(); } else { headers.add(new Header(event.getAttributeValue(_name), event.getAttributeValue(_value))); } } else if (XProcConstants.c_multipart.equals(event.getNodeName()) || XProcConstants.c_body.equals(event.getNodeName())) { body = event; } else { throw new UnsupportedOperationException("Unexpected request element: " + event.getNodeName()); } } } String lcMethod = method.toLowerCase(); // You can only have a body on PUT or POST if (body != null && !("put".equals(lcMethod) || "post".equals(lcMethod))) { throw XProcException.stepError(5); } HttpMethodBase httpResult; if ("get".equals(lcMethod)) { httpResult = doGet(); } else if ("post".equals(lcMethod)) { httpResult = doPost(body); } else if ("put".equals(lcMethod)) { httpResult = doPut(body); } else if ("head".equals(lcMethod)) { httpResult = doHead(); } else if ("delete".equals(lcMethod)) { httpResult = doDelete(); } else { throw new UnsupportedOperationException("Unrecognized http method: " + method); } TreeWriter tree = new TreeWriter(runtime); tree.startDocument(requestURI); try { // Execute the method. int statusCode = client.executeMethod(httpResult); // Deal with cookies if (saveCookieKey != null) { runtime.clearCookies(saveCookieKey); state = client.getState(); Cookie[] cookies = state.getCookies(); for (Cookie cookie : cookies) { runtime.addCookie(saveCookieKey, cookie); } } String contentType = getContentType(httpResult); if (overrideContentType != null) { if ((xmlContentType(contentType) && overrideContentType.startsWith("image/")) || (contentType.startsWith("text/") && overrideContentType.startsWith("image/")) || (contentType.startsWith("image/") && xmlContentType(overrideContentType)) || (contentType.startsWith("image/") && overrideContentType.startsWith("text/")) || (contentType.startsWith("multipart/") && !overrideContentType.startsWith("multipart/")) || (!contentType.startsWith("multipart/") && overrideContentType.startsWith("multipart/"))) { throw XProcException.stepError(30); } //System.err.println(overrideContentType + " overrides " + contentType); contentType = overrideContentType; } if (detailed) { tree.addStartElement(XProcConstants.c_response); tree.addAttribute(_status, "" + statusCode); tree.startContent(); for (Header header : httpResult.getResponseHeaders()) { // I don't understand why/how HeaderElement parsing works. I get very weird results. // So I'm just going to go the long way around... String h = header.toString(); int cp = h.indexOf(":"); String name = header.getName(); String value = h.substring(cp + 1).trim(); tree.addStartElement(XProcConstants.c_header); tree.addAttribute(_name, name); tree.addAttribute(_value, value); tree.startContent(); tree.addEndElement(); } if (statusOnly) { // Skip reading the result } else { // Read the response body. InputStream bodyStream = httpResult.getResponseBodyAsStream(); if (bodyStream != null) { readBodyContent(tree, bodyStream, httpResult); } } tree.addEndElement(); } else { if (statusOnly) { // Skip reading the result } else { // Read the response body. InputStream bodyStream = httpResult.getResponseBodyAsStream(); if (bodyStream != null) { readBodyContent(tree, bodyStream, httpResult); } else { throw XProcException.dynamicError(6); } } } } catch (Exception e) { throw new XProcException(e); } finally { // Release the connection. httpResult.releaseConnection(); } tree.endDocument(); XdmNode resultNode = tree.getResult(); result.write(stepContext, resultNode); }
From source file:de.fuberlin.wiwiss.marbles.loading.CacheController.java
/** * Retrieves a cached response header field from the metadata cache * /*from w w w . ja v a 2 s .c o m*/ * @param metaDataConn A connection to the metadata repository * @param mainResource The resource of interest * @param headerField The header field of interest * @return Header data * @throws RepositoryException */ public Header getCachedHeaderData(RepositoryConnection metaDataConn, Resource mainResource, String headerField) throws RepositoryException { Header header = null; RepositoryResult<Statement> results = metaDataConn.getStatements(mainResource, dataRepository.getValueFactory().createURI(Constants.nsHTTP, headerField), null, false, contextCacheDataURI); if (results.hasNext()) { Statement st = results.next(); if (st.getObject() instanceof Literal) header = new Header(headerField, ((Literal) st.getObject()).getLabel()); } results.close(); return header; }
From source file:com.sa.npopa.samples.hbase.rest.client.Client.java
/** * Send a POST request//w ww . j ava 2 s . c om * @param cluster the cluster definition * @param path the path or URI * @param contentType the content MIME type * @param content the content bytes * @return a Response object with response detail * @throws IOException */ public Response post(Cluster cluster, String path, String contentType, byte[] content) throws IOException { Header[] headers = new Header[1]; headers[0] = new Header("Content-Type", contentType); return post(cluster, path, headers, content); }
From source file:com.groupon.odo.Proxy.java
/** * Retrieves all of the headers from the servlet request and sets them on * the proxy request/* ww w .j a va 2s. co m*/ * * @param httpServletRequest The request object representing the client's request to the * servlet engine * @param httpMethodProxyRequest The request that we are about to send to the proxy host */ @SuppressWarnings("unchecked") private void setProxyRequestHeaders(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) throws Exception { String hostName = HttpUtilities.getHostNameFromURL(httpServletRequest.getRequestURL().toString()); // Get an Enumeration of all of the header names sent by the client Enumeration<String> enumerationOfHeaderNames = httpServletRequest.getHeaderNames(); while (enumerationOfHeaderNames.hasMoreElements()) { String stringHeaderName = enumerationOfHeaderNames.nextElement(); if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME)) continue; logger.info("Current header: {}", stringHeaderName); // As per the Java Servlet API 2.5 documentation: // Some headers, such as Accept-Language can be sent by clients // as several headers each with a different value rather than // sending the header as a comma separated list. // Thus, we get an Enumeration of the header values sent by the // client Enumeration<String> enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName); while (enumerationOfHeaderValues.hasMoreElements()) { String stringHeaderValue = enumerationOfHeaderValues.nextElement(); // In case the proxy host is running multiple virtual servers, // rewrite the Host header to ensure that we get content from // the correct virtual server if (stringHeaderName.equalsIgnoreCase(STRING_HOST_HEADER_NAME) && requestInformation.get().handle) { String hostValue = getHostHeaderForHost(hostName); if (hostValue != null) { stringHeaderValue = hostValue; } } Header header = new Header(stringHeaderName, stringHeaderValue); // Set the same header on the proxy request httpMethodProxyRequest.addRequestHeader(header); } } // bail if we aren't fully handling this request if (!requestInformation.get().handle) { return; } // deal with header overrides for the request processRequestHeaderOverrides(httpMethodProxyRequest); }