Example usage for org.apache.http.message AbstractHttpMessage getAllHeaders

List of usage examples for org.apache.http.message AbstractHttpMessage getAllHeaders

Introduction

In this page you can find the example usage for org.apache.http.message AbstractHttpMessage getAllHeaders.

Prototype

public Header[] getAllHeaders() 

Source Link

Usage

From source file:org.dasein.cloud.opsource.OpSourceMethod.java

public Document invoke() throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("enter - " + OpSource.class.getName() + ".invoke()");
    }//from  www  .j  ava 2  s  .  co m
    try {
        URL url = null;
        try {
            url = new URL(endpoint);
        } catch (MalformedURLException e1) {
            throw new CloudException(e1);
        }
        final String host = url.getHost();
        final int urlPort = url.getPort() == -1 ? url.getDefaultPort() : url.getPort();
        final String urlStr = url.toString();

        DefaultHttpClient httpclient = new DefaultHttpClient();

        /**  HTTP Authentication */
        String uid = new String(provider.getContext().getAccessPublic());
        String pwd = new String(provider.getContext().getAccessPrivate());

        /** Type of authentication */
        List<String> authPrefs = new ArrayList<String>(2);
        authPrefs.add(AuthPolicy.BASIC);

        httpclient.getParams().setParameter("http.auth.scheme-pref", authPrefs);
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(host, urlPort, null),
                new UsernamePasswordCredentials(uid, pwd));

        if (wire.isDebugEnabled()) {
            wire.debug("--------------------------------------------------------------> " + urlStr);
            wire.debug("");
        }

        AbstractHttpMessage method = this.getMethod(parameters.get(OpSource.HTTP_Method_Key), urlStr);
        method.setParams(new BasicHttpParams().setParameter(urlStr, url));
        /**  Set headers */
        method.addHeader(OpSource.Content_Type_Key, parameters.get(OpSource.Content_Type_Key));

        /** POST/PUT method specific logic */
        if (method instanceof HttpEntityEnclosingRequest) {
            HttpEntityEnclosingRequest entityEnclosingMethod = (HttpEntityEnclosingRequest) method;
            String requestBody = parameters.get(OpSource.HTTP_Post_Body_Key);

            if (requestBody != null) {
                if (wire.isDebugEnabled()) {
                    wire.debug(requestBody);
                }

                AbstractHttpEntity entity = new ByteArrayEntity(requestBody.getBytes());
                entity.setContentType(parameters.get(OpSource.Content_Type_Key));
                entityEnclosingMethod.setEntity(entity);
            } else {
                throw new CloudException("The request body is null for a post request");
            }
        }

        /** Now parse the xml */
        try {

            HttpResponse httpResponse;
            int status;
            if (wire.isDebugEnabled()) {
                for (org.apache.http.Header header : method.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
            }
            /**  Now execute the request */
            APITrace.trace(provider, method.toString() + " " + urlStr);
            httpResponse = httpclient.execute((HttpUriRequest) method);
            status = httpResponse.getStatusLine().getStatusCode();
            if (wire.isDebugEnabled()) {
                wire.debug("invoke(): HTTP Status " + httpResponse.getStatusLine().getStatusCode() + " "
                        + httpResponse.getStatusLine().getReasonPhrase());
            }
            org.apache.http.Header[] headers = httpResponse.getAllHeaders();

            HttpEntity entity = httpResponse.getEntity();
            if (wire.isDebugEnabled()) {
                wire.debug("HTTP xml status code ---------" + status);
                for (org.apache.http.Header h : headers) {
                    if (h.getValue() != null) {
                        wire.debug(h.getName() + ": " + h.getValue().trim());
                    } else {
                        wire.debug(h.getName() + ":");
                    }
                }
                /** Can not enable this line, otherwise the entity would be empty*/
                // wire.debug("OpSource Response Body for request " + urlStr + " = " + EntityUtils.toString(entity));
                wire.debug("-----------------");
            }
            if (entity == null) {
                parseError(status, "Empty entity");
            }

            String responseBody = EntityUtils.toString(entity);

            if (status == HttpStatus.SC_OK) {
                InputStream input = null;
                try {
                    input = new ByteArrayInputStream(responseBody.getBytes("UTF-8"));
                    if (input != null) {
                        Document doc = null;
                        try {
                            doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input);
                            if (wire.isDebugEnabled()) {
                                try {
                                    TransformerFactory transfac = TransformerFactory.newInstance();
                                    Transformer trans = transfac.newTransformer();
                                    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                                    trans.setOutputProperty(OutputKeys.INDENT, "yes");

                                    StringWriter sw = new StringWriter();
                                    StreamResult result = new StreamResult(sw);
                                    DOMSource source = new DOMSource(doc);
                                    trans.transform(source, result);
                                    String xmlString = sw.toString();
                                    wire.debug(xmlString);
                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                }
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            logger.debug(ex.toString(), ex);
                        }
                        return doc;
                    }
                } catch (IOException e) {
                    logger.error(
                            "invoke(): Failed to read xml error due to a cloud I/O error: " + e.getMessage());
                    throw new CloudException(e);
                }
                /*
                catch( SAXException e ) {
                throw new CloudException(e);
                }                    
                catch( ParserConfigurationException e ) {
                throw new InternalException(e);
                }
                */
            } else if (status == HttpStatus.SC_NOT_FOUND) {
                throw new CloudException("An internal error occured: The endpoint was not found");
            } else {
                if (responseBody != null) {
                    parseError(status, responseBody);
                    Document parsedError = null;
                    if (!responseBody.contains("<HR")) {
                        parsedError = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                                .parse(new ByteArrayInputStream(responseBody.getBytes("UTF-8")));
                        if (wire.isDebugEnabled()) {
                            try {
                                TransformerFactory transfac = TransformerFactory.newInstance();
                                Transformer trans = transfac.newTransformer();
                                trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                                trans.setOutputProperty(OutputKeys.INDENT, "yes");

                                StringWriter sw = new StringWriter();
                                StreamResult result = new StreamResult(sw);
                                DOMSource source = new DOMSource(parsedError);
                                trans.transform(source, result);
                                String xmlString = sw.toString();
                                wire.debug(xmlString);
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    } else
                        logger.debug("Error message was unparsable");
                    return parsedError;
                }
            }
        } catch (ParseException e) {
            throw new CloudException(e);
        } catch (SAXException e) {
            throw new CloudException(e);
        } catch (IOException e) {
            e.printStackTrace();
            throw new CloudException(e);
        } catch (ParserConfigurationException e) {
            throw new CloudException(e);
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("exit - " + OpSource.class.getName() + ".invoke()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("--------------------------------------------------------------> " + endpoint);
        }
    }
    return null;
}