List of usage examples for org.apache.commons.httpclient HttpMethod addRequestHeader
public abstract void addRequestHeader(String paramString1, String paramString2);
From source file:org.josso.tc60.gateway.reverseproxy.ReverseProxyValve.java
/** * Intercepts Http request and redirects it to the configured SSO partner application. * * @param request The servlet request to be processed * @param response The servlet response to be created * in the current processing pipeline/*w w w.j a v a 2 s . co m*/ * @exception IOException if an input/output error occurs * @exception javax.servlet.ServletException if a servlet error occurs */ public void invoke(Request request, Response response) throws IOException, javax.servlet.ServletException { if (container.getLogger().isDebugEnabled()) container.getLogger().debug("ReverseProxyValve Acting."); ProxyContextConfig[] contexts = _rpc.getProxyContexts(); // Create an instance of HttpClient. HttpClient client = new HttpClient(); HttpServletRequest hsr = (HttpServletRequest) request.getRequest(); String uri = hsr.getRequestURI(); String uriContext = null; StringTokenizer st = new StringTokenizer(uri.substring(1), "/"); while (st.hasMoreTokens()) { String token = st.nextToken(); uriContext = "/" + token; break; } if (uriContext == null) uriContext = uri; // Obtain the target host from the String proxyForwardHost = null; String proxyForwardUri = null; for (int i = 0; i < contexts.length; i++) { if (contexts[i].getContext().equals(uriContext)) { log("Proxy context mapped to host/uri: " + contexts[i].getForwardHost() + contexts[i].getForwardUri()); proxyForwardHost = contexts[i].getForwardHost(); proxyForwardUri = contexts[i].getForwardUri(); break; } } if (proxyForwardHost == null) { log("URI '" + uri + "' can't be mapped to host"); getNext().invoke(request, response); return; } if (proxyForwardUri == null) { // trim the uri context before submitting the http request int uriTrailStartPos = uri.substring(1).indexOf("/") + 1; proxyForwardUri = uri.substring(uriTrailStartPos); } else { int uriTrailStartPos = uri.substring(1).indexOf("/") + 1; proxyForwardUri = proxyForwardUri + uri.substring(uriTrailStartPos); } // log ("Proxy request mapped to " + "http://" + proxyForwardHost + proxyForwardUri); HttpMethod method; // to be moved to a builder which instantiates and build concrete methods. if (hsr.getMethod().equals(METHOD_GET)) { // Create a method instance. HttpMethod getMethod = new GetMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); method = getMethod; } else if (hsr.getMethod().equals(METHOD_POST)) { // Create a method instance. PostMethod postMethod = new PostMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); postMethod.setRequestBody(hsr.getInputStream()); method = postMethod; } else if (hsr.getMethod().equals(METHOD_HEAD)) { // Create a method instance. HeadMethod headMethod = new HeadMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); method = headMethod; } else if (hsr.getMethod().equals(METHOD_PUT)) { method = new PutMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); } else throw new java.lang.UnsupportedOperationException("Unknown method : " + hsr.getMethod()); // copy incoming http headers to reverse proxy request Enumeration hne = hsr.getHeaderNames(); while (hne.hasMoreElements()) { String hn = (String) hne.nextElement(); // Map the received host header to the target host name // so that the configured virtual domain can // do the proper handling. if (hn.equalsIgnoreCase("host")) { method.addRequestHeader("Host", proxyForwardHost); continue; } Enumeration hvals = hsr.getHeaders(hn); while (hvals.hasMoreElements()) { String hv = (String) hvals.nextElement(); method.addRequestHeader(hn, hv); } } // Add Reverse-Proxy-Host header String reverseProxyHost = getReverseProxyHost(request); method.addRequestHeader(Constants.JOSSO_REVERSE_PROXY_HEADER, reverseProxyHost); if (container.getLogger().isDebugEnabled()) container.getLogger().debug("Sending " + Constants.JOSSO_REVERSE_PROXY_HEADER + " " + reverseProxyHost); // DO NOT follow redirects ! method.setFollowRedirects(false); // By default the httpclient uses HTTP v1.1. We are downgrading it // to v1.0 so that the target server doesn't set a reply using chunked // transfer encoding which doesn't seem to be handled properly. client.getParams().setVersion(new HttpVersion(1, 0)); // Execute the method. int statusCode = -1; try { // execute the method. statusCode = client.executeMethod(method); } catch (HttpRecoverableException e) { log("A recoverable exception occurred " + e.getMessage()); } catch (IOException e) { log("Failed to connect."); e.printStackTrace(); } // Check that we didn't run out of retries. if (statusCode == -1) { log("Failed to recover from exception."); } // Read the response body. byte[] responseBody = method.getResponseBody(); // Release the connection. method.releaseConnection(); HttpServletResponse sres = (HttpServletResponse) response.getResponse(); // First thing to do is to copy status code to response, otherwise // catalina will do it as soon as we set a header or some other part of the response. sres.setStatus(method.getStatusCode()); // copy proxy response headers to client response Header[] responseHeaders = method.getResponseHeaders(); for (int i = 0; i < responseHeaders.length; i++) { Header responseHeader = responseHeaders[i]; String name = responseHeader.getName(); String value = responseHeader.getValue(); // Adjust the URL in the Location, Content-Location and URI headers on HTTP redirect responses // This is essential to avoid by-passing the reverse proxy because of HTTP redirects on the // backend servers which stay behind the reverse proxy switch (method.getStatusCode()) { case HttpStatus.SC_MOVED_TEMPORARILY: case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_SEE_OTHER: case HttpStatus.SC_TEMPORARY_REDIRECT: if ("Location".equalsIgnoreCase(name) || "Content-Location".equalsIgnoreCase(name) || "URI".equalsIgnoreCase(name)) { // Check that this redirect must be adjusted. if (value.indexOf(proxyForwardHost) >= 0) { String trail = value.substring(proxyForwardHost.length()); value = getReverseProxyHost(request) + trail; if (container.getLogger().isDebugEnabled()) container.getLogger().debug("Adjusting redirect header to " + value); } } break; } //end of switch sres.addHeader(name, value); } // Sometimes this is null, when no body is returned ... if (responseBody != null && responseBody.length > 0) sres.getOutputStream().write(responseBody); sres.getOutputStream().flush(); if (container.getLogger().isDebugEnabled()) container.getLogger().debug("ReverseProxyValve finished."); return; }
From source file:org.mule.transport.http.HttpConnector.java
protected void setupClientAuthorization(MuleEvent event, HttpMethod httpMethod, HttpClient client, ImmutableEndpoint endpoint) throws UnsupportedEncodingException { httpMethod.setDoAuthentication(true); client.getParams().setAuthenticationPreemptive(true); if (event != null && event.getCredentials() != null) { MuleMessage msg = event.getMessage(); String authScopeHost = msg.getOutboundProperty(HTTP_PREFIX + "auth.scope.host", event.getMessageSourceURI().getHost()); int authScopePort = msg.getOutboundProperty(HTTP_PREFIX + "auth.scope.port", event.getMessageSourceURI().getPort()); String authScopeRealm = msg.getOutboundProperty(HTTP_PREFIX + "auth.scope.realm", AuthScope.ANY_REALM); String authScopeScheme = msg.getOutboundProperty(HTTP_PREFIX + "auth.scope.scheme", AuthScope.ANY_SCHEME);//www . j a va 2 s.co m client.getState().setCredentials( new AuthScope(authScopeHost, authScopePort, authScopeRealm, authScopeScheme), new UsernamePasswordCredentials(event.getCredentials().getUsername(), new String(event.getCredentials().getPassword()))); } else if (endpoint.getEndpointURI().getUserInfo() != null && endpoint.getProperty(HttpConstants.HEADER_AUTHORIZATION) == null) { // Add User Creds StringBuffer header = new StringBuffer(128); header.append("Basic "); header.append(new String( Base64.encodeBase64(endpoint.getEndpointURI().getUserInfo().getBytes(endpoint.getEncoding())))); httpMethod.addRequestHeader(HttpConstants.HEADER_AUTHORIZATION, header.toString()); } //TODO MULE-4501 this sohuld be removed and handled only in the ObjectToHttpRequest transformer else if (event != null && event.getMessage().getOutboundProperty(HttpConstants.HEADER_AUTHORIZATION) != null && httpMethod.getRequestHeader(HttpConstants.HEADER_AUTHORIZATION) == null) { String auth = event.getMessage().getOutboundProperty(HttpConstants.HEADER_AUTHORIZATION); httpMethod.addRequestHeader(HttpConstants.HEADER_AUTHORIZATION, auth); } else { // don't use preemptive if there are no credentials to send client.getParams().setAuthenticationPreemptive(false); } }
From source file:org.mule.transport.http.transformers.ObjectToHttpClientMethodRequest.java
protected void setHeaders(HttpMethod httpMethod, MuleMessage msg) throws TransformerException { for (String headerName : msg.getOutboundPropertyNames()) { String headerValue = ObjectUtils.getString(msg.getOutboundProperty(headerName), null); if (headerName.startsWith(MuleProperties.PROPERTY_PREFIX)) { // Define Mule headers a custom headers headerName = new StringBuffer(30).append("X-").append(headerName).toString(); httpMethod.addRequestHeader(headerName, headerValue); }/* w w w . j av a 2s. c o m*/ else if (!HttpConstants.RESPONSE_HEADER_NAMES.containsKey(headerName) && !HttpConnector.HTTP_INBOUND_PROPERTIES.contains(headerName) && !HttpConnector.HTTP_COOKIES_PROPERTY.equals(headerName)) { httpMethod.addRequestHeader(headerName, headerValue); } } }
From source file:org.mule.transport.legstar.http.LegstarHttpConnector.java
/** * {@inheritDoc}/*from ww w .jav a 2 s . c o m*/ * We override this method from HttpConnector in order to provide basic * authentication using the host credentials setup at the connector level * or passed as message properties. We do that only if authentication was not setup * any other way. * * */ protected void setupClientAuthorization(final MuleEvent event, final HttpMethod httpMethod, final HttpClient client, final ImmutableEndpoint endpoint) throws UnsupportedEncodingException { /* give HttpConnector a chance to setup security*/ super.setupClientAuthorization(event, httpMethod, client, endpoint); HostCredentials hostCredentials = getHostCredentials(event.getMessage()); if (httpMethod.getRequestHeader(HttpConstants.HEADER_AUTHORIZATION) == null && hostCredentials.getUserInfo() != null) { if (_log.isDebugEnabled()) { _log.debug("adding security header " + hostCredentials.toString()); } StringBuffer header = new StringBuffer(128); header.append("Basic "); header.append(new String( Base64.encodeBase64(hostCredentials.getUserInfo().getBytes(endpoint.getEncoding())))); httpMethod.addRequestHeader(HttpConstants.HEADER_AUTHORIZATION, header.toString()); } }
From source file:org.mule.transport.legstar.http.LegstarHttpMessageDispatcher.java
/** * We override this method because we need to perform LegStar messaging specific * transformations and also need to force the http header content type. * {@inheritDoc}// w w w .java 2 s .c om * */ public final HttpMethod getMethod(final MuleEvent event) throws TransformerException { if (_log.isDebugEnabled()) { _log.debug("Creating http method for endpoint " + getEndpoint()); } HttpMethod httpMethod = super.getMethod(event); /* Force the content type expected by the Mainframe */ httpMethod.removeRequestHeader(HttpConstants.HEADER_CONTENT_TYPE); httpMethod.addRequestHeader(HttpConstants.HEADER_CONTENT_TYPE, LEGSTAR_HTTP_CONTENT_TYPE); if (isHostTraceOn(event.getMessage()) || _log.isDebugEnabled()) { httpMethod.addRequestHeader(LEGSTAR_HTTP_HEADER_TRACE_MODE, "true"); } return httpMethod; }
From source file:org.olat.modules.tu.IframeTunnelController.java
/** * Constructor for a tunnel component wrapper controller * //ww w.java2 s . c o m * @param ureq the userrequest * @param wControl the windowcontrol * @param config the module configuration */ public IframeTunnelController(final UserRequest ureq, final WindowControl wControl, final ModuleConfiguration config) { super(ureq, wControl); // use iframe translator for generic iframe title text setTranslator(Util.createPackageTranslator(IFrameDisplayController.class, ureq.getLocale())); this.config = config; // configuration.... final int configVersion = config.getConfigurationVersion(); // since config version 1 final String proto = (String) config.get(TUConfigForm.CONFIGKEY_PROTO); final String host = (String) config.get(TUConfigForm.CONFIGKEY_HOST); final Integer port = (Integer) config.get(TUConfigForm.CONFIGKEY_PORT); final String user = (String) config.get(TUConfigForm.CONFIGKEY_USER); final String startUri = (String) config.get(TUConfigForm.CONFIGKEY_URI); final String pass = (String) config.get(TUConfigForm.CONFIGKEY_PASS); String firstQueryString = null; if (configVersion == 2) { // query string is available since config version 2 firstQueryString = (String) config.get(TUConfigForm.CONFIGKEY_QUERY); } final boolean usetunnel = config.getBooleanSafe(TUConfigForm.CONFIG_TUNNEL); myContent = createVelocityContainer("iframe_index"); if (!usetunnel) { // display content directly final String rawurl = TUConfigForm.getFullURL(proto, host, port, startUri, firstQueryString).toString(); myContent.contextPut("url", rawurl); } else { // tunnel final Identity ident = ureq.getIdentity(); if (user != null && user.length() > 0) { httpClientInstance = HttpClientFactory.getHttpClientInstance(host, port.intValue(), proto, user, pass); } else { httpClientInstance = HttpClientFactory.getHttpClientInstance(host, port.intValue(), proto, null, null); } final Locale loc = ureq.getLocale(); final Mapper mapper = new Mapper() { @Override public MediaResource handle(final String relPath, final HttpServletRequest hreq) { MediaResource mr = null; final String method = hreq.getMethod(); String uri = relPath; HttpMethod meth = null; if (uri == null) { uri = (startUri == null) ? "" : startUri; } if (uri.length() > 0 && uri.charAt(0) != '/') { uri = "/" + uri; } // String contentType = hreq.getContentType(); // if (allowedToSendPersonalHeaders) { final String userName = ident.getName(); final User u = ident.getUser(); final String lastName = u.getProperty(UserConstants.LASTNAME, loc); final String firstName = u.getProperty(UserConstants.FIRSTNAME, loc); final String email = u.getProperty(UserConstants.EMAIL, loc); if (method.equals("GET")) { final GetMethod cmeth = new GetMethod(uri); final String queryString = hreq.getQueryString(); if (queryString != null) { cmeth.setQueryString(queryString); } meth = cmeth; // if response is a redirect, follow it if (meth == null) { return null; } meth.setFollowRedirects(true); } else if (method.equals("POST")) { // if (contentType == null || contentType.equals("application/x-www-form-urlencoded")) { // regular post, no file upload // } final Map params = hreq.getParameterMap(); final PostMethod pmeth = new PostMethod(uri); final Set postKeys = params.keySet(); for (final Iterator iter = postKeys.iterator(); iter.hasNext();) { final String key = (String) iter.next(); final String vals[] = (String[]) params.get(key); for (int i = 0; i < vals.length; i++) { pmeth.addParameter(key, vals[i]); } meth = pmeth; } if (meth == null) { return null; // Redirects are not supported when using POST method! // See RFC 2616, section 10.3.3, page 62 } } // Add olat specific headers to the request, can be used by external // applications to identify user and to get other params // test page e.g. http://cgi.algonet.se/htbin/cgiwrap/ug/test.py meth.addRequestHeader("X-OLAT-USERNAME", userName); meth.addRequestHeader("X-OLAT-LASTNAME", lastName); meth.addRequestHeader("X-OLAT-FIRSTNAME", firstName); meth.addRequestHeader("X-OLAT-EMAIL", email); boolean ok = false; try { httpClientInstance.executeMethod(meth); ok = true; } catch (final Exception e) { // handle error later } if (!ok) { // error meth.releaseConnection(); return new NotFoundMediaResource(relPath); } // get or post successfully final Header responseHeader = meth.getResponseHeader("Content-Type"); if (responseHeader == null) { // error return new NotFoundMediaResource(relPath); } mr = new HttpRequestMediaResource(meth); return mr; } }; final String amapPath = registerMapper(mapper); String alluri = amapPath + startUri; if (firstQueryString != null) { alluri += "?" + firstQueryString; } myContent.contextPut("url", alluri); } final String frameId = "ifdc" + hashCode(); // for e.g. js use myContent.contextPut("frameId", frameId); putInitialPanel(myContent); }
From source file:org.olat.modules.tu.TunnelComponent.java
/** * @param tuReq// w w w . j av a 2 s . com * @param client * @return HttpMethod */ public HttpMethod fetch(final TURequest tuReq, final HttpClient client) { final String modulePath = tuReq.getUri(); HttpMethod meth = null; final String method = tuReq.getMethod(); if (method.equals("GET")) { final GetMethod cmeth = new GetMethod(modulePath); final String queryString = tuReq.getQueryString(); if (queryString != null) { cmeth.setQueryString(queryString); } meth = cmeth; if (meth == null) { return null; } // if response is a redirect, follow it meth.setFollowRedirects(true); } else if (method.equals("POST")) { final String type = tuReq.getContentType(); if (type == null || type.equals("application/x-www-form-urlencoded")) { // regular post, no file upload } final PostMethod pmeth = new PostMethod(modulePath); final Set postKeys = tuReq.getParameterMap().keySet(); for (final Iterator iter = postKeys.iterator(); iter.hasNext();) { final String key = (String) iter.next(); final String vals[] = (String[]) tuReq.getParameterMap().get(key); for (int i = 0; i < vals.length; i++) { pmeth.addParameter(key, vals[i]); } meth = pmeth; } if (meth == null) { return null; // Redirects are not supported when using POST method! // See RFC 2616, section 10.3.3, page 62 } } // Add olat specific headers to the request, can be used by external // applications to identify user and to get other params // test page e.g. http://cgi.algonet.se/htbin/cgiwrap/ug/test.py meth.addRequestHeader("X-OLAT-USERNAME", tuReq.getUserName()); meth.addRequestHeader("X-OLAT-LASTNAME", tuReq.getLastName()); meth.addRequestHeader("X-OLAT-FIRSTNAME", tuReq.getFirstName()); meth.addRequestHeader("X-OLAT-EMAIL", tuReq.getEmail()); try { client.executeMethod(meth); return meth; } catch (final Exception e) { meth.releaseConnection(); } return null; }
From source file:org.openanzo.client.BinaryStoreClient.java
protected int executeAuthenticatedHttpClientMethod(HttpMethod method) throws HttpException, IOException, AnzoException { method.addRequestHeader("X-Requested-With", "XMLHttpRequest"); String serviceUser = anzoClient.getServiceUser(); if (serviceUser != null && serviceUser.equals(anzoClient.clientDatasource.getServiceUser())) method.addRequestHeader(AUTHRUNAS_HEADER, anzoClient.clientDatasource.getServiceUser()); int rc = httpclient.executeMethod(method); if (rc == HttpStatus.SC_FORBIDDEN) { method.releaseConnection();//from ww w.ja v a 2 s.c om authenticate(); rc = httpclient.executeMethod(method); } return rc; }
From source file:org.openqa.selenium.remote.HttpCommandExecutor.java
public Response execute(Command command) throws Exception { CommandInfo info = nameToUrl.get(command.getName()); HttpMethod httpMethod = info.getMethod(remotePath, command); httpMethod.addRequestHeader("Accept", "application/json, image/png"); String payload = new BeanToJsonConverter().convert(command.getParameters()); if (httpMethod instanceof PostMethod) { ((PostMethod) httpMethod)/*from ww w. j ava2 s .c o m*/ .setRequestEntity(new StringRequestEntity(payload, "application/json", "UTF-8")); } client.executeMethod(httpMethod); // TODO: SimonStewart: 2008-04-25: This is really shabby if (isRedirect(httpMethod)) { Header newLocation = httpMethod.getResponseHeader("location"); httpMethod = new GetMethod(newLocation.getValue()); httpMethod.setFollowRedirects(true); httpMethod.addRequestHeader("Accept", "application/json, image/png"); client.executeMethod(httpMethod); } return createResponse(httpMethod); }
From source file:org.openrdf.http.client.HTTPClient.java
protected void getTupleQueryResult(HttpMethod method, TupleQueryResultHandler handler) throws IOException, TupleQueryResultHandlerException, RepositoryException, MalformedQueryException, UnauthorizedException, QueryInterruptedException { // Specify which formats we support using Accept headers Set<TupleQueryResultFormat> tqrFormats = TupleQueryResultParserRegistry.getInstance().getKeys(); if (tqrFormats.isEmpty()) { throw new RepositoryException("No tuple query result parsers have been registered"); }// w ww. ja v a 2s .c o m for (TupleQueryResultFormat format : tqrFormats) { // Determine a q-value that reflects the user specified preference int qValue = 10; if (preferredTQRFormat != null && !preferredTQRFormat.equals(format)) { // Prefer specified format over other formats qValue -= 2; } for (String mimeType : format.getMIMETypes()) { String acceptParam = mimeType; if (qValue < 10) { acceptParam += ";q=0." + qValue; } method.addRequestHeader(ACCEPT_PARAM_NAME, acceptParam); } } int httpCode = httpClient.executeMethod(method); if (httpCode == HttpURLConnection.HTTP_OK) { String mimeType = getResponseMIMEType(method); try { TupleQueryResultFormat format = TupleQueryResultFormat.matchMIMEType(mimeType, tqrFormats); TupleQueryResultParser parser = QueryResultIO.createParser(format, getValueFactory()); parser.setTupleQueryResultHandler(handler); parser.parse(method.getResponseBodyAsStream()); } catch (UnsupportedQueryResultFormatException e) { throw new RepositoryException("Server responded with an unsupported file format: " + mimeType); } catch (QueryResultParseException e) { throw new RepositoryException("Malformed query result from server", e); } } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new UnauthorizedException(); } else if (httpCode == HttpURLConnection.HTTP_UNAVAILABLE) { throw new QueryInterruptedException(); } else { ErrorInfo errInfo = getErrorInfo(method); // Throw appropriate exception if (errInfo.getErrorType() == ErrorType.MALFORMED_QUERY) { throw new MalformedQueryException(errInfo.getErrorMessage()); } else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_QUERY_LANGUAGE) { throw new UnsupportedQueryLanguageException(errInfo.getErrorMessage()); } else { throw new RepositoryException(errInfo.toString()); } } }