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.energy_home.jemma.internal.shapi.M2MLocalService.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   w w w.java  2  s  .co m*/
            } catch (Exception e) {
                LOG.error("Exception on postBatchRequest", e);
                itemStatus.setBatchStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            }
        }
    }
    return batchResponse;
}

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

public void invoke(@Nonnull String strMethod, @Nonnull String resource, @Nonnull Map<String, String> queries,
        @Nullable String body, @Nullable Map<String, String> headerMap, boolean authorization)
        throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("enter - " + AzureStorageMethod.class.getName() + "." + strMethod + "("
                + getStorageAccount() + "," + resource + ")");
    }//w w w.  j av a  2 s  .c om
    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("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_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);
            } 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);

            if (items != null) {
                logger.error(strMethod + "(): [" + status.getStatusCode() + " : " + items.message + "] "
                        + items.details);
                throw new AzureException(items);
            } else {
                throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), "UnknownError",
                        result);
            }
        }
    } 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.dasein.cloud.rackspace.AbstractMethod.java

@SuppressWarnings("unused")
protected @Nullable String postStream(@Nonnull String authToken, @Nonnull String endpoint,
        @Nonnull String resource, @Nullable String md5Hash, @Nullable InputStream stream)
        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() + ".postStream(" + authToken + "," + endpoint
                + "," + resource + "," + md5Hash + ",INPUTSTREAM)");
    }/* w  w w. j  a va2s .  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/octet-stream");
        post.addHeader("X-Auth-Token", authToken);

        post.setEntity(new InputStreamEntity(stream, -1, ContentType.APPLICATION_OCTET_STREAM));

        if (wire.isDebugEnabled()) {
            wire.debug(post.getRequestLine().toString());
            for (Header header : post.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
            wire.debug("--> BINARY DATA <--");
        }
        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);

        String responseHash = null;

        for (Header h : response.getAllHeaders()) {
            if (h.getName().equals("ETag")) {
                responseHash = h.getValue();
            }
        }
        if (responseHash != null && md5Hash != null && !responseHash.equals(md5Hash)) {
            throw new CloudException("MD5 hash values do not match, probably data corruption");
        }
        if (code != HttpServletResponse.SC_ACCEPTED && code != HttpServletResponse.SC_NO_CONTENT) {
            std.error("postStream(): Expected ACCEPTED or NO CONTENT 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("postStream(): [" + code + " : " + items.message + "] " + items.details);
            throw new RackspaceException(items);
        } else {
            wire.debug("");
            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 - " + RackspaceCloud.class.getName() + ".postStream()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("---------------------------------------------------------------------------------"
                    + endpoint + resource);
        }
    }
}

From source file:com.imaginary.home.cloud.CloudTest.java

@Test
public void flipOn() throws Exception {
    HashMap<String, Object> action = new HashMap<String, Object>();

    action.put("action", testCommandId == null ? "flipOn" : "flipOff");
    action.put("arguments", new ArrayList<Map<String, Object>>());

    HttpClient client = getClient();/*from w  w w.j  a v a  2 s . com*/

    HttpPut method = new HttpPut(cloudAPI + "/device/" + testDeviceId);
    long timestamp = System.currentTimeMillis();

    method.addHeader("Content-Type", "application/json");
    method.addHeader("x-imaginary-version", VERSION);
    method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp));
    method.addHeader("x-imaginary-api-key", apiKeyId);
    method.addHeader("x-imaginary-signature", CloudService.sign(apiKeySecret.getBytes("utf-8"),
            "put:/device/" + testDeviceId + ":" + apiKeyId + ":" + timestamp + ":" + VERSION));

    //noinspection deprecation
    method.setEntity(new StringEntity((new JSONObject(action)).toString(), "application/json", "UTF-8"));

    HttpResponse response;
    StatusLine status;

    try {
        response = client.execute(method);
        status = response.getStatusLine();
    } catch (IOException e) {
        e.printStackTrace();
        throw new CommunicationException(e);
    }
    if (status.getStatusCode() == HttpServletResponse.SC_ACCEPTED) {
        String json = EntityUtils.toString(response.getEntity());
        JSONArray cmds = new JSONArray(json);
        JSONObject cmd = cmds.getJSONObject(0);

        String commandId = cmd.getString("commandId");

        out("Total: " + cmds.length());
        out("ID:    " + commandId);
        out("DATA:  " + json);
        Assert.assertNotNull("No commandId was present", commandId);
        if (testCommandId == null) {
            testCommandId = commandId;
        }
    } else {
        Assert.fail("Failed to send flipOn command  (" + status.getStatusCode() + ": "
                + EntityUtils.toString(response.getEntity()));
    }
}

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

protected @Nullable String putHeaders(@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() + ".putHeaders(" + authToken + "," + endpoint
                + "," + resource + "," + customHeaders + ")");
    }//from   w  w w.j av  a 2  s .c o m
    if (wire.isDebugEnabled()) {
        wire.debug("---------------------------------------------------------------------------------"
                + endpoint + resource);
        wire.debug("");
    }
    try {
        HttpClient client = getClient();
        HttpPut put = new HttpPut(endpoint + resource);

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

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

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

        try {
            response = client.execute(put);
            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_CREATED && code != HttpServletResponse.SC_ACCEPTED
                && code != HttpServletResponse.SC_NO_CONTENT) {
            std.error("putString(): Expected CREATED, ACCEPTED, or NO CONTENT for put 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("putString(): [" + code + " : " + items.message + "] " + items.details);
            throw new RackspaceException(items);
        } else {
            if (code == HttpServletResponse.SC_ACCEPTED || code == HttpServletResponse.SC_CREATED) {
                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() + ".putString()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("---------------------------------------------------------------------------------"
                    + endpoint + resource);
        }
    }
}

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

public void putWithFile(@Nonnull String strMethod, @Nonnull String resource, Map<String, String> queries,
        File file, Map<String, String> headerMap, boolean authorization)
        throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("enter - " + AzureStorageMethod.class.getName() + "." + strMethod + "("
                + getStorageAccount() + "," + resource + ")");
    }/*from  ww  w  .ja  v a 2s  .  c o m*/
    String endpoint = getStorageEnpoint();

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

    long begin = System.currentTimeMillis();
    try {

        HttpClient client = getClient();

        String contentLength = null;

        if (file != null) {
            contentLength = String.valueOf(file.length());
        } else {
            contentLength = "0";
        }

        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 (file != null) {
                wire.debug(file);
                wire.debug("");
            }
        }

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

            HttpEntityEnclosingRequestBase entityEnclosingMethod = (HttpEntityEnclosingRequestBase) method;

            if (file != null) {
                entityEnclosingMethod.setEntity(new FileEntity(file, ContentType.APPLICATION_OCTET_STREAM));
            }
        }

        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();
            }

            long end = System.currentTimeMillis();
            logger.debug("Totoal time -> " + (end - begin));
            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_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);
            } 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);
        }
    } 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

protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    String requestUri = servletRequest.getRequestURI();
    initResponse(servletResponse);/*  w w  w  .ja  v  a 2 s  . c o  m*/
    requestUri = replaceFilters(requestUri, false);
    if (requestUri.startsWith(M2MConstants.URL_HAG_SCL_BASE)) {
        try {
            if (requestUri.equals(subscriptionItemsAddressedId)) {
                long now = System.currentTimeMillis();
                Subscription subscription = (Subscription) readXmlObject(servletRequest);
                if (subscription.getId() != null || subscription.getContact() == null) {
                    servletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    for (Iterator iterator = subscriptionInfos.iterator(); iterator.hasNext();) {
                        // Only one subscription for each contact uri is allowed (last subscription overwrite a previous existing one)
                        if (subscription.getContact()
                                .equals(((SubscriptionInfo) iterator.next()).subscription.getContact())) {
                            iterator.remove();
                            break;
                        }
                    }
                    subscription.setCreationTime(now);
                    subscription.setLastModifiedTime(now);
                    subscription.setId(UUID.randomUUID().toString());
                    writeXmlObject(servletResponse, subscription);
                    subscriptionInfos.add(new SubscriptionInfo(subscription));
                }

            } else if (requestUri.endsWith(M2MConstants.URL_CIS_BATCH_REQUEST)) {
                ContentInstancesBatchRequest batchRequest = (ContentInstancesBatchRequest) readXmlObject(
                        servletRequest);
                ContentInstancesBatchResponse batchResponse = postBatchRequest(batchRequest);
                writeXmlObject(servletResponse, batchResponse);
            } else {
                AHContainerAddress containerAddress = new AHM2MContainerAddress(requestUri);
                if (!isValidLocalHagId(containerAddress.getHagId()))
                    servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                String containerName = containerAddress.getContainerName();
                if (containerName != null) {
                    ContentInstance ci = (ContentInstance) readXmlObject(servletRequest);
                    ci = postContentInstance(containerAddress, ci);
                    if (ci == null)
                        servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                    else if (ServiceClusterProxy.isAnUnconfirmedCommand(containerAddress))
                        servletResponse.setStatus(HttpServletResponse.SC_ACCEPTED);
                    else
                        servletResponse.setStatus(HttpServletResponse.SC_OK);
                    writeXmlObject(servletResponse, ci);
                } else {
                    servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                }
            }
            commitApplianceConfigurationUpdates();
        } catch (Exception e) {
            log.error("service: error while parsing local request", e);
            servletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } else {
        servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

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

public void putWithBytes(@Nonnull String strMethod, @Nonnull String resource, Map<String, String> queries,
        byte[] body, Map<String, String> headerMap, boolean authorization)
        throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("enter - " + AzureStorageMethod.class.getName() + "." + strMethod + "("
                + getStorageAccount() + "," + resource + ")");
    }//  w ww.  ja  v a 2s.c o m
    String endpoint = getStorageEnpoint();

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

        HttpClient client = getClient();

        String contentLength = null;
        if (body != null) {
            contentLength = String.valueOf(body.length);
        } else {
            contentLength = "0";
        }

        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 ByteArrayEntity(body));
            }
        }

        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("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_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);
            } 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);
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("exit - " + AzureMethod.class.getName() + ".getStream()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("--------------------------------------------------------> ");
        }
    }
}

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

protected @Nullable String putString(@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() + ".putString(" + authToken + "," + endpoint + ","
                + resource + "," + payload + ")");
    }//from  w  ww.j  a  v a 2s .c  om
    if (wire.isDebugEnabled()) {
        wire.debug("---------------------------------------------------------------------------------"
                + endpoint + resource);
        wire.debug("");
    }
    try {
        HttpClient client = getClient();
        HttpPut put = new HttpPut(endpoint + resource);

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

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

        try {
            response = client.execute(put);
            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_CREATED && code != HttpServletResponse.SC_ACCEPTED
                && code != HttpServletResponse.SC_NO_CONTENT) {
            std.error("putString(): Expected CREATED, ACCEPTED, or NO CONTENT for put 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("putString(): [" + code + " : " + items.message + "] " + items.details);
            throw new RackspaceException(items);
        } else {
            if (code == HttpServletResponse.SC_ACCEPTED || code == HttpServletResponse.SC_CREATED) {
                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() + ".putString()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("---------------------------------------------------------------------------------"
                    + endpoint + resource);
        }
    }
}

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

protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    String requestUri = servletRequest.getRequestURI();
    initResponse(servletResponse);/*from www  .j a  v a 2s .  c  o  m*/
    requestUri = replaceFilters(requestUri, false);
    if (requestUri.startsWith(M2MConstants.URL_HAG_SCL_BASE)) {
        try {
            if (requestUri.equals(subscriptionItemsAddressedId)) {
                long now = System.currentTimeMillis();
                Subscription subscription = (Subscription) readXmlObject(servletRequest);
                if (subscription.getId() != null || subscription.getContact() == null) {
                    servletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    for (Iterator iterator = subscriptionInfos.iterator(); iterator.hasNext();) {
                        // Only one subscription for each contact uri is allowed (last subscription overwrite a previous existing one)
                        if (subscription.getContact()
                                .equals(((SubscriptionInfo) iterator.next()).subscription.getContact())) {
                            iterator.remove();
                            break;
                        }
                    }
                    subscription.setCreationTime(now);
                    subscription.setLastModifiedTime(now);
                    subscription.setId(UUID.randomUUID().toString());
                    writeXmlObject(servletResponse, subscription);
                    subscriptionInfos.add(new SubscriptionInfo(subscription));
                }

            } else if (requestUri.endsWith(M2MConstants.URL_CIS_BATCH_REQUEST)) {
                ContentInstancesBatchRequest batchRequest = (ContentInstancesBatchRequest) readXmlObject(
                        servletRequest);
                ContentInstancesBatchResponse batchResponse = postBatchRequest(batchRequest);
                writeXmlObject(servletResponse, batchResponse);
            } else {
                try {
                    AHContainerAddress containerAddress = new AHM2MContainerAddress(requestUri);
                    if (!isValidLocalHagId(containerAddress.getHagId()))
                        servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                    String containerName = containerAddress.getContainerName();
                    if (containerName != null) {
                        ContentInstance ci = (ContentInstance) readXmlObject(servletRequest);
                        ci = postContentInstance(containerAddress, ci);
                        if (ci == null)
                            servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                        else if (ServiceClusterProxy.isAnUnconfirmedCommand(containerAddress))
                            servletResponse.setStatus(HttpServletResponse.SC_ACCEPTED);
                        else
                            servletResponse.setStatus(HttpServletResponse.SC_OK);
                        writeXmlObject(servletResponse, ci);
                    } else {
                        servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                    }
                } catch (Exception e) {
                    LOG.error("Exception on doPost", e);
                    servletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                }
            }
            commitApplianceConfigurationUpdates();
        } catch (Exception e) {
            LOG.error("service: error while parsing local request", e);
            servletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } else {
        servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}