Example usage for javax.servlet.http HttpServletResponse SC_CREATED

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

Introduction

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

Prototype

int SC_CREATED

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

Click Source Link

Document

Status code (201) indicating the request succeeded and created a new resource on the server.

Usage

From source file:com.lp.webapp.cc.CCOrderResponseServlet.java

private int getHttpStatusforEjbStatus(CreateOrderResult result) {
    if (Helper.isOneOf(result.getRc(),
            new int[] { CreateOrderResult.ERROR_EMPTY_ORDER, CreateOrderResult.ERROR_JAXB_EXCEPTION,
                    CreateOrderResult.ERROR_SAX_EXCEPTION, CreateOrderResult.ERROR_UNMARSHALLING })) {
        return HttpServletResponse.SC_BAD_REQUEST;
    }/* w  ww  . jav a  2s.c o  m*/

    if (result.getRc() == CreateOrderResult.ERROR_AUTHENTIFICATION) {
        return HttpServletResponse.SC_FORBIDDEN;
    }

    if (result.getRc() == CreateOrderResult.ERROR_CUSTOMER_NOT_FOUND) {
        return HttpServletResponse.SC_NOT_FOUND;
    }

    if (result.getRc() >= CreateOrderResult.ERROR_EJB_EXCEPTION) {
        return HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    if (result.getRc() == BaseRequestResult.OKAY) {
        return HttpServletResponse.SC_CREATED;
    }

    return HttpServletResponse.SC_EXPECTATION_FAILED;
}

From source file:org.opencastproject.staticfiles.endpoint.StaticFileRestService.java

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)/*w ww . j  a va2 s  . com*/
@Path("")
@RestQuery(name = "postStaticFile", description = "Post a new static resource", bodyParameter = @RestParameter(description = "The static resource file", isRequired = true, name = "BODY", type = RestParameter.Type.FILE), reponses = {
        @RestResponse(description = "Returns the id of the uploaded static resource", responseCode = HttpServletResponse.SC_CREATED),
        @RestResponse(description = "No filename or file to upload found", responseCode = HttpServletResponse.SC_BAD_REQUEST),
        @RestResponse(description = "The upload size is too big", responseCode = HttpServletResponse.SC_BAD_REQUEST) }, returnDescription = "")
public Response postStaticFile(@Context HttpServletRequest request) {
    if (maxUploadSize > 0 && request.getContentLength() > maxUploadSize) {
        logger.warn("Preventing upload of static file as its size {} is larger than the max size allowed {}",
                request.getContentLength(), maxUploadSize);
        return Response.status(Status.BAD_REQUEST).build();
    }
    ProgressInputStream inputStream = null;
    try {
        String filename = null;
        if (ServletFileUpload.isMultipartContent(request)) {
            boolean isDone = false;
            for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext();) {
                FileItemStream item = iter.next();
                if (item.isFormField()) {
                    continue;
                } else {
                    logger.debug("Processing file item");
                    filename = item.getName();
                    inputStream = new ProgressInputStream(item.openStream());
                    inputStream.addPropertyChangeListener(new PropertyChangeListener() {
                        @Override
                        public void propertyChange(PropertyChangeEvent evt) {
                            long totalNumBytesRead = (Long) evt.getNewValue();
                            if (totalNumBytesRead > maxUploadSize) {
                                logger.warn("Upload limit of {} bytes reached, returning a bad request.",
                                        maxUploadSize);
                                throw new WebApplicationException(Status.BAD_REQUEST);
                            }
                        }
                    });
                    isDone = true;
                }
                if (isDone)
                    break;
            }
        } else {
            logger.warn("Request is not multi part request, returning a bad request.");
            return Response.status(Status.BAD_REQUEST).build();
        }

        if (filename == null) {
            logger.warn("Request was missing the filename, returning a bad request.");
            return Response.status(Status.BAD_REQUEST).build();
        }

        if (inputStream == null) {
            logger.warn("Request was missing the file, returning a bad request.");
            return Response.status(Status.BAD_REQUEST).build();
        }

        String uuid = staticFileService.storeFile(filename, inputStream);
        try {
            return Response.created(getStaticFileURL(uuid)).entity(uuid).build();
        } catch (NotFoundException e) {
            logger.error("Previous stored file with uuid {} couldn't beren found: {}", uuid,
                    ExceptionUtils.getStackTrace(e));
            return Response.serverError().build();
        }
    } catch (WebApplicationException e) {
        return e.getResponse();
    } catch (Exception e) {
        logger.error("Unable to store file because: {}", ExceptionUtils.getStackTrace(e));
        return Response.serverError().build();
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:jp.or.openid.eiwg.scim.servlet.Users.java

/**
 * POST?//from  w  w w  .  j  a  va  2 s. c o m
 *
 * @param request 
 * @param response ?
 * @throws ServletException
 * @throws IOException
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ?
    ServletContext context = getServletContext();

    // ??
    Operation op = new Operation();
    boolean result = op.Authentication(context, request);

    if (!result) {
        // 
        errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
    } else {
        // ?
        String targetId = request.getPathInfo();
        String attributes = request.getParameter("attributes");

        if (targetId != null && !targetId.isEmpty()) {
            // ?'/'???
            targetId = targetId.substring(1);
        }

        if (targetId == null || targetId.isEmpty()) {
            // POST(JSON)?
            request.setCharacterEncoding("UTF-8");
            String body = IOUtils.toString(request.getReader());

            // ?
            LinkedHashMap<String, Object> resultObject = op.createUserInfo(context, request, attributes, body);
            if (resultObject != null) {
                // javaJSON??
                ObjectMapper mapper = new ObjectMapper();
                StringWriter writer = new StringWriter();
                mapper.writeValue(writer, resultObject);

                // Location?URL?
                String location = request.getScheme() + "://" + request.getServerName();
                int serverPort = request.getServerPort();
                if (serverPort != 80 && serverPort != 443) {
                    location += ":" + Integer.toString(serverPort);
                }
                location += request.getContextPath();
                location += "/scim/Users/";
                if (resultObject.get("id") != null) {
                    location += resultObject.get("id").toString();
                }

                // ??
                response.setStatus(HttpServletResponse.SC_CREATED);
                response.setContentType("application/scim+json;charset=UTF-8");
                response.setHeader("Location", location);

                PrintWriter out = response.getWriter();
                out.println(writer.toString());
            } else {
                // 
                errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
            }
        } else {
            errorResponse(response, HttpServletResponse.SC_BAD_REQUEST, null,
                    MessageConstants.ERROR_NOT_SUPPORT_OPERATION);
        }
    }
}

From source file:com.sun.faban.harness.webclient.RunUploader.java

/**
 * Post method to upload the run.//ww w. ja va  2  s  .co  m
 * @param request The servlet request
 * @param response The servlet response
 * @throws ServletException If the servlet fails
 * @throws IOException If there is an I/O error
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String host = null;
    String key = null;
    boolean origin = false; // Whether the upload is to the original
    // run requestor. If so, key is needed.

    DiskFileUpload fu = new DiskFileUpload();
    // No maximum size
    fu.setSizeMax(-1);
    // maximum size that will be stored in memory
    fu.setSizeThreshold(4096);
    // the location for saving data that is larger than getSizeThreshold()
    fu.setRepositoryPath(Config.TMP_DIR);

    List fileItems = null;
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        throw new ServletException(e);
    }
    // assume we know there are two files. The first file is a small
    // text file, the second is unknown and is written to a file on
    // the server
    for (Iterator i = fileItems.iterator(); i.hasNext();) {
        FileItem item = (FileItem) i.next();
        String fieldName = item.getFieldName();
        if (item.isFormField()) {
            if ("host".equals(fieldName)) {
                host = item.getString();
            } else if ("key".equals(fieldName)) {
                key = item.getString();
            } else if ("origin".equals(fieldName)) {
                String value = item.getString();
                origin = Boolean.parseBoolean(value);
            }
            continue;
        }

        if (host == null) {
            logger.warning("Host not received on upload request!");
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            break;
        }

        // The host, origin, key info must be here before we receive
        // any file.
        if (origin) {
            if (Config.daemonMode != Config.DaemonModes.POLLEE) {
                logger.warning("Origin upload requested. Not pollee!");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                break;
            }
            if (key == null) {
                logger.warning("Origin upload requested. No key!");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                break;
            }
            if (!RunRetriever.authenticate(host, key)) {
                logger.warning("Origin upload requested. " + "Host/key mismatch: " + host + '/' + key + "!");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                break;
            }
        }

        if (!"jarfile".equals(fieldName)) // ignore
            continue;

        String fileName = item.getName();

        if (fileName == null) // We don't process files without names
            continue;

        // Now, this name may have a path attached, dependent on the
        // source browser. We need to cover all possible clients...
        char[] pathSeparators = { '/', '\\' };
        // Well, if there is another separator we did not account for,
        // just add it above.

        for (int j = 0; j < pathSeparators.length; j++) {
            int idx = fileName.lastIndexOf(pathSeparators[j]);
            if (idx != -1) {
                fileName = fileName.substring(idx + 1);
                break;
            }
        }

        // Ignore all non-jarfiles.
        if (!fileName.toLowerCase().endsWith(".jar"))
            continue;
        File uploadFile = new File(Config.TMP_DIR, host + '.' + fileName);
        try {
            item.write(uploadFile);
        } catch (Exception e) {
            throw new ServletException(e);
        }
        File runTmp = unjarTmp(uploadFile);

        String runId = null;

        if (origin) {
            // Change origin file to know where this run came from.
            File metaInf = new File(runTmp, "META-INF");
            File originFile = new File(metaInf, "origin");
            if (!originFile.exists()) {
                logger.warning("Origin upload requested. Origin file" + "does not exist!");
                response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Origin file does not exist!");
                break;
            }

            RunId origRun;
            try {
                origRun = new RunId(readStringFromFile(originFile).trim());
            } catch (IndexOutOfBoundsException e) {
                response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
                        "Origin file error. " + e.getMessage());
                break;
            }

            runId = origRun.getBenchName() + '.' + origRun.getRunSeq();
            String localHost = origRun.getHostName();
            if (!localHost.equals(Config.FABAN_HOST)) {
                logger.warning("Origin upload requested. Origin host " + localHost
                        + " does not match this host " + Config.FABAN_HOST + '!');
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                break;
            }
            writeStringToFile(runTmp.getName(), originFile);
        } else {
            runId = runTmp.getName();
        }

        if (recursiveCopy(runTmp, new File(Config.OUT_DIR, runId))) {
            uploadFile.delete();
            recursiveDelete(runTmp);
        } else {
            logger.warning("Origin upload requested. Copy error!");
            response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE);
            break;
        }

        response.setStatus(HttpServletResponse.SC_CREATED);
        break;
    }
}

From source file:org.egov.restapi.web.rest.ContractorController.java

@RequestMapping(value = "/egworks/contractor", method = PUT, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
public String updateContractor(@RequestBody final String requestJson, final HttpServletResponse response)
        throws IOException {
    List<RestErrors> errors = new ArrayList<>();
    final RestErrors restErrors = new RestErrors();
    ApplicationThreadLocals.setUserId(2L);
    if (StringUtils.isBlank(requestJson)) {
        restErrors.setErrorCode(RestApiConstants.THIRD_PARTY_ERR_CODE_NO_JSON_REQUEST);
        restErrors.setErrorMessage(RestApiConstants.THIRD_PARTY_ERR_MSG_NO_JSON_REQUEST);
        errors.add(restErrors);//from  w  ww  .j  a v  a  2 s.  c o m
        return JsonConvertor.convert(restErrors);
    }
    final ContractorHelper contractorHelper = (ContractorHelper) getObjectFromJSONRequest(requestJson,
            ContractorHelper.class);
    errors = externalContractorService.validateContactorToUpdate(contractorHelper);
    if (!errors.isEmpty()) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return JsonConvertor.convert(errors);
    } else {
        final Contractor contractor = externalContractorService.populateContractorToUpdate(contractorHelper);
        final Contractor savedContractor = externalContractorService.updateContractor(contractor);
        final StringBuilder modifyMessage = new StringBuilder();
        modifyMessage.append("Contractor data modified successfully with code ")
                .append(savedContractor.getCode());
        response.setStatus(HttpServletResponse.SC_CREATED);
        return JsonConvertor.convert(modifyMessage);
    }
}

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

@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_APPLICATION_ADD })
@RequestMapping(method = RequestMethod.POST, value = "/{id}/item")
public ModelAndView createApplicationItem(@PathVariable(value = ID) String apiKey, @RequestBody String data,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    User user = (User) request.getAttribute(Constants.USER);
    ActionResponseDTO<ApplicationItem> responseDTO = getApplicationService()
            .createApplicationItem(buildApplicationItemFromInputParameters(data), apiKey, user);
    if (responseDTO.getErrors().getErrorCount() > 0) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else {//from  www .  j  a v a  2  s  . c  om
        response.setStatus(HttpServletResponse.SC_CREATED);
    }
    String includes[] = (String[]) ArrayUtils.addAll(APPLICATION_ITEM_INCLUDES, ERROR_INCLUDE);
    return toModelAndViewWithIoFilter(responseDTO.getModelData(), RESPONSE_FORMAT_JSON, EXCLUDE_ALL, true,
            includes);
}

From source file:org.eclipse.orion.server.git.servlets.GitConfigHandlerV1.java

private boolean handlePost(HttpServletRequest request, HttpServletResponse response, String path)
        throws CoreException, IOException, JSONException, ServletException, URISyntaxException,
        ConfigInvalidException {// w w w .j  av  a2 s.  com
    Path p = new Path(path);
    if (p.segment(0).equals(Clone.RESOURCE) && p.segment(1).equals("file")) { //$NON-NLS-1$
        // expected path /gitapi/config/clone/file/{path}
        File gitDir = GitUtils.getGitDir(p.removeFirstSegments(1));
        if (gitDir == null)
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND,
                            NLS.bind("No repository found under {0}", p.removeFirstSegments(1)), null));
        Repository db = FileRepositoryBuilder.create(gitDir);
        URI cloneLocation = BaseToCloneConverter.getCloneLocation(getURI(request), BaseToCloneConverter.CONFIG);
        JSONObject toPost = OrionServlet.readJSONRequest(request);
        String key = toPost.optString(GitConstants.KEY_CONFIG_ENTRY_KEY, null);
        if (key == null || key.isEmpty())
            return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                    HttpServletResponse.SC_BAD_REQUEST, "Config entry key must be provided", null));
        String value = toPost.optString(GitConstants.KEY_CONFIG_ENTRY_VALUE, null);
        if (value == null || value.isEmpty())
            return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                    HttpServletResponse.SC_BAD_REQUEST, "Config entry value must be provided", null));
        try {
            ConfigOption configOption = new ConfigOption(cloneLocation, db, key);
            boolean present = configOption.exists();
            if (present)
                return statusHandler.handleRequest(request, response,
                        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_CONFLICT,
                                NLS.bind("Config entry for {0} already exists", key), null));
            save(configOption, value);

            JSONObject result = configOption.toJSON();
            OrionServlet.writeJSONResponse(request, response, result);
            response.setHeader(ProtocolConstants.HEADER_LOCATION,
                    result.getString(ProtocolConstants.KEY_LOCATION));
            response.setStatus(HttpServletResponse.SC_CREATED);
            return true;
        } catch (IllegalArgumentException e) {
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, e.getMessage(), e));
        }
    }
    return false;
}

From source file:au.org.ala.biocache.web.AssertionController.java

/**
 * add an assertion/* w w  w .java 2  s .  c  o  m*/
 */
@RequestMapping(value = { "/occurrences/{recordUuid}/assertions/add" }, method = RequestMethod.POST)
public void addAssertion(@PathVariable(value = "recordUuid") String recordUuid, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String code = request.getParameter("code");
    String comment = request.getParameter("comment");
    String userId = request.getParameter("userId");
    String userDisplayName = request.getParameter("userDisplayName");
    String apiKey = request.getParameter("apiKey");

    if (shouldPerformOperation(apiKey, response)) {
        try {
            logger.debug("Adding assertion to:" + recordUuid + ", code:" + code + ", comment:" + comment
                    + ", userId:" + userId + ", userDisplayName:" + userDisplayName);

            QualityAssertion qa = au.org.ala.biocache.model.QualityAssertion.apply(Integer.parseInt(code));
            qa.setComment(comment);
            qa.setUserId(userId);
            qa.setUserDisplayName(userDisplayName);

            Store.addUserAssertion(recordUuid, qa);
            //NC 2013-07-25 No need to post a notification to the collectory the biocache service is queried for the annotations required by the notification service
            //                if(qa.getUuid() != null) {
            //                    //send this assertion addition event to the notification service
            //                    postNotificationEvent("create", recordUuid, qa.getUuid());
            //                }

            String server = request.getSession().getServletContext().getInitParameter("serverName");
            response.setHeader("Location",
                    server + "/occurrences/" + recordUuid + "/assertions/" + qa.getUuid());
            response.setStatus(HttpServletResponse.SC_CREATED);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    }
}

From source file:org.waveprotocol.box.server.rpc.AttachmentServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Process only multipart requests.
    if (ServletFileUpload.isMultipartContent(request)) {
        // Create a factory for disk-based file items.
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler.
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request.
        try {//from   w w  w  . jav a  2s. co  m
            @SuppressWarnings("unchecked")
            List<FileItem> items = upload.parseRequest(request);
            AttachmentId id = null;
            String waveRefStr = null;
            FileItem fileItem = null;
            for (FileItem item : items) {
                // Process only file upload - discard other form item types.
                if (item.isFormField()) {
                    if (item.getFieldName().equals("attachmentId")) {
                        id = AttachmentId.deserialise(item.getString());
                    }
                    if (item.getFieldName().equals("waveRef")) {
                        waveRefStr = item.getString();
                    }
                } else {
                    fileItem = item;
                }
            }

            if (id == null) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No attachment Id in the request.");
                return;
            }
            if (waveRefStr == null) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No wave reference in request.");
                return;
            }

            WaveletName waveletName = AttachmentUtil.waveRef2WaveletName(waveRefStr);
            ParticipantId user = sessionManager.getLoggedInUser(request.getSession(false));
            boolean isAuthorized = waveletProvider.checkAccessPermission(waveletName, user);
            if (!isAuthorized) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }

            // Get only the file name not whole path.
            if (fileItem != null && fileItem.getName() != null) {
                String fileName = FilenameUtils.getName(fileItem.getName());
                service.storeAttachment(id, fileItem.getInputStream(), waveletName, fileName, user);
                response.setStatus(HttpServletResponse.SC_CREATED);
                String msg = String.format("The file with name: %s and id: %s was created successfully.",
                        fileName, id);
                LOG.fine(msg);
                response.getWriter().print("OK");
                response.flushBuffer();
            }
        } catch (Exception e) {
            LOG.severe("Upload error", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while upload the file : " + e.getMessage());
        }
    } else {
        LOG.severe("Request contents type is not supported by the servlet.");
        response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

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

private void setActionResponseStatus(HttpServletResponse response, ActionResponseDTO<?> responseData) {
    response.setStatus((responseData.getErrors().hasErrors()) ? HttpServletResponse.SC_BAD_REQUEST
            : HttpServletResponse.SC_CREATED);
}