Example usage for javax.servlet.http HttpServletResponse SC_ACCEPTED

List of usage examples for javax.servlet.http HttpServletResponse SC_ACCEPTED

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_ACCEPTED.

Prototype

int SC_ACCEPTED

To view the source code for javax.servlet.http HttpServletResponse SC_ACCEPTED.

Click Source Link

Document

Status code (202) indicating that a request was accepted for processing, but was not completed.

Usage

From source file:org.dasein.cloud.ibm.sce.SCEMethod.java

public @Nullable String put(@Nonnull String resource, @Nullable List<NameValuePair> parameters)
        throws CloudException, InternalException {
    Logger std = SCE.getLogger(SCEMethod.class, "std");
    Logger wire = SCE.getLogger(SCEMethod.class, "wire");

    if (std.isTraceEnabled()) {
        std.trace("enter - " + SCEMethod.class.getName() + ".post(" + resource + ")");
    }/* w  ww .j  a va  2 s.  c o  m*/
    if (wire.isDebugEnabled()) {
        wire.debug("POST --------------------------------------------------------> " + endpoint + resource);
        wire.debug("");
    }
    try {
        HttpClient client = getClient();

        HttpPut method = new HttpPut(endpoint + resource);

        method.addHeader("Content-Type", "application/x-www-form-urlencoded");
        method.addHeader("Accept", "text/xml");

        if (wire.isDebugEnabled()) {
            wire.debug(method.getRequestLine().toString());
            for (Header header : method.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
            if (parameters != null) {
                Iterator<NameValuePair> it = parameters.iterator();
                StringBuilder str = new StringBuilder();

                while (it.hasNext()) {
                    NameValuePair p = it.next();

                    str.append(p.getName()).append("=").append(p.getValue());
                    if (it.hasNext()) {
                        str.append("&");
                    }
                }
                wire.debug(str.toString());
                wire.debug("");
            }
        }
        if (parameters != null) {
            try {
                method.setEntity(new UrlEncodedFormEntity(parameters, "utf-8"));
            } catch (UnsupportedEncodingException e) {
                throw new InternalException(e);
            }
        }
        HttpResponse response;
        StatusLine status;

        try {
            APITrace.trace(provider, resource);
            response = client.execute(method);
            status = response.getStatusLine();
        } catch (IOException e) {
            std.error("post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
            if (std.isTraceEnabled()) {
                e.printStackTrace();
            }
            throw new CloudException(e);
        }
        if (std.isDebugEnabled()) {
            std.debug("post(): HTTP Status " + status);
        }
        Header[] headers = response.getAllHeaders();

        if (wire.isDebugEnabled()) {
            wire.debug(status.toString());
            for (Header h : headers) {
                if (h.getValue() != null) {
                    wire.debug(h.getName() + ": " + h.getValue().trim());
                } else {
                    wire.debug(h.getName() + ":");
                }
            }
            wire.debug("");
        }
        if (status.getStatusCode() != HttpServletResponse.SC_OK
                && status.getStatusCode() != HttpServletResponse.SC_CREATED
                && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) {
            std.error("post(): Expected OK for GET request, got " + status.getStatusCode());

            HttpEntity entity = response.getEntity();
            String body;

            if (entity == null) {
                throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(),
                        "An error was returned without explanation");
            }
            try {
                body = EntityUtils.toString(entity);
            } catch (IOException e) {
                throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(),
                        e.getMessage());
            }
            if (wire.isDebugEnabled()) {
                wire.debug(body);
            }
            wire.debug("");
            throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(),
                    body);
        } else if (status.getStatusCode() == HttpServletResponse.SC_NO_CONTENT) {
            return null;
        } else {
            HttpEntity entity = response.getEntity();

            if (entity == null) {
                return null;
            }
            try {
                return EntityUtils.toString(entity);
            } catch (IOException e) {
                throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(),
                        e.getMessage());
            }
        }
    } finally {
        if (std.isTraceEnabled()) {
            std.trace("exit - " + SCEMethod.class.getName() + ".post()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("POST --------------------------------------------------------> " + endpoint + resource);
        }
    }
}

From source file:org.dasein.cloud.rackspace.AbstractMethod.java

@SuppressWarnings("unused")
protected @Nullable String postHeaders(@Nonnull String authToken, @Nonnull String endpoint,
        @Nonnull String resource, @Nonnull Map<String, String> customHeaders)
        throws CloudException, InternalException {
    Logger std = RackspaceCloud.getLogger(RackspaceCloud.class, "std");
    Logger wire = RackspaceCloud.getLogger(RackspaceCloud.class, "wire");

    if (std.isTraceEnabled()) {
        std.trace("enter - " + AbstractMethod.class.getName() + ".postString(" + authToken + "," + endpoint
                + "," + resource + "," + customHeaders + ")");
    }//from  ww  w  .j  a  v  a 2  s .  c  om
    if (wire.isDebugEnabled()) {
        wire.debug("---------------------------------------------------------------------------------"
                + endpoint + resource);
        wire.debug("");
    }
    try {
        HttpClient client = getClient();
        HttpPost post = new HttpPost(endpoint + resource);

        post.addHeader("Content-Type", "application/json");
        post.addHeader("X-Auth-Token", authToken);
        if (customHeaders != null) {
            for (Map.Entry<String, String> entry : customHeaders.entrySet()) {
                String val = (entry.getValue() == null ? "" : entry.getValue());

                post.addHeader(entry.getKey(), val);
            }
        }

        if (wire.isDebugEnabled()) {
            wire.debug(post.getRequestLine().toString());
            for (Header header : post.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
        }
        HttpResponse response;

        try {
            response = client.execute(post);
            if (wire.isDebugEnabled()) {
                wire.debug(response.getStatusLine().toString());
                for (Header header : response.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                wire.debug("");
            }
        } catch (IOException e) {
            std.error("I/O error from server communications: " + e.getMessage());
            e.printStackTrace();
            throw new InternalException(e);
        }
        int code = response.getStatusLine().getStatusCode();

        std.debug("HTTP STATUS: " + code);

        if (code != HttpServletResponse.SC_ACCEPTED && code != HttpServletResponse.SC_NO_CONTENT) {
            std.error("postString(): Expected ACCEPTED for POST request, got " + code);
            HttpEntity entity = response.getEntity();
            String json = null;

            if (entity != null) {
                try {
                    json = EntityUtils.toString(entity);

                    if (wire.isDebugEnabled()) {
                        wire.debug(json);
                        wire.debug("");
                    }
                } catch (IOException e) {
                    throw new CloudException(e);
                }
            }
            RackspaceException.ExceptionItems items = (json == null ? null
                    : RackspaceException.parseException(code, json));

            if (items == null) {
                items = new RackspaceException.ExceptionItems();
                items.code = 404;
                items.type = CloudErrorType.COMMUNICATION;
                items.message = "itemNotFound";
                items.details = "No such object: " + resource;
            }
            std.error("postString(): [" + code + " : " + items.message + "] " + items.details);
            throw new RackspaceException(items);
        } else {
            if (code == HttpServletResponse.SC_ACCEPTED) {
                HttpEntity entity = response.getEntity();
                String json = null;

                if (entity != null) {
                    try {
                        json = EntityUtils.toString(entity);

                        if (wire.isDebugEnabled()) {
                            wire.debug(json);
                            wire.debug("");
                        }
                    } catch (IOException e) {
                        throw new CloudException(e);
                    }
                }
                if (json != null && !json.trim().equals("")) {
                    return json;
                }
            }
            return null;
        }
    } finally {
        if (std.isTraceEnabled()) {
            std.trace("exit - " + AbstractMethod.class.getName() + ".postString()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("---------------------------------------------------------------------------------"
                    + endpoint + resource);
        }
    }
}

From source file:org.dasein.cloud.azure.AzureMethod.java

public String invoke(@Nonnull String method, @Nonnull String account, @Nonnull String resource,
        @Nonnull String body) throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("enter - " + AzureMethod.class.getName() + ".post(" + account + "," + resource + ")");
    }//w w w . j  a v a  2  s . c  o m
    if (wire.isDebugEnabled()) {
        wire.debug("POST --------------------------------------------------------> " + endpoint + account
                + resource);
        wire.debug("");
    }
    String requestId = null;
    try {
        HttpClient client = getClient();
        String url = endpoint + account + resource;

        HttpRequestBase httpMethod = getMethod(method, url);

        //If it is networking configuration services
        if (httpMethod instanceof HttpPut) {
            if (url.endsWith("/services/networking/media")) {
                httpMethod.addHeader("Content-Type", "text/plain");
            } else {
                httpMethod.addHeader("Content-Type", "application/xml;charset=UTF-8");
            }
        } else {
            httpMethod.addHeader("Content-Type", "application/xml;charset=UTF-8");
        }

        //dmayne version is older for anything to do with images and for disk deletion
        if (url.indexOf("/services/images") > -1
                || (httpMethod instanceof HttpDelete && url.indexOf("/services/disks") > -1)) {
            httpMethod.addHeader("x-ms-version", "2012-08-01");
        } else {
            httpMethod.addHeader("x-ms-version", "2012-03-01");
        }
        if (wire.isDebugEnabled()) {
            wire.debug(httpMethod.getRequestLine().toString());
            for (Header header : httpMethod.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
            if (body != null) {
                wire.debug(body);
                wire.debug("");
            }
        }

        if (httpMethod instanceof HttpEntityEnclosingRequestBase) {

            HttpEntityEnclosingRequestBase entityEnclosingMethod = (HttpEntityEnclosingRequestBase) httpMethod;

            if (body != null) {
                try {
                    entityEnclosingMethod.setEntity(new StringEntity(body, "application/xml", "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    throw new CloudException(e);
                }
            }
        }

        HttpResponse response;
        StatusLine status;

        try {
            response = client.execute(httpMethod);
            status = response.getStatusLine();
        } catch (IOException e) {
            logger.error("post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
            if (logger.isTraceEnabled()) {
                e.printStackTrace();
            }
            throw new CloudException(e);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("post(): HTTP Status " + status);
        }
        Header[] headers = response.getAllHeaders();

        if (wire.isDebugEnabled()) {
            wire.debug(status.toString());
            for (Header h : headers) {
                if (h.getValue() != null) {
                    wire.debug(h.getName() + ": " + h.getValue().trim());
                    if (h.getName().equalsIgnoreCase("x-ms-request-id")) {
                        requestId = h.getValue().trim();
                    }
                } else {
                    wire.debug(h.getName() + ":");
                }
            }
            wire.debug("");
        }
        if (status.getStatusCode() == HttpServletResponse.SC_TEMPORARY_REDIRECT) {
            logger.warn("Expected OK, got " + status.getStatusCode());

            String responseBody = "";

            HttpEntity entity = response.getEntity();

            if (entity == null) {
                throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), "An error was returned without explanation");
            }
            try {
                responseBody = EntityUtils.toString(entity);
            } catch (IOException e) {
                throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), e.getMessage());
            }
            logger.debug(responseBody);
            logger.debug("https: char " + responseBody.indexOf("https://"));
            logger.debug("account number: char " + responseBody.indexOf(account));
            String tempEndpoint = responseBody.substring(responseBody.indexOf("https://"),
                    responseBody.indexOf(account) - responseBody.indexOf("https://"));
            logger.debug("temp redirect location: " + tempEndpoint);
            tempRedirectInvoke(tempEndpoint, method, account, resource, body);
        } else if (status.getStatusCode() != HttpServletResponse.SC_OK
                && status.getStatusCode() != HttpServletResponse.SC_CREATED
                && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) {
            logger.error("post(): Expected OK for GET request, got " + status.getStatusCode());

            HttpEntity entity = response.getEntity();

            if (entity == null) {
                throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), "An error was returned without explanation");
            }
            try {
                body = EntityUtils.toString(entity);
            } catch (IOException e) {
                throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), e.getMessage());
            }
            if (wire.isDebugEnabled()) {
                wire.debug(body);
            }
            wire.debug("");
            AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body);

            if (items == null) {
                throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), "Unknown", "Unknown");
            }
            logger.error("post(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details);
            throw new AzureException(items);
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("exit - " + AzureMethod.class.getName() + ".post()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("POST --------------------------------------------------------> " + endpoint + account
                    + resource);
        }
    }
    return requestId;
}

From source file:de.mendelson.comm.as2.send.MessageHttpUploader.java

/**Uploads the data, returns the HTTP result code*/
public int performUpload(HttpConnectionParameter connectionParameter, AS2Message message, Partner sender,
        Partner receiver, URL receiptURL) {
    String ediintFeatures = "multiple-attachments, CEM";
    //set the http connection/routing/protocol parameter
    HttpParams httpParams = new BasicHttpParams();
    if (connectionParameter.getConnectionTimeoutMillis() != -1) {
        HttpConnectionParams.setConnectionTimeout(httpParams, connectionParameter.getConnectionTimeoutMillis());
    }/*from w w  w .j  a v a 2 s.  co  m*/
    if (connectionParameter.getSoTimeoutMillis() != -1) {
        HttpConnectionParams.setSoTimeout(httpParams, connectionParameter.getSoTimeoutMillis());
    }
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, connectionParameter.isStaleConnectionCheck());
    if (connectionParameter.getHttpProtocolVersion() == null) {
        //default settings: HTTP 1.1
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    } else if (connectionParameter.getHttpProtocolVersion().equals(HttpConnectionParameter.HTTP_1_0)) {
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_0);
    } else if (connectionParameter.getHttpProtocolVersion().equals(HttpConnectionParameter.HTTP_1_1)) {
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    }
    HttpProtocolParams.setUseExpectContinue(httpParams, connectionParameter.isUseExpectContinue());
    HttpProtocolParams.setUserAgent(httpParams, connectionParameter.getUserAgent());
    if (connectionParameter.getLocalAddress() != null) {
        ConnRouteParams.setLocalAddress(httpParams, connectionParameter.getLocalAddress());
    }
    int status = -1;
    HttpPost filePost = null;
    DefaultHttpClient httpClient = null;
    try {
        ClientConnectionManager clientConnectionManager = this.createClientConnectionManager(httpParams);
        httpClient = new DefaultHttpClient(clientConnectionManager, httpParams);
        //some ssl implementations have problems with a session/connection reuse
        httpClient.setReuseStrategy(new NoConnectionReuseStrategy());
        //disable SSL hostname verification. Do not confuse this with SSL trust verification!
        SSLSocketFactory sslFactory = (SSLSocketFactory) httpClient.getConnectionManager().getSchemeRegistry()
                .get("https").getSocketFactory();
        sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        //determine the receipt URL if it is not set
        if (receiptURL == null) {
            //async MDN requested?
            if (message.isMDN()) {
                if (this.runtimeConnection == null) {
                    throw new IllegalArgumentException(
                            "MessageHTTPUploader.performUpload(): A MDN receipt URL is not set, unable to determine where to send the MDN");
                }
                MessageAccessDB messageAccess = new MessageAccessDB(this.configConnection,
                        this.runtimeConnection);
                AS2MessageInfo relatedMessageInfo = messageAccess
                        .getLastMessageEntry(((AS2MDNInfo) message.getAS2Info()).getRelatedMessageId());
                receiptURL = new URL(relatedMessageInfo.getAsyncMDNURL());
            } else {
                receiptURL = new URL(receiver.getURL());
            }
        }
        filePost = new HttpPost(receiptURL.toExternalForm());
        filePost.addHeader("as2-version", "1.2");
        filePost.addHeader("ediint-features", ediintFeatures);
        filePost.addHeader("mime-version", "1.0");
        filePost.addHeader("recipient-address", receiptURL.toExternalForm());
        filePost.addHeader("message-id", "<" + message.getAS2Info().getMessageId() + ">");
        filePost.addHeader("as2-from", AS2Message.escapeFromToHeader(sender.getAS2Identification()));
        filePost.addHeader("as2-to", AS2Message.escapeFromToHeader(receiver.getAS2Identification()));
        String originalFilename = null;
        if (message.getPayloads() != null && message.getPayloads().size() > 0) {
            originalFilename = message.getPayloads().get(0).getOriginalFilename();
        }
        if (originalFilename != null) {
            String subject = this.replace(message.getAS2Info().getSubject(), "${filename}", originalFilename);
            filePost.addHeader("subject", subject);
            //update the message infos subject with the actual content
            if (!message.isMDN()) {
                ((AS2MessageInfo) message.getAS2Info()).setSubject(subject);
                //refresh this in the database if it is requested
                if (this.runtimeConnection != null) {
                    MessageAccessDB access = new MessageAccessDB(this.configConnection, this.runtimeConnection);
                    access.updateSubject((AS2MessageInfo) message.getAS2Info());
                }
            }
        } else {
            filePost.addHeader("subject", message.getAS2Info().getSubject());
        }
        filePost.addHeader("from", sender.getEmail());
        filePost.addHeader("connection", "close, TE");
        //the data header must be always in english locale else there would be special
        //french characters (e.g. 13 dc. 2011 16:28:56 CET) which is not allowed after 
        //RFC 4130           
        DateFormat format = new SimpleDateFormat("EE, dd MMM yyyy HH:mm:ss zz", Locale.US);
        filePost.addHeader("date", format.format(new Date()));
        String contentType = null;
        if (message.getAS2Info().getEncryptionType() != AS2Message.ENCRYPTION_NONE) {
            contentType = "application/pkcs7-mime; smime-type=enveloped-data; name=smime.p7m";
        } else {
            contentType = message.getContentType();
        }
        filePost.addHeader("content-type", contentType);
        //MDN header, this is always the way for async MDNs
        if (message.isMDN()) {
            if (this.logger != null) {
                this.logger.log(Level.INFO,
                        this.rb.getResourceString("sending.mdn.async",
                                new Object[] { message.getAS2Info().getMessageId(), receiptURL }),
                        message.getAS2Info());
            }
            filePost.addHeader("server", message.getAS2Info().getUserAgent());
        } else {
            AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info();
            //outbound AS2/CEM message
            if (messageInfo.requestsSyncMDN()) {
                if (this.logger != null) {
                    if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_CEM) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.cem.sync",
                                        new Object[] { messageInfo.getMessageId(), receiver.getURL() }),
                                messageInfo);
                    } else if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_AS2) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.msg.sync",
                                        new Object[] { messageInfo.getMessageId(), receiver.getURL() }),
                                messageInfo);
                    }
                }
            } else {
                //Message with ASYNC MDN request
                if (this.logger != null) {
                    if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_CEM) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.cem.async", new Object[] {
                                        messageInfo.getMessageId(), receiver.getURL(), sender.getMdnURL() }),
                                messageInfo);
                    } else if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_AS2) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.msg.async", new Object[] {
                                        messageInfo.getMessageId(), receiver.getURL(), sender.getMdnURL() }),
                                messageInfo);
                    }
                }
                //The following header indicates that this requests an asnc MDN.
                //When the header "receipt-delivery-option" is present,
                //the header "disposition-notification-to" serves as a request
                //for an asynchronous MDN.
                //The header "receipt-delivery-option" must always be accompanied by
                //the header "disposition-notification-to".
                //When the header "receipt-delivery-option" is not present and the header
                //"disposition-notification-to" is present, the header "disposition-notification-to"
                //serves as a request for a synchronous MDN.
                filePost.addHeader("receipt-delivery-option", sender.getMdnURL());
            }
            filePost.addHeader("disposition-notification-to", sender.getMdnURL());
            //request a signed MDN if this is set up in the partner configuration
            if (receiver.isSignedMDN()) {
                filePost.addHeader("disposition-notification-options",
                        messageInfo.getDispositionNotificationOptions().getHeaderValue());
            }
            if (messageInfo.getSignType() != AS2Message.SIGNATURE_NONE) {
                filePost.addHeader("content-disposition", "attachment; filename=\"smime.p7m\"");
            } else if (messageInfo.getSignType() == AS2Message.SIGNATURE_NONE
                    && message.getAS2Info().getSignType() == AS2Message.ENCRYPTION_NONE) {
                filePost.addHeader("content-disposition",
                        "attachment; filename=\"" + message.getPayload(0).getOriginalFilename() + "\"");
            }
        }
        int port = receiptURL.getPort();
        if (port == -1) {
            port = receiptURL.getDefaultPort();
        }
        filePost.addHeader("host", receiptURL.getHost() + ":" + port);
        InputStream rawDataInputStream = message.getRawDataInputStream();
        InputStreamEntity postEntity = new InputStreamEntity(rawDataInputStream, message.getRawDataSize());
        postEntity.setContentType(contentType);
        filePost.setEntity(postEntity);
        if (connectionParameter.getProxy() != null) {
            this.setProxyToConnection(httpClient, message, connectionParameter.getProxy());
        }
        this.setHTTPAuthentication(httpClient, receiver, message.getAS2Info().isMDN());
        this.updateUploadHttpHeader(filePost, receiver);
        HttpHost targetHost = new HttpHost(receiptURL.getHost(), receiptURL.getPort(),
                receiptURL.getProtocol());
        BasicHttpContext localcontext = new BasicHttpContext();
        // Generate BASIC scheme object and stick it to the local
        // execution context. Without this a HTTP authentication will not be sent
        BasicScheme basicAuth = new BasicScheme();
        localcontext.setAttribute("preemptive-auth", basicAuth);
        HttpResponse httpResponse = httpClient.execute(targetHost, filePost, localcontext);
        rawDataInputStream.close();
        this.responseData = this.readEntityData(httpResponse);
        if (httpResponse != null) {
            this.responseStatusLine = httpResponse.getStatusLine();
            status = this.responseStatusLine.getStatusCode();
            this.responseHeader = httpResponse.getAllHeaders();
        }
        for (Header singleHeader : filePost.getAllHeaders()) {
            if (singleHeader.getValue() != null) {
                this.requestHeader.setProperty(singleHeader.getName(), singleHeader.getValue());
            }
        }
        //accept all 2xx answers
        //SC_ACCEPTED Status code (202) indicating that a request was accepted for processing, but was not completed.
        //SC_CREATED  Status code (201) indicating the request succeeded and created a new resource on the server.
        //SC_NO_CONTENT Status code (204) indicating that the request succeeded but that there was no new information to return.
        //SC_NON_AUTHORITATIVE_INFORMATION Status code (203) indicating that the meta information presented by the client did not originate from the server.
        //SC_OK Status code (200) indicating the request succeeded normally.
        //SC_RESET_CONTENT Status code (205) indicating that the agent SHOULD reset the document view which caused the request to be sent.
        //SC_PARTIAL_CONTENT Status code (206) indicating that the server has fulfilled the partial GET request for the resource.
        if (status != HttpServletResponse.SC_OK && status != HttpServletResponse.SC_ACCEPTED
                && status != HttpServletResponse.SC_CREATED && status != HttpServletResponse.SC_NO_CONTENT
                && status != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION
                && status != HttpServletResponse.SC_RESET_CONTENT
                && status != HttpServletResponse.SC_PARTIAL_CONTENT) {
            if (this.logger != null) {
                this.logger
                        .severe(this.rb.getResourceString("error.httpupload",
                                new Object[] { message.getAS2Info().getMessageId(),
                                        URLDecoder.decode(
                                                this.responseStatusLine == null ? ""
                                                        : this.responseStatusLine.getReasonPhrase(),
                                                "UTF-8") }));
            }
        }
    } catch (Exception ex) {
        if (this.logger != null) {
            StringBuilder errorMessage = new StringBuilder(message.getAS2Info().getMessageId());
            errorMessage.append(": MessageHTTPUploader.performUpload: [");
            errorMessage.append(ex.getClass().getSimpleName());
            errorMessage.append("]");
            if (ex.getMessage() != null) {
                errorMessage.append(": ").append(ex.getMessage());
            }
            this.logger.log(Level.SEVERE, errorMessage.toString(), message.getAS2Info());
        }
    } finally {
        if (httpClient != null && httpClient.getConnectionManager() != null) {
            //shutdown the HTTPClient to release the resources
            httpClient.getConnectionManager().shutdown();
        }
    }
    return (status);
}

From source file:org.dasein.cloud.azure.AzureStorageMethod.java

public String getBlobProperty(@Nonnull String strMethod, @Nonnull String resource,
        @Nonnull Map<String, String> queries, String body, @Nullable Map<String, String> headerMap,
        boolean authorization, String propertyName) throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("enter - " + AzureStorageMethod.class.getName() + "." + strMethod + "("
                + getStorageAccount() + "," + resource + ")");
    }/*from  w w  w  . j  av  a 2s  . co  m*/
    String endpoint = getStorageEnpoint();

    if (wire.isDebugEnabled()) {
        wire.debug(strMethod + "--------------------------------------------------------> " + endpoint
                + getStorageAccount() + resource);
        wire.debug("");
    }
    try {

        HttpClient client = getClient();

        if (headerMap == null) {
            headerMap = new HashMap<String, String>();
        }

        HttpRequestBase method = getMethod(strMethod, buildUrl(resource, queries), queries, headerMap,
                authorization);

        if (wire.isDebugEnabled()) {
            wire.debug(method.getRequestLine().toString());
            for (Header header : method.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
            if (body != null) {
                wire.debug(body);
                wire.debug("");
            }
        }

        // If it is post or put
        if (method instanceof HttpEntityEnclosingRequestBase) {

            HttpEntityEnclosingRequestBase entityEnclosingMethod = (HttpEntityEnclosingRequestBase) method;

            if (body != null) {
                entityEnclosingMethod.setEntity(new StringEntity(body, "application/xml", "utf-8"));
            }
        }

        HttpResponse response;
        StatusLine status;

        try {
            response = client.execute(method);
            status = response.getStatusLine();
        } catch (IOException e) {
            logger.error("post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
            if (logger.isTraceEnabled()) {
                e.printStackTrace();
            }
            throw new CloudException(e);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("get(): HTTP Status " + status);
        }

        if (wire.isDebugEnabled()) {
            Header[] headers = response.getAllHeaders();
            wire.debug(status.toString());
            for (Header h : headers) {
                if (h.getValue() != null) {
                    wire.debug(h.getName() + ": " + h.getValue().trim());
                } else {
                    wire.debug(h.getName() + ":");
                }
            }
            wire.debug("");
        }
        if (status.getStatusCode() == HttpServletResponse.SC_NOT_FOUND) {
            return null;
        }
        if ((status.getStatusCode() != HttpServletResponse.SC_CREATED
                && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED
                && status.getStatusCode() != HttpServletResponse.SC_OK)
                && status.getStatusCode() != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION) {
            logger.error(
                    strMethod + "(): Expected OK for " + strMethod + "request, got " + status.getStatusCode());

            HttpEntity entity = response.getEntity();
            String result;

            if (entity == null) {
                throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), "An error was returned without explanation");
            }
            try {
                result = EntityUtils.toString(entity);

                int index = result.indexOf("<");
                // The result may not be a stardard xml format
                if (index > 0) {
                    result = result.substring(index);
                }
            } catch (IOException e) {
                throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), e.getMessage());
            }
            if (wire.isDebugEnabled()) {
                wire.debug(result);
            }
            wire.debug("");
            AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), result);
            logger.error(strMethod + "(): [" + status.getStatusCode() + " : " + items.message + "] "
                    + items.details);
            throw new AzureException(items);
        } else {
            Header header = response.getFirstHeader(propertyName);
            if (header != null) {
                return header.getValue();
            } else {
                return null;
            }
        }
    } catch (UnsupportedEncodingException e) {
        throw new CloudException(e);
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("exit - " + AzureMethod.class.getName() + ".getStream()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("--------------------------------------------------------> ");
        }
    }
}

From source file:org.energy_home.jemma.internal.shapi.HapProxy.java

private ContentInstancesBatchResponse postBatchRequest(ContentInstancesBatchRequest batchRequest) {
    ContentInstancesBatchResponse batchResponse = new ContentInstancesBatchResponse();
    List<ContentInstanceItemsStatus> responseStatusList = batchResponse.getContentInstanceItemsStatuses();
    List<ContentInstanceItems> itemsList = batchRequest.getContentInstanceItems();
    for (Iterator iterator = itemsList.iterator(); iterator.hasNext();) {
        ContentInstanceItems contentInstanceItems = (ContentInstanceItems) iterator.next();
        ContentInstanceItemsStatus itemsStatus = new ContentInstanceItemsStatus();
        itemsStatus.setAddressedId(contentInstanceItems.getAddressedId());
        responseStatusList.add(itemsStatus);
        for (Iterator iterator2 = contentInstanceItems.getContentInstances().iterator(); iterator2.hasNext();) {
            ContentInstance ci = (ContentInstance) iterator2.next();
            ContentInstanceItemStatus itemStatus = new ContentInstanceItemStatus();
            itemStatus.setResourceId(new Long(System.currentTimeMillis()));
            itemsStatus.getContentInstanceItemStatuses().add(itemStatus);
            try {
                AHContainerAddress itemContainerAddress = new AHM2MContainerAddress(
                        contentInstanceItems.getAddressedId());
                if (!isValidLocalHagId(itemContainerAddress.getHagId())) {
                    itemStatus.setBatchStatus(HttpServletResponse.SC_NOT_FOUND);
                } else {
                    ci = postContentInstance(itemContainerAddress, ci);
                    if (ci == null)
                        itemStatus.setBatchStatus(HttpServletResponse.SC_NOT_FOUND);
                    else if (ServiceClusterProxy.isAnUnconfirmedCommand(itemContainerAddress))
                        itemStatus.setBatchStatus(HttpServletResponse.SC_ACCEPTED);
                    else
                        itemStatus.setBatchStatus(HttpServletResponse.SC_OK);
                }//from ww w .  jav a  2 s. c o  m
            } catch (Exception e) {
                log.error("", e);
                itemStatus.setBatchStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            }
        }
    }
    return batchResponse;
}

From source file:org.dasein.cloud.rackspace.AbstractMethod.java

protected @Nullable String postString(@Nonnull String authToken, @Nonnull String endpoint,
        @Nonnull String resource, @Nullable String payload) throws CloudException, InternalException {
    Logger std = RackspaceCloud.getLogger(RackspaceCloud.class, "std");
    Logger wire = RackspaceCloud.getLogger(RackspaceCloud.class, "wire");

    if (std.isTraceEnabled()) {
        std.trace("enter - " + AbstractMethod.class.getName() + ".postString(" + authToken + "," + endpoint
                + "," + resource + "," + payload + ")");
    }//from  w w  w. ja va  2 s. c o  m
    if (wire.isDebugEnabled()) {
        wire.debug("---------------------------------------------------------------------------------"
                + endpoint + resource);
        wire.debug("");
    }
    try {
        HttpClient client = getClient();
        HttpPost post = new HttpPost(endpoint + resource);

        post.addHeader("Content-Type", "application/json");
        post.addHeader("X-Auth-Token", authToken);

        if (payload != null) {
            post.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));
        }
        if (wire.isDebugEnabled()) {
            wire.debug(post.getRequestLine().toString());
            for (Header header : post.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
            if (payload != null) {
                wire.debug(payload);
                wire.debug("");
            }
        }
        HttpResponse response;

        try {
            response = client.execute(post);
            if (wire.isDebugEnabled()) {
                wire.debug(response.getStatusLine().toString());
                for (Header header : response.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                wire.debug("");
            }
        } catch (IOException e) {
            std.error("I/O error from server communications: " + e.getMessage());
            e.printStackTrace();
            throw new InternalException(e);
        }
        int code = response.getStatusLine().getStatusCode();

        std.debug("HTTP STATUS: " + code);

        if (code != HttpServletResponse.SC_ACCEPTED && code != HttpServletResponse.SC_NO_CONTENT) {
            std.error("postString(): Expected ACCEPTED for POST request, got " + code);
            HttpEntity entity = response.getEntity();
            String json = null;

            if (entity != null) {
                try {
                    json = EntityUtils.toString(entity);

                    if (wire.isDebugEnabled()) {
                        wire.debug(json);
                        wire.debug("");
                    }
                } catch (IOException e) {
                    throw new CloudException(e);
                }
            }
            RackspaceException.ExceptionItems items = (json == null ? null
                    : RackspaceException.parseException(code, json));

            if (items == null) {
                items = new RackspaceException.ExceptionItems();
                items.code = 404;
                items.type = CloudErrorType.COMMUNICATION;
                items.message = "itemNotFound";
                items.details = "No such object: " + resource;
            }
            std.error("postString(): [" + code + " : " + items.message + "] " + items.details);
            throw new RackspaceException(items);
        } else {
            if (code == HttpServletResponse.SC_ACCEPTED) {
                HttpEntity entity = response.getEntity();
                String json = null;

                if (entity != null) {
                    try {
                        json = EntityUtils.toString(entity);

                        if (wire.isDebugEnabled()) {
                            wire.debug(json);
                            wire.debug("");
                        }
                    } catch (IOException e) {
                        throw new CloudException(e);
                    }
                }
                if (json != null && !json.trim().equals("")) {
                    return json;
                }
            }
            return null;
        }
    } finally {
        if (std.isTraceEnabled()) {
            std.trace("exit - " + AbstractMethod.class.getName() + ".postString()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("---------------------------------------------------------------------------------"
                    + endpoint + resource);
        }
    }
}

From source file:org.dasein.cloud.vcloud.vCloudMethod.java

public @Nullable String delete(@Nonnull String resource, @Nonnull String id)
        throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER: " + vCloudMethod.class.getName() + ".delete(" + resource + "," + id + ")");
    }//www . ja  v  a  2s.c  o  m
    try {
        Org org = authenticate(false);
        String endpoint = toURL(resource, id);
        HttpClient client = null;

        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug(">>> [DELETE (" + (new Date()) + ")] -> " + endpoint
                    + " >--------------------------------------------------------------------------------------");
        }
        try {
            client = getClient(false);
            HttpDelete delete = new HttpDelete(endpoint);

            delete.addHeader("Accept", "application/*+xml;version=" + org.version.version
                    + ",application/*+xml;version=" + org.version.version);
            addAuth(delete, org.token);

            if (wire.isDebugEnabled()) {
                wire.debug(delete.getRequestLine().toString());
                for (Header header : delete.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                wire.debug("");
            }
            HttpResponse response;

            try {
                APITrace.trace(provider, "DELETE " + resource);
                response = client.execute(delete);
                if (wire.isDebugEnabled()) {
                    wire.debug(response.getStatusLine().toString());
                    for (Header header : response.getAllHeaders()) {
                        wire.debug(header.getName() + ": " + header.getValue());
                    }
                    wire.debug("");
                }
            } catch (IOException e) {
                logger.error("I/O error from server communications: " + e.getMessage());
                throw new InternalException(e);
            }
            int code = response.getStatusLine().getStatusCode();

            logger.debug("HTTP STATUS: " + code);

            if (code == HttpServletResponse.SC_UNAUTHORIZED) {
                authenticate(true);
                return delete(resource, id);
            } else if (code != HttpServletResponse.SC_NOT_FOUND && code != HttpServletResponse.SC_NO_CONTENT
                    && code != HttpServletResponse.SC_OK && code != HttpServletResponse.SC_ACCEPTED) {
                logger.error("DELETE request got unexpected " + code);
                String xml = null;

                try {
                    HttpEntity entity = response.getEntity();

                    if (entity != null) {
                        xml = EntityUtils.toString(entity);
                        if (wire.isDebugEnabled()) {
                            wire.debug(xml);
                            wire.debug("");
                        }
                    }
                } catch (IOException e) {
                    logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
                    throw new CloudException(e);
                }

                vCloudException.Data data = null;

                if (xml != null && !xml.equals("")) {
                    Document doc = parseXML(xml);
                    String docElementTagName = doc.getDocumentElement().getTagName();
                    String nsString = "";
                    if (docElementTagName.contains(":"))
                        nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1);
                    NodeList errors = doc.getElementsByTagName(nsString + "Error");

                    if (errors.getLength() > 0) {
                        data = vCloudException.parseException(code, errors.item(0));
                    }
                }
                if (data == null) {
                    throw new vCloudException(CloudErrorType.GENERAL, code,
                            response.getStatusLine().getReasonPhrase(), "No further information");
                }
                logger.error("[" + code + " : " + data.title + "] " + data.description);
                throw new vCloudException(data);
            } else {
                String xml = null;

                try {
                    HttpEntity entity = response.getEntity();

                    if (entity != null) {
                        xml = EntityUtils.toString(entity);
                        if (wire.isDebugEnabled()) {
                            wire.debug(xml);
                            wire.debug("");
                        }
                    }
                } catch (IOException e) {
                    logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
                    throw new CloudException(e);
                }
                return xml;
            }
        } finally {
            if (client != null) {
                client.getConnectionManager().shutdown();
            }
            if (wire.isDebugEnabled()) {
                wire.debug("<<< [DELETE (" + (new Date()) + ")] -> " + endpoint
                        + " <--------------------------------------------------------------------------------------");
                wire.debug("");
            }
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("EXIT: " + vCloudMethod.class.getName() + ".delete()");
        }

    }
}

From source file:org.dasein.cloud.azure.AzureMethod.java

public void tempRedirectInvoke(@Nonnull String tempEndpoint, @Nonnull String method, @Nonnull String account,
        @Nonnull String resource, @Nonnull String body) throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("enter - " + AzureMethod.class.getName() + ".post(" + account + "," + resource + ")");
    }/* w  w  w .j a  va  2 s . co  m*/
    if (wire.isDebugEnabled()) {
        wire.debug("POST --------------------------------------------------------> " + endpoint + account
                + resource);
        wire.debug("");
    }
    try {
        HttpClient client = getClient();
        String url = tempEndpoint + account + resource;

        HttpRequestBase httpMethod = getMethod(method, url);

        //If it is networking configuration services
        if (httpMethod instanceof HttpPut) {
            if (url.endsWith("/services/networking/media")) {
                httpMethod.addHeader("Content-Type", "text/plain");
            } else {
                httpMethod.addHeader("Content-Type", "application/xml;charset=UTF-8");
            }
        } else {
            httpMethod.addHeader("Content-Type", "application/xml;charset=UTF-8");
        }

        //dmayne version is older for anything to do with images and for disk deletion
        if (url.indexOf("/services/images") > -1
                || (httpMethod instanceof HttpDelete && url.indexOf("/services/disks") > -1)) {
            httpMethod.addHeader("x-ms-version", "2012-08-01");
        } else {
            httpMethod.addHeader("x-ms-version", "2012-03-01");
        }
        if (wire.isDebugEnabled()) {
            wire.debug(httpMethod.getRequestLine().toString());
            for (Header header : httpMethod.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
            if (body != null) {
                wire.debug(body);
                wire.debug("");
            }
        }

        if (httpMethod instanceof HttpEntityEnclosingRequestBase) {

            HttpEntityEnclosingRequestBase entityEnclosingMethod = (HttpEntityEnclosingRequestBase) httpMethod;

            if (body != null) {
                try {
                    entityEnclosingMethod.setEntity(new StringEntity(body, "application/xml", "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        HttpResponse response;
        StatusLine status;

        try {
            response = client.execute(httpMethod);
            status = response.getStatusLine();
        } catch (IOException e) {
            logger.error("post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
            if (logger.isTraceEnabled()) {
                e.printStackTrace();
            }
            throw new CloudException(e);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("post(): HTTP Status " + status);
        }
        Header[] headers = response.getAllHeaders();

        if (wire.isDebugEnabled()) {
            wire.debug(status.toString());
            for (Header h : headers) {
                if (h.getValue() != null) {
                    wire.debug(h.getName() + ": " + h.getValue().trim());
                } else {
                    wire.debug(h.getName() + ":");
                }
            }
            wire.debug("");
        }
        if (status.getStatusCode() != HttpServletResponse.SC_OK
                && status.getStatusCode() != HttpServletResponse.SC_CREATED
                && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) {
            logger.error("post(): Expected OK for GET request, got " + status.getStatusCode());

            HttpEntity entity = response.getEntity();

            if (entity == null) {
                throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), "An error was returned without explanation");
            }
            try {
                body = EntityUtils.toString(entity);
            } catch (IOException e) {
                throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), e.getMessage());
            }
            if (wire.isDebugEnabled()) {
                wire.debug(body);
            }
            wire.debug("");
            AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body);

            if (items == null) {
                throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), "Unknown", "Unknown");
            }
            logger.error("post(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details);
            throw new AzureException(items);
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("exit - " + AzureMethod.class.getName() + ".post()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("POST --------------------------------------------------------> " + endpoint + account
                    + resource);
        }
    }
}