Example usage for javax.servlet.http HttpServletResponse SC_NO_CONTENT

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

Introduction

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

Prototype

int SC_NO_CONTENT

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

Click Source Link

Document

Status code (204) indicating that the request succeeded but that there was no new information to return.

Usage

From source file:de.iteratec.iteraplan.presentation.dialog.History.HistoryController.java

@ExceptionHandler(IteraplanTechnicalException.class)
public ModelAndView handleException(Throwable ex, HttpServletRequest req, HttpServletResponse resp) {
    ModelAndView mav = new ModelAndView("errorOutsideFlow");
    mav.addObject(Constants.JSP_ATTRIBUTE_EXCEPTION_MESSAGE, ex.getLocalizedMessage());
    LOGGER.error("During history retrieval, an error occurred", ex);
    IteraplanProblemReport.createFromController(ex, req);
    resp.setStatus(HttpServletResponse.SC_NO_CONTENT); // status code 204
    return mav;//ww  w .j  ava 2  s  .c o  m
}

From source file:org.ednovo.gooru.controllers.v2.api.FeedbackRestV2Controller.java

@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_FEEDBACK_DELETE })
@RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
public void deleteFeedback(@PathVariable(value = ID) final String feedbackId, @RequestBody final String data,
        final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final User user = (User) request.getAttribute(Constants.USER);
    this.getFeedbackService().deleteFeedback(feedbackId, user);
    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}

From source file:org.structr.rest.servlet.CsvServlet.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws UnsupportedEncodingException {

    SecurityContext securityContext = null;
    Authenticator authenticator = null;
    Result result = null;/*  w  w  w . j av  a 2 s.co m*/
    Resource resource = null;

    try {

        // isolate request authentication in a transaction
        try (final Tx tx = StructrApp.getInstance().tx()) {
            authenticator = config.getAuthenticator();
            securityContext = authenticator.initializeAndExamineRequest(request, response);
            tx.success();
        }
        final App app = StructrApp.getInstance(securityContext);

        //                      logRequest("GET", request);
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/csv; charset=utf-8");

        // set default value for property view
        propertyView.set(securityContext, defaultPropertyView);

        // evaluate constraints and measure query time
        double queryTimeStart = System.nanoTime();

        // isolate resource authentication
        try (final Tx tx = app.tx()) {

            resource = ResourceHelper.optimizeNestedResourceChain(
                    ResourceHelper.parsePath(securityContext, request, resourceMap, propertyView));
            authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(),
                    propertyView.get(securityContext));

            tx.success();
        }

        try (final Tx tx = app.tx()) {

            String resourceSignature = resource.getResourceSignature();

            // let authenticator examine request again
            authenticator.checkResourceAccess(securityContext, request, resourceSignature,
                    propertyView.get(securityContext));

            // add sorting & paging
            String pageSizeParameter = request.getParameter(JsonRestServlet.REQUEST_PARAMETER_PAGE_SIZE);
            String pageParameter = request.getParameter(JsonRestServlet.REQUEST_PARAMETER_PAGE_NUMBER);
            String offsetId = request.getParameter(JsonRestServlet.REQUEST_PARAMETER_OFFSET_ID);
            String sortOrder = request.getParameter(JsonRestServlet.REQUEST_PARAMETER_SORT_ORDER);
            String sortKeyName = request.getParameter(JsonRestServlet.REQUEST_PARAMETER_SORT_KEY);
            boolean sortDescending = (sortOrder != null && "desc".equals(sortOrder.toLowerCase()));
            int pageSize = Services.parseInt(pageSizeParameter, NodeFactory.DEFAULT_PAGE_SIZE);
            int page = Services.parseInt(pageParameter, NodeFactory.DEFAULT_PAGE);
            PropertyKey sortKey = null;

            // set sort key
            if (sortKeyName != null) {

                Class<? extends GraphObject> type = resource.getEntityClass();

                sortKey = StructrApp.getConfiguration().getPropertyKeyForDatabaseName(type, sortKeyName, false);

            }

            // Should line breaks be removed?
            removeLineBreaks = StringUtils.equals(request.getParameter(REMOVE_LINE_BREAK_PARAM), "1");

            // Should a leading BOM be written?
            writeBom = StringUtils.equals(request.getParameter(WRITE_BOM), "1");

            // do action
            result = resource.doGet(sortKey, sortDescending, pageSize, page, offsetId);

            result.setIsCollection(resource.isCollectionResource());
            result.setIsPrimitiveArray(resource.isPrimitiveArray());

            // Integer rawResultCount = (Integer) Services.getAttribute(NodeFactory.RAW_RESULT_COUNT + Thread.currentThread().getId());
            PagingHelper.addPagingParameter(result, pageSize, page);

            // Services.removeAttribute(NodeFactory.RAW_RESULT_COUNT + Thread.currentThread().getId());
            // timing..
            double queryTimeEnd = System.nanoTime();

            // commit response
            if (result != null) {

                // store property view that will be used to render the results
                result.setPropertyView(propertyView.get(securityContext));

                // allow resource to modify result set
                resource.postProcessResultSet(result);

                DecimalFormat decimalFormat = new DecimalFormat("0.000000000",
                        DecimalFormatSymbols.getInstance(Locale.ENGLISH));

                result.setQueryTime(decimalFormat.format((queryTimeEnd - queryTimeStart) / 1000000000.0));

                Writer writer = response.getWriter();

                if (writeBom) {
                    writeUtf8Bom(writer);
                }

                // gson.toJson(result, writer);
                writeCsv(result, writer, propertyView.get(securityContext));
                response.setStatus(HttpServletResponse.SC_OK);
                writer.flush();
                writer.close();
            } else {

                logger.log(Level.WARNING, "Result was null!");

                int code = HttpServletResponse.SC_NO_CONTENT;

                response.setStatus(code);

                Writer writer = response.getWriter();

                // writer.append(jsonError(code, "Result was null!"));
                writer.flush();
                writer.close();

            }
            tx.success();
        }
    } catch (FrameworkException frameworkException) {

        // set status
        response.setStatus(frameworkException.getStatus());

        // gson.toJson(frameworkException, response.getWriter());
        //                      response.getWriter().println();
        //                      response.getWriter().flush();
        //                      response.getWriter().close();
    } catch (JsonSyntaxException jsex) {

        logger.log(Level.WARNING, "JsonSyntaxException in GET", jsex);

        int code = HttpServletResponse.SC_BAD_REQUEST;

        response.setStatus(code);

        // response.getWriter().append(jsonError(code, "JsonSyntaxException in GET: " + jsex.getMessage()));
    } catch (JsonParseException jpex) {

        logger.log(Level.WARNING, "JsonParseException in GET", jpex);

        int code = HttpServletResponse.SC_BAD_REQUEST;

        response.setStatus(code);

        // response.getWriter().append(jsonError(code, "JsonSyntaxException in GET: " + jpex.getMessage()));
    } catch (Throwable t) {

        logger.log(Level.WARNING, "Exception in GET", t);

        int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;

        response.setStatus(code);

        // response.getWriter().append(jsonError(code, "JsonSyntaxException in GET: " + t.getMessage()));
    }

}

From source file:com.imaginary.home.cloud.api.call.CommandCall.java

@Override
public void put(@Nonnull String requestId, @Nullable String userId, @Nonnull String[] path,
        @Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp,
        @Nonnull Map<String, Object> headers, @Nonnull Map<String, Object> parameters)
        throws RestException, IOException {
    if (userId != null) {
        throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.USER_NOT_ALLOWED,
                "A user cannot update a command state");
    }/*from  w  ww  .ja  v a  2 s .c  om*/
    String commandId = (path.length > 1 ? path[1] : null);

    if (commandId == null) {
        throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_OPERATION,
                "You cannot PUT against the command root");
    }
    try {
        PendingCommand cmd = PendingCommand.getCommand(commandId);

        if (cmd == null) {
            throw new RestException(HttpServletResponse.SC_NOT_FOUND, RestException.NO_SUCH_OBJECT,
                    "No such command: " + commandId);
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
        StringBuilder source = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            source.append(line);
            source.append(" ");
        }
        JSONObject object = new JSONObject(source.toString());
        String action;

        if (object.has("action") && !object.isNull("action")) {
            action = object.getString("action");
        } else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_ACTION,
                    "An invalid action was specified (or not specified) in the PUT");
        }
        if (action.equals("complete")) {
            object = object.getJSONObject("result");
            boolean result = (object.has("result") && object.getBoolean("result"));
            String errorMessage = (object.has("errorMessage") ? object.getString("errorMessage") : null);
            ControllerRelay relay = ControllerRelay.getRelay(cmd.getRelayId());

            cmd.update(PendingCommandState.EXECUTED, result, errorMessage);

            if (relay != null) {
                resp.setHeader("x-imaginary-has-commands", String.valueOf(PendingCommand.hasCommands(relay)));
            }
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_ACTION,
                    "The action " + action + " is not a valid action.");
        }
    } catch (JSONException e) {
        throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_JSON,
                "Invalid JSON in request");
    } catch (PersistenceException e) {
        throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR,
                e.getMessage());
    }

}

From source file:com.basetechnology.s0.agentserver.appserver.HandlePost.java

public boolean handlePost() throws IOException, ServletException, AgentAppServerException, SymbolException,
        RuntimeException, AgentServerException, JSONException, TokenizerException, ParserException {
    // Extract out commonly used info
    String path = httpInfo.path;/*from ww  w.  j a v  a2s  . c o  m*/
    String[] pathParts = httpInfo.pathParts;
    Request request = httpInfo.request;
    HttpServletResponse response = httpInfo.response;
    AgentServer agentServer = httpInfo.agentServer;
    String lcPath = path.toLowerCase();

    if (path.equalsIgnoreCase("/users")) {
        // User can specify parameters in JSON or as query parameters
        // Query overrides JSON if query parameter is non-null
        JSONObject userJson = getJsonRequest(httpInfo);

        String id = request.getParameter("id");
        if (id == null)
            id = userJson.optString("id");
        else
            userJson.put("id", id);
        String password = request.getParameter("password");
        if (password == null)
            password = userJson.optString("password");
        else
            userJson.put("password", password);
        String passwordHint = request.getParameter("password_hint");
        if (passwordHint == null)
            passwordHint = userJson.optString("password_hint");
        else
            userJson.put("password_hint", passwordHint);
        String fullName = request.getParameter("full_name");
        if (fullName == null)
            fullName = userJson.optString("full_name");
        else
            userJson.put("full_name", fullName);
        String displayName = request.getParameter("display_name");
        if (displayName == null)
            displayName = userJson.optString("display_name");
        else
            userJson.put("display_name", displayName);
        String nickName = request.getParameter("nick_name");
        if (nickName == null)
            nickName = userJson.optString("nick_name");
        else
            userJson.put("nick_name", nickName);
        String organization = request.getParameter("organization");
        if (organization == null)
            organization = userJson.optString("organization");
        else
            userJson.put("organization", organization);
        String bio = request.getParameter("bio");
        if (bio == null)
            bio = userJson.optString("bio");
        else
            userJson.put("bio", bio);
        String interests = request.getParameter("interests");
        if (interests == null)
            interests = userJson.optString("interests");
        else
            userJson.put("interests", interests);
        String incognitoString = request.getParameter("incognito");
        boolean incognito = incognitoString != null && (incognitoString.equalsIgnoreCase("true")
                || incognitoString.equalsIgnoreCase("yes") || incognitoString.equalsIgnoreCase("on"));
        if (incognitoString == null)
            incognito = userJson.optBoolean("incognito");
        else
            userJson.put("incognito", incognito ? "true" : false);
        String email = request.getParameter("email");
        if (email == null)
            email = userJson.optString("email");
        else
            userJson.put("email", email);
        String comment = request.getParameter("comment");
        if (comment == null)
            comment = userJson.optString("comment");
        else
            userJson.put("comment", comment);

        if (id == null) {
            throw new AgentAppServerBadRequestException("Missing id query parameter");
        } else if (id.trim().length() == 0) {
            throw new AgentAppServerBadRequestException("Empty id query parameter");
        } else if (id.trim().length() < User.MIN_ID_LENGTH) {
            throw new AgentAppServerBadRequestException("Id must be at least 4 characters");
        } else if (password == null) {
            throw new AgentAppServerBadRequestException("Missing password query parameter");
        } else if (password.trim().length() == 0) {
            throw new AgentAppServerBadRequestException("Empty password query parameter");
        } else if (password.trim().length() < User.MIN_ID_LENGTH) {
            throw new AgentAppServerBadRequestException("Password must be at least 4 characters");
        } else if (agentServer.users.containsKey(id.trim())) {
            throw new AgentAppServerBadRequestException("User with that id already exists");
        } else {
            id = id.trim();
            password = password.trim();
            log.info("Adding new user: " + id);
            Boolean approved = !agentServer.config.getBoolean("admin_approve_user_create");
            User newUser = new User(id, password, passwordHint, fullName, displayName, nickName, organization,
                    bio, interests, email, incognito, comment, approved, true, true, null, null);
            newUser.generateSha();
            agentServer.addUser(newUser);
            response.setStatus(HttpServletResponse.SC_CREATED);
            // TODO: Set Location header with URL
            return true;
        }
    } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-]*/agent_definitions$")) {
        User user = checkUserAccess(true);
        JSONObject agentDefinitionJson = getJsonRequest(httpInfo);

        if (agentDefinitionJson == null)
            throw new AgentAppServerBadRequestException("Invalid agent definition JSON object");

        log.info("Adding new agent definition for user: " + user.id);

        // Parse and add the agent definition
        AgentDefinition agentDefinition = agentServer.addAgentDefinition(user, agentDefinitionJson);

        // Done
        response.setStatus(HttpServletResponse.SC_CREATED);
    } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-]*/agents$")) {
        User user = checkUserAccess(true);
        JSONObject agentInstanceJson = getJsonRequest(httpInfo);

        if (agentInstanceJson == null)
            throw new AgentAppServerBadRequestException("Invalid agent instance JSON object");

        log.info("Adding new agent instance for user: " + user.id);

        // Parse and add the agent instance
        AgentInstance agentInstance = agentServer.addAgentInstance(user, agentInstanceJson);

        // Done
        response.setStatus(HttpServletResponse.SC_CREATED);
    } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-*]*/website_access$")) {
        User user = checkAdminUserAccess();
        JSONObject accessControlsJson = getJsonRequest(httpInfo);

        if (accessControlsJson == null)
            throw new AgentAppServerBadRequestException("Invalid website access JSON object");

        log.info("Adding web site access controls for user: " + user.id);

        // Add the web site access controls for the user
        agentServer.addWebSiteAccessControls(user, accessControlsJson);

        // Done
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else {
        throw new AgentAppServerException(HttpServletResponse.SC_NOT_FOUND,
                "Path does not address any existing object");
    }
    return true;

}

From source file:org.sakaiproject.citation.impl.CitationListAccessServlet.java

protected void handleExportRequest(HttpServletRequest req, HttpServletResponse res, Reference ref,
        String format, String subtype)
        throws EntityNotDefinedException, EntityAccessOverloadException, EntityPermissionException {
    if (!ContentHostingService.allowGetResource(req.getParameter("resourceId"))) {
        String url = (req.getRequestURL()).toString();
        String user = "";
        if (req.getUserPrincipal() != null) {
            user = req.getUserPrincipal().getName();
        }/*from  w  w w  . j  av a2  s.c o m*/
        throw new EntityPermissionException(user, ContentHostingService.EVENT_RESOURCE_READ,
                ref.getReference());
    }

    String fileName = req.getParameter("resourceDisplayName");
    if (fileName == null || fileName.trim().equals("")) {
        fileName = rb.getString("export.default.filename");
    }

    if (org.sakaiproject.citation.api.CitationService.RIS_FORMAT.equals(format)) {
        String citationCollectionId = req.getParameter("citationCollectionId");
        List<String> citationIds = new java.util.ArrayList<String>();
        CitationCollection collection = null;
        try {
            collection = CitationService.getCollection(citationCollectionId);
        } catch (IdUnusedException e) {
            throw new EntityNotDefinedException(ref.getReference());
        }

        // decide whether to export selected or entire list
        if (org.sakaiproject.citation.api.CitationService.REF_TYPE_EXPORT_RIS_SEL.equals(subtype)) {
            // export selected
            String[] paramCitationIds = req.getParameterValues("citationId");

            if (paramCitationIds == null || paramCitationIds.length < 1) {
                // none selected - do not continue
                try {
                    res.sendError(HttpServletResponse.SC_BAD_REQUEST, rb.getString("export.none_selected"));
                } catch (IOException e) {
                    m_log.warn(
                            "export-selected request received with not citations selected. citationCollectionId: "
                                    + citationCollectionId);
                }

                return;
            }
            citationIds.addAll(Arrays.asList(paramCitationIds));

            fileName = rb.getFormattedMessage("export.filename.selected.ris", fileName);
        } else {
            // export all

            // iterate through ids
            List<Citation> citations = collection.getCitations();

            if (citations == null || citations.size() < 1) {
                // no citations to export - do not continue 
                try {
                    res.sendError(HttpServletResponse.SC_NO_CONTENT, rb.getString("export.empty_collection"));
                } catch (IOException e) {
                    m_log.warn(
                            "export-all request received for empty citation collection. citationCollectionId: "
                                    + citationCollectionId);
                }

                return;
            }

            for (Citation citation : citations) {
                citationIds.add(citation.getId());
            }
            fileName = rb.getFormattedMessage("export.filename.all.ris", fileName);
        }

        // We need to write to a temporary stream for better speed, plus
        // so we can get a byte count. Internet Explorer has problems
        // if we don't make the setContentLength() call.
        StringBuilder buffer = new StringBuilder(4096);
        // StringBuilder contentType = new StringBuilder();

        try {
            collection.exportRis(buffer, citationIds);
        } catch (IOException e) {
            throw new EntityAccessOverloadException(ref.getReference());
        }

        // Set the mime type for a RIS file
        res.addHeader("Content-disposition", "attachment; filename=\"" + fileName + "\"");
        //res.addHeader("Content-Disposition", "attachment; filename=\"citations.RIS\"");
        res.setContentType("application/x-Research-Info-Systems");
        res.setContentLength(buffer.length());

        if (buffer.length() > 0) {
            // Increase the buffer size for more speed.
            res.setBufferSize(buffer.length());
        }

        OutputStream out = null;
        try {
            out = res.getOutputStream();
            if (buffer.length() > 0) {
                out.write(buffer.toString().getBytes());
            }
            out.flush();
            out.close();
        } catch (Throwable ignore) {
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Throwable ignore) {
                }
            }
        }

    }

}

From source file:org.dasein.cloud.aws.platform.CloudFrontMethod.java

CloudFrontResponse invoke(String... args) throws CloudFrontException, CloudException, InternalException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new InternalException("Context not specified for this request");
    }//from www.  ja  va 2 s.  c  o  m
    StringBuilder url = new StringBuilder();
    String dateString = getDate();
    HttpRequestBase method;
    HttpClient client;

    url.append(CLOUD_FRONT_URL + "/" + CF_VERSION + "/distribution");
    if (args != null && args.length > 0) {
        for (String arg : args) {
            url.append("/");
            url.append(arg);
        }
    }
    method = action.getMethod(url.toString());
    method.addHeader(AWSCloud.P_AWS_DATE, dateString);
    try {
        String signature = provider.signCloudFront(new String(ctx.getAccessPublic(), "utf-8"),
                ctx.getAccessPrivate(), dateString);

        method.addHeader(AWSCloud.P_CFAUTH, signature);
    } catch (UnsupportedEncodingException e) {
        logger.error(e);
        e.printStackTrace();
        throw new InternalException(e);
    }
    if (headers != null) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            method.addHeader(entry.getKey(), entry.getValue());
        }
    }
    if (body != null) {
        try {
            ((HttpEntityEnclosingRequestBase) method)
                    .setEntity(new StringEntity(body, "application/xml", "utf-8"));
        } catch (UnsupportedEncodingException e) {
            throw new InternalException(e);
        }
    }
    attempts++;
    client = getClient(url.toString());
    CloudFrontResponse response = new CloudFrontResponse();

    HttpResponse httpResponse;
    int status;

    try {
        APITrace.trace(provider, action.toString());
        httpResponse = client.execute(method);
        status = httpResponse.getStatusLine().getStatusCode();

    } catch (IOException e) {
        logger.error(e);
        e.printStackTrace();
        throw new InternalException(e);
    }
    Header header = httpResponse.getFirstHeader("ETag");

    if (header != null) {
        response.etag = header.getValue();
    } else {
        response.etag = null;
    }
    if (status == HttpServletResponse.SC_OK || status == HttpServletResponse.SC_CREATED
            || status == HttpServletResponse.SC_ACCEPTED) {
        try {
            HttpEntity entity = httpResponse.getEntity();

            if (entity == null) {
                throw new CloudFrontException(status, null, null, "NoResponse",
                        "No response body was specified");
            }
            InputStream input;

            try {
                input = entity.getContent();
            } catch (IOException e) {
                throw new CloudException(e);
            }
            try {
                response.document = parseResponse(input);
                return response;
            } finally {
                input.close();
            }
        } catch (IOException e) {
            logger.error(e);
            e.printStackTrace();
            throw new CloudException(e);
        }
    } else if (status == HttpServletResponse.SC_NO_CONTENT) {
        return null;
    } else {
        if (status == HttpServletResponse.SC_SERVICE_UNAVAILABLE
                || status == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) {
            if (attempts >= 5) {
                String msg;

                if (status == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {
                    msg = "Cloud service is currently unavailable.";
                } else {
                    msg = "The cloud service encountered a server error while processing your request.";
                }
                logger.error(msg);
                throw new CloudException(msg);
            } else {
                try {
                    Thread.sleep(5000L);
                } catch (InterruptedException ignore) {
                }
                return invoke(args);
            }
        }
        try {
            HttpEntity entity = httpResponse.getEntity();

            if (entity == null) {
                throw new CloudFrontException(status, null, null, "NoResponse",
                        "No response body was specified");
            }
            InputStream input;

            try {
                input = entity.getContent();
            } catch (IOException e) {
                throw new CloudException(e);
            }
            Document doc;

            try {
                doc = parseResponse(input);
            } finally {
                input.close();
            }
            if (doc != null) {
                String code = null, message = null, requestId = null, type = null;
                NodeList blocks = doc.getElementsByTagName("Error");

                if (blocks.getLength() > 0) {
                    Node error = blocks.item(0);
                    NodeList attrs;

                    attrs = error.getChildNodes();
                    for (int i = 0; i < attrs.getLength(); i++) {
                        Node attr = attrs.item(i);

                        if (attr.getNodeName().equals("Code")) {
                            code = attr.getFirstChild().getNodeValue().trim();
                        } else if (attr.getNodeName().equals("Type")) {
                            type = attr.getFirstChild().getNodeValue().trim();
                        } else if (attr.getNodeName().equals("Message")) {
                            message = attr.getFirstChild().getNodeValue().trim();
                        }
                    }

                }
                blocks = doc.getElementsByTagName("RequestId");
                if (blocks.getLength() > 0) {
                    Node id = blocks.item(0);

                    requestId = id.getFirstChild().getNodeValue().trim();
                }
                if (message == null) {
                    throw new CloudException(
                            "Unable to identify error condition: " + status + "/" + requestId + "/" + code);
                }
                throw new CloudFrontException(status, requestId, type, code, message);
            }
            throw new CloudException("Unable to parse error.");
        } catch (IOException e) {
            logger.error(e);
            e.printStackTrace();
            throw new CloudException(e);
        }
    }
}

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

/**Returns the created header for the sent data*/
public Properties upload(HttpConnectionParameter connectionParameter, AS2Message message, Partner sender,
        Partner receiver) throws Exception {
    NumberFormat formatter = new DecimalFormat("0.00");
    AS2Info as2Info = message.getAS2Info();
    MessageAccessDB messageAccess = null;
    MDNAccessDB mdnAccess = null;//from w  w w. j av a 2  s.  com
    if (this.runtimeConnection != null && messageAccess == null && !as2Info.isMDN()) {
        messageAccess = new MessageAccessDB(this.configConnection, this.runtimeConnection);
        messageAccess.initializeOrUpdateMessage((AS2MessageInfo) as2Info);
    } else if (this.runtimeConnection != null && as2Info.isMDN()) {
        mdnAccess = new MDNAccessDB(this.configConnection, this.runtimeConnection);
        mdnAccess.initializeOrUpdateMDN((AS2MDNInfo) as2Info);
    }
    if (this.clientserver != null) {
        this.clientserver.broadcastToClients(new RefreshClientMessageOverviewList());
    }
    long startTime = System.currentTimeMillis();
    //sets the global requestHeader
    int returnCode = this.performUpload(connectionParameter, message, sender, receiver);
    long size = message.getRawDataSize();
    long transferTime = System.currentTimeMillis() - startTime;
    float bytePerSec = (float) ((float) size * 1000f / (float) transferTime);
    float kbPerSec = (float) (bytePerSec / 1024f);
    if (returnCode == HttpServletResponse.SC_OK) {
        if (this.logger != null) {
            this.logger.log(Level.INFO,
                    this.rb.getResourceString("returncode.ok",
                            new Object[] { as2Info.getMessageId(), String.valueOf(returnCode),
                                    AS2Tools.getDataSizeDisplay(size), AS2Tools.getTimeDisplay(transferTime),
                                    formatter.format(kbPerSec), }),
                    as2Info);
        }
    } else if (returnCode == HttpServletResponse.SC_ACCEPTED || returnCode == HttpServletResponse.SC_CREATED
            || returnCode == HttpServletResponse.SC_NO_CONTENT
            || returnCode == HttpServletResponse.SC_RESET_CONTENT
            || returnCode == HttpServletResponse.SC_PARTIAL_CONTENT) {
        if (this.logger != null) {
            this.logger.log(Level.INFO,
                    this.rb.getResourceString("returncode.accepted",
                            new Object[] { as2Info.getMessageId(), String.valueOf(returnCode),
                                    AS2Tools.getDataSizeDisplay(size), AS2Tools.getTimeDisplay(transferTime),
                                    formatter.format(kbPerSec), }),
                    as2Info);
        }
    } else {
        //the system was unable to connect the partner
        if (returnCode < 0) {
            throw new NoConnectionException(
                    this.rb.getResourceString("error.noconnection", as2Info.getMessageId()));
        }
        if (this.runtimeConnection != null) {
            if (messageAccess == null) {
                messageAccess = new MessageAccessDB(this.configConnection, this.runtimeConnection);
            }
            messageAccess.setMessageState(as2Info.getMessageId(), AS2Message.STATE_STOPPED);
        }
        throw new Exception(as2Info.getMessageId() + ": HTTP " + returnCode);
    }
    if (this.configConnection != null) {
        //inc the sent data size, this is for new connections (as2 messages, async mdn)
        AS2Server.incRawSentData(size);
        if (message.getAS2Info().isMDN()) {
            AS2MDNInfo mdnInfo = (AS2MDNInfo) message.getAS2Info();
            //ASYNC MDN sent: insert an entry into the statistic table
            QuotaAccessDB.incReceivedMessages(this.configConnection, this.runtimeConnection,
                    mdnInfo.getSenderId(), mdnInfo.getReceiverId(), mdnInfo.getState(),
                    mdnInfo.getRelatedMessageId());
        }
    }
    if (this.configConnection != null) {
        MessageStoreHandler messageStoreHandler = new MessageStoreHandler(this.configConnection,
                this.runtimeConnection);
        messageStoreHandler.storeSentMessage(message, sender, receiver, this.requestHeader);
    }
    //inform the server of the result if a sync MDN has been requested
    if (!message.isMDN()) {
        AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info();
        if (messageInfo.requestsSyncMDN()) {
            //perform a check if the answer really contains a MDN or is just an empty HTTP 200 with some header data
            //this check looks for the existance of some key header values
            boolean as2FromExists = false;
            boolean as2ToExists = false;
            for (int i = 0; i < this.getResponseHeader().length; i++) {
                String key = this.getResponseHeader()[i].getName();
                if (key.toLowerCase().equals("as2-to")) {
                    as2ToExists = true;
                } else if (key.toLowerCase().equals("as2-from")) {
                    as2FromExists = true;
                }
            }
            if (!as2ToExists) {
                throw new Exception(this.rb.getResourceString("answer.no.sync.mdn",
                        new Object[] { as2Info.getMessageId(), "as2-to" }));
            }
            //send the data to the as2 server. It does not care if the MDN has been sync or async anymore
            GenericClient client = new GenericClient();
            CommandObjectIncomingMessage commandObject = new CommandObjectIncomingMessage();
            //create temporary file to store the data
            File tempFile = AS2Tools.createTempFile("SYNCMDN_received", ".bin");
            FileOutputStream outStream = new FileOutputStream(tempFile);
            ByteArrayInputStream memIn = new ByteArrayInputStream(this.responseData);
            this.copyStreams(memIn, outStream);
            memIn.close();
            outStream.flush();
            outStream.close();
            commandObject.setMessageDataFilename(tempFile.getAbsolutePath());
            for (int i = 0; i < this.getResponseHeader().length; i++) {
                String key = this.getResponseHeader()[i].getName();
                String value = this.getResponseHeader()[i].getValue();
                commandObject.addHeader(key.toLowerCase(), value);
                if (key.toLowerCase().equals("content-type")) {
                    commandObject.setContentType(value);
                }
            }
            //compatibility issue: some AS2 systems do not send a as2-from in the sync case, even if
            //this if _NOT_ RFC conform
            //see RFC 4130, section 6.2: The AS2-To and AS2-From header fields MUST be
            //present in all AS2 messages and AS2 MDNs whether asynchronous or synchronous in nature,
            //except for asynchronous MDNs, which are sent using SMTP.
            if (!as2FromExists) {
                commandObject.addHeader("as2-from",
                        AS2Message.escapeFromToHeader(receiver.getAS2Identification()));
            }
            ErrorObject errorObject = client.send(commandObject);
            if (errorObject.getErrors() > 0) {
                messageAccess.setMessageState(as2Info.getMessageId(), AS2Message.STATE_STOPPED);
            }
            tempFile.delete();
        }
    }
    return (this.requestHeader);
}

From source file:org.cruxframework.crux.core.server.rest.spi.HttpUtil.java

public static void writeResponse(HttpRequest request, HttpResponse response, MethodReturn methodReturn)
        throws IOException {
    HttpServletResponseHeaders outputHeaders = response.getOutputHeaders();
    if (methodReturn == null) {
        response.sendEmptyResponse();// w w  w.j  a va  2  s . co m
    } else if (methodReturn.getCheckedExceptionData() != null) {
        response.sendError(HttpResponseCodes.SC_FORBIDDEN, methodReturn.getCheckedExceptionData());
    } else if (!methodReturn.hasReturnType()) {
        response.setContentLength(0);
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else if (methodReturn.getConditionalResponse() != null) {
        writeConditionalResponse(response, methodReturn, outputHeaders);
    } else {
        CacheInfo cacheInfo = methodReturn.getCacheInfo();
        if (cacheInfo != null) {
            writeCacheHeaders(response, cacheInfo, methodReturn.getEtag(), methodReturn.getDateModified(),
                    methodReturn.isEtagGenerationEnabled());
        }

        String responseContent = methodReturn.getReturn();
        byte[] responseBytes = getResponseBytes(request, response, responseContent);
        response.setContentLength(responseBytes.length);
        response.setStatus(HttpServletResponse.SC_OK);
        outputHeaders.putSingle(HttpHeaderNames.CONTENT_TYPE, new MediaType("application", "json", "UTF-8"));
        response.getOutputStream().write(responseBytes);
    }
}

From source file:org.ednovo.gooru.controllers.v2.api.OAuthRestV2Controller.java

@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_OAUTH_DELETE })
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
@RequestMapping(method = { RequestMethod.DELETE }, value = "/{id}")
public void deleteOAuthClientByOAuthKey(@PathVariable(value = ID) String oauthKey, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    User apiCaller = (User) request.getAttribute(Constants.USER);
    this.getOAuthService().deleteOAuthClientByOAuthKey(oauthKey, apiCaller);
    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}