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.apache.hadoop.hbase.rest.Status.java

public void setAccepted() {
    this.statusCode = HttpServletResponse.SC_ACCEPTED;
    this.message = new StatusMessage(HttpServletResponse.SC_ACCEPTED, false, "success");
}

From source file:org.alfresco.rest.api.tests.TestDownloads.java

/**
 * Tests the creation of download nodes.
 *
 * <p>POST:</p>/* www . ja v  a 2  s. c o m*/
 * {@literal <host>:<port>/alfresco/api/-default-/private/alfresco/versions/1/downloads}
 *
 */
@Test
public void test001CreateDownload() throws Exception {
    //test creating a download with a single file
    Download download = createDownload(HttpServletResponse.SC_ACCEPTED, zippableDocId1);

    assertPendingDownloadProps(download);

    assertValidZipNodeid(download);

    assertDoneDownload(download, 1, 13);

    //test creating a multiple file archive
    download = createDownload(HttpServletResponse.SC_ACCEPTED, zippableDocId1, zippableDocId2);

    assertPendingDownloadProps(download);

    assertValidZipNodeid(download);

    assertDoneDownload(download, 2, 26);

    //test creating a zero file archive
    createDownload(HttpServletResponse.SC_BAD_REQUEST);

    //test creating an archive with the same file twice
    download = createDownload(HttpServletResponse.SC_BAD_REQUEST, zippableDocId1, zippableDocId1);

    //test creating an archive with a folder and a file which is contained in the folder
    download = createDownload(HttpServletResponse.SC_ACCEPTED, zippableFolderId1, zippableDocId3_InFolder1);

    assertPendingDownloadProps(download);

    assertValidZipNodeid(download);

    assertDoneDownload(download, 3, 39);

    //test creating an archive with a file and a folder containing that file but only as a secondary parent child association
    download = createDownload(HttpServletResponse.SC_ACCEPTED, zippableDocId1, zippableFolderId3);

    assertPendingDownloadProps(download);

    assertValidZipNodeid(download);

    assertDoneDownload(download, 2, 26);

    //test creating an archive with two files, one of which user1 does not have permissions for
    download = createDownload(HttpServletResponse.SC_FORBIDDEN, zippableDocId1, zippableDoc_user2);
}

From source file:org.apache.axis2.transport.http.AxisServlet.java

/**
 * Implementaion of POST interface// w ww .  jav a2s .  co  m
 *
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //set the initial buffer for a larger value
    response.setBufferSize(BUFFER_SIZE);

    preprocessRequest(request);

    MessageContext msgContext;
    OutputStream out = response.getOutputStream();
    String contentType = request.getContentType();
    if (!HTTPTransportUtils.isRESTRequest(contentType)) {
        msgContext = createMessageContext(request, response);
        msgContext.setProperty(Constants.Configuration.CONTENT_TYPE, contentType);
        try {
            // adding ServletContext into msgContext;
            String url = request.getRequestURL().toString();

            OutputStream bufferedOut = new BufferedOutputStream(out);

            InvocationResponse pi = HTTPTransportUtils.processHTTPPostRequest(msgContext,
                    new BufferedInputStream(request.getInputStream()), bufferedOut, contentType,
                    request.getHeader(HTTPConstants.HEADER_SOAP_ACTION), url);

            Boolean holdResponse = (Boolean) msgContext.getProperty(RequestResponseTransport.HOLD_RESPONSE);

            if (pi.equals(InvocationResponse.SUSPEND)
                    || (holdResponse != null && Boolean.TRUE.equals(holdResponse))) {
                ((RequestResponseTransport) msgContext.getProperty(RequestResponseTransport.TRANSPORT_CONTROL))
                        .awaitResponse();
            }

            // if data has not been sent back and this is not a signal response
            if (!TransportUtils.isResponseWritten(msgContext) && (((RequestResponseTransport) msgContext
                    .getProperty(RequestResponseTransport.TRANSPORT_CONTROL))
                            .getStatus() != RequestResponseTransport.RequestResponseTransportStatus.SIGNALLED)) {
                response.setStatus(HttpServletResponse.SC_ACCEPTED);
                // only set contentType in this scenario, not if response already set
                log.debug("Response not written. Setting response contentType to text/xml; " + "charset="
                        + msgContext.getProperty(Constants.Configuration.CHARACTER_SET_ENCODING));
                response.setContentType("text/xml; charset="
                        + msgContext.getProperty(Constants.Configuration.CHARACTER_SET_ENCODING));
            }

            // Make sure that no data remains in the BufferedOutputStream even if the message
            // formatter doesn't call flush
            bufferedOut.flush();

        } catch (AxisFault e) {
            setResponseState(msgContext, response);
            log.debug(e);
            if (msgContext != null) {
                processAxisFault(msgContext, response, out, e);
            } else {
                throw new ServletException(e);
            }
        } catch (Throwable t) {
            log.error(t.getMessage(), t);
            try {
                // If the fault is not going along the back channel we should be 202ing
                if (AddressingHelper.isFaultRedirected(msgContext)) {
                    response.setStatus(HttpServletResponse.SC_ACCEPTED);
                } else {
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

                    AxisBindingOperation axisBindingOperation = (AxisBindingOperation) msgContext
                            .getProperty(Constants.AXIS_BINDING_OPERATION);
                    if (axisBindingOperation != null) {
                        AxisBindingMessage axisBindingMessage = axisBindingOperation
                                .getFault((String) msgContext.getProperty(Constants.FAULT_NAME));
                        if (axisBindingMessage != null) {
                            Integer code = (Integer) axisBindingMessage
                                    .getProperty(WSDL2Constants.ATTR_WHTTP_CODE);
                            if (code != null) {
                                response.setStatus(code.intValue());
                            }
                        }
                    }
                }
                handleFault(msgContext, out, new AxisFault(t.toString(), t));
            } catch (AxisFault e2) {
                log.info(e2);
                throw new ServletException(e2);
            }
        } finally {
            closeStaxBuilder(msgContext);
            TransportUtils.deleteAttachments(msgContext);
        }
    } else {
        if (!disableREST) {
            new RestRequestProcessor(Constants.Configuration.HTTP_METHOD_POST, request, response)
                    .processXMLRequest();
        } else {
            showRestDisabledErrorMessage(response);
        }
    }
}

From source file:com.enjoyxstudy.selenium.autoexec.CommandHandler.java

/**
 * run async command.//from   ww w .ja  v  a2s. co m
 *
 * @param type
 * @param response
 * @throws IOException
 */
private void commandRunAsync(String type, HttpResponse response) throws IOException {

    if (autoExecServer.getStatus() == AutoExecServer.STATUS_IDLE) {
        // idle
        new Thread(new Runnable() {
            public void run() {
                try {
                    autoExecServer.process();
                } catch (Exception e) {
                    log.error("Error exec process.", e);
                }
            }
        }).start();

        response.setStatus(HttpServletResponse.SC_ACCEPTED);
        resultToResponse(response, SUCCESS, type);

    } else {
        // running
        response.setStatus(HttpServletResponse.SC_CONFLICT);
        resultToResponse(response, DUPLICATE, type);
    }
}

From source file:org.clothocad.phagebook.controllers.AutoCompleteController.java

@RequestMapping(value = "/autoCompleteVendors", method = RequestMethod.GET)
protected void autoCompleteVendors(@RequestParam Map<String, String> params, HttpServletResponse response)
        throws ServletException, IOException {
    //I WILL RETURN THE MAP AS A JSON OBJECT.. it is client side's issue to parse all data for what they need!
    //they could check over there if the schema matches what they are querying for and so i can do this generically!
    //user should be logged in so I will log in as that user.

    String name = params.get("name") != null ? params.get("name") : "";
    boolean isValid = false;
    System.out.println("Name is: " + name);
    if (!name.equals("")) {
        isValid = true;/*from  w  w  w  .ja  v a  2 s  . c  om*/
    }

    if (isValid) {
        ClothoConnection conn = new ClothoConnection(Args.clothoLocation);
        Clotho clothoObject = new Clotho(conn);
        //TODO: we need to have an authentication token at some point

        String username = this.backendPhagebookUser;
        String password = this.backendPhagebookPassword;
        Map loginMap = new HashMap();
        loginMap.put("username", username);
        loginMap.put("credentials", password);

        clothoObject.login(loginMap);
        Map query = new HashMap();

        query.put("query", name); // the value for which we are querying.
        query.put("key", "name"); // the key of the object we are querying

        List<Vendor> vendors = ClothoAdapter.queryVendor(query, clothoObject,
                ClothoAdapter.QueryMode.STARTSWITH);
        org.json.JSONArray responseArray = new org.json.JSONArray();
        for (Vendor vend : vendors) {
            JSONObject obj = new JSONObject();
            obj.put("id", vend.getId());
            obj.put("name", vend.getName());
            responseArray.put(obj);
        }

        response.setStatus(HttpServletResponse.SC_ACCEPTED);
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        out.print(responseArray);
        out.flush();
        out.close();

        clothoObject.logout();
        conn.closeConnection();

    }
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    response.setContentType("application/json");
    JSONObject reply = new JSONObject();
    reply.put("message", "Auto Complete requires a query parameter");
    PrintWriter out = response.getWriter();
    out.print(reply);
    out.flush();
    out.close();
}

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 w  ww.  j  a  v a 2 s .co  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:org.alfresco.rest.api.tests.TestDownloads.java

/**
  * Tests retrieving info about a download node
  */*from  w  ww . ja  v a  2 s  .c  o m*/
  * <p>GET:</p>
  * {@literal <host>:<port>/alfresco/api/-default-/private/alfresco/versions/1/downloads/<download_id>}
  *
  */
@Test
public void test002GetDownloadInfo() throws Exception {
    Download download = createDownload(HttpServletResponse.SC_ACCEPTED, zippableFolderId1,
            zippableFolderId2_InFolder1, zippableDocId4_InFolder2);

    //test retrieving information about an ongoing download
    assertInProgressDownload(download, 4, 52);

    //test retrieving information about a finished download
    assertDoneDownload(download, 4, 52);

    //test retrieving the status of a cancelled download
    cancelWithRetry(() -> {
        Download downloadToBeCancelled = createDownload(HttpServletResponse.SC_ACCEPTED, zippableFolderId1,
                zippableDocId3_InFolder1);
        cancel(downloadToBeCancelled.getId());
        assertCancelledDownload(downloadToBeCancelled, 3, 39);
    });
}

From source file:org.jahia.modules.userregistration.actions.NewReservation.java

public ActionResult doExecute(HttpServletRequest req, RenderContext renderContext, final Resource resource,
        JCRSessionWrapper session, final Map<String, List<String>> parameters, URLResolver urlResolver)
        throws Exception {
    final HttpServletRequest requ = req;
    final String nom = getParameter(parameters, "nom");
    final String prenom = getParameter(parameters, "prenom");
    final String adresse = getParameter(parameters, "adresse");
    final String codePostal = getParameter(parameters, "codePostal");
    final String ville = getParameter(parameters, "ville");
    final String telephone = getParameter(parameters, "telephone");
    final String email = getParameter(parameters, "email");
    final String places = getParameter(parameters, "places");

    if (StringUtils.isEmpty(nom) || StringUtils.isEmpty(prenom) || StringUtils.isEmpty(adresse)
            || StringUtils.isEmpty(email)) {
        return ActionResult.BAD_REQUEST;
    }//  w ww.j  av a 2  s  .co  m
    /*
     * final Properties properties = new Properties();
     * properties.put("j:email",parameters.get("desired_email").get(0));
     * properties.put("j:firstName",parameters.get("desired_firstname").get(
     * 0));
     * properties.put("j:lastName",parameters.get("desired_lastname").get(0)
     * ); for (Map.Entry<String, List<String>> param :
     * parameters.entrySet()) { if (param.getKey().startsWith("j:")) {
     * String value = getParameter(parameters, param.getKey()); if (value !=
     * null) { properties.put(param.getKey(), value); } } }
     */
    JCRTemplate.getInstance().doExecuteWithSystemSession(new JCRCallback<Boolean>() {
        @Override
        public Boolean doInJCR(JCRSessionWrapper session) throws RepositoryException {

            // final JCRUserNode user =
            // userManagerService.createUser(username, password, properties,
            // session);
            // session.save();
            JCRNodeWrapper reservationFolder = session.getNode("/sites/LARBRE/contents/reservations");
            JCRNodeWrapper emailFolder;
            if (reservationFolder.hasNode(email))
                emailFolder = reservationFolder.getNode(email);
            else
                emailFolder = reservationFolder.addNode(email, "jnt:contentFolder");
            session.save();
            String key = generateKey(email);
            JCRNodeWrapper uneReservation = emailFolder.addNode(key, "jnt:uneReservation");
            uneReservation.setProperty("nom", nom);
            uneReservation.setProperty("prenom", prenom);
            uneReservation.setProperty("adresse", adresse);
            uneReservation.setProperty("codePostal", codePostal);
            uneReservation.setProperty("ville", ville);
            uneReservation.setProperty("telephone", telephone);
            uneReservation.setProperty("email", email);
            uneReservation.setProperty("places", places);
            session.save();
            if (mailService.isEnabled()) {
                // Prepare mail to be sent :
                boolean toAdministratorMail = Boolean
                        .valueOf(getParameter(parameters, "toAdministrator", "false"));
                String cc = toAdministratorMail ? mailService.getSettings().getTo()
                        : getParameter(parameters, "cc");
                String from = cc;
                logger.info("send copie to :" + cc);
                //String cc = parameters.get("cc") == null ? null : getParameter(parameters, "cc");
                String bcc = parameters.get("bcc") == null ? null : getParameter(parameters, "bcc");

                Map<String, Object> bindings = new HashMap<String, Object>();
                final JCRNodeWrapper node = resource.getNode();
                logger.info("********Node :" + node.getName());
                logger.info("Template path:" + templatePath);
                bindings.put("reservation", uneReservation);
                bindings.put("confirmationlink",
                        requ.getScheme() + "://" + requ.getServerName() + ":" + requ.getServerPort()
                                + Jahia.getContextPath() + Render.getRenderServletPath() + "/live/"
                                + node.getLanguage() + node.getPath() + ".confirmationReservation.do?email="
                                + email + "&key=" + key + "&copie=" + cc + "&confirmationPage="
                                + parameters.get("confirmationReservationPage").get(0));

                try {
                    mailService.sendMessageWithTemplate(templatePath, bindings, email, from, cc, bcc,
                            resource.getLocale(), "Jahia User Registration");
                } catch (ScriptException e) {
                    logger.error("Error sending e-mail notification for user creation", e);
                }
            }

            return true;
        }
    });

    return new ActionResult(HttpServletResponse.SC_ACCEPTED, parameters.get("newReservationPage").get(0),
            new JSONObject());
}

From source file:org.appcelerator.transport.UploadTransportServlet.java

@Override
@SuppressWarnings("unchecked")
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getMethod().equalsIgnoreCase("POST")) {
        // paranoia check -we don't accept urlencoded transfers which are very bad performance wise
        if (false == ServletFileUpload.isMultipartContent(request)) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "must be 'multipart/form-data'");
            return;
        }//from  www. ja va2 s  .c  o m

        String type = null;
        String callback = null;
        long size = 0L;
        // String instanceid = null;
        IMessageDataObject data = MessageUtils.createMessageDataObject();

        try {
            ServletFileUpload upload = new ServletFileUpload(fileFactory);
            List items = upload.parseRequest(request);
            for (Iterator i = items.iterator(); i.hasNext();) {
                FileItem item = (FileItem) i.next();
                if (item.isFormField()) {
                    if (item.getFieldName().equals("callback")) {
                        callback = item.getString();
                        continue;
                    } else if (item.getFieldName().equals("type")) {
                        type = item.getString();
                        continue;
                    } else if (item.getFieldName().equals("instanceid")) {
                        //instanceid = item.getString();
                        continue;
                    }
                    // place it in the data payload
                    data.put(item.getFieldName(), item.getString());
                } else {
                    File f = null;
                    if (tempDirectory != null) {
                        f = File.createTempFile("sup", ".tmp", tempDirectory);
                    } else {
                        f = File.createTempFile("sup", ".tmp");
                    }

                    f.deleteOnExit();

                    // write out the temporary file
                    item.write(f);

                    size = item.getSize();

                    IMessageDataObject filedata = MessageUtils.createMessageDataObject();

                    filedata.put("file", f.getAbsolutePath());
                    filedata.put("size", size);
                    filedata.put("contentType", item.getContentType());
                    filedata.put("fieldName", item.getFieldName());
                    filedata.put("fileName", item.getName());

                    data.put("filedata", filedata);
                }
            }

            // required parameter type
            if (type == null || type.equals("")) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "missing 'type' parameter");
                return;
            }
        } catch (Throwable fe) {
            fe.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fe.getMessage());
            return;
        }

        String scope = request.getParameter("scope");
        String version = request.getParameter("version");

        if (scope == null) {
            scope = "appcelerator";
        }
        if (version == null) {
            version = "1.0";
        }

        // create a message
        Message msg = new Message();
        msg.setUser(request.getUserPrincipal());
        msg.setSession(request.getSession());
        msg.setServletRequest(request);
        msg.setType(type);
        msg.setData(data);
        msg.setAddress(InetAddress.getByName(request.getRemoteAddr()));
        msg.setScope(scope);
        msg.setVersion(version);

        // send the data
        ArrayList<Message> responses = new ArrayList<Message>();
        try {
            ServiceRegistry.dispatch(msg, responses);
        } catch (Exception ex) {
            LOG.error("error dispatching upload message: " + msg, ex);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
        response.setDateHeader("Expires", System.currentTimeMillis() - TimeUtil.ONE_YEAR);
        response.setContentType("text/html;charset=UTF-8");

        // optionally, invoke a callback function/message on upload in the client
        if (callback != null || !responses.isEmpty()) {
            StringBuilder code = new StringBuilder();
            code.append("<html><head><script>");

            if (callback != null) {
                if (callback.startsWith("l:") || callback.startsWith("local:") || callback.startsWith("r:")
                        || callback.startsWith("remote:")) {
                    code.append(makeMessage(callback, "{size:" + size + "}", scope, version));
                } else {
                    // a javascript function to call
                    code.append("window.parent.").append(callback).append("();");
                }
            }

            for (Message m : responses) {
                code.append(makeMessage(m.getType(), m.getData().toDataString(), m.getScope(), m.getVersion()));
            }

            code.append("</script></head><body></body></html>");

            // send the response
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().print(code.toString());
        } else {
            response.setStatus(HttpServletResponse.SC_ACCEPTED);
        }
    } else {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "method was: " + request.getMethod());
    }
}

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 a  v a 2  s  .c o  m*/
    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);
}