Example usage for org.apache.http.client.methods HttpRequestBase getURI

List of usage examples for org.apache.http.client.methods HttpRequestBase getURI

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpRequestBase getURI.

Prototype

public URI getURI() 

Source Link

Document

Returns the original request URI.

Usage

From source file:nl.nn.adapterframework.extensions.cmis.CmisHttpSender.java

@Override
public HttpRequestBase getMethod(URIBuilder uri, String message, ParameterValueList pvl,
        Map<String, String> headersParamsMap, IPipeLineSession session) throws SenderException {
    HttpRequestBase method = null;

    try {/*from w  w  w.  j  av  a  2s.c om*/
        if (getMethodType().equals("GET")) {
            method = new HttpGet(uri.build());
        } else if (getMethodType().equals("POST")) {
            HttpPost httpPost = new HttpPost(uri.build());

            // send data
            if (pvl.getParameterValue("writer") != null) {
                Output writer = (Output) pvl.getParameterValue("writer").getValue();
                ByteArrayOutputStream out = new ByteArrayOutputStream();

                Object clientCompression = pvl.getParameterValue(SessionParameter.CLIENT_COMPRESSION);
                if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) {
                    httpPost.setHeader("Content-Encoding", "gzip");
                    writer.write(new GZIPOutputStream(out, 4096));
                } else {
                    writer.write(out);
                }

                HttpEntity entity = new BufferedHttpEntity(new ByteArrayEntity(out.toByteArray()));
                httpPost.setEntity(entity);
                out.close();

                method = httpPost;
            }
        } else if (getMethodType().equals("PUT")) {
            HttpPut httpPut = new HttpPut(uri.build());

            // send data
            if (pvl.getParameterValue("writer") != null) {
                Output writer = (Output) pvl.getParameterValue("writer").getValue();
                ByteArrayOutputStream out = new ByteArrayOutputStream();

                Object clientCompression = pvl.getParameterValue(SessionParameter.CLIENT_COMPRESSION);
                if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) {
                    httpPut.setHeader("Content-Encoding", "gzip");
                    writer.write(new GZIPOutputStream(out, 4096));
                } else {
                    writer.write(out);
                }

                HttpEntity entity = new BufferedHttpEntity(new ByteArrayEntity(out.toByteArray()));
                httpPut.setEntity(entity);
                out.close();

                method = httpPut;
            }
        } else if (getMethodType().equals("DELETE")) {
            method = new HttpDelete(uri.build());
        } else {
            throw new MethodNotSupportedException("method [" + getMethodType() + "] not implemented");
        }
    } catch (Exception e) {
        throw new SenderException(e);
    }

    for (Map.Entry<String, String> entry : headers.entrySet()) {
        log.debug("append header [" + entry.getKey() + "] with value [" + entry.getValue() + "]");

        method.addHeader(entry.getKey(), entry.getValue());
    }

    //Cmis creates it's own contentType depending on the method and bindingType
    method.setHeader("Content-Type", getContentType());

    log.debug(getLogPrefix() + "HttpSender constructed " + getMethodType() + "-method [" + method.getURI()
            + "] query [" + method.getURI().getQuery() + "] ");
    return method;
}

From source file:org.dasein.cloud.azure.AzureStorageMethod.java

private String calculatedSharedKeyLiteSignature(@Nonnull HttpRequestBase method,
        @Nonnull Map<String, String> queryParams) throws CloudException, InternalException {
    fetchKeys();/*w  ww.jav a  2  s . com*/

    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new AzureConfigException("No context was specified for this request");
    }
    Header h = method.getFirstHeader("content-type");
    String contentType = (h == null ? null : h.getValue());

    if (contentType == null) {
        contentType = "";
    }
    StringBuilder stringToSign = new StringBuilder();

    stringToSign.append(method.getMethod().toUpperCase()).append("\n");
    stringToSign.append("\n"); // content-md5
    stringToSign.append(contentType).append("\n");
    stringToSign.append(method.getFirstHeader("date").getValue()).append("\n");

    Header[] headers = method.getAllHeaders();
    TreeSet<String> keys = new TreeSet<String>();

    for (Header header : headers) {
        if (header.getName().startsWith(Header_Prefix_MS)) {
            keys.add(header.getName().toLowerCase());
        }
    }

    for (String key : keys) {
        Header header = method.getFirstHeader(key);

        if (header != null) {
            Header[] all = method.getHeaders(key);

            stringToSign.append(key.toLowerCase().trim()).append(":");
            if (all != null && all.length > 0) {
                for (Header current : all) {
                    String v = (current.getValue() != null ? current.getValue() : "");

                    stringToSign.append(v.trim().replaceAll("\n", " ")).append(",");
                }
            }
            stringToSign.deleteCharAt(stringToSign.lastIndexOf(","));
        } else {
            stringToSign.append(key.toLowerCase().trim()).append(":");
        }
        stringToSign.append("\n");
    }

    stringToSign.append("/").append(getStorageAccount()).append(method.getURI().getPath());

    keys.clear();
    for (String key : queryParams.keySet()) {
        if (key.equalsIgnoreCase("comp")) {
            key = key.toLowerCase();
            keys.add(key);
        }
    }
    if (!keys.isEmpty()) {
        stringToSign.append("?");
        for (String key : keys) {
            String value = queryParams.get(key);

            if (value == null) {
                value = "";
            }
            stringToSign.append(key).append("=").append(value).append("&");
        }
        stringToSign.deleteCharAt(stringToSign.lastIndexOf("&"));
    }
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("BEGIN STRING TO SIGN");
            logger.debug(stringToSign.toString());
            logger.debug("END STRING TO SIGN");
        }
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(Base64.decodeBase64(ctx.getStoragePrivate()), "HmacSHA256"));

        String signature = new String(
                Base64.encodeBase64(mac.doFinal(stringToSign.toString().getBytes("UTF-8"))));

        if (logger.isDebugEnabled()) {
            logger.debug("signature=" + signature);
        }
        return signature;
    } catch (UnsupportedEncodingException e) {
        logger.error("UTF-8 not supported: " + e.getMessage());
        throw new InternalException(e);
    } catch (NoSuchAlgorithmException e) {
        logger.error("No such algorithm: " + e.getMessage());
        throw new InternalException(e);
    } catch (InvalidKeyException e) {
        logger.error("Invalid key: " + e.getMessage());
        throw new InternalException(e);
    }
}

From source file:com.ibm.sbt.service.basic.ProxyService.java

public void prepareResponse(HttpRequestBase method, HttpServletRequest request, HttpServletResponse response,
        HttpResponse clientResponse, boolean isCopy) throws ServletException {
    Object timedObject = ProxyProfiler.getTimedObject();
    try {/*w  w w.  j  a v  a 2  s  .co  m*/
        int statusCode = clientResponse.getStatusLine().getStatusCode();
        if (statusCode == 401 || statusCode == 403) {
            clientResponse.setHeader("WWW-Authenticate", "");
        }
        response.setStatus(statusCode);
        if (getDebugHook() != null) {
            getDebugHook().getDumpResponse().setStatus(statusCode);
        }

        // Passed back all heads, but process cookies differently.
        Header[] headers = clientResponse.getAllHeaders();
        for (Header header : headers) {
            String headername = header.getName();

            if (headername.equalsIgnoreCase("Set-Cookie")) { // $NON-NLS-1$
                if (forwardCookies(method, request)) {
                    // If cookie, have to rewrite domain/path for browser.
                    String setcookieval = header.getValue();

                    if (setcookieval != null) {
                        String thisserver = request.getServerName();

                        String thisdomain;
                        if (thisserver.indexOf('.') == -1) {
                            thisdomain = "";
                        } else {
                            thisdomain = thisserver.substring(thisserver.indexOf('.'));
                        }
                        String domain = null;

                        // path info = /protocol/server/path-on-server
                        //Matcher m = cookiePathPattern.matcher(request.getPathInfo());
                        String thispath = request.getContextPath() + request.getServletPath();
                        String path = null;

                        String[][] cookparams = getCookieStrings(setcookieval);

                        for (int j = 1; j < cookparams.length; j++) {
                            if ("domain".equalsIgnoreCase(cookparams[j][0])) { // $NON-NLS-1$
                                domain = cookparams[j][1];
                                cookparams[j][1] = null;
                            } else if ("path".equalsIgnoreCase(cookparams[j][0])) { // $NON-NLS-1$
                                path = cookparams[j][1];
                                cookparams[j][1] = null;
                            }
                        }

                        if (domain == null) {
                            domain = method.getURI().getHost();
                        }

                        // Set cookie name
                        String encoded = encodeCookieNameAndPath(cookparams[0][0], path, domain);
                        if (encoded != null) {
                            String newcookiename = PASSTHRUID + encoded;

                            StringBuilder newset = new StringBuilder(newcookiename);
                            newset.append('=');
                            newset.append(cookparams[0][1]);

                            for (int j = 1; j < cookparams.length; j++) {
                                String settingname = cookparams[j][0];
                                String settingvalue = cookparams[j][1];
                                if (settingvalue != null) {
                                    newset.append("; ").append(settingname); // $NON-NLS-1$
                                    newset.append('=').append(settingvalue); // $NON-NLS-1$
                                }
                            }

                            newset.append("; domain=").append(thisdomain); // $NON-NLS-1$
                            newset.append("; path=").append(thispath); // $NON-NLS-1$

                            String newsetcookieval = newset.toString();
                            // this implementation of HttpServletRequest seems to have issues... setHeader works as I would
                            // expect addHeader to.
                            response.setHeader(headername, newsetcookieval);
                            if (getDebugHook() != null) {
                                getDebugHook().getDumpResponse().addCookie(headername, newsetcookieval);
                            }
                        }
                    }
                }
            } else if (!headername.equalsIgnoreCase("Transfer-Encoding")) { // $NON-NLS-1$
                String headerval = header.getValue();

                if (headername.equalsIgnoreCase("content-type")) {
                    int loc = headerval.indexOf(';');
                    String type;
                    if (loc > 0) {
                        type = headerval.substring(0, loc).trim();
                    } else {
                        type = headerval;
                    }
                    if (!isMimeTypeAllowed(type)) {
                        isCopy = false;
                        break;
                    } else {
                        response.setHeader(headername, headerval);
                        if (getDebugHook() != null) {
                            getDebugHook().getDumpResponse().addHeader(headername, headerval);
                        }
                    }
                } else if ((statusCode == 401 || statusCode == 403)
                        && headername.equalsIgnoreCase("WWW-Authenticate")) { // $NON-NLS-1$
                    if (headerval.indexOf("Basic") != -1) { // $NON-NLS-1$
                        String pathInfo = request.getPathInfo();
                        String[] pathParts = (pathInfo.startsWith("/") ? pathInfo.substring(1) : pathInfo)
                                .split("/");
                        if (pathParts.length > 1) {
                            StringBuilder strb = new StringBuilder("Basic realm=\""); // $NON-NLS-1$
                            strb.append(request.getContextPath());
                            strb.append(request.getServletPath());
                            strb.append('/');
                            strb.append(pathParts[0]);
                            strb.append('/');
                            strb.append(pathParts[1]);
                            strb.append('"');
                            headerval = strb.toString();
                            response.setHeader(headername, headerval);
                            if (getDebugHook() != null) {
                                getDebugHook().getDumpResponse().addHeader(headername, headerval);
                            }
                        }
                    }
                } else {
                    response.setHeader(headername, headerval);
                    if (getDebugHook() != null) {
                        getDebugHook().getDumpResponse().addHeader(headername, headerval);
                    }
                }
            }
        }

        // Need to move response body over too
        if (statusCode == HttpServletResponse.SC_NO_CONTENT
                || statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
            response.setHeader("Content-Length", "0");
            if (getDebugHook() != null) {
                getDebugHook().getDumpResponse().addHeader("Content-Length", "0");
            }
        } else if (isCopy) {
            HttpEntity entity = clientResponse.getEntity();
            InputStream inStream = entity.getContent();
            if (inStream != null) {
                OutputStream os = response.getOutputStream();
                if (TRACE) {
                    OutputStream tos = new TraceOutputStream(os, System.out, false);
                    os = tos;
                }
                StreamUtil.copyStream(inStream, os);
                os.flush();
            } else {
                response.setHeader("Content-Length", "0");
                if (getDebugHook() != null) {
                    getDebugHook().getDumpResponse().addHeader("Content-Length", "0");
                }
            }
        }
    } catch (IOException ex) {
        throw new ServletException(ex);
    }
    ProxyProfiler.profileTimedRequest(timedObject, "prepareResponse");
}

From source file:net.www_eee.portal.channels.ProxyChannel.java

/**
 * {@linkplain #createProxyClient(Page.Request) Create} an {@link HttpClient} and use it to
 * {@linkplain HttpClient#execute(HttpUriRequest, HttpContext) execute} a
 * {@linkplain #createProxyRequest(Page.Request, Channel.Mode, CloseableHttpClient) proxy request} to retrieve the
 * content to be returned/rendered in response to the supplied <code>pageRequest</code>.
 * /*from   w  w  w .  j  a v  a2  s. c  o m*/
 * @param pageRequest The {@link net.www_eee.portal.Page.Request Request} currently being processed.
 * @param mode The {@link net.www_eee.portal.Channel.Mode Mode} of the request.
 * @return An {@link HttpClientContext} containing the {@linkplain ExecutionContext#HTTP_RESPONSE response} from the
 * proxied server.
 * @throws WWWEEEPortal.Exception If a problem occurred while determining the result.
 * @throws WebApplicationException If a problem occurred while determining the result.
 * @see #PROXY_RESPONSE_HOOK
 */
protected HttpClientContext doProxyRequest(final Page.Request pageRequest, final Mode mode)
        throws WWWEEEPortal.Exception, WebApplicationException {
    final HttpClientContext proxyContext = HttpClientContext.create();
    final CloseableHttpClient proxyClient = createProxyClient(pageRequest);
    proxyContext.setAttribute(HTTP_CLIENT_CONTEXT_ID, proxyClient);

    try {

        CloseableHttpResponse proxyResponse = null;

        while (proxyResponse == null) { // Keep trying again if a plugin filter null's out the previous response.

            final HttpRequestBase proxyRequest = createProxyRequest(pageRequest, mode, proxyClient);
            try {

                final Object[] context = new Object[] { mode, proxyContext, proxyClient, proxyRequest };
                proxyResponse = PROXY_RESPONSE_HOOK.value(plugins, context, pageRequest);

                if (proxyResponse == null) {
                    try {

                        proxyResponse = proxyClient.execute(proxyRequest, proxyContext);

                    } catch (UnknownHostException uhe) {
                        throw new ConfigManager.ConfigException(uhe);
                    } catch (IOException ioe) {
                        throw new WWWEEEPortal.OperationalException(ioe);
                    }
                }

                proxyResponse = PROXY_RESPONSE_HOOK.filter(plugins, context, pageRequest, proxyResponse);

            } catch (WWWEEEPortal.Exception wpe) {
                LogAnnotation.annotate(wpe, "ProxyRequest", proxyRequest, null, false);
                LogAnnotation.annotate(wpe, "ProxyResponse", proxyResponse, null, false);
                LogAnnotation.annotate(wpe, "ProxiedFileURL", proxyRequest.getURI(), null, false);
                throw wpe;
            }

        } // while (proxyResponse == null)

        return validateProxyResponse(proxyContext, pageRequest, mode);

    } catch (WWWEEEPortal.Exception wpe) {
        LogAnnotation.annotate(wpe, "ProxyContext", proxyContext, null, false);
        try {
            LogAnnotation.annotate(wpe, "ProxiedFileURL", HttpUtil.getRequestTargetURL(proxyContext), null,
                    false); // This wouldn't be necessary if any of the previous annotations could actually toString() themselves usefully.
        } catch (Exception e) {
        }
        throw wpe;
    }

}

From source file:de.betterform.connector.http.AbstractHTTPConnector.java

protected void execute(HttpRequestBase httpRequestBase) throws Exception {
    //      (new HttpClient()).executeMethod(httpMethod);
    //HttpClient client = new HttpClient();
    HttpParams httpParams = new BasicHttpParams();

    DefaultHttpClient client = ConnectorFactory.getFactory().getHttpClient(httpParams);

    if (!getContext().containsKey(AbstractHTTPConnector.SSL_CUSTOM_SCHEME)) {
        LOGGER.debug("SSL_CUSTOM_SCHEME");
        LOGGER.debug("SSL_CUSTOM_SCHEME: Factory: "
                + Config.getInstance().getProperty(AbstractHTTPConnector.HTTPCLIENT_SSL_CONTEXT));
        String contextPath = Config.getInstance().getProperty(AbstractHTTPConnector.HTTPCLIENT_SSL_CONTEXT);
        if (contextPath != null) {
            initSSLScheme(contextPath);//w w w . ja  va 2s. c  om
        }
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("context params>>>");
        Map map = getContext();
        Iterator keys = map.keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next().toString();
            Object value = map.get(key);
            if (value != null)
                LOGGER.debug(key + "=" + value.toString());
        }
        LOGGER.debug("<<<end params");
    }
    String username = null;
    String password = null;
    String realm = null;

    //add custom header to signal XFormsFilter to not process this internal request
    //httpMethod.setRequestHeader(BetterFORMConstants.BETTERFORM_INTERNAL,"true");
    httpRequestBase.addHeader(BetterFORMConstants.BETTERFORM_INTERNAL, "true");

    /// *** copy all keys in map HTTP_REQUEST_HEADERS as http-submissionHeaders
    if (getContext().containsKey(HTTP_REQUEST_HEADERS)) {
        RequestHeaders httpRequestHeaders = (RequestHeaders) getContext().get(HTTP_REQUEST_HEADERS);

        // Iterator it =
        Map headersToAdd = new HashMap();
        for (RequestHeader header : httpRequestHeaders.getAllHeaders()) {
            String headername = header.getName();
            String headervalue = header.getValue();

            if (headername.equals("username")) {
                username = headervalue;
            } else if (headername.equals("password")) {
                password = headervalue;
            } else if (headername.equals("realm")) {
                realm = headervalue;
            } else {
                if (headersToAdd.containsKey(headername)) {
                    String formerValue = (String) headersToAdd.get(headername);
                    headersToAdd.put(headername, formerValue + "," + headervalue);
                } else {
                    if (headername.equals("accept-encoding")) {
                        // do nothing
                        LOGGER.debug("do not add accept-encoding:" + headervalue + " for request");
                    } else {
                        headersToAdd.put(headername, headervalue);
                        if (LOGGER.isDebugEnabled()) {
                            LOGGER.debug("setting header: " + headername + " value: " + headervalue);
                        }
                    }
                }
            }
        }
        Iterator keyIterator = headersToAdd.keySet().iterator();
        while (keyIterator.hasNext()) {
            String key = (String) keyIterator.next();
            //httpMethod.setRequestHeader(new Header(key,(String) headersToAdd.get(key)));
            httpRequestBase.setHeader(key, (String) headersToAdd.get(key));
            //httpRequestBase.addHeader(key, (String) headersToAdd.get(key));
        }
    }
    if (httpRequestBase.containsHeader("Content-Length")) {
        //remove content-length if present httpclient will recalucalte the value.
        httpRequestBase.removeHeaders("Content-Length");
    }
    if (username != null && password != null) {
        URI targetURI = null;
        //targetURI = httpMethod.getURI();
        targetURI = httpRequestBase.getURI();
        //client.getParams().setAuthenticationPreemptive(true);

        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        if (realm == null) {
            realm = AuthScope.ANY_REALM;
        }
        //client.getState().setCredentials(new AuthScope(targetURI.getHost(), targetURI.getPort(), realm), defaultcreds);
        client.getCredentialsProvider()
                .setCredentials(new AuthScope(targetURI.getHost(), targetURI.getPort(), realm), defaultcreds);
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();

        authCache.put(new HttpHost(targetURI.getHost()), basicAuth);
        BasicHttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

        //Needed? httpMethod.setDoAuthentication(true);

    }
    //alternative method for non-tomcat servers
    if (getContext().containsKey(REQUEST_COOKIE)) {
        //HttpState state = client.getState();
        HttpParams state = client.getParams();

        //state.setCookiePolicy(CookiePolicy.COMPATIBILITY);
        state.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

        if (getContext().get(REQUEST_COOKIE) instanceof Cookie[]) {
            Cookie[] cookiesIn = (Cookie[]) getContext().get(REQUEST_COOKIE);
            if (cookiesIn[0] != null) {
                for (int i = 0; i < cookiesIn.length; i++) {
                    Cookie cookie = cookiesIn[i];
                    //state.addCookie(cookie);
                    client.getCookieStore().addCookie(cookie);
                }
                /*
                  Cookie[] cookies = state.getCookies();
                        
                Header cookieOut = new CookieSpecBase().formatCookieHeader(cookies);
                httpMethod.setRequestHeader(cookieOut);
                client.setState(state);
                  */
                List<Cookie> cookies = client.getCookieStore().getCookies();
                List<Header> cookieHeaders = new BrowserCompatSpec().formatCookies(cookies);
                Header[] headers = cookieHeaders.toArray(new Header[0]);

                for (int i = 0; i < headers.length; i++) {
                    httpRequestBase.addHeader(headers[i]);
                }

                client.setParams(state);
            }
        } else {
            throw new MalformedCookieException(
                    "Cookies must be passed as org.apache.commons.httpclient.Cookie objects.");
        }
    }

    if (getContext().containsKey(AbstractHTTPConnector.SSL_CUSTOM_SCHEME)) {
        LOGGER.debug("Using customSSL-Protocol-Handler");
        Iterator<Scheme> schemes = ((Vector<Scheme>) getContext().get(AbstractHTTPConnector.SSL_CUSTOM_SCHEME))
                .iterator();

        while (schemes.hasNext()) {
            client.getConnectionManager().getSchemeRegistry().register(schemes.next());
        }
    }

    if (httpRequestBase.getURI().isAbsolute()) {
        httpRequestBase.setHeader("host", httpRequestBase.getURI().getHost());
    }

    HttpResponse httpResponse = client.execute(httpRequestBase);
    statusCode = httpResponse.getStatusLine().getStatusCode();
    reasonPhrase = httpResponse.getStatusLine().getReasonPhrase();
    try {
        if (statusCode >= 300) {
            // Allow 302 only
            if (statusCode != 302) {
                throw new XFormsInternalSubmitException(statusCode, reasonPhrase,
                        EntityUtils.toString(httpResponse.getEntity()), XFormsConstants.RESOURCE_ERROR);
            }
        }
        this.handleHttpMethod(httpResponse);
    } catch (Exception e) {

        LOGGER.trace("AbstractHTTPConnector Exception: ", e);
        try {
            throw new XFormsInternalSubmitException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase(),
                    EntityUtils.toString(httpResponse.getEntity()), XFormsConstants.RESOURCE_ERROR);
        } catch (IOException e1) {
            throw new XFormsInternalSubmitException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase(), XFormsConstants.RESOURCE_ERROR);
        }
    }

}

From source file:sk.datalan.solr.impl.HttpSolrServer.java

protected NamedList<Object> executeMethod(HttpRequestBase method, final ResponseParser processor)
        throws SolrServerException {
    //    // XXX client already has this set, is this needed?
    //    method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS,
    //        followRedirects);
    method.addHeader("User-Agent", AGENT);

    InputStream respBody = null;//www .  j ava 2 s .  c om
    boolean shouldClose = true;
    boolean success = false;
    try {
        // Execute the method.
        final HttpResponse response = httpClient.execute(method);
        int httpStatus = response.getStatusLine().getStatusCode();

        // Read the contents
        respBody = response.getEntity().getContent();
        Header ctHeader = response.getLastHeader("content-type");
        String contentType;
        if (ctHeader != null) {
            contentType = ctHeader.getValue();
        } else {
            contentType = "";
        }

        // handle some http level checks before trying to parse the response
        switch (httpStatus) {
        case HttpStatus.SC_OK:
        case HttpStatus.SC_BAD_REQUEST:
        case HttpStatus.SC_CONFLICT: // 409
            break;
        case HttpStatus.SC_MOVED_PERMANENTLY:
        case HttpStatus.SC_MOVED_TEMPORARILY:
            if (!followRedirects) {
                throw new SolrServerException(
                        "Server at " + getBaseURL() + " sent back a redirect (" + httpStatus + ").");
            }
            break;
        default:
            if (processor == null) {
                throw new RemoteSolrException(httpStatus,
                        "Server at " + getBaseURL() + " returned non ok status:" + httpStatus + ", message:"
                                + response.getStatusLine().getReasonPhrase(),
                        null);
            }
        }
        if (processor == null) {

            // no processor specified, return raw stream
            NamedList<Object> rsp = new NamedList<>();
            rsp.add("stream", respBody);
            // Only case where stream should not be closed
            shouldClose = false;
            success = true;
            return rsp;
        }

        String procCt = processor.getContentType();
        if (procCt != null) {
            String procMimeType = ContentType.parse(procCt).getMimeType().trim().toLowerCase(Locale.ROOT);
            String mimeType = ContentType.parse(contentType).getMimeType().trim().toLowerCase(Locale.ROOT);
            if (!procMimeType.equals(mimeType)) {
                // unexpected mime type
                String msg = "Expected mime type " + procMimeType + " but got " + mimeType + ".";
                Header encodingHeader = response.getEntity().getContentEncoding();
                String encoding;
                if (encodingHeader != null) {
                    encoding = encodingHeader.getValue();
                } else {
                    encoding = "UTF-8"; // try UTF-8
                }
                try {
                    msg = msg + " " + IOUtils.toString(respBody, encoding);
                } catch (IOException e) {
                    throw new RemoteSolrException(httpStatus,
                            "Could not parse response with encoding " + encoding, e);
                }
                RemoteSolrException e = new RemoteSolrException(httpStatus, msg, null);
                throw e;
            }
        }

        //      if(true) {
        //        ByteArrayOutputStream copy = new ByteArrayOutputStream();
        //        IOUtils.copy(respBody, copy);
        //        String val = new String(copy.toByteArray());
        //        System.out.println(">RESPONSE>"+val+"<"+val.length());
        //        respBody = new ByteArrayInputStream(copy.toByteArray());
        //      }
        NamedList<Object> rsp = null;
        ContentType ct = ContentType.getOrDefault(response.getEntity());
        try {
            rsp = processor.processResponse(respBody, ct.getCharset().toString());
        } catch (Exception e) {
            throw new RemoteSolrException(httpStatus, e.getMessage(), e);
        }
        if (httpStatus != HttpStatus.SC_OK) {
            String reason = null;
            try {
                NamedList err = (NamedList) rsp.get("error");
                if (err != null) {
                    reason = (String) err.get("msg");
                    if (reason == null) {
                        reason = (String) err.get("trace");
                    }
                }
            } catch (Exception ex) {
            }
            if (reason == null) {
                StringBuilder msg = new StringBuilder();
                msg.append(response.getStatusLine().getReasonPhrase());
                msg.append("\n\n");
                msg.append("request: ").append(method.getURI());
                reason = java.net.URLDecoder.decode(msg.toString(), UTF_8);
            }
            throw new RemoteSolrException(httpStatus, reason, null);
        }
        success = true;
        return rsp;
    } catch (ConnectException e) {
        throw new SolrServerException("Server refused connection at: " + getBaseURL(), e);
    } catch (SocketTimeoutException e) {
        throw new SolrServerException("Timeout occured while waiting response from server at: " + getBaseURL(),
                e);
    } catch (IOException e) {
        throw new SolrServerException("IOException occured when talking to server at: " + getBaseURL(), e);
    } finally {
        if (respBody != null && shouldClose) {
            try {
                respBody.close();
            } catch (IOException e) {
                log.error("", e);
            } finally {
                if (!success) {
                    method.abort();
                }
            }
        }
    }
}

From source file:com.mirth.connect.connectors.http.HttpDispatcher.java

@Override
public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) {
    HttpDispatcherProperties httpDispatcherProperties = (HttpDispatcherProperties) connectorProperties;
    eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
            getDestinationName(), ConnectionStatusEventType.WRITING));

    String responseData = null;//from  w  w  w  . j  a  v a  2s.c  o m
    String responseError = null;
    String responseStatusMessage = null;
    Status responseStatus = Status.QUEUED;
    boolean validateResponse = false;

    CloseableHttpClient client = null;
    HttpRequestBase httpMethod = null;
    CloseableHttpResponse httpResponse = null;
    File tempFile = null;
    int socketTimeout = NumberUtils.toInt(httpDispatcherProperties.getSocketTimeout(), 30000);

    try {
        configuration.configureDispatcher(this, httpDispatcherProperties);

        long dispatcherId = getDispatcherId();
        client = clients.get(dispatcherId);
        if (client == null) {
            BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
                    socketFactoryRegistry.build());
            httpClientConnectionManager
                    .setSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeout).build());
            HttpClientBuilder clientBuilder = HttpClients.custom()
                    .setConnectionManager(httpClientConnectionManager);
            HttpUtil.configureClientBuilder(clientBuilder);

            if (httpDispatcherProperties.isUseProxyServer()) {
                clientBuilder.setRoutePlanner(new DynamicProxyRoutePlanner());
            }

            client = clientBuilder.build();
            clients.put(dispatcherId, client);
        }

        URI hostURI = new URI(httpDispatcherProperties.getHost());
        String host = hostURI.getHost();
        String scheme = hostURI.getScheme();
        int port = hostURI.getPort();
        if (port == -1) {
            if (scheme.equalsIgnoreCase("https")) {
                port = 443;
            } else {
                port = 80;
            }
        }

        // Parse the content type field first, and then add the charset if needed
        ContentType contentType = ContentType.parse(httpDispatcherProperties.getContentType());
        Charset charset = null;
        if (contentType.getCharset() == null) {
            charset = Charset.forName(CharsetUtils.getEncoding(httpDispatcherProperties.getCharset()));
        } else {
            charset = contentType.getCharset();
        }

        if (httpDispatcherProperties.isMultipart()) {
            tempFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
        }

        HttpHost target = new HttpHost(host, port, scheme);

        httpMethod = buildHttpRequest(hostURI, httpDispatcherProperties, connectorMessage, tempFile,
                contentType, charset);

        HttpClientContext context = HttpClientContext.create();

        // authentication
        if (httpDispatcherProperties.isUseAuthentication()) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
            Credentials credentials = new UsernamePasswordCredentials(httpDispatcherProperties.getUsername(),
                    httpDispatcherProperties.getPassword());
            credsProvider.setCredentials(authScope, credentials);
            AuthCache authCache = new BasicAuthCache();
            RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.<AuthSchemeProvider>create();

            if (AuthSchemes.DIGEST.equalsIgnoreCase(httpDispatcherProperties.getAuthenticationType())) {
                logger.debug("using Digest authentication");
                registryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory(charset));

                if (httpDispatcherProperties.isUsePreemptiveAuthentication()) {
                    processDigestChallenge(authCache, target, credentials, httpMethod, context);
                }
            } else {
                logger.debug("using Basic authentication");
                registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory(charset));

                if (httpDispatcherProperties.isUsePreemptiveAuthentication()) {
                    authCache.put(target, new BasicScheme());
                }
            }

            context.setCredentialsProvider(credsProvider);
            context.setAuthSchemeRegistry(registryBuilder.build());
            context.setAuthCache(authCache);

            logger.debug("using authentication with credentials: " + credentials);
        }

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(socketTimeout)
                .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).build();
        context.setRequestConfig(requestConfig);

        // Set proxy information
        if (httpDispatcherProperties.isUseProxyServer()) {
            context.setAttribute(PROXY_CONTEXT_KEY, new HttpHost(httpDispatcherProperties.getProxyAddress(),
                    Integer.parseInt(httpDispatcherProperties.getProxyPort())));
        }

        // execute the method
        logger.debug(
                "executing method: type=" + httpMethod.getMethod() + ", uri=" + httpMethod.getURI().toString());
        httpResponse = client.execute(target, httpMethod, context);
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        logger.debug("received status code: " + statusCode);

        Map<String, List<String>> headers = new HashMap<String, List<String>>();
        for (Header header : httpResponse.getAllHeaders()) {
            List<String> list = headers.get(header.getName());

            if (list == null) {
                list = new ArrayList<String>();
                headers.put(header.getName(), list);
            }

            list.add(header.getValue());
        }

        connectorMessage.getConnectorMap().put("responseStatusLine", statusLine.toString());
        connectorMessage.getConnectorMap().put("responseHeaders",
                new MessageHeaders(new CaseInsensitiveMap(headers)));

        ContentType responseContentType = ContentType.get(httpResponse.getEntity());
        if (responseContentType == null) {
            responseContentType = ContentType.TEXT_PLAIN;
        }

        Charset responseCharset = charset;
        if (responseContentType.getCharset() != null) {
            responseCharset = responseContentType.getCharset();
        }

        final String responseBinaryMimeTypes = httpDispatcherProperties.getResponseBinaryMimeTypes();
        BinaryContentTypeResolver binaryContentTypeResolver = new BinaryContentTypeResolver() {
            @Override
            public boolean isBinaryContentType(ContentType contentType) {
                return HttpDispatcher.this.isBinaryContentType(responseBinaryMimeTypes, contentType);
            }
        };

        /*
         * First parse out the body of the HTTP response. Depending on the connector settings,
         * this could end up being a string encoded with the response charset, a byte array
         * representing the raw response payload, or a MimeMultipart object.
         */
        Object responseBody = "";

        // The entity could be null in certain cases such as 204 responses
        if (httpResponse.getEntity() != null) {
            // Only parse multipart if XML Body is selected and Parse Multipart is enabled
            if (httpDispatcherProperties.isResponseXmlBody()
                    && httpDispatcherProperties.isResponseParseMultipart()
                    && responseContentType.getMimeType().startsWith(FileUploadBase.MULTIPART)) {
                responseBody = new MimeMultipart(new ByteArrayDataSource(httpResponse.getEntity().getContent(),
                        responseContentType.toString()));
            } else if (binaryContentTypeResolver.isBinaryContentType(responseContentType)) {
                responseBody = IOUtils.toByteArray(httpResponse.getEntity().getContent());
            } else {
                responseBody = IOUtils.toString(httpResponse.getEntity().getContent(), responseCharset);
            }
        }

        /*
         * Now that we have the response body, we need to create the actual Response message
         * data. Depending on the connector settings this could be our custom serialized XML, a
         * Base64 string encoded from the raw response payload, or a string encoded from the
         * payload with the request charset.
         */
        if (httpDispatcherProperties.isResponseXmlBody()) {
            responseData = HttpMessageConverter.httpResponseToXml(statusLine.toString(), headers, responseBody,
                    responseContentType, httpDispatcherProperties.isResponseParseMultipart(),
                    httpDispatcherProperties.isResponseIncludeMetadata(), binaryContentTypeResolver);
        } else if (responseBody instanceof byte[]) {
            responseData = new String(Base64Util.encodeBase64((byte[]) responseBody), "US-ASCII");
        } else {
            responseData = (String) responseBody;
        }

        validateResponse = httpDispatcherProperties.getDestinationConnectorProperties().isValidateResponse();

        if (statusCode < HttpStatus.SC_BAD_REQUEST) {
            responseStatus = Status.SENT;
        } else {
            eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                    connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                    connectorProperties.getName(), "Received error response from HTTP server.", null));
            responseStatusMessage = ErrorMessageBuilder
                    .buildErrorResponse("Received error response from HTTP server.", null);
            responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), responseData,
                    null);
        }
    } catch (Exception e) {
        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                connectorProperties.getName(), "Error connecting to HTTP server.", e));
        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error connecting to HTTP server", e);
        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                "Error connecting to HTTP server", e);
    } finally {
        try {
            HttpClientUtils.closeQuietly(httpResponse);

            // Delete temp files if we created them
            if (tempFile != null) {
                tempFile.delete();
                tempFile = null;
            }
        } finally {
            eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                    getDestinationName(), ConnectionStatusEventType.IDLE));
        }
    }

    return new Response(responseStatus, responseData, responseStatusMessage, responseError, validateResponse);
}

From source file:org.apache.solr.client.solrj.impl.HttpSolrClient.java

protected NamedList<Object> executeMethod(HttpRequestBase method, final ResponseParser processor)
        throws SolrServerException {
    method.addHeader("User-Agent", AGENT);

    org.apache.http.client.config.RequestConfig.Builder requestConfigBuilder = HttpClientUtil
            .createDefaultRequestConfigBuilder();
    if (soTimeout != null) {
        requestConfigBuilder.setSocketTimeout(soTimeout);
    }// w w w . ja  v a 2 s  .c  o m
    if (connectionTimeout != null) {
        requestConfigBuilder.setConnectTimeout(connectionTimeout);
    }
    if (followRedirects != null) {
        requestConfigBuilder.setRedirectsEnabled(followRedirects);
    }

    method.setConfig(requestConfigBuilder.build());

    HttpEntity entity = null;
    InputStream respBody = null;
    boolean shouldClose = true;
    try {
        // Execute the method.
        HttpClientContext httpClientRequestContext = HttpClientUtil.createNewHttpClientRequestContext();
        final HttpResponse response = httpClient.execute(method, httpClientRequestContext);
        int httpStatus = response.getStatusLine().getStatusCode();

        // Read the contents
        entity = response.getEntity();
        respBody = entity.getContent();
        Header ctHeader = response.getLastHeader("content-type");
        String contentType;
        if (ctHeader != null) {
            contentType = ctHeader.getValue();
        } else {
            contentType = "";
        }

        // handle some http level checks before trying to parse the response
        switch (httpStatus) {
        case HttpStatus.SC_OK:
        case HttpStatus.SC_BAD_REQUEST:
        case HttpStatus.SC_CONFLICT: // 409
            break;
        case HttpStatus.SC_MOVED_PERMANENTLY:
        case HttpStatus.SC_MOVED_TEMPORARILY:
            if (!followRedirects) {
                throw new SolrServerException(
                        "Server at " + getBaseURL() + " sent back a redirect (" + httpStatus + ").");
            }
            break;
        default:
            if (processor == null || "".equals(contentType)) {
                throw new RemoteSolrException(baseUrl, httpStatus, "non ok status: " + httpStatus + ", message:"
                        + response.getStatusLine().getReasonPhrase(), null);
            }
        }
        if (processor == null || processor instanceof InputStreamResponseParser) {

            // no processor specified, return raw stream
            NamedList<Object> rsp = new NamedList<>();
            rsp.add("stream", respBody);
            // Only case where stream should not be closed
            shouldClose = false;
            return rsp;
        }

        String procCt = processor.getContentType();
        if (procCt != null) {
            String procMimeType = ContentType.parse(procCt).getMimeType().trim().toLowerCase(Locale.ROOT);
            String mimeType = ContentType.parse(contentType).getMimeType().trim().toLowerCase(Locale.ROOT);
            if (!procMimeType.equals(mimeType)) {
                // unexpected mime type
                String msg = "Expected mime type " + procMimeType + " but got " + mimeType + ".";
                Header encodingHeader = response.getEntity().getContentEncoding();
                String encoding;
                if (encodingHeader != null) {
                    encoding = encodingHeader.getValue();
                } else {
                    encoding = "UTF-8"; // try UTF-8
                }
                try {
                    msg = msg + " " + IOUtils.toString(respBody, encoding);
                } catch (IOException e) {
                    throw new RemoteSolrException(baseUrl, httpStatus,
                            "Could not parse response with encoding " + encoding, e);
                }
                throw new RemoteSolrException(baseUrl, httpStatus, msg, null);
            }
        }

        NamedList<Object> rsp = null;
        String charset = EntityUtils.getContentCharSet(response.getEntity());
        try {
            rsp = processor.processResponse(respBody, charset);
        } catch (Exception e) {
            throw new RemoteSolrException(baseUrl, httpStatus, e.getMessage(), e);
        }
        if (httpStatus != HttpStatus.SC_OK) {
            NamedList<String> metadata = null;
            String reason = null;
            try {
                NamedList err = (NamedList) rsp.get("error");
                if (err != null) {
                    reason = (String) err.get("msg");
                    if (reason == null) {
                        reason = (String) err.get("trace");
                    }
                    metadata = (NamedList<String>) err.get("metadata");
                }
            } catch (Exception ex) {
            }
            if (reason == null) {
                StringBuilder msg = new StringBuilder();
                msg.append(response.getStatusLine().getReasonPhrase()).append("\n\n").append("request: ")
                        .append(method.getURI());
                reason = java.net.URLDecoder.decode(msg.toString(), UTF_8);
            }
            RemoteSolrException rss = new RemoteSolrException(baseUrl, httpStatus, reason, null);
            if (metadata != null)
                rss.setMetadata(metadata);
            throw rss;
        }
        return rsp;
    } catch (ConnectException e) {
        throw new SolrServerException("Server refused connection at: " + getBaseURL(), e);
    } catch (SocketTimeoutException e) {
        throw new SolrServerException("Timeout occured while waiting response from server at: " + getBaseURL(),
                e);
    } catch (IOException e) {
        throw new SolrServerException("IOException occured when talking to server at: " + getBaseURL(), e);
    } finally {
        if (shouldClose) {
            Utils.consumeFully(entity);
        }
    }
}