Example usage for org.apache.commons.httpclient HttpClient getParams

List of usage examples for org.apache.commons.httpclient HttpClient getParams

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpClient getParams.

Prototype

public HttpClientParams getParams() 

Source Link

Usage

From source file:de.mpg.escidoc.pubman.sword.SwordUtil.java

/**
 * Logs in the given user with the given password.
 * @param userid The id of the user to log in.
 * @param password The password of the user to log in.
 * @return The handle for the logged in user.
 * @throws HttpException/*www  . j a va  2  s  .  c  o m*/
 * @throws IOException
 * @throws ServiceException
 * @throws URISyntaxException
 */
@Deprecated
public String loginUser(String userid, String password)
        throws HttpException, IOException, ServiceException, URISyntaxException {
    String frameworkUrl = ServiceLocator.getFrameworkUrl();
    StringTokenizer tokens = new StringTokenizer(frameworkUrl, "//");
    if (tokens.countTokens() != NUMBER_OF_URL_TOKENS) {
        throw new IOException(
                "Url in the config file is in the wrong format, needs to be http://<host>:<port>");
    }
    tokens.nextToken();
    StringTokenizer hostPort = new StringTokenizer(tokens.nextToken(), ":");

    if (hostPort.countTokens() != NUMBER_OF_URL_TOKENS) {
        throw new IOException(
                "Url in the config file is in the wrong format, needs to be http://<host>:<port>");
    }
    String host = hostPort.nextToken();
    int port = Integer.parseInt(hostPort.nextToken());

    HttpClient client = new HttpClient();

    client.getHostConfiguration().setHost(host, port, "http");
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    PostMethod login = new PostMethod(frameworkUrl + "/aa/j_spring_security_check");
    login.addParameter("j_username", userid);
    login.addParameter("j_password", password);

    client.executeMethod(login);

    login.releaseConnection();
    CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies());

    Cookie sessionCookie = logoncookies[0];

    PostMethod postMethod = new PostMethod(LOGIN_URL);
    postMethod.addParameter("target", frameworkUrl);
    client.getState().addCookie(sessionCookie);
    client.executeMethod(postMethod);

    if (HttpServletResponse.SC_SEE_OTHER != postMethod.getStatusCode()) {
        throw new HttpException("Wrong status code: " + login.getStatusCode());
    }

    String userHandle = null;
    Header[] headers = postMethod.getResponseHeaders();
    for (int i = 0; i < headers.length; ++i) {
        if ("Location".equals(headers[i].getName())) {
            String location = headers[i].getValue();
            int index = location.indexOf('=');
            userHandle = new String(Base64.decode(location.substring(index + 1, location.length())));
        }
    }
    if (userHandle == null) {
        throw new ServiceException("User not logged in.");
    }
    return userHandle;
}

From source file:com.ning.http.client.providers.apache.ApacheAsyncHttpProvider.java

public <T> ListenableFuture<T> execute(Request request, AsyncHandler<T> handler) throws IOException {
    if (isClose.get()) {
        throw new IOException("Closed");
    }//from w  w w  .  jav  a 2  s. co  m

    if (ResumableAsyncHandler.class.isAssignableFrom(handler.getClass())) {
        request = ResumableAsyncHandler.class.cast(handler).adjustRequestRange(request);
    }

    if (config.getMaxTotalConnections() > -1 && (maxConnections.get() + 1) > config.getMaxTotalConnections()) {
        throw new IOException(String.format("Too many connections %s", config.getMaxTotalConnections()));
    }

    if (idleConnectionTimeoutThread != null) {
        idleConnectionTimeoutThread.shutdown();
        idleConnectionTimeoutThread = null;
    }

    int requestTimeout = requestTimeout(config, request.getPerRequestConfig());
    if (config.getIdleConnectionTimeoutInMs() > 0 && requestTimeout != -1
            && requestTimeout < config.getIdleConnectionTimeoutInMs()) {
        idleConnectionTimeoutThread = new IdleConnectionTimeoutThread();
        idleConnectionTimeoutThread.setConnectionTimeout(config.getIdleConnectionTimeoutInMs());
        idleConnectionTimeoutThread.addConnectionManager(connectionManager);
        idleConnectionTimeoutThread.start();
    }

    HttpClient httpClient = new HttpClient(params, connectionManager);

    Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
    if (realm != null) {
        httpClient.getParams().setAuthenticationPreemptive(realm.getUsePreemptiveAuth());
        Credentials defaultcreds = new UsernamePasswordCredentials(realm.getPrincipal(), realm.getPassword());
        httpClient.getState().setCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM), defaultcreds);
    }

    HttpMethodBase method = createMethod(httpClient, request);
    ApacheResponseFuture f = new ApacheResponseFuture<T>(handler, requestTimeout, request, method);
    f.touch();

    f.setInnerFuture(
            config.executorService().submit(new ApacheClientRunnable(request, handler, method, f, httpClient)));
    maxConnections.incrementAndGet();
    return f;
}

From source file:fedora.test.api.TestRESTAPI.java

private HttpClient getClient(boolean auth) {
    HttpClient client = new HttpClient();
    client.getParams().setAuthenticationPreemptive(true);
    if (auth) {//from  w ww  . ja v  a  2  s . com
        client.getState().setCredentials(new AuthScope(getHost(), Integer.valueOf(getPort()), "realm"),
                new UsernamePasswordCredentials(getUsername(), getPassword()));
    }
    return client;
}

From source file:com.polarion.alm.ws.client.internal.connection.CommonsHTTPSender.java

/**
 * invoke creates a socket connection, sends the request SOAP message and
 * then reads the response SOAP message back from the SOAP server
 * //from  w w  w . j a  v a  2  s . c  o  m
 * @param msgContext
 *            the messsage context
 * 
 * @throws AxisFault
 */
public void invoke(MessageContext msgContext) throws AxisFault {
    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.
        HttpClient httpClient = new HttpClient(this.connectionManager);
        // the timeout value for allocation of connections from the pool
        httpClient.getParams().setConnectionManagerTimeout(this.clientProperties.getConnectionPoolTimeout());
        httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new RetryHandler());

        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);
            }
            ((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 = hostConfiguration.getHost();
            String path = targetURL.getPath();
            boolean secure = hostConfiguration.getProtocol().isSecure();
            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(hostConfiguration, method, null);

        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:at.ait.dme.yuma.server.annotation.ImageAnnotationManager.java

private EuropeanaAnnotationService getAnnotationService(MultivaluedMap<String, String> headers) {

    List<String> cookieHeaders = (headers != null) ? headers.get("Set-Cookie") : new ArrayList<String>();

    HttpClient client = new HttpClient();
    // make sure to forward all cookies             
    javax.servlet.http.Cookie[] cookies = clientRequest.getCookies();
    for (javax.servlet.http.Cookie c : cookies) {
        c.setDomain(clientRequest.getServerName());
        c.setPath("/");

        String value = c.getValue();
        for (String cookieHeader : cookieHeaders) {
            if (cookieHeader.startsWith(c.getName())) {
                String cookieHeaderParts[] = cookieHeader.split("=");
                if (cookieHeaderParts.length >= 2)
                    value = cookieHeaderParts[1];
            }// ww  w  . ja v  a 2s. c  om
        }
        Cookie apacheCookie = new Cookie(c.getDomain(), c.getName(), value, c.getPath(), c.getMaxAge(),
                c.getSecure());
        client.getState().addCookie(apacheCookie);
    }
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    return ProxyFactory.create(EuropeanaAnnotationService.class, annotationServiceBaseUrl,
            new ApacheHttpClientExecutor(client));
}

From source file:edu.ku.brc.specify.tasks.subpane.lm.LifeMapperPane.java

/**
 * @param searchStr//  w  w w .j  ava2s. co m
 * @param cbListener
 */
private void doSearchGenusSpecies(final String searchStr, final LMSearchCallbackListener cbListener) {
    UsageTracker.incrUsageCount("LM.GenSpSearch");

    updateMyDataUIState(false);

    final SimpleGlassPane glassPane = writeSimpleGlassPaneMsg(getLocalizedMessage("LifeMapperTask.PROCESSING"),
            GLASS_FONT_SIZE);
    glassPane.setTextYPos((int) ((double) getSize().height * 0.25));

    SwingWorker<String, String> worker = new SwingWorker<String, String>() {
        @Override
        protected String doInBackground() throws Exception {
            HttpClient httpClient = new HttpClient();
            httpClient.getParams().setParameter("http.useragent", getClass().getName()); //$NON-NLS-1$
            httpClient.getParams().setParameter("http.socket.timeout", 15000);

            String genusSpecies = StringUtils.replace(searchStr, " ", "%20");
            String url = "http://www.lifemapper.org/hint/species/" + genusSpecies
                    + "?maxReturned=1000&format=json";
            //System.out.println(url);

            GetMethod getMethod = new GetMethod(url);
            try {
                httpClient.executeMethod(getMethod);
                return getMethod.getResponseBodyAsString();
            } catch (java.net.UnknownHostException uex) {
                //log.error(uex.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                UsageTracker.incrUsageCount("LM.GenSpSearchErr");
            }
            return null;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void done() {
            super.done();

            ArrayList<OccurrenceSetIFace> items = null;

            String errMsgKey = "LifeMapperTask.PROC_ERR";
            String responseString;
            try {
                responseString = get();
                //System.out.println(responseString);

                if (responseString != null) {
                    if (responseString.startsWith("None of the species")) {
                        errMsgKey = "LM_NO_LM_DATA";

                    } else if (responseString.startsWith("Search too broad")) {
                        errMsgKey = "LM_TOO_BROAD";

                    } else if (StringUtils.isNotEmpty(responseString)
                            && StringUtils.contains(responseString.toLowerCase(), "{")) {
                        JSONTokener tok = new JSONTokener(responseString);
                        while (tok.more()) {
                            JSONObject obj = (JSONObject) tok.nextValue();
                            JSONArray pointArray = (JSONArray) obj.get("columns");
                            Iterator<Object> iter = (Iterator<Object>) pointArray.iterator();
                            while (iter.hasNext()) {
                                JSONArray arrayObj = (JSONArray) iter.next();
                                //System.out.println(arrayObj);
                                Iterator<Object> iterInner = (Iterator<Object>) arrayObj.iterator();
                                while (iterInner.hasNext()) {
                                    JSONObject pObj = (JSONObject) iterInner.next();
                                    String binomial = (String) pObj.get("binomial");
                                    String gnSpName = (String) pObj.get("name");
                                    String numPoints = (String) pObj.get("numPoints");
                                    String occurrenceSet = (String) pObj.get("occurrenceSet");

                                    if (StringUtils.isNotEmpty(gnSpName) && StringUtils.isNotEmpty(numPoints)
                                            && StringUtils.isNotEmpty(occurrenceSet)) {
                                        try {
                                            int numPnts = Integer.parseInt(numPoints);
                                            int occurId = Integer.parseInt(occurrenceSet);
                                            if (numPnts > 0 && occurId > 0) {
                                                if (items == null) {
                                                    items = new ArrayList<OccurrenceSetIFace>();
                                                }
                                                items.add(new GenusSpeciesDataItem(
                                                        String.format("%s (%s)", gnSpName, numPoints),
                                                        occurrenceSet, binomial));
                                            }
                                        } catch (Exception ex) {
                                            // no op
                                        }
                                        errMsgKey = items == null || items.size() == 0 ? "LM_NO_LOCAL_DATA"
                                                : null;
                                    }
                                }
                            }
                        }
                    }
                }

            } catch (InterruptedException e) {
                e.printStackTrace();

            } catch (ExecutionException e) {
                e.printStackTrace();
            }

            if (errMsgKey != null) {
                showErrorMsg(glassPane, errMsgKey);
                cbListener.noItems();

            } else {
                //System.out.println("Num Genus/Species: "+items.size());
                clearSimpleGlassPaneMsg();
                cbListener.itemsFound(items);
            }
        }
    };
    worker.execute();
}

From source file:com.zimbra.qa.unittest.TestZimbraHttpConnectionManager.java

private void runTest(HttpClient httpClient, String id, boolean authPreemp) {

    GetMethod method = new GetMethod("http://localhost:7070/");

    long startTime = System.currentTimeMillis();
    long endTime;

    try {//from  w w w . j ava 2s  .c  o  m
        System.out.println(id + " - about to get something from " + method.getURI());
        // execute the method

        if (authPreemp) {
            httpClient.getParams().setAuthenticationPreemptive(true);
        }

        int respCode = HttpClientUtil.executeMethod(httpClient, method);

        System.out.println(id + " - get executed");
        // get the response body as an array of bytes
        // byte[] bytes = method.getResponseBody();
        // dumpResponse(respCode, mMethod, Integer.valueOf(mId).toString());

    } catch (Exception e) {
        System.out.println(id + " - error: " + e);
        e.printStackTrace();
    } finally {

        endTime = System.currentTimeMillis();
        long elapsedTime = endTime - startTime;
        // System.out.println(id + " - Finished, elapsedTime=" + elapsedTime + " milli seconds");

        // always release the connection after we're done 
        method.releaseConnection();
        System.out.println(id + " - connection released");
    }
}

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//w w  w. ja v  a2 s. co  m
 */
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:edu.ku.brc.specify.tasks.subpane.lm.LifeMapperPane.java

/**
 * /*from   ww w. j av a  2s  .  c  o  m*/
 */
@SuppressWarnings("unchecked")
public void doSearchOccur(final String occurrenceId) {
    updateMyDataUIState(false);

    points.clear();

    final SimpleGlassPane glassPane = writeSimpleGlassPaneMsg(getLocalizedMessage("LifeMapperTask.PROCESSING"),
            GLASS_FONT_SIZE);
    glassPane.setTextYPos((int) ((double) getSize().height * 0.25));

    // check the website for the info about the latest version
    final HttpClient httpClient = new HttpClient();
    httpClient.getParams().setParameter("http.useragent", getClass().getName()); //$NON-NLS-1$
    httpClient.getParams().setParameter("http.socket.timeout", 15000);

    if (list.getSelectedIndex() < 0) {
        return;
    }

    UsageTracker.incrUsageCount("LM.OccurSearch");

    final String lmURL = String.format(
            "http://www.lifemapper.org/services/sdm/occurrences/%s/json?format=specify&fillPoints=true",
            occurrenceId);
    //System.out.println(lmURL);

    SwingWorker<String, String> worker = new SwingWorker<String, String>() {
        @Override
        protected String doInBackground() throws Exception {
            GetMethod getMethod = new GetMethod(lmURL);
            try {
                httpClient.executeMethod(getMethod);

                // get the server response
                //String responseString = getMethod.getResponseBodyAsString();
                byte[] bytes = getMethod.getResponseBody();
                if (bytes != null && bytes.length > 0) {
                    return new String(bytes, "UTF-8");
                }
                //if (StringUtils.isNotEmpty(responseString))
                //{
                //    System.err.println(responseString);
                //}
                return null;
            } catch (java.net.UnknownHostException uex) {
                //log.error(uex.getMessage());
            } catch (java.net.SocketTimeoutException ex) {
                UsageTracker.incrUsageCount("LM.OccurSearchErr");
            } catch (Exception e) {
                e.printStackTrace();
                UsageTracker.incrUsageCount("LM.OccurSearchErr");
            }

            return null;
        }

        @Override
        protected void done() {
            super.done();

            boolean isError = true;
            boolean parseError = false;

            try {
                String responseString = get();

                if (StringUtils.isNotEmpty(responseString)
                        && StringUtils.contains(responseString.toLowerCase(), "{")) {
                    // Need to change this to using regex to strip away unwanted chars
                    StringBuilder sb = new StringBuilder();
                    String[] lines = StringUtils.split(responseString, '\n');
                    for (String str : lines) {
                        if (str.indexOf("resname") == -1) {
                            sb.append(str);
                        }
                    }
                    String cleaned = sb.toString();

                    parseError = false;
                    try {
                        JSONTokener tok = new JSONTokener(cleaned);
                        if (tok != null) {
                            while (tok.more()) {
                                JSONObject obj = (JSONObject) tok.nextValue();
                                if (obj != null) {
                                    JSONArray pointArray = (JSONArray) obj.get("feature");
                                    if (pointArray != null) {
                                        Iterator<Object> iter = (Iterator<Object>) pointArray.iterator();
                                        while (iter.hasNext()) {
                                            JSONObject pObj = (JSONObject) iter.next();
                                            if (pObj != null) {
                                                String lat = null;//(String)pObj.get("lat");
                                                String lon = null;//(String)pObj.get("lon");
                                                String geomwkt = (String) pObj.get("geomwkt");
                                                if (geomwkt != null) {
                                                    //quel cheapo...
                                                    geomwkt = geomwkt.replace("POINT", "");
                                                    geomwkt = geomwkt.replace("(", "");
                                                    geomwkt = geomwkt.replace(")", "");
                                                    geomwkt = geomwkt.trim();
                                                    String[] geocs = geomwkt.split(" ");
                                                    if (geocs.length == 2) {
                                                        lon = geocs[0];
                                                        lat = geocs[1];
                                                    }
                                                }
                                                //System.out.println(lat+"  "+lon);
                                                if (lat != null && lon != null) {
                                                    LatLonPlacemark plcMark = new LatLonPlacemark(markerImg,
                                                            Double.parseDouble(lat.trim()),
                                                            Double.parseDouble(lon.trim()));
                                                    points.add(plcMark);
                                                }
                                            }
                                        }
                                        isError = false;
                                    }
                                }
                            }
                        }
                    } catch (net.sf.json.JSONException ex) {
                        System.err.println(ex.getLocalizedMessage());
                        parseError = true;
                    }

                    boolean hasPnts = points.size() > 0;
                    updateMyDataUIState(hasPnts && StringUtils.isNotEmpty(myDataTF.getText()));
                    if (hasPnts) {
                        imgDisplay.setImage((Image) null);
                        wwPanel.placeMarkers(points, false, true, 0, null, false);

                        imgRequestCnt = 0;

                        imgURL = makeURL(occurSet);

                        getImageFromWeb(imgURL, pointsMapImageListener);

                    } else {
                        isError = false;
                    }

                } else {
                    UsageTracker.incrUsageCount("LM.OccurSearchErr");
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }

            if (isError || parseError) {
                showErrorMsg(glassPane, "LifeMapperTask.PROC_ERR");
            } else {
                clearSimpleGlassPaneMsg();
            }
        }
    };
    worker.execute();
}

From source file:com.globalsight.everest.webapp.applet.admin.customer.FileSystemApplet.java

/**
 * Sets up the HttpClient to use a proxy if one needs to be used.
 * Also sets up for proxy authentication (NTLM and Basic)
 * //  www  . jav a2  s. c o m
 * @param p_httpClient
 */
private void setUpClientForProxy(HttpClient p_client) throws Exception {
    //first see if a proxy needs to be used at all
    //detectProxyInfoFromSystem() is known to work at Dell
    //        ProxyInfo proxyInfo = detectProxyInfoFromSystem();

    //detectProxyInfoFromBrowser() is probably more correct,
    String urlPrefix = AppletHelper.getUrlPrefix(this);
    String servletUrl = getParameter(AppletHelper.SERVLET_URL);
    String randID = getParameter(AppletHelper.RANDOM);
    String servletLocation = urlPrefix + servletUrl + randID;
    ProxyInfo proxyInfo = GlobalSightProxyInfo.detectProxyInfoFromBrowser(new URL(servletLocation));

    if (proxyInfo != null) {
        System.out.println("---- Setting up client for proxy.");
        //set to use proxy
        p_client.getHostConfiguration().setProxy(proxyInfo.getHost(), proxyInfo.getPort());

        //set to authenticate to proxy if need be
        p_client.getParams().setParameter(CredentialsProvider.PROVIDER, s_authPrompter);
    } else {
        System.out.println("---- No need to set client for proxy.");
    }
}