List of usage examples for org.apache.commons.httpclient HttpMethodBase addRequestHeader
@Override public void addRequestHeader(String headerName, String headerValue)
From source file:com.progress.codeshare.esbservice.http.HTTPService.java
public void service(final XQServiceContext ctx) throws XQServiceException { try {//from w w w. j a va 2s . c o m final XQMessageFactory factory = ctx.getMessageFactory(); final XQParameters params = ctx.getParameters(); final int messagePart = params.getIntParameter(PARAM_MESSAGE_PART, XQConstants.PARAM_STRING); final String method = params.getParameter(PARAM_METHOD, XQConstants.PARAM_STRING); final String uri = params.getParameter(PARAM_URI, XQConstants.PARAM_STRING); while (ctx.hasNextIncoming()) { final XQEnvelope env = ctx.getNextIncoming(); final XQMessage origMsg = env.getMessage(); final XQMessage newMsg = factory.createMessage(); final HttpClient client = new HttpClient(); final Iterator headerIterator = origMsg.getHeaderNames(); if (METHOD_DELETE.equals(method)) { final HttpMethodBase req = new DeleteMethod(uri); /* * Copy all XQ headers and extract HTTP headers and * parameters */ while (headerIterator.hasNext()) { final String header = (String) headerIterator.next(); newMsg.setHeaderValue(header, origMsg.getHeaderValue(header)); final Matcher matcher = PATTERN_HEADER.matcher(header); if (matcher.find()) req.addRequestHeader(matcher.group(1), (String) origMsg.getHeaderValue(matcher.group())); } client.executeMethod(req); /* Transform all HTTP to XQ headers */ final Header[] headers = req.getResponseHeaders(); for (int i = 0; i < headers.length; i++) newMsg.setHeaderValue(PREFIX_HEADER + headers[i].getName(), headers[i].getValue()); final XQPart newPart = newMsg.createPart(); newPart.setContentId("Result"); newPart.setContent(new String(req.getResponseBody()), req.getResponseHeader("Content-Type").getValue()); newMsg.addPart(newPart); } else if (METHOD_GET.equals(method)) { final HttpMethodBase req = new GetMethod(); final List paramList = new ArrayList(); /* * Copy all XQ headers and extract HTTP headers and * parameters */ while (headerIterator.hasNext()) { final String header = (String) headerIterator.next(); newMsg.setHeaderValue(header, origMsg.getHeaderValue(header)); final Matcher headerMatcher = PATTERN_HEADER.matcher(header); if (headerMatcher.find()) { req.addRequestHeader(headerMatcher.group(1), (String) origMsg.getHeaderValue(headerMatcher.group())); continue; } final Matcher paramMatcher = PATTERN_PARAM.matcher(header); if (paramMatcher.find()) paramList.add(new NameValuePair(paramMatcher.group(1), (String) origMsg.getHeaderValue(paramMatcher.group()))); } req.setQueryString((NameValuePair[]) paramList.toArray(new NameValuePair[] {})); client.executeMethod(req); /* Transform all HTTP to XQ headers */ final Header[] headers = req.getResponseHeaders(); for (int i = 0; i < headers.length; i++) newMsg.setHeaderValue(PREFIX_HEADER + headers[i].getName(), headers[i].getValue()); final XQPart newPart = newMsg.createPart(); newPart.setContentId("Result"); newPart.setContent(new String(req.getResponseBody()), req.getResponseHeader("Content-Type").getValue()); newMsg.addPart(newPart); } else if (METHOD_POST.equals(method)) { final PostMethod req = new PostMethod(uri); /* * Copy all XQ headers and extract HTTP headers and * parameters */ while (headerIterator.hasNext()) { final String header = (String) headerIterator.next(); newMsg.setHeaderValue(header, origMsg.getHeaderValue(header)); final Matcher headerMatcher = PATTERN_HEADER.matcher(header); if (headerMatcher.find()) { req.addRequestHeader(headerMatcher.group(1), (String) origMsg.getHeaderValue(headerMatcher.group())); continue; } final Matcher paramMatcher = PATTERN_PARAM.matcher(header); if (paramMatcher.find()) req.addParameter(new NameValuePair(paramMatcher.group(1), (String) origMsg.getHeaderValue(paramMatcher.group()))); } final XQPart origPart = origMsg.getPart(messagePart); req.setRequestEntity(new StringRequestEntity((String) origPart.getContent(), origPart.getContentType(), null)); client.executeMethod(req); /* Transform all HTTP to XQ headers */ final Header[] headers = req.getResponseHeaders(); for (int i = 0; i < headers.length; i++) newMsg.setHeaderValue(PREFIX_HEADER + headers[i].getName(), headers[i].getValue()); final XQPart newPart = newMsg.createPart(); newPart.setContentId("Result"); newPart.setContent(new String(req.getResponseBody()), req.getResponseHeader("Content-Type").getValue()); newMsg.addPart(newPart); } else if (METHOD_PUT.equals(method)) { final EntityEnclosingMethod req = new PutMethod(uri); /* Copy all XQ headers and extract HTTP headers */ while (headerIterator.hasNext()) { final String header = (String) headerIterator.next(); newMsg.setHeaderValue(header, origMsg.getHeaderValue(header)); final Matcher matcher = PATTERN_HEADER.matcher(header); if (matcher.find()) req.addRequestHeader(matcher.group(1), (String) origMsg.getHeaderValue(matcher.group())); } final XQPart origPart = origMsg.getPart(messagePart); req.setRequestEntity(new StringRequestEntity((String) origPart.getContent(), origPart.getContentType(), null)); client.executeMethod(req); /* Transform all HTTP to XQ headers */ final Header[] headers = req.getResponseHeaders(); for (int i = 0; i < headers.length; i++) newMsg.setHeaderValue(PREFIX_HEADER + headers[i].getName(), headers[i].getValue()); final XQPart newPart = newMsg.createPart(); newPart.setContentId("Result"); newPart.setContent(new String(req.getResponseBody()), req.getResponseHeader("Content-Type").getValue()); newMsg.addPart(newPart); } env.setMessage(newMsg); final Iterator addressIterator = env.getAddresses(); if (addressIterator.hasNext()) ctx.addOutgoing(env); } } catch (final Exception e) { throw new XQServiceException(e); } }
From source file:com.eucalyptus.blockstorage.HttpTransfer.java
/** * Calculates and sets the Authorization header value for the request using the EucaRSA-V2 signing algorithm * Algorithm Overview://from ww w. j av a2 s. co m * * 1. Generate the canonical Request * a.) CanonicalRequest = * HTTPRequestMethod + '\n' + * CanonicalURI + '\n' + * CanonicalQueryString + '\n' + * CanonicalHeaders + '\n' + * SignedHeaders * b.) Where CanonicalURI = * c.) Where CanonicalQueryString = * d.) Where CanonicalHeaders = sorted (by lowercased header name) ';' delimited list of <lowercase(headername)>:<value> items * e.) Where SignedHeaders = sorted, ';' delimited list of headers in CanonicalHeaders * * 2. Signature = RSA(privkey, SHA256(CanonicalRequest)) * * 3. Add an Authorization HTTP header to the request that contains the following strings, separated by spaces: * EUCA2-RSA-SHA256 * The lower-case hexadecimal encoding of the component's X.509 certificate's md5 fingerprint * The SignedHeaders list calculated in Task 1 * The Base64 encoding of the Signature calculated in Task 2 * * @param httpBaseRequest -- the request, the 'Authorization' header will be added to the request */ public static void signEucaInternal(HttpMethodBase httpBaseRequest) { StringBuilder canonicalRequest = new StringBuilder(); String canonicalURI = null; String verb = httpBaseRequest.getName(); canonicalURI = httpBaseRequest.getPath(); String canonicalQuery = calcCanonicalQuery(httpBaseRequest); String[] processedHeaders = getCanonicalAndSignedHeaders(httpBaseRequest); String canonicalHeaders = processedHeaders[0]; String signedHeaders = processedHeaders[1]; canonicalRequest.append(verb).append('\n'); canonicalRequest.append(canonicalURI).append('\n'); canonicalRequest.append(canonicalQuery).append('\n'); canonicalRequest.append(canonicalHeaders).append('\n'); canonicalRequest.append(signedHeaders); StringBuilder authHeader = new StringBuilder(EUCA2_AUTH_ID); String signature = null; String fingerprint = null; try { Credentials ccCreds = SystemCredentials.lookup(Storage.class); PrivateKey ccPrivateKey = ccCreds.getPrivateKey(); fingerprint = ccCreds.getCertFingerprint(); Signature sign = Signature.getInstance("SHA256withRSA"); sign.initSign(ccPrivateKey); LOG.debug("Signing canonical request: " + canonicalRequest.toString()); sign.update(canonicalRequest.toString().getBytes()); byte[] sig = sign.sign(); signature = new String(Base64.encode(sig)); } catch (Exception ex) { LOG.error("Signing error while signing request", ex); } authHeader.append(" ").append(fingerprint.toLowerCase()).append(" ").append(signedHeaders.toString()) .append(" ").append(signature); httpBaseRequest.addRequestHeader(EUCA2_AUTH_HEADER_NAME, authHeader.toString()); }
From source file:com.nextcloud.android.sso.InputStreamBinder.java
private InputStream processRequest(final NextcloudRequest request) throws UnsupportedOperationException, com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException, OperationCanceledException, AuthenticatorException, IOException { Account account = AccountUtils.getOwnCloudAccountByName(context, request.getAccountName()); // TODO handle case that account is not found! if (account == null) { throw new IllegalStateException(EXCEPTION_ACCOUNT_NOT_FOUND); }//from w w w . j a v a 2 s .c o m // Validate token if (!isValid(request)) { throw new IllegalStateException(EXCEPTION_INVALID_TOKEN); } // Validate URL if (request.getUrl().length() == 0 || request.getUrl().charAt(0) != PATH_SEPARATOR) { throw new IllegalStateException(EXCEPTION_INVALID_REQUEST_URL, new IllegalStateException("URL need to start with a /")); } OwnCloudClientManager ownCloudClientManager = OwnCloudClientManagerFactory.getDefaultSingleton(); OwnCloudAccount ocAccount = new OwnCloudAccount(account, context); OwnCloudClient client = ownCloudClientManager.getClientFor(ocAccount, context); String requestUrl = client.getBaseUri() + request.getUrl(); HttpMethodBase method; switch (request.getMethod()) { case "GET": method = new GetMethod(requestUrl); break; case "POST": method = new PostMethod(requestUrl); if (request.getRequestBody() != null) { StringRequestEntity requestEntity = new StringRequestEntity(request.getRequestBody(), CONTENT_TYPE_APPLICATION_JSON, CHARSET_UTF8); ((PostMethod) method).setRequestEntity(requestEntity); } break; case "PUT": method = new PutMethod(requestUrl); if (request.getRequestBody() != null) { StringRequestEntity requestEntity = new StringRequestEntity(request.getRequestBody(), CONTENT_TYPE_APPLICATION_JSON, CHARSET_UTF8); ((PutMethod) method).setRequestEntity(requestEntity); } break; case "DELETE": method = new DeleteMethod(requestUrl); break; default: throw new UnsupportedOperationException(EXCEPTION_UNSUPPORTED_METHOD); } method.setQueryString(convertMapToNVP(request.getParameter())); method.addRequestHeader("OCS-APIREQUEST", "true"); client.setFollowRedirects(request.isFollowRedirects()); int status = client.executeMethod(method); // Check if status code is 2xx --> https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#2xx_Success if (status >= HTTP_STATUS_CODE_OK && status < HTTP_STATUS_CODE_MULTIPLE_CHOICES) { return method.getResponseBodyAsStream(); } else { throw new IllegalStateException(EXCEPTION_HTTP_REQUEST_FAILED, new IllegalStateException(String.valueOf(status))); } }
From source file:flex.messaging.services.http.proxy.RequestFilter.java
/** * Add any custom headers./*from w w w .j a v a2 s .c om*/ * * @param context the context */ protected void addCustomHeaders(ProxyContext context) { HttpMethodBase httpMethod = context.getHttpMethod(); String contentType = context.getContentType(); if (contentType != null) { httpMethod.setRequestHeader(ProxyConstants.HEADER_CONTENT_TYPE, contentType); } Map customHeaders = context.getHeaders(); if (customHeaders != null) { for (Object entry : customHeaders.entrySet()) { String name = (String) ((Map.Entry) entry).getKey(); Object value = ((Map.Entry) entry).getValue(); if (value == null) { httpMethod.setRequestHeader(name, ""); } // Single value for the name. else if (value instanceof String) { httpMethod.setRequestHeader(name, (String) value); } // Multiple values for the name. else if (value instanceof List) { List valueList = (List) value; for (Object currentValue : valueList) { if (currentValue == null) { httpMethod.addRequestHeader(name, ""); } else { httpMethod.addRequestHeader(name, (String) currentValue); } } } else if (value.getClass().isArray()) { Object[] valueArray = (Object[]) value; for (Object currentValue : valueArray) { if (currentValue == null) { httpMethod.addRequestHeader(name, ""); } else { httpMethod.addRequestHeader(name, (String) currentValue); } } } } } if (context.isSoapRequest()) { // add the appropriate headers context.getHttpMethod().setRequestHeader(ProxyConstants.HEADER_CONTENT_TYPE, MessageIOConstants.CONTENT_TYPE_XML); // get SOAPAction, and if it doesn't exist, create it String soapAction = null; Header header = context.getHttpMethod().getRequestHeader(MessageIOConstants.HEADER_SOAP_ACTION); if (header != null) { soapAction = header.getValue(); } if (soapAction == null) { HttpServletRequest clientRequest = FlexContext.getHttpRequest(); if (clientRequest != null) { soapAction = clientRequest.getHeader(MessageIOConstants.HEADER_SOAP_ACTION); } // SOAPAction has to be quoted per the SOAP 1.1 spec. if (soapAction != null && !soapAction.startsWith("\"") && !soapAction.endsWith("\"")) { soapAction = "\"" + soapAction + "\""; } // If soapAction happens to still be null at this point, we'll end up not sending // one, which should generate a fault on the server side which we'll happily convey // back to the client. context.getHttpMethod().setRequestHeader(MessageIOConstants.HEADER_SOAP_ACTION, soapAction); } } }
From source file:com.esri.gpt.framework.http.HttpClientRequest.java
/** * Create the HTTP method./* w ww .j ava 2 s . c o m*/ * <br/>A GetMethod will be created if the RequestEntity associated with * the ContentProvider is null. Otherwise, a PostMethod will be created. * @return the HTTP method */ private HttpMethodBase createMethod() throws IOException { HttpMethodBase method = null; MethodName name = this.getMethodName(); // make the method if (name == null) { if (this.getContentProvider() == null) { this.setMethodName(MethodName.GET); method = new GetMethod(this.getUrl()); } else { this.setMethodName(MethodName.POST); method = new PostMethod(this.getUrl()); } } else if (name.equals(MethodName.DELETE)) { method = new DeleteMethod(this.getUrl()); } else if (name.equals(MethodName.GET)) { method = new GetMethod(this.getUrl()); } else if (name.equals(MethodName.POST)) { method = new PostMethod(this.getUrl()); } else if (name.equals(MethodName.PUT)) { method = new PutMethod(this.getUrl()); } // write the request body if necessary if (this.getContentProvider() != null) { if (method instanceof EntityEnclosingMethod) { EntityEnclosingMethod eMethod = (EntityEnclosingMethod) method; RequestEntity eAdapter = getContentProvider() instanceof MultiPartContentProvider ? new MultiPartProviderAdapter(this, eMethod, (MultiPartContentProvider) getContentProvider()) : new ApacheEntityAdapter(this, this.getContentProvider()); eMethod.setRequestEntity(eAdapter); if (eAdapter.getContentType() != null) { eMethod.setRequestHeader("Content-type", eAdapter.getContentType()); } } else { // TODO: possibly will need an exception here in the future } } // set headers, add the retry method for (Map.Entry<String, String> hdr : this.requestHeaders.entrySet()) { method.addRequestHeader(hdr.getKey(), hdr.getValue()); } // declare possible gzip handling method.setRequestHeader("Accept-Encoding", "gzip"); this.addRetryHandler(method); return method; }
From source file:com.jaspersoft.ireport.jasperserver.ws.CommonsHTTPSender.java
/** * invoke creates a socket connection, sends the request SOAP message and then * reads the response SOAP message back from the SOAP server * * @param msgContext the messsage context * * @throws AxisFault/*from www . j a v a2 s . c om*/ */ public void invoke(MessageContext msgContext) throws AxisFault { //test(); HttpMethodBase method = null; if (log.isDebugEnabled()) { log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke")); } try { URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL)); // no need to retain these, as the cookies/credentials are // stored in the message context across multiple requests. // the underlying connection manager, however, is retained // so sockets get recycled when possible. //org.apache.log4j.LogManager.getRootLogger().setLevel(org.apache.log4j.Level.DEBUG); HttpClient httpClient = new HttpClient(this.connectionManager); // the timeout value for allocation of connections from the pool httpClient.getParams().setConnectionManagerTimeout(this.clientProperties.getConnectionPoolTimeout()); HostConfiguration hostConfiguration = getHostConfiguration(httpClient, msgContext, targetURL); boolean posting = true; // If we're SOAP 1.2, allow the web method to be set from the // MessageContext. if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD); if (webMethod != null) { posting = webMethod.equals(HTTPConstants.HEADER_POST); } } if (posting) { Message reqMessage = msgContext.getRequestMessage(); method = new PostMethod(targetURL.toString()); // set false as default, addContetInfo can overwrite method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); addContextInfo(method, httpClient, msgContext, targetURL); MessageRequestEntity requestEntity = null; if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) { requestEntity = new GzipMessageRequestEntity(method, reqMessage, httpChunkStream); } else { requestEntity = new MessageRequestEntity(method, reqMessage, httpChunkStream); } method.addRequestHeader(HTTPConstants.HEADER_CONTENT_LENGTH, "" + requestEntity.getContentLength()); ((PostMethod) method).setRequestEntity(requestEntity); } else { method = new GetMethod(targetURL.toString()); addContextInfo(method, httpClient, msgContext, targetURL); } String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION); if (httpVersion != null) { if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) { method.getParams().setVersion(HttpVersion.HTTP_1_0); } // assume 1.1 } // don't forget the cookies! // Cookies need to be set on HttpState, since HttpMethodBase // overwrites the cookies from HttpState if (msgContext.getMaintainSession()) { HttpState state = httpClient.getState(); method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); String host = targetURL.getHost(); String path = targetURL.getPath(); boolean secure = targetURL.getProtocol().equals("https"); fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE, host, path, secure); fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE2, host, path, secure); httpClient.setState(state); } int returnCode = httpClient.executeMethod(method); org.apache.log4j.LogManager.getRootLogger().setLevel(org.apache.log4j.Level.ERROR); String contentType = getHeader(method, HTTPConstants.HEADER_CONTENT_TYPE); String contentLocation = getHeader(method, HTTPConstants.HEADER_CONTENT_LOCATION); String contentLength = getHeader(method, HTTPConstants.HEADER_CONTENT_LENGTH); if ((returnCode > 199) && (returnCode < 300)) { // SOAP return is OK - so fall through } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { // For now, if we're SOAP 1.2, fall through, since the range of // valid result codes is much greater } else if ((contentType != null) && !contentType.equals("text/html") && ((returnCode > 499) && (returnCode < 600))) { // SOAP Fault should be in here - so fall through } else { String statusMessage = method.getStatusText(); AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null); try { fault.setFaultDetailString( Messages.getMessage("return01", "" + returnCode, method.getResponseBodyAsString())); fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode)); throw fault; } finally { method.releaseConnection(); // release connection back to pool. } } // wrap the response body stream so that close() also releases // the connection back to the pool. InputStream releaseConnectionOnCloseStream = createConnectionReleasingInputStream(method); Header contentEncoding = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING); if (contentEncoding != null) { if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) { releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream); } else { AxisFault fault = new AxisFault("HTTP", "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null, null); throw fault; } } Message outMsg = new Message(releaseConnectionOnCloseStream, false, contentType, contentLocation); // Transfer HTTP headers of HTTP message to MIME headers of SOAP message Header[] responseHeaders = method.getResponseHeaders(); MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders(); for (int i = 0; i < responseHeaders.length; i++) { Header responseHeader = responseHeaders[i]; responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue()); } outMsg.setMessageType(Message.RESPONSE); msgContext.setResponseMessage(outMsg); if (log.isDebugEnabled()) { if (null == contentLength) { log.debug("\n" + Messages.getMessage("no00", "Content-Length")); } log.debug("\n" + Messages.getMessage("xmlRecd00")); log.debug("-----------------------------------------------"); log.debug(outMsg.getSOAPPartAsString()); } // if we are maintaining session state, // handle cookies (if any) if (msgContext.getMaintainSession()) { Header[] headers = method.getResponseHeaders(); for (int i = 0; i < headers.length; i++) { if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) { handleCookie(HTTPConstants.HEADER_COOKIE, headers[i].getValue(), msgContext); } else if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) { handleCookie(HTTPConstants.HEADER_COOKIE2, headers[i].getValue(), msgContext); } } } // always release the connection back to the pool if // it was one way invocation if (msgContext.isPropertyTrue("axis.one.way")) { method.releaseConnection(); } } catch (Exception e) { log.debug(e); throw AxisFault.makeFault(e); } if (log.isDebugEnabled()) { log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke")); } }
From source file:com.polarion.alm.ws.client.internal.connection.CommonsHTTPSender.java
/** * Extracts info from message context./*from ww w . j a v a2 s .c o m*/ * * @param method * Post method * @param httpClient * The client used for posting * @param msgContext * the message context * @param tmpURL * the url to post to. * * @throws Exception */ private void addContextInfo(HttpMethodBase method, HttpClient httpClient, MessageContext msgContext, URL tmpURL) throws Exception { // optionally set a timeout for the request if (msgContext.getTimeout() != 0) { /* * ISSUE: these are not the same, but MessageContext has only one * definition of timeout */ // SO_TIMEOUT -- timeout for blocking reads httpClient.getHttpConnectionManager().getParams().setSoTimeout(msgContext.getTimeout()); // timeout for initial connection httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(msgContext.getTimeout()); } // Get SOAPAction, default to "" String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : ""; if (action == null) { action = ""; } Message msg = msgContext.getRequestMessage(); if (msg != null) { method.setRequestHeader(new Header(HTTPConstants.HEADER_CONTENT_TYPE, msg.getContentType(msgContext.getSOAPConstants()))); } method.setRequestHeader(new Header(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\"")); method.setRequestHeader(new Header(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent"))); String userID = msgContext.getUsername(); String passwd = msgContext.getPassword(); // if UserID is not part of the context, but is in the URL, use // the one in the URL. if ((userID == null) && (tmpURL.getUserInfo() != null)) { String info = tmpURL.getUserInfo(); int sep = info.indexOf(':'); if ((sep >= 0) && (sep + 1 < info.length())) { userID = info.substring(0, sep); passwd = info.substring(sep + 1); } else { userID = info; } } if (userID != null) { Credentials proxyCred = new UsernamePasswordCredentials(userID, passwd); // if the username is in the form "user\domain" // then use NTCredentials instead. int domainIndex = userID.indexOf("\\"); if (domainIndex > 0) { String domain = userID.substring(0, domainIndex); if (userID.length() > domainIndex + 1) { String user = userID.substring(domainIndex + 1); proxyCred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain); } } httpClient.getState().setCredentials(AuthScope.ANY, proxyCred); } // add compression headers if needed if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) { method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, HTTPConstants.COMPRESSION_GZIP); } if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) { method.addRequestHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP); } // Transfer MIME headers of SOAPMessage to HTTP headers. MimeHeaders mimeHeaders = msg.getMimeHeaders(); if (mimeHeaders != null) { for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) { MimeHeader mimeHeader = (MimeHeader) i.next(); // HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set. // Let's not duplicate them. String headerName = mimeHeader.getName(); if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE) || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) { continue; } method.addRequestHeader(mimeHeader.getName(), mimeHeader.getValue()); } } // process user defined headers for information. Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS); if (userHeaderTable != null) { for (Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) { Map.Entry me = (Map.Entry) e.next(); Object keyObj = me.getKey(); if (null == keyObj) { continue; } String key = keyObj.toString().trim(); String value = me.getValue().toString().trim(); if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT) && value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) { method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) { String val = me.getValue().toString(); if (null != val) { httpChunkStream = JavaUtils.isTrue(val); } } else { method.addRequestHeader(key, value); } } } }
From source file:com.jaspersoft.ireport.jasperserver.ws.CommonsHTTPSender.java
/** * Extracts info from message context./*from w w w. jav a 2 s .c om*/ * * @param method Post method * @param httpClient The client used for posting * @param msgContext the message context * @param tmpURL the url to post to. * * @throws Exception */ private void addContextInfo(HttpMethodBase method, HttpClient httpClient, MessageContext msgContext, URL tmpURL) throws Exception { // optionally set a timeout for the request if (msgContext.getTimeout() != 0) { /* ISSUE: these are not the same, but MessageContext has only one definition of timeout */ // SO_TIMEOUT -- timeout for blocking reads httpClient.getHttpConnectionManager().getParams().setSoTimeout(msgContext.getTimeout()); // timeout for initial connection httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(msgContext.getTimeout()); } // Get SOAPAction, default to "" String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : ""; if (action == null) { action = ""; } Message msg = msgContext.getRequestMessage(); if (msg != null) { method.setRequestHeader(new Header(HTTPConstants.HEADER_CONTENT_TYPE, msg.getContentType(msgContext.getSOAPConstants()))); } method.setRequestHeader(new Header(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\"")); method.setRequestHeader(new Header(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent"))); String userID = msgContext.getUsername(); String passwd = msgContext.getPassword(); // if UserID is not part of the context, but is in the URL, use // the one in the URL. if ((userID == null) && (tmpURL.getUserInfo() != null)) { String info = tmpURL.getUserInfo(); int sep = info.indexOf(':'); if ((sep >= 0) && (sep + 1 < info.length())) { userID = info.substring(0, sep); passwd = info.substring(sep + 1); } else { userID = info; } } if (userID != null) { Credentials proxyCred = new UsernamePasswordCredentials(userID, passwd); // if the username is in the form "user\domain" // then use NTCredentials instead. int domainIndex = userID.indexOf("\\"); if (domainIndex > 0) { String domain = userID.substring(0, domainIndex); if (userID.length() > domainIndex + 1) { String user = userID.substring(domainIndex + 1); proxyCred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain); } } httpClient.getState().setCredentials(AuthScope.ANY, proxyCred); } // add compression headers if needed if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) { method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, HTTPConstants.COMPRESSION_GZIP); } if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) { method.addRequestHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP); } // Transfer MIME headers of SOAPMessage to HTTP headers. MimeHeaders mimeHeaders = msg.getMimeHeaders(); if (mimeHeaders != null) { for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) { MimeHeader mimeHeader = (MimeHeader) i.next(); //HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set. //Let's not duplicate them. String headerName = mimeHeader.getName(); if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE) || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) { continue; } method.addRequestHeader(mimeHeader.getName(), mimeHeader.getValue()); } } // process user defined headers for information. Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS); if (userHeaderTable != null) { for (Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) { Map.Entry me = (Map.Entry) e.next(); Object keyObj = me.getKey(); if (null == keyObj) { continue; } String key = keyObj.toString().trim(); String value = me.getValue().toString().trim(); if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT) && value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) { method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) { String val = me.getValue().toString(); if (null != val) { httpChunkStream = JavaUtils.isTrue(val); } } else { method.addRequestHeader(key, value); } } } }
From source file:gov.va.med.imaging.proxy.ImageXChangeHttpCommonsSender.java
/** * Extracts info from message context.//w w w . j a v a 2s .com * * @param method * Post method * @param httpClient * The client used for posting * @param msgContext * the message context * @param tmpURL * the url to post to. * * @throws Exception */ private void addContextInfo(HttpMethodBase method, HttpClient httpClient, MessageContext msgContext, URL tmpURL) throws Exception { // optionally set a timeout for the request if (msgContext.getTimeout() != 0) { /* * ISSUE: these are not the same, but MessageContext has only one * definition of timeout */ // SO_TIMEOUT -- timeout for blocking reads httpClient.getHttpConnectionManager().getParams().setSoTimeout(msgContext.getTimeout()); // timeout for initial connection httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(msgContext.getTimeout()); } // Get SOAPAction, default to "" String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : ""; if (action == null) { action = ""; } Message msg = msgContext.getRequestMessage(); if (msg != null) { method.setRequestHeader(new Header(HTTPConstants.HEADER_CONTENT_TYPE, msg.getContentType(msgContext.getSOAPConstants()))); } method.setRequestHeader(new Header(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\"")); method.setRequestHeader(new Header(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent"))); //method.setRequestHeader( // new Header(HTTPConstants.HEADER_USER_AGENT, "Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.5072)") //); String userID = msgContext.getUsername(); String passwd = msgContext.getPassword(); //System.out.println("ImageXChangeHttpCommonsSender setting credentials = '" + userID + ". " + passwd + "'"); // if UserID is not part of the context, but is in the URL, use // the one in the URL. if ((userID == null) && (tmpURL.getUserInfo() != null)) { String info = tmpURL.getUserInfo(); int sep = info.indexOf(':'); if ((sep >= 0) && (sep + 1 < info.length())) { userID = info.substring(0, sep); passwd = info.substring(sep + 1); } else { userID = info; } } if (userID != null) { Credentials proxyCred = new UsernamePasswordCredentials(userID, passwd); // if the username is in the form "user\domain" // then use NTCredentials instead. int domainIndex = userID.indexOf("\\"); if (domainIndex > 0) { String domain = userID.substring(0, domainIndex); if (userID.length() > domainIndex + 1) { String user = userID.substring(domainIndex + 1); proxyCred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain); } } httpClient.getState().setCredentials(AuthScope.ANY, proxyCred); //System.out.println("ImageXChangeHttpCommonsSender setting credentials = '" + userID + ". " + passwd + "'"); } // add compression headers if needed // if we accept GZIP then add the accept-encoding header if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) { // accept both gzip and deflate if the gzip property is set method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, HTTPConstants.COMPRESSION_GZIP + "," + COMPRESSION_DEFLATE); //method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, COMPRESSION_DEFLATE); } // if we will gzip the request then add the content-encoding header if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) { method.addRequestHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP); } // Transfer MIME headers of SOAPMessage to HTTP headers. MimeHeaders mimeHeaders = msg.getMimeHeaders(); if (mimeHeaders != null) { for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) { MimeHeader mimeHeader = (MimeHeader) i.next(); // HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set. // Let's not duplicate them. String headerName = mimeHeader.getName(); if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE) || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) continue; method.addRequestHeader(mimeHeader.getName(), mimeHeader.getValue()); } } // process user defined headers for information. Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS); if (userHeaderTable != null) { for (Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) { Map.Entry me = (Map.Entry) e.next(); Object keyObj = me.getKey(); if (null == keyObj) { continue; } String key = keyObj.toString().trim(); String value = me.getValue().toString().trim(); if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT) && value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) { method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) { String val = me.getValue().toString(); if (null != val) { httpChunkStream = JavaUtils.isTrue(val); } } else { method.addRequestHeader(key, value); } } } }
From source file:com.day.cq.wcm.foundation.impl.Rewriter.java
/** * Process a page.//w w w . j a va2 s. co m */ public void rewrite(HttpServletRequest request, HttpServletResponse response) throws IOException { try { targetURL = new URI(target); } catch (URISyntaxException e) { IOException ioe = new IOException("Bad URI syntax: " + target); ioe.initCause(e); throw ioe; } setHostPrefix(targetURL); HttpClient httpClient = new HttpClient(); HttpState httpState = new HttpState(); HostConfiguration hostConfig = new HostConfiguration(); HttpMethodBase httpMethod; // define host hostConfig.setHost(targetURL.getHost(), targetURL.getPort()); // create http method String method = (String) request.getAttribute("cq.ext.app.method"); if (method == null) { method = request.getMethod(); } method = method.toUpperCase(); boolean isPost = "POST".equals(method); String urlString = targetURL.getPath(); StringBuffer query = new StringBuffer(); if (targetURL.getQuery() != null) { query.append("?"); query.append(targetURL.getQuery()); } //------------ GET --------------- if ("GET".equals(method)) { // add internal props Iterator<String> iter = extraParams.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String value = extraParams.get(name); if (query.length() == 0) { query.append("?"); } else { query.append("&"); } query.append(Text.escape(name)); query.append("="); query.append(Text.escape(value)); } if (passInput) { // add request params @SuppressWarnings("unchecked") Enumeration<String> e = request.getParameterNames(); while (e.hasMoreElements()) { String name = e.nextElement(); if (targetParamName.equals(name)) { continue; } String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { if (query.length() == 0) { query.append("?"); } else { query.append("&"); } query.append(Text.escape(name)); query.append("="); query.append(Text.escape(values[i])); } } } httpMethod = new GetMethod(urlString + query); //------------ POST --------------- } else if ("POST".equals(method)) { PostMethod m = new PostMethod(urlString + query); httpMethod = m; String contentType = request.getContentType(); boolean mp = contentType != null && contentType.toLowerCase().startsWith("multipart/"); if (mp) { //------------ MULTPART POST --------------- List<Part> parts = new LinkedList<Part>(); Iterator<String> iter = extraParams.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String value = extraParams.get(name); parts.add(new StringPart(name, value)); } if (passInput) { // add request params @SuppressWarnings("unchecked") Enumeration<String> e = request.getParameterNames(); while (e.hasMoreElements()) { String name = e.nextElement(); if (targetParamName.equals(name)) { continue; } String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { parts.add(new StringPart(name, values[i])); } } } m.setRequestEntity( new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), m.getParams())); } else { //------------ NORMAL POST --------------- // add internal props Iterator<String> iter = extraParams.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String value = extraParams.get(name); m.addParameter(name, value); } if (passInput) { // add request params @SuppressWarnings("unchecked") Enumeration e = request.getParameterNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); if (targetParamName.equals(name)) { continue; } String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { m.addParameter(name, values[i]); } } } } } else { log.error("Unsupported method ''{0}''", method); throw new IOException("Unsupported http method " + method); } log.debug("created http connection for method {0} to {1}", method, urlString + query); // add some request headers httpMethod.addRequestHeader("User-Agent", request.getHeader("User-Agent")); httpMethod.setFollowRedirects(!isPost); httpMethod.getParams().setSoTimeout(soTimeout); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout); // send request httpClient.executeMethod(hostConfig, httpMethod, httpState); String contentType = httpMethod.getResponseHeader("Content-Type").getValue(); log.debug("External app responded: {0}", httpMethod.getStatusLine()); log.debug("External app contenttype: {0}", contentType); // check response code int statusCode = httpMethod.getStatusCode(); if (statusCode >= HttpURLConnection.HTTP_BAD_REQUEST) { PrintWriter writer = response.getWriter(); writer.println("External application returned status code: " + statusCode); return; } else if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM) { String location = httpMethod.getResponseHeader("Location").getValue(); if (location == null) { response.sendError(HttpURLConnection.HTTP_NOT_FOUND); return; } response.sendRedirect(rewriteURL(location, false)); return; } // open input stream InputStream in = httpMethod.getResponseBodyAsStream(); // check content type if (contentType != null && contentType.startsWith("text/html")) { rewriteHtml(in, contentType, response); } else { // binary mode if (contentType != null) { response.setContentType(contentType); } OutputStream outs = response.getOutputStream(); try { byte buf[] = new byte[8192]; int len; while ((len = in.read(buf)) != -1) { outs.write(buf, 0, len); } } finally { if (in != null) { in.close(); } } } }