Example usage for org.apache.commons.httpclient HttpState HttpState

List of usage examples for org.apache.commons.httpclient HttpState HttpState

Introduction

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

Prototype

HttpState

Source Link

Usage

From source file:org.apache.cocoon.components.language.markup.xsp.XSPSOAPHelper.java

public XScriptObject invoke() throws ProcessingException {
    HttpConnection conn = null;//w w  w .  j a v  a  2s  .  c  o  m

    try {
        if (this.action == null || this.action.length() == 0) {
            this.action = "\"\"";
        }

        String host = this.url.getHost();
        int port = this.url.getPort();
        Protocol protocol = Protocol.getProtocol(this.url.getProtocol());

        if (System.getProperty("http.proxyHost") != null) {
            String proxyHost = System.getProperty("http.proxyHost");
            int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort"));
            conn = new HttpConnection(proxyHost, proxyPort, host, null, port, protocol);
        } else {
            conn = new HttpConnection(host, port, protocol);
        }
        conn.setSoTimeout(1000 * timeoutSeconds);

        PostMethod method = new PostMethod(this.url.getFile());
        String request;

        try {
            // Write the SOAP request body
            if (this.xscriptObject instanceof XScriptObjectInlineXML) {
                // Skip overhead
                request = ((XScriptObjectInlineXML) this.xscriptObject).getContent();
            } else {
                StringBuffer bodyBuffer = new StringBuffer();
                InputSource saxSource = this.xscriptObject.getInputSource();

                Reader r = null;
                // Byte stream or character stream?
                if (saxSource.getByteStream() != null) {
                    r = new InputStreamReader(saxSource.getByteStream());
                } else {
                    r = saxSource.getCharacterStream();
                }

                try {
                    char[] buffer = new char[1024];
                    int len;
                    while ((len = r.read(buffer)) > 0) {
                        bodyBuffer.append(buffer, 0, len);
                    }
                } finally {
                    if (r != null) {
                        r.close();
                    }
                }

                request = bodyBuffer.toString();
            }

        } catch (Exception ex) {
            throw new ProcessingException("Error assembling request", ex);
        }

        method.setRequestHeader(new Header("Content-type", "text/xml; charset=utf-8"));
        method.setRequestHeader(new Header("SOAPAction", this.action));
        method.setRequestBody(request);

        if (this.authorization != null && !this.authorization.equals("")) {
            method.setRequestHeader(
                    new Header("Authorization", "Basic " + SourceUtil.encodeBASE64(this.authorization)));
        }

        method.execute(new HttpState(), conn);

        String contentType = method.getResponseHeader("Content-type").toString();
        // Check if charset given, if not, use defaultResponseEncoding
        // (cannot just use getResponseCharSet() as it fills in
        // "ISO-8859-1" if the charset is not specified)
        String charset = contentType.indexOf("charset=") == -1 ? this.defaultResponseEncoding
                : method.getResponseCharSet();
        String ret = new String(method.getResponseBody(), charset);

        return new XScriptObjectInlineXML(this.xscriptManager, ret);
    } catch (ProcessingException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new ProcessingException("Error invoking remote service: " + ex, ex);
    } finally {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception ex) {
        }
    }
}

From source file:org.apache.cocoon.generation.GenericProxyGenerator.java

/**
 * Get the request data, pass them on to the forwarder and return the result.
 *
 * TODO: much better header handling//w  ww. ja v a  2s. c o m
 * TODO: handle non XML and bodyless responses (probably needs a smarter Serializer,
 *            since some XML has to go through the pipeline anyway.
 *
 * @see org.apache.cocoon.generation.Generator#generate()
 */
public void generate() throws IOException, SAXException, ProcessingException {
    RequestForwardingHttpMethod method = new RequestForwardingHttpMethod(request, destination);

    // Build the forwarded connection
    HttpConnection conn = new HttpConnection(destination.getHost(), destination.getPort());
    HttpState state = new HttpState();
    state.setCredentials(null, destination.getHost(),
            new UsernamePasswordCredentials(destination.getUser(), destination.getPassword()));
    method.setPath(path);

    // Execute the method
    method.execute(state, conn);

    // Send the output to the client: set the status code...
    response.setStatus(method.getStatusCode());

    // ... retrieve the headers from the origin server and pass them on
    Header[] methodHeaders = method.getResponseHeaders();
    for (int i = 0; i < methodHeaders.length; i++) {
        // there is more than one DAV header
        if (methodHeaders[i].getName().equals("DAV")) {
            response.addHeader(methodHeaders[i].getName(), methodHeaders[i].getValue());
        } else if (methodHeaders[i].getName().equals("Content-Length")) {
            // drop the original Content-Length header. Don't ask me why but there
            // it's always one byte off
        } else {
            response.setHeader(methodHeaders[i].getName(), methodHeaders[i].getValue());
        }
    }

    // no HTTP keepalives here...
    response.setHeader("Connection", "close");

    // Parse the XML, if any
    if (method.getResponseHeader("Content-Type").getValue().startsWith("text/xml")) {
        InputStream stream = method.getResponseBodyAsStream();
        parser.parse(new InputSource(stream), this.contentHandler, this.lexicalHandler);
    } else {
        // Just send a dummy XML
        this.contentHandler.startDocument();
        this.contentHandler.startElement("", "no-xml-content", "no-xml-content", XMLUtils.EMPTY_ATTRIBUTES);
        this.contentHandler.endElement("", "no-xml-content", "no-xml-content");
        this.contentHandler.endDocument();
    }

    // again, no keepalive here.
    conn.close();
}

From source file:org.apache.cocoon.generation.HttpProxyGenerator.java

/**
 * Parse the remote <code>InputStream</code> accessed over HTTP.
 *
 * @throws ResourceNotFoundException If the remote HTTP resource could not be found.
 * @throws ProcessingException If an error occurred processing generation.
 * @throws SAXException If an error occurred parsing or processing XML in the pipeline.
 * @throws IOException If an I/O error occurred accessing the HTTP server.
 *//*from   w w  w.j  av  a 2  s  .c  o m*/
public void generate() throws ResourceNotFoundException, ProcessingException, SAXException, IOException {
    /* Do the boring stuff in case we have to do a debug output (blablabla) */
    if (this.debug) {
        this.generateDebugOutput();
        return;
    }

    /* Call up the remote HTTP server */
    HttpConnection connection = new HttpConnection(this.method.getHostConfiguration());
    HttpState state = new HttpState();
    this.method.setFollowRedirects(true);
    int status = this.method.execute(state, connection);
    if (status == 404) {
        throw new ResourceNotFoundException(
                "Unable to access \"" + this.method.getURI() + "\" (HTTP 404 Error)");
    } else if ((status < 200) || (status > 299)) {
        throw new IOException("Unable to access HTTP resource at \"" + this.method.getURI().toString()
                + "\" (status=" + status + ")");
    }
    InputStream response = this.method.getResponseBodyAsStream();

    /* Let's try to set up our InputSource from the response output stream and to parse it */
    SAXParser parser = null;
    try {
        InputSource inputSource = new InputSource(response);
        parser = (SAXParser) this.manager.lookup(SAXParser.ROLE);
        parser.parse(inputSource, super.xmlConsumer);
    } catch (ServiceException ex) {
        throw new ProcessingException("Unable to get parser", ex);
    } finally {
        this.manager.release(parser);
        this.method.releaseConnection();
        connection.close();
    }
}

From source file:org.apache.cocoon.transformation.DASLTransformer.java

protected void performSearchMethod(String query) throws SAXException {
    OptionsMethod optionsMethod = null;//  www . ja v  a  2 s .  co m
    SearchMethod searchMethod = null;
    try {
        DOMStreamer propertyStreamer = new DOMStreamer(this.xmlConsumer);
        optionsMethod = new OptionsMethod(this.targetUrl);
        searchMethod = new SearchMethod(this.targetUrl, query);
        HttpURL url = new HttpURL(this.targetUrl);
        HttpState state = new HttpState();
        state.setCredentials(null, new UsernamePasswordCredentials(url.getUser(), url.getPassword()));
        HttpConnection conn = new HttpConnection(url.getHost(), url.getPort());

        // eventcaching stuff
        SourceValidity extraValidity = makeWebdavEventValidity(url);
        if (extraValidity != null && m_validity != null)
            m_validity.add(extraValidity);
        // end eventcaching stuff

        WebdavResource resource = new WebdavResource(new HttpURL(this.targetUrl));
        if (!resource.exists()) {
            throw new SAXException("The WebDAV resource don't exist");
        }
        optionsMethod.execute(state, conn);
        if (!optionsMethod.isAllowed("SEARCH")) {
            throw new SAXException("The server doesn't support the SEARCH method");
        }
        int httpstatus = searchMethod.execute(state, conn);

        this.contentHandler.startElement(DASL_QUERY_NS, RESULT_ROOT_TAG, PREFIX + ":" + RESULT_ROOT_TAG,
                XMLUtils.EMPTY_ATTRIBUTES);

        // something might have gone wrong, report it
        // 207 = multistatus webdav response
        if (httpstatus != 207) {

            this.contentHandler.startElement(DASL_QUERY_NS, ERROR_ROOT_TAG, PREFIX + ":" + ERROR_ROOT_TAG,
                    XMLUtils.EMPTY_ATTRIBUTES);

            // dump whatever the server said
            propertyStreamer.stream(searchMethod.getResponseDocument());

            this.contentHandler.endElement(DASL_QUERY_NS, ERROR_ROOT_TAG, PREFIX + ":" + ERROR_ROOT_TAG);

        } else {
            // show results

            Enumeration enumeration = searchMethod.getAllResponseURLs();

            while (enumeration.hasMoreElements()) {
                String path = (String) enumeration.nextElement();
                Enumeration properties = searchMethod.getResponseProperties(path);
                AttributesImpl attr = new AttributesImpl();
                attr.addAttribute(DASL_QUERY_NS, PATH_NODE_NAME, PREFIX + ":" + PATH_NODE_NAME, "CDATA", path);

                this.contentHandler.startElement(DASL_QUERY_NS, RESOURCE_NODE_NAME,
                        PREFIX + ":" + RESOURCE_NODE_NAME, attr);
                while (properties.hasMoreElements()) {
                    BaseProperty metadata = (BaseProperty) properties.nextElement();
                    Element propertyElement = metadata.getElement();
                    propertyStreamer.stream(propertyElement);
                }

                this.contentHandler.endElement(DASL_QUERY_NS, RESOURCE_NODE_NAME,
                        PREFIX + ":" + RESOURCE_NODE_NAME);
            }
        }

        this.contentHandler.endElement(DASL_QUERY_NS, RESULT_ROOT_TAG, PREFIX + ":" + RESULT_ROOT_TAG);
    } catch (SAXException e) {
        throw new SAXException("Unable to fetch the query data:", e);
    } catch (HttpException e1) {
        this.getLogger().error("Unable to contact Webdav server", e1);
        throw new SAXException("Unable to connect with server: ", e1);
    } catch (IOException e2) {
        throw new SAXException("Unable to connect with server: ", e2);
    } catch (NullPointerException e) {
        throw new SAXException("Unable to fetch the query data:", e);
    } catch (Exception e) {
        throw new SAXException("Generic Error:", e);
    } finally {
        // cleanup
        if (searchMethod != null)
            searchMethod.releaseConnection();
        if (optionsMethod != null)
            optionsMethod.releaseConnection();
    }
}

From source file:org.apache.cocoon.transformation.WebDAVTransformer.java

public void setup(SourceResolver resolver, Map objectModel, String src, Parameters par)
        throws ProcessingException, SAXException, IOException {
    super.setup(resolver, objectModel, src, par);

    m_state = new HttpState();

    if (null != par.getParameter("username", null)) {
        m_state.setCredentials(null, null, new UsernamePasswordCredentials(par.getParameter("username", ""),
                par.getParameter("password", "")));
    }/*from w  w  w  .  ja  v  a  2s  .  c o m*/

    if (m_eventfactory == null) {
        try {
            m_eventfactory = (WebDAVEventFactory) manager.lookup(WebDAVEventFactory.ROLE);
        } catch (ServiceException e) {
            // ignore, no eventcaching configured
            m_eventfactory = null;
        }
    }
}

From source file:org.apache.commons.httpclient.demo.CookiesTrial.java

@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {

    //A new cookie for the domain 127.0.0.1
    //Cookie Name= ABCD   Value=00000   Path=/  MaxAge=-1   Secure=False
    Cookie mycookie = new Cookie("90.0.12.20", "ABCD", "00000", "/", -1, false);

    //Create a new HttpState container
    HttpState initialState = new HttpState();
    initialState.addCookie(mycookie);//w w w .  j  a  v  a2  s. c o  m

    //Set to COMPATIBILITY for it to work in as many cases as possible
    initialState.setCookiePolicy(CookiePolicy.COMPATIBILITY);
    //create new client
    HttpClient httpclient = new HttpClient();
    //set the HttpState for the client
    httpclient.setState(initialState);

    GetMethod getMethod = new GetMethod(url);
    //Execute a GET method
    //int result = httpclient.executeMethod(getMethod);

    System.out.println("statusLine>>>" + getMethod.getStatusLine());

    //Get cookies stored in the HttpState for this instance of HttpClient
    Cookie[] cookies = httpclient.getState().getCookies();

    for (int i = 0; i < cookies.length; i++) {
        System.out.println("\nCookieName=" + cookies[i].getName());
        System.out.println("Value=" + cookies[i].getValue());
        System.out.println("Domain=" + cookies[i].getDomain());
    }

    getMethod.releaseConnection();
}

From source file:org.apache.maven.doxia.linkcheck.validation.OnlineHTTPLinkValidator.java

/** Initialize the HttpClient. */
private void initHttpClient() {
    LOG.debug("A new HttpClient instance is needed ...");

    this.cl = new HttpClient(new MultiThreadedHttpConnectionManager());

    // Default params
    if (this.http.getTimeout() != 0) {
        this.cl.getHttpConnectionManager().getParams().setConnectionTimeout(this.http.getTimeout());
        this.cl.getHttpConnectionManager().getParams().setSoTimeout(this.http.getTimeout());
    }//from  w  w w.  jav a 2s . com
    this.cl.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);

    HostConfiguration hc = new HostConfiguration();

    HttpState state = new HttpState();
    if (StringUtils.isNotEmpty(this.http.getProxyHost())) {
        hc.setProxy(this.http.getProxyHost(), this.http.getProxyPort());

        if (LOG.isDebugEnabled()) {
            LOG.debug("Proxy Host:" + this.http.getProxyHost());
            LOG.debug("Proxy Port:" + this.http.getProxyPort());
        }

        if (StringUtils.isNotEmpty(this.http.getProxyUser()) && this.http.getProxyPassword() != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Proxy User:" + this.http.getProxyUser());
            }

            Credentials credentials;
            if (StringUtils.isNotEmpty(this.http.getProxyNtlmHost())) {
                credentials = new NTCredentials(this.http.getProxyUser(), this.http.getProxyPassword(),
                        this.http.getProxyNtlmHost(), this.http.getProxyNtlmDomain());
            } else {
                credentials = new UsernamePasswordCredentials(this.http.getProxyUser(),
                        this.http.getProxyPassword());
            }

            state.setProxyCredentials(AuthScope.ANY, credentials);
        }
    } else {
        LOG.debug("Not using a proxy");
    }

    this.cl.setHostConfiguration(hc);
    this.cl.setState(state);

    LOG.debug("New HttpClient instance created.");
}

From source file:org.apache.maven.plugin.jira.AbstractJiraDownloader.java

/**
 * Execute the query on the JIRA server.
 *
 * @throws Exception on error// ww w  .  java 2 s  . c  om
 */
public void doExecute() throws Exception {
    try {
        HttpClient client = new HttpClient();

        // MCHANGES-89 Allow circular redirects
        HttpClientParams clientParams = client.getParams();
        clientParams.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);

        HttpState state = new HttpState();

        HostConfiguration hc = new HostConfiguration();

        client.setHostConfiguration(hc);

        client.setState(state);

        Map<String, String> urlMap = JiraHelper.getJiraUrlAndProjectId(project.getIssueManagement().getUrl());

        String jiraUrl = urlMap.get("url");
        getLog().debug("JIRA lives at: " + jiraUrl);

        String jiraId = urlMap.get("id");

        determineProxy(jiraUrl, client);

        prepareBasicAuthentication(client);

        boolean jiraAuthenticationSuccessful = false;
        if (isJiraAuthenticationConfigured()) {
            jiraAuthenticationSuccessful = doJiraAuthentication(client, jiraUrl);
        }

        if ((isJiraAuthenticationConfigured() && jiraAuthenticationSuccessful)
                || !isJiraAuthenticationConfigured()) {
            if (jiraId == null || jiraId.length() == 0) {
                log.debug("The JIRA URL " + project.getIssueManagement().getUrl()
                        + " doesn't include a pid, trying to extract it from JIRA.");
                jiraId = JiraHelper.getPidFromJira(log, project.getIssueManagement().getUrl(), client);
            }

            if (jiraId == null) {
                getLog().error("The issue management URL in the POM does not include a pid,"
                        + " and it was not possible to extract it from the page at that URL.");
            } else {
                // create the URL for getting the proper issues from JIRA
                String fullURL = jiraUrl + "/secure/IssueNavigator.jspa?view=rss&pid=" + jiraId;

                if (getFixFor() != null) {
                    fullURL += "&fixfor=" + getFixFor();
                }

                String createdFilter = createFilter();
                if (createdFilter.charAt(0) != '&') {
                    fullURL += "&";
                }
                fullURL += createdFilter;

                fullURL += ("&tempMax=" + nbEntriesMax + "&reset=true&decorator=none");

                if (log.isDebugEnabled()) {
                    log.debug("download jira issues from url " + fullURL);
                }

                // execute the GET
                download(client, fullURL);
            }
        }
    } catch (Exception e) {
        if (project.getIssueManagement() != null) {
            getLog().error("Error accessing " + project.getIssueManagement().getUrl(), e);
        } else {
            getLog().error("Error accessing mock project issues", e);
        }
    }
}

From source file:org.apache.maven.plugin.jira.ClassicJiraDownloader.java

/**
 * Execute the query on the JIRA server.
 *
 * @throws Exception on error/*from ww w  . j  a v a 2s  .c  o  m*/
 */
public void doExecute() throws Exception {
    try {
        HttpClient client = new HttpClient();

        // MCHANGES-89 Allow circular redirects
        HttpClientParams clientParams = client.getParams();
        clientParams.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        clientParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); //MCHANGES-237

        HttpState state = new HttpState();

        HostConfiguration hc = new HostConfiguration();

        client.setHostConfiguration(hc);

        client.setState(state);

        String baseUrl = JiraHelper.getBaseUrl(project.getIssueManagement().getUrl());

        getLog().debug("JIRA lives at: " + baseUrl);
        // Here we only need the host part of the URL
        determineProxy(baseUrl, client);

        prepareBasicAuthentication(client);

        boolean jiraAuthenticationSuccessful = false;
        if (isJiraAuthenticationConfigured()) {
            // Here we only need the parts up to and including the host part of the URL
            jiraAuthenticationSuccessful = doJiraAuthentication(client, baseUrl);
        }

        if ((isJiraAuthenticationConfigured() && jiraAuthenticationSuccessful)
                || !isJiraAuthenticationConfigured()) {
            String fullUrl;

            if (useJql) {
                fullUrl = getJqlQueryURL();
            } else {
                fullUrl = getParameterBasedQueryURL(client);
            }
            if (log.isDebugEnabled()) {
                log.debug("download jira issues from url " + fullUrl);
            }

            // execute the GET
            download(client, fullUrl);
        }
    } catch (Exception e) {
        if (project.getIssueManagement() != null) {
            getLog().error("Error accessing " + project.getIssueManagement().getUrl(), e);
        } else {
            getLog().error("Error accessing mock project issues", e);
        }
    }
}

From source file:org.apache.slide.webdav.event.NotificationTrigger.java

protected void notifySubscriber(String callback, String subscribers) {
    if (callback.startsWith(TCP_PROTOCOL)) {
        Domain.log("Notify subscribers with adress='" + callback + "' via TCP with id's " + subscribers,
                LOG_CHANNEL, Logger.INFO);
        NotifyMethod notifyMethod = new NotifyMethod(callback.toString());
        notifyMethod.addRequestHeader(H_SUBSCRIPTION_ID_RESPONSE, subscribers);
        try {//w  ww  .j  a v a  2 s  .  c  o m
            URL url = new URL(callback);
            notifyMethod.execute(new HttpState(),
                    new HttpConnection(url.getHost(), url.getPort() != -1 ? url.getPort() : 80));
        } catch (IOException e) {
            Domain.log("Notification of subscriber '" + callback.toString() + "' failed!");
        }
    } else if (callback.startsWith(UDP_PROTOCOL) && socket != null) {
        Domain.log("Notify subscribers with adress='" + callback + "' via UDP with id's " + subscribers + "\n",
                LOG_CHANNEL, Logger.INFO);
        try {
            URL url = new URL(TCP_PROTOCOL + callback.substring(UDP_PROTOCOL.length()));
            String notification = "NOTIFY " + callback + " HTTP/1.1\nSubscription-id: " + subscribers;
            byte[] buf = notification.getBytes();
            InetAddress address = InetAddress.getByName(url.getHost());
            DatagramPacket packet = new DatagramPacket(buf, buf.length, address,
                    url.getPort() != -1 ? url.getPort() : 80);
            socket.send(packet);
        } catch (IOException e) {
            Domain.log("Notification of subscriber '" + callback.toString() + "' failed!", LOG_CHANNEL,
                    Logger.ERROR);
        }
    }
}