Example usage for org.apache.commons.httpclient HttpMethod releaseConnection

List of usage examples for org.apache.commons.httpclient HttpMethod releaseConnection

Introduction

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

Prototype

public abstract void releaseConnection();

Source Link

Usage

From source file:org.iavante.sling.gad.transcoder.TranscoderServiceImplIT.java

/**
 * Tests if the transcoder folder is created and the preview transformation
 * type/*ww w.j  a v a2s  . com*/
 **/
public void test_transcoder_folder() {

    try {
        Thread.sleep(4000);
    } catch (InterruptedException e1) {

        e1.printStackTrace();
    }

    // Get transcoder folder
    HttpMethod get_trans_folder = new GetMethod(SLING_URL + "/" + "content" + "/" + COMPONENTS_FOLDER + "/"
            + TRANSCODER_FOLDER + "/" + PREVIEW_TRANSFORMATION + ".html");
    get_trans_folder.setDoAuthentication(true);
    try {
        client.executeMethod(get_trans_folder);
    } catch (HttpException e) {

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

        e.printStackTrace();
    }

    assertEquals(200, get_trans_folder.getStatusCode());
    get_trans_folder.releaseConnection();
}

From source file:org.iavante.sling.transcodingServer.TranscodingServerTestIT.java

public void test_error_job() {

    try {/*from w  w  w  .j  a  va  2  s  .  c  om*/
        Thread.sleep(6000);
    } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    //System.out.println("---------------------     test_error_job        ---------------------------------");
    HttpMethod get_job = new GetMethod(SLING_URL + JOBS_ERROR_URL + title + ".xml");

    try {
        this.client.executeMethod(get_job);
    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String response_body = "";
    try {
        response_body = get_job.getResponseBodyAsString();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    //System.out.println("-------------------------------------------------------");
    //System.out.println(response_body);
    //System.out.println("-------------------------------------------------------");
    assertTrue(response_body.contains("state=\"Error\""));
    get_job.releaseConnection();
}

From source file:org.infoglue.cms.applications.managementtool.actions.UploadPortletAction.java

/**
* Report to deliver engines that a portlet has been uploaded
* 
* @param contentId/*from  w ww .ja  va2  s.c o  m*/
*            contentId of portlet
*/
private void updateDeliverEngines(Integer digitalAssetId) {
    List allUrls = CmsPropertyHandler.getInternalDeliveryUrls();
    allUrls.addAll(CmsPropertyHandler.getPublicDeliveryUrls());

    Iterator urlIterator = allUrls.iterator();
    while (urlIterator.hasNext()) {
        String url = (String) urlIterator.next() + "/DeployPortlet.action";

        try {
            HttpClient client = new HttpClient();

            // establish a connection within 5 seconds
            client.setConnectionTimeout(5000);

            // set the default credentials
            HttpMethod method = new GetMethod(url);
            method.setQueryString("digitalAssetId=" + digitalAssetId);
            method.setFollowRedirects(true);

            // execute the method
            client.executeMethod(method);
            StatusLine status = method.getStatusLine();
            if (status != null && status.getStatusCode() == 200) {
                log.info("Successfully deployed portlet at " + url);
            } else {
                log.warn("Failed to deploy portlet at " + url + ": " + status);
            }

            //clean up the connection resources
            method.releaseConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     Properties props = CmsPropertyHandler.getProperties();
     for (Enumeration keys = props.keys(); keys.hasMoreElements();) {
    String key = (String) keys.nextElement();
    if (key.startsWith(PORTLET_DEPLOY_PREFIX)) {
        String url = props.getProperty(key);
        try {
            HttpClient client = new HttpClient();
            
            //establish a connection within 5 seconds
            client.setConnectionTimeout(5000);
            
            //set the default credentials
            HttpMethod method = new GetMethod(url);
            method.setQueryString("digitalAssetId=" + digitalAssetId);
            method.setFollowRedirects(true);
            
            //execute the method
            client.executeMethod(method);
            StatusLine status = method.getStatusLine();
            if (status != null && status.getStatusCode() == 200) {
                log.info("Successfully deployed portlet at " + url);
            } else {
                log.warn("Failed to deploy portlet at " + url + ": " + status);
            }
            
            //clean up the connection resources
            method.releaseConnection();
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        }
    }
     }
     */

}

From source file:org.infoscoop.request.filter.ProxyFilterContainer.java

public final int invoke(HttpClient client, HttpMethod method, ProxyRequest request) throws Exception {
    int preStatus = prepareInvoke(client, method, request);
    switch (preStatus) {
    case 0:/*w w  w . ja v  a 2s .  co  m*/
        break;
    case EXECUTE_POST_STATUS:
        doFilterChain(request, request.getResponseBody());
    default:
        return preStatus;
    }
    // copy headers sent target server
    List ignoreHeaderNames = request.getIgnoreHeaders();
    List allowedHeaderNames = request.getAllowedHeaders();
    boolean allowAllHeader = false;

    Proxy proxy = request.getProxy();
    if (proxy != null) {
        allowAllHeader = proxy.isAllowAllHeader();
        if (!allowAllHeader)
            allowedHeaderNames.addAll(proxy.getAllowedHeaders());
    }

    AuthenticatorUtil.doAuthentication(client, method, request);

    StringBuffer headersSb = new StringBuffer();
    for (String name : request.getRequestHeaders().keySet()) {

        String value = request.getRequestHeader(name);
        String lowname = name.toLowerCase();

        if (!allowAllHeader && !allowedHeaderNames.contains(lowname))
            continue;

        if (ignoreHeaderNames.contains(lowname))
            continue;

        if ("cookie".equalsIgnoreCase(name)) {
            if (proxy.getSendingCookies() != null) {
                value = RequestUtil.removeCookieParam(value, proxy.getSendingCookies());
            }
        }

        if ("if-modified-since".equalsIgnoreCase(name) && "Thu, 01 Jun 1970 00:00:00 GMT".equals(value))
            continue;

        method.addRequestHeader(new Header(name, value));
        headersSb.append(name + "=" + value + ",  ");
    }

    int cacheStatus = getCache(client, method, request);
    if (cacheStatus != 0)
        return cacheStatus;

    if (log.isInfoEnabled())
        log.info("RequestHeader: " + headersSb);

    // execute http method and process redirect
    method.setFollowRedirects(false);

    client.executeMethod(method);

    int statusCode = method.getStatusCode();

    for (int i = 0; statusCode == HttpStatus.SC_MOVED_TEMPORARILY
            || statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_SEE_OTHER
            || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT; i++) {

        // connection release
        method.releaseConnection();

        if (i == 5) {
            log.error("The circular redirect is limited by five times.");
            return 500;
        }

        Header location = method.getResponseHeader("Location");
        String redirectUrl = location.getValue();

        // According to 2,068 1.1 rfc http spec, we cannot appoint the relative URL,
        // but microsoft.com gives back the relative URL.
        if (redirectUrl.startsWith("/")) {
            URI baseURI = method.getURI();
            baseURI.setPath(redirectUrl);

            redirectUrl = baseURI.toString();
        }

        //method.setURI(new URI(redirectUrl, false));
        Header[] headers = method.getRequestHeaders();
        method = new GetMethod(redirectUrl);
        for (int j = 0; j < headers.length; j++) {
            String headerName = headers[j].getName();
            if (!headerName.equalsIgnoreCase("content-length") && !headerName.equalsIgnoreCase("authorization"))
                method.setRequestHeader(headers[j]);
        }
        AuthenticatorUtil.doAuthentication(client, method, request);
        method.setRequestHeader("authorization", request.getRequestHeader("Authorization"));
        method.setFollowRedirects(false);
        client.executeMethod(method);
        statusCode = method.getStatusCode();
        request.setRedirectURL(redirectUrl);

        if (log.isInfoEnabled())
            log.info("Redirect " + request.getTargetURL() + " to " + location + ".");
    }

    // copy response headers to proxyReqeust
    Header[] headers = method.getResponseHeaders();
    for (int i = 0; i < headers.length; i++) {
        request.putResponseHeader(headers[i].getName(), headers[i].getValue());
    }

    if (log.isInfoEnabled())
        log.info("Original Status:" + statusCode);

    // check response code
    if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
        log.error("Proxy Authentication Required. Confirm ajax proxy setting.");
        throw new Exception(
                "Http Status 407, Proxy Authentication Required. Please contuct System Administrator.");
    }
    if (statusCode == HttpStatus.SC_NOT_MODIFIED || statusCode == HttpStatus.SC_RESET_CONTENT) {
        return statusCode;
    } else if (statusCode < 200 || statusCode >= 300) {
        request.setResponseBody(method.getResponseBodyAsStream());
        return statusCode;
    }

    // process response body
    InputStream responseStream = null;
    if (statusCode != HttpStatus.SC_NO_CONTENT) {
        if (request.allowUserPublicCache()) {
            byte[] responseBody = method.getResponseBody();

            Map<String, List<String>> responseHeaders = request.getResponseHeaders();
            if (request.getRedirectURL() != null)
                responseHeaders.put("X-IS-REDIRECTED-FROM",
                        Arrays.asList(new String[] { request.getRedirectURL() }));
            if (method instanceof GetMethod) {
                putCache(request.getOriginalURL(), new ByteArrayInputStream(responseBody), responseHeaders);
            }

            responseStream = new ByteArrayInputStream(responseBody);
        } else {
            responseStream = method.getResponseBodyAsStream();
        }
    }
    doFilterChain(request, responseStream);

    return statusCode != HttpStatus.SC_NO_CONTENT ? method.getStatusCode() : 200;
}

From source file:org.intermine.webservice.server.VersionServiceTest.java

@Test
public void wsVersion() throws HttpException, IOException {
    HttpMethod get = new GetMethod(baseurl + "/version");
    try {/*  w  ww . j ava 2  s.c  om*/
        int statusCode = client.executeMethod(get);
        assertEquals("Request should be successful", 200, statusCode);
        assertEquals("Version should be " + expectedVersion, "" + expectedVersion,
                get.getResponseBodyAsString().trim());
    } finally {
        get.releaseConnection();
    }
}

From source file:org.intermine.webservice.server.VersionServiceTest.java

@Test
public void wsVersionJSON() throws Exception {
    HttpMethod get = new GetMethod(baseurl + "/version/json");
    try {// w w w. j a  v  a 2 s .  c  o m
        int statusCode = client.executeMethod(get);
        assertEquals("Request should be successful", 200, statusCode);
        JSONObject resp = new JSONObject(get.getResponseBodyAsString());
        assertEquals("Version should be " + expectedVersion, expectedVersion, resp.getInt("version"));
    } finally {
        get.releaseConnection();
    }
}

From source file:org.intermine.webservice.server.VersionServiceTest.java

@Test
public void wsVersionJSONP() throws Exception {
    HttpMethod get = new GetMethod(baseurl + "/version?callback=foo");
    try {/* w  w  w  . j a v a  2s.  c  o  m*/
        int statusCode = client.executeMethod(get);
        assertEquals("Request should be successful", 200, statusCode);
        String body = get.getResponseBodyAsString();
        assertTrue("JSONP responses have the callback", body.startsWith("foo"));
        String json = body.substring(body.indexOf("foo(") + 4, body.length() - 1);
        JSONObject resp = new JSONObject(json);
        assertEquals("Version should be " + expectedVersion, expectedVersion, resp.getInt("version"));
    } finally {
        get.releaseConnection();
    }
}

From source file:org.j2free.http.HttpCallable.java

public HttpCallResult call() throws IOException {
    HttpMethod method;

    if (task.method == HttpCallTask.Method.GET)
        method = new GetMethod(task.toString());
    else {/*from  www .j  a  v a  2  s . c o m*/
        method = new PostMethod(task.url);

        String postBody = task.getExplicitPostBody();
        if (postBody != null) {

            ((PostMethod) method).setRequestEntity(new StringRequestEntity(postBody, "text/xml", null));
        } else {
            List<KeyValuePair<String, String>> params = task.getQueryParams();
            NameValuePair[] data = new NameValuePair[params.size()];

            int i = 0;
            for (KeyValuePair<String, String> param : params) {
                data[i] = new NameValuePair(param.key, param.value);
                i++;
            }

            ((PostMethod) method).setRequestBody(data);
        }
    }

    for (Header header : task.getRequestHeaders()) {
        method.setRequestHeader(header);
    }

    method.setFollowRedirects(task.followRedirects);

    try {
        if (log.isDebugEnabled())
            log.debug("Making HTTP call [url=" + task.toString() + "]");

        client.executeMethod(method);

        if (log.isDebugEnabled())
            log.debug("Call returned [status=" + method.getStatusCode() + "]");

        return new HttpCallResult(method);
    } finally {
        // ALWAYS release the connection!!!
        method.releaseConnection();
    }
}

From source file:org.jaggeryjs.hostobjects.ws.WSRequestHostObject.java

private static Scriptable setOptionsOpenWSDL(WSRequestHostObject wsRequest, Object[] args)
        throws ScriptException {
    Scriptable object = null;//from  w  ww .j av a 2 s .c o m
    String wsdlURL;
    QName serviceQName = null;
    String endpointName = null;
    switch (args.length) {
    case 0:
        throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
    case 1:
        throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
    case 2:
        if (args[0] instanceof String) {
            wsdlURL = (String) args[0];
        } else {
            throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
        }
        if (args[1] instanceof Boolean) {
            wsRequest.async = (Boolean) args[1];
        } else {
            throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
        }
        break;
    case 3:
        if (args[0] instanceof String) {
            wsdlURL = (String) args[0];
        } else {
            throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
        }
        if (args[1] instanceof Boolean) {
            wsRequest.async = (Boolean) args[1];
        } else {
            throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
        }
        if (args[2] instanceof Scriptable) {
            object = (Scriptable) args[2];
        } else {
            throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
        }
        break;
    case 5:
        if (args[0] instanceof String) {
            wsdlURL = (String) args[0];
        } else {
            throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
        }
        if (args[1] instanceof Boolean) {
            wsRequest.async = (Boolean) args[1];
        } else {
            throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
        }
        if (args[2] instanceof Scriptable) {
            object = (Scriptable) args[2];
        } else {
            throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
        }
        if (args[3] instanceof QName) {
            QName qName = (QName) args[3];
            String uri = qName.getNamespaceURI();
            String localName = qName.getLocalPart();
            serviceQName = new QName(uri, localName);
        } else {
            throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
        }
        if (args[4] instanceof String) {
            endpointName = (String) args[4];
        } else {
            throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
        }

        wsRequest.wsdlMode = true;
        break;
    default:
        throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
    }

    HttpMethod method = new GetMethod(wsdlURL);
    try {
        int statusCode = HostObjectUtil.getURL(wsdlURL, null, null);
        if (statusCode != HttpStatus.SC_OK) {
            throw new ScriptException("An error occured while getting the resource at " + wsdlURL + ". Reason :"
                    + method.getStatusLine());
        }
        Document doc = XMLUtils.newDocument(method.getResponseBodyAsStream());
        WSDLReader reader = WSDLFactory.newInstance().newWSDLReader();
        reader.setFeature("javax.wsdl.importDocuments", true);
        Definition definition = reader.readWSDL(getBaseURI(wsdlURL), doc);
        wsRequest.targetNamespace = definition.getTargetNamespace();
        Service service;
        Port returnPort;
        if (serviceQName == null) {
            Map services = definition.getServices();
            service = null;
            for (Object o : services.values()) {
                service = (Service) o;
                if (service.getPorts().size() > 0) {
                    //i.e we have found a service with ports
                    break;
                }
            }
            if (service == null) {
                throw Context
                        .reportRuntimeError("The WSDL given does not contain any services " + "that has ports");
            }
            Map ports = service.getPorts();
            Port port;
            returnPort = null;
            for (Iterator portsIterator = ports.values().iterator(); (portsIterator.hasNext()
                    && returnPort == null);) {
                port = (Port) portsIterator.next();
                List extensibilityElements = port.getExtensibilityElements();
                for (Object extElement : extensibilityElements) {
                    if (extElement instanceof SOAPAddress) {
                        // SOAP 1.1 address found - keep this and loop until http address is found
                        returnPort = port;
                        String location = ((SOAPAddress) extElement).getLocationURI().trim();
                        if ((location != null) && location.startsWith("http:")) {
                            // i.e we have found an http port so return from here
                            break;
                        }
                    }
                }
            }

            if (returnPort == null) {
                for (Object o : ports.values()) {
                    port = (Port) o;
                    List extensibilityElements = port.getExtensibilityElements();
                    for (Object extElement : extensibilityElements) {
                        if (extElement instanceof SOAP12Address) {
                            // SOAP 1.2 address found - keep this and loop until http address is found
                            returnPort = port;
                            String location = ((SOAP12Address) extElement).getLocationURI().trim();
                            if ((location != null) && location.startsWith("http:")) {
                                // i.e we have found an http port so return from here
                                break;
                            }
                        }
                    }
                }

                if (returnPort == null) {
                    for (Object o : ports.values()) {
                        port = (Port) o;
                        List extensibilityElements = port.getExtensibilityElements();
                        for (Object extElement : extensibilityElements) {
                            if (extElement instanceof HTTPAddress) {
                                // HTTP address found - keep this and loop until http address is found
                                returnPort = port;
                                String location = ((HTTPAddress) extElement).getLocationURI().trim();
                                if ((location != null) && location.startsWith("http:")) {
                                    // i.e we have found an http port so return from here
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            if (returnPort == null) {
                throw Context.reportRuntimeError(
                        "The WSDL given does not contain any ports " + "that use the http transport");
            } else {
                serviceQName = service.getQName();
                endpointName = returnPort.getName();

            }
        }
        wsRequest.sender = new ServiceClient(null, definition, serviceQName, endpointName);
    } catch (MalformedURLException e) {
        String message = "Malformed URL : " + wsdlURL;
        log.error(message, e);
        throw new ScriptException(message, e);
    } catch (Exception e) {
        String message = "Error occurred while reading the WSDL content from the URL : " + wsdlURL;
        log.error(message, e);
        throw new ScriptException(message, e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return object;
}

From source file:org.jahia.test.services.logout.LogoutTest.java

protected String logout(String url) throws Exception {
    String returnUrl = null;//from  w  ww.  j  a  v  a  2  s .  co  m
    String baseurl = getBaseServerURL() + Jahia.getContextPath();
    HttpMethod method = new GetMethod(baseurl + "/cms/logout");
    try {
        method.setRequestHeader("Referer", baseurl + url);
        getHttpClient().executeMethod(method);
        returnUrl = StringUtils.isEmpty(Jahia.getContextPath())
                || !(method.getPath().startsWith(Jahia.getContextPath())) ? method.getPath()
                        : StringUtils.substringAfter(method.getPath(), Jahia.getContextPath());
    } finally {
        method.releaseConnection();
    }
    return returnUrl;
}