Example usage for org.apache.commons.httpclient HttpMethodBase getResponseHeader

List of usage examples for org.apache.commons.httpclient HttpMethodBase getResponseHeader

Introduction

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

Prototype

@Override
public Header getResponseHeader(String headerName) 

Source Link

Document

Gets the response header associated with the given name.

Usage

From source file:org.eclipse.mylyn.internal.provisional.commons.soap.AxisHttpFault.java

private void extractDetails(HttpMethodBase method) {
    Header locationHeader = method.getResponseHeader("location"); //$NON-NLS-1$
    if (locationHeader != null) {
        this.location = locationHeader.getValue();
    }//from w  w  w  .  j a v a  2  s  . c  om
}

From source file:org.eclipse.mylyn.internal.provisional.commons.soap.CommonsHttpSender.java

/**
 * invoke creates a socket connection, sends the request SOAP message and then reads the response SOAP message back
 * from the SOAP server/* w  ww.  j  a  v a2  s.  c  om*/
 * 
 * @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());

        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") //$NON-NLS-1$
                && ((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); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

            try {
                //               fault.setFaultDetailString(Messages.getMessage("return01", "" + returnCode, //$NON-NLS-1$ //$NON-NLS-2$
                //                     method.getResponseBodyAsString()));
                //               fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode));
                //               throw fault;
                throw AxisHttpFault.makeFault(method);
            } 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 if (contentEncoding.getValue().equals("") //$NON-NLS-1$
                    && msgContext.isPropertyTrue(SoapHttpSender.ALLOW_EMPTY_CONTENT_ENCODING)) {
                // assume no encoding
            } else {
                AxisFault fault = new AxisFault("HTTP", "unsupported content-encoding of '" //$NON-NLS-1$ //$NON-NLS-2$
                        + contentEncoding.getValue() + "' found", null, null); //$NON-NLS-1$
                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 (Header responseHeader : responseHeaders) {
            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 (Header header : headers) {
                if (header.getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE, header.getValue(), msgContext);
                } else if (header.getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE2, header.getValue(), msgContext);
                }
            }
        }

        // always release the connection back to the pool if 
        // it was one way invocation
        if (msgContext.isPropertyTrue("axis.one.way")) { //$NON-NLS-1$
            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:org.eclipse.osee.framework.core.util.HttpProcessor.java

private static String getContentType(HttpMethodBase method) {
    String contentType = null;/*from   www  .ja  va  2  s.com*/
    Header header = method.getResponseHeader(CONTENT_TYPE);
    if (header != null) {
        contentType = header.getValue();
        if (Strings.isValid(contentType)) {
            int index = contentType.indexOf(';');
            if (index > 0) {
                contentType = contentType.substring(0, index);
            }
        }
    }
    return contentType;
}

From source file:org.fcrepo.server.security.servletfilters.pubcookie.ConnectPubcookie.java

public final void connect(String urlString, Map requestParameters, Cookie[] requestCookies,
        String truststoreLocation, String truststorePassword) {
    if (logger.isDebugEnabled()) {
        logger.debug("Entered .connect() " + " url==" + urlString + " requestParameters==" + requestParameters
                + " requestCookies==" + requestCookies);
    }/*from  www.j  a v  a 2 s .  co  m*/
    responseCookies2 = null;
    URL url = null;
    try {
        url = new URL(urlString);
    } catch (MalformedURLException mue) {
        logger.error("Malformed url: " + urlString, mue);
    }

    if (urlString.startsWith("https:") && null != truststoreLocation && !"".equals(truststoreLocation)
            && null != truststorePassword && !"".equals(truststorePassword)) {
        logger.debug("setting " + FilterPubcookie.TRUSTSTORE_LOCATION_KEY + " to " + truststoreLocation);
        System.setProperty(FilterPubcookie.TRUSTSTORE_LOCATION_KEY, truststoreLocation);
        logger.debug("setting " + FilterPubcookie.TRUSTSTORE_PASSWORD_KEY + " to " + truststorePassword);
        System.setProperty(FilterPubcookie.TRUSTSTORE_PASSWORD_KEY, truststorePassword);

        logger.debug("setting " + FilterPubcookie.KEYSTORE_LOCATION_KEY + " to " + truststoreLocation);
        System.setProperty(FilterPubcookie.KEYSTORE_LOCATION_KEY, truststoreLocation);
        logger.debug("setting " + FilterPubcookie.KEYSTORE_PASSWORD_KEY + " to " + truststorePassword);
        System.setProperty(FilterPubcookie.KEYSTORE_PASSWORD_KEY, truststorePassword);

        System.setProperty("javax.net.debug", "ssl,handshake,data,trustmanager");

    } else {
        logger.debug("DIAGNOSTIC urlString==" + urlString);
        logger.debug("didn't set " + FilterPubcookie.TRUSTSTORE_LOCATION_KEY + " to " + truststoreLocation);
        logger.debug("didn't set " + FilterPubcookie.TRUSTSTORE_PASSWORD_KEY + " to " + truststorePassword);
    }

    HttpClient client = new HttpClient();
    logger.debug(".connect() requestCookies==" + requestCookies);
    HttpMethodBase method = setup(client, url, requestParameters, requestCookies);
    int statusCode = 0;
    try {
        client.executeMethod(method);
        statusCode = method.getStatusCode();
    } catch (Exception e) {
        logger.error("failed original connect, url==" + urlString, e);
    }

    logger.debug("status code==" + statusCode);

    if (302 == statusCode) {
        Header redirectHeader = method.getResponseHeader("Location");
        if (redirectHeader != null) {
            String redirectString = redirectHeader.getValue();
            if (redirectString != null) {
                URL redirectURL = null;
                try {
                    redirectURL = new URL(redirectString);
                    method = setup(client, redirectURL, requestParameters, requestCookies);
                } catch (MalformedURLException mue) {
                    logger.error(".connect() malformed redirect url: " + urlString);
                }
                statusCode = 0;
                try {
                    client.executeMethod(method);
                    statusCode = method.getStatusCode();
                    logger.debug(".connect() (on redirect) statusCode==" + statusCode);
                } catch (Exception e) {
                    logger.error(".connect() " + "failed redirect connect");
                }
            }
        }
    }
    if (statusCode == 200) { // this is either the original, non-302, status code or the status code after redirect
        String content = null;
        try {
            content = method.getResponseBodyAsString();
        } catch (IOException e) {
            logger.error("Error getting content", e);
            return;
        }
        if (content == null) {
            logger.error("Content is null");
            return;
        } else {
            Tidy tidy = null;
            try {
                tidy = new Tidy();
            } catch (Throwable t) {
                logger.error("Error creating Tidy instance?!", t);
            }
            byte[] inputBytes = content.getBytes();
            ByteArrayInputStream inputStream = new ByteArrayInputStream(inputBytes);
            responseDocument = tidy.parseDOM(inputStream, null); //use returned root node as only output
        }
        HttpState state = client.getState();
        try {
            responseCookies2 = method.getRequestHeaders();
            if (logger.isDebugEnabled()) {
                for (Header element : responseCookies2) {
                    logger.debug("Header: {}={}", element.getName(), element.getValue());
                }
            }
            responseCookies = state.getCookies();
            logger.debug(this.getClass().getName() + ".connect() responseCookies==" + responseCookies);
        } catch (Throwable t) {
            logger.error(this.getClass().getName() + ".connect() exception==" + t.getMessage());
            if (t.getCause() != null) {
                logger.error(this.getClass().getName() + ".connect() cause==" + t.getCause().getMessage());
            }
        }
        completedFully = true;
        logger.debug(this.getClass().getName() + ".connect() completedFully==" + completedFully);
    }
}

From source file:org.httpobjects.proxy.Proxy.java

protected Response createResponse(final HttpMethodBase method, ResponseCode responseCode,
        List<HeaderField> headersReturned) {
    return new Response(responseCode, new Representation() {
        @Override//w w  w .  jav  a  2  s.c om
        public String contentType() {
            Header h = method.getResponseHeader("Content-Type");
            return h == null ? null : h.getValue();
        }

        @Override
        public void write(OutputStream out) {
            try {
                if (method.getResponseBodyAsStream() != null) {

                    byte[] buffer = new byte[1024];
                    InputStream in = method.getResponseBodyAsStream();
                    for (int x = in.read(buffer); x != -1; x = in.read(buffer)) {
                        out.write(buffer, 0, x);
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("Error writing response", e);
            }
        }
    }, headersReturned.toArray(new HeaderField[] {}));
}

From source file:org.jahia.modules.filter.WebClippingFilter.java

private String getResponse(String urlToClip, RenderContext renderContext, Resource resource, RenderChain chain,
        HttpMethodBase httpMethod, HttpClient httpClient) {
    try {//from   w w  w .j  a  va  2s .c o  m
        httpMethod.getParams().setParameter("http.connection.timeout",
                resource.getNode().getPropertyAsString("connectionTimeout"));
        httpMethod.getParams().setParameter("http.protocol.expect-continue",
                Boolean.valueOf(resource.getNode().getPropertyAsString("expectContinue")));
        httpMethod.getParams().setCookiePolicy(CookiePolicy.RFC_2965);

        int statusCode = httpClient.executeMethod(httpMethod);

        if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY || statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                || statusCode == HttpStatus.SC_SEE_OTHER || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
            if (log.isDebugEnabled()) {
                log.debug("We follow a redirection ");
            }
            String redirectLocation;
            Header locationHeader = httpMethod.getResponseHeader("location");
            if (locationHeader != null) {
                redirectLocation = locationHeader.getValue();
                if (!redirectLocation.startsWith("http")) {
                    URL siteURL = new URL(urlToClip);
                    String tmpURL = siteURL.getProtocol() + "://" + siteURL.getHost()
                            + ((siteURL.getPort() > 0) ? ":" + siteURL.getPort() : "") + "/" + redirectLocation;
                    httpMethod = new GetMethod(tmpURL);
                    // Set a default retry handler (see httpclient doc).
                    httpMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                            new DefaultHttpMethodRetryHandler(3, false));
                    httpMethod.getParams().setParameter("http.connection.timeout",
                            resource.getNode().getPropertyAsString("connectionTimeout"));
                    httpMethod.getParams().setParameter("http.protocol.expect-continue",
                            resource.getNode().getPropertyAsString("expectContinue"));
                    httpMethod.getParams().setCookiePolicy(CookiePolicy.RFC_2965);
                } else {
                    httpMethod = new GetMethod(redirectLocation);
                }
            }
        }
        if (statusCode != HttpStatus.SC_OK) {
            //this.cacheable = false;
            StringBuffer buffer = new StringBuffer("<html>\n<body>");
            buffer.append('\n' + "Error getting ").append(urlToClip).append(" failed with error code ")
                    .append(statusCode);
            buffer.append("\n</body>\n</html>");
            return buffer.toString();
        }

        String[] type = httpMethod.getResponseHeader("Content-Type").getValue().split(";");
        String contentCharset = "UTF-8";
        if (type.length == 2) {
            contentCharset = type[1].split("=")[1];
        }
        InputStream inputStream = new BufferedInputStream(httpMethod.getResponseBodyAsStream());
        if (inputStream != null) {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream(100 * 1024);
            byte[] buffer = new byte[100 * 1024];
            int len;
            while ((len = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.close();
            inputStream.close();
            final byte[] responseBodyAsBytes = outputStream.toByteArray();
            String responseBody = new String(responseBodyAsBytes, "US-ASCII");
            Source source = new Source(responseBody);
            List list = source.getAllStartTags(HTMLElementName.META);
            for (Object aList : list) {
                StartTag startTag = (StartTag) aList;
                Attributes attributes = startTag.getAttributes();
                final Attribute attribute = attributes.get("http-equiv");
                if (attribute != null && attribute.getValue().equalsIgnoreCase("content-type")) {
                    type = attributes.get("content").getValue().split(";");
                    if (type.length == 2) {
                        contentCharset = type[1].split("=")[1];
                    }
                }
            }
            final String s = contentCharset.toUpperCase();
            return rewriteBody(new String(responseBodyAsBytes, s), urlToClip, s, resource, renderContext);
        }
    } catch (Exception e) {
        e.printStackTrace();
        //this.cacheable = false;
        StringBuffer buffer = new StringBuffer("<html>\n<body>");
        buffer.append('\n' + "Error getting ").append(urlToClip).append(" failed with error : ")
                .append(e.toString());
        buffer.append("\n</body>\n</html>");
        return buffer.toString();
    }
    return null;
}

From source file:org.jboss.mod_cluster.Client.java

public int runit() throws Exception {

    PostMethod pm = null;//from w ww  .j  a  va2  s .c o m
    GetMethod gm = null;
    HttpMethodBase bm = null;
    long starttime, endtime;
    if (httpClient == null)
        httpClient = new HttpClient();
    if (fd != null) {
        pm = new PostMethod(URL);
        // InputStreamRequestEntity buf = new InputStreamRequestEntity(fd);
        // XXX: Ugly hack to test...
        byte[] buffet = new byte[6144];
        for (int i = 0; i < buffet.length; i++)
            buffet[i] = 'a';
        ByteArrayRequestEntity buf = new ByteArrayRequestEntity(buffet);
        pm.setRequestEntity(buf);
        // pm.setRequestBody(fd);
        pm.setHttp11(true);
        pm.setContentChunked(true);
        // pm.setRequestContentLength(PostMethod.CONTENT_LENGTH_CHUNKED);
        bm = pm;
    } else if (post != null) {
        pm = new PostMethod(URL);
        pm.setRequestEntity(new StringRequestEntity(post, "application/x-www-form-urlencoded", "UTF8"));
        bm = pm;
    } else {
        gm = new GetMethod(URL);
        bm = gm;
    }
    if (user != null) {
        Credentials cred = new UsernamePasswordCredentials(user, pass);
        httpClient.getState().setCredentials(org.apache.commons.httpclient.auth.AuthScope.ANY, cred);
    }

    // System.out.println("Connecting to " + URL);

    Integer connectionTimeout = 40000;
    bm.getParams().setParameter("http.socket.timeout", connectionTimeout);
    bm.getParams().setParameter("http.connection.timeout", connectionTimeout);
    if (VirtualHost != null)
        bm.getParams().setVirtualHost(VirtualHost);
    httpClient.getParams().setParameter("http.socket.timeout", connectionTimeout);
    httpClient.getParams().setParameter("http.connection.timeout", connectionTimeout);
    if (jsessionid != null) {
        // System.out.println("jsessionid: " + jsessionid);
        bm.setRequestHeader("Cookie", "JSESSIONID=" + jsessionid);
    }

    try {
        if (gm == null) {
            pm.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
            starttime = System.currentTimeMillis();
            httpResponseCode = httpClient.executeMethod(pm);
            endtime = System.currentTimeMillis();
        } else {
            gm.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
            starttime = System.currentTimeMillis();
            httpResponseCode = httpClient.executeMethod(gm);
            endtime = System.currentTimeMillis();
        }

        if (httpResponseCode == 200) {
            response = bm.getResponseBodyAsString();
            Cookie[] cookies = httpClient.getState().getCookies();
            // System.out.println( "Cookies: " + cookies);
            if (cookies != null && cookies.length != 0) {
                for (int i = 0; i < cookies.length; i++) {
                    Cookie cookie = cookies[i];
                    // System.out.println( "Cookie: " + cookie.getName() + ", Value: " + cookie.getValue());
                    if (cookie.getName().equals("JSESSIONID")) {
                        if (jsessionid == null) {
                            jsessionid = cookie.getValue();
                            String nodes[] = jsessionid.split("\\.");
                            if (nodes.length == 2)
                                node = nodes[1];
                            System.out.println("cookie first time: " + jsessionid);
                            bm.releaseConnection();
                            return 0; // first time ok.
                        } else {
                            if (jsessionid.compareTo(cookie.getValue()) == 0) {
                                if (logok)
                                    if (bm.getResponseHeader("Date") != null)
                                        System.out.println("cookie ok: "
                                                + bm.getResponseHeader("Date").toString().replace('\r', ' ')
                                                        .replace('\n', ' ')
                                                + " response time: " + (endtime - starttime));
                                    else {
                                        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                                        Date date = new Date();
                                        System.out.println("cookie ok: " + dateFormat.format(date)
                                                + " response time: " + (endtime - starttime));
                                    }
                                bm.releaseConnection();
                                return 0;
                            } else {
                                System.out.println(
                                        "cookie \"second\" time: " + cookie.getValue() + " : " + jsessionid);
                                System.out.println("cookie changed");
                                bm.releaseConnection();
                                if (checkcookie)
                                    return -1;
                                else if (checknode) {
                                    String nodes[] = cookie.getValue().split("\\.");
                                    if (nodes.length != 2) {
                                        System.out.println("Can't find node in cookie");
                                        return -1;
                                    }
                                    if (nodes[1].compareTo(node) == 0) {
                                        return 0;
                                    } else {
                                        System.out.println("node " + nodes[1] + " changed too");
                                        return -1;
                                    }
                                } else
                                    return 0;
                            }
                        }
                    }
                }
            } else {
                // Look in the response to make sure that there is a cookie.
                int len = (int) bm.getResponseContentLength();

                if (jsessionid != null && bm.getResponseBodyAsString(len).indexOf(jsessionid) != -1) {
                    bm.releaseConnection();
                    return 0;
                }
                if (jsessionid == null && !checkcookie) {
                    return 0;
                }
                System.out.println("No cookies");
            }
            Header head = bm.getResponseHeader("getRequestedSessionId");
            if (head != null) {
                HeaderElement[] heade = head.getElements();
                requestedSessionId = heade[0].getValue();
            } else {
                requestedSessionId = null;
            }
        } else {
            System.out.println("response: " + httpResponseCode);
            System.out.println("response: " + bm.getStatusLine());
            response = bm.getResponseBodyAsString();
            System.out.println("response: " + response);
            success = false;
            httpClient = null;
        }
        // System.out.println("response:\n" + bm.getResponseBodyAsString(len)); 
    } catch (HttpException e) {
        e.printStackTrace();
        success = false;
        httpClient = null;
    }
    System.out.println("DONE: " + httpResponseCode);
    bm.releaseConnection();
    return httpResponseCode;
}

From source file:org.jboss.test.classloader.test.ScopingUnitTestCase.java

/**
 * Deploy a sar with nested wars that reference jars in
 * the sar through the war manifest classpath.
 *//* w w w.  j  a v a 2 s.  c  o  m*/
public void testNestedWarManifest() throws Exception {
    getLog().debug("+++ testNestedWarManifest");
    String baseURL = HttpUtils.getBaseURL();
    URL url = new URL(baseURL + "staticarray-web1/validate.jsp"
            + "?Sequencer.info.expected=1,2,3,4,5,6,7,8,9,10" + "&op=set" + "&array=1,2,3,4,5,6,7,8,9,10");
    try {
        deploy("staticarray.sar");
        // Set the static array value to a non-default from war1
        HttpMethodBase request = HttpUtils.accessURL(url);
        Header errors = request.getResponseHeader("X-Error");
        log.info("war1 X-Error: " + errors);
        assertTrue("war1 X-Error(" + errors + ") is null", errors == null);
        // Validate that war2 sees the changed values
        url = new URL(
                baseURL + "staticarray-web2/validate.jsp" + "?Sequencer.info.expected=1,2,3,4,5,6,7,8,9,10");
        request = HttpUtils.accessURL(url);
        errors = request.getResponseHeader("X-Error");
        log.info("war2 X-Error: " + errors);
        assertTrue("war2 X-Error(" + errors + ") is null", errors == null);

    } catch (Exception e) {
        getLog().info("Failed to access: " + url, e);
        throw e;
    } finally {
        undeploy("staticarray.sar");
    }
}

From source file:org.jboss.test.securitymgr.test.WarPermissionsUnitTestCase.java

public void testPackedAllowedPermissions() throws Exception {
    URL url = new URL(baseURL + "packed/FileAccessServlet?file=allow");
    HttpMethodBase request = HttpUtils.accessURL(url);
    Header hdr = request.getResponseHeader("X-CodeSource");
    log.info("X-CodeSource: " + hdr);
    assertTrue("X-CodeSource(" + hdr + ") is NOT null", hdr != null);
    hdr = request.getResponseHeader("X-RealPath");
    log.info("X-RealPath: " + hdr);
    assertTrue("X-RealPath(" + hdr + ") is NOT null", hdr != null);
    hdr = request.getResponseHeader("X-Exception");
    log.info("X-Exception: " + hdr);
    assertTrue("X-Exception(" + hdr + ") is null", hdr == null);
}

From source file:org.jboss.test.securitymgr.test.WarPermissionsUnitTestCase.java

public void testUnpackedAllowedPermissions() throws Exception {
    URL url = new URL(baseURL + "unpacked/FileAccessServlet?file=allow");
    HttpMethodBase request = HttpUtils.accessURL(url);
    Header hdr = request.getResponseHeader("X-CodeSource");
    log.info("X-CodeSource: " + hdr);
    assertTrue("X-CodeSource(" + hdr + ") is NOT null", hdr != null);
    hdr = request.getResponseHeader("X-RealPath");
    log.info("X-RealPath: " + hdr);
    assertTrue("X-RealPath(" + hdr + ") is NOT null", hdr != null);
    hdr = request.getResponseHeader("X-Exception");
    log.info("X-Exception: " + hdr);
    assertTrue("X-Exception(" + hdr + ") is null", hdr == null);
}