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:nl.lumc.nanopub.store.api.NanopubControllerIntegrationTest.java

@DirtiesContext
@Test/*from   w ww . j a v  a  2 s. co m*/
public void testStoreNanopub()
        throws MalformedNanopubException, OpenRDFException, IOException, NanopubDaoException, Exception {

    MockHttpServletRequest request;
    MockHttpServletResponse response;

    String nanopub = getNanopubAsString("example");
    String contentType = "application/x-trig";

    request = new MockHttpServletRequest();
    request.setContentType(contentType);
    response = new MockHttpServletResponse();

    request.setMethod("POST");
    request.setRequestURI("/nanopubs/");
    request.setContent(nanopub.getBytes());
    Object handler;

    handler = handlerMapping.getHandler(request).getHandler();
    handlerAdapter.handle(request, response, handler);

    assertEquals(HttpServletResponse.SC_CREATED, response.getStatus());
    assertNotNull(response.getHeaderValue("Location"));
    assertNotNull(response.getHeaderValue("Content-Type"));
}

From source file:edu.iastate.airl.semtus.server.UploadServiceController.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {

        // 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 {//  w  ww  .  j av a 2s .  co  m
            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                // process only file upload - discard other form item types
                if (item.isFormField())
                    continue;

                String fileName = item.getName();
                // get only the file name not whole path
                if (fileName != null) {
                    fileName = FilenameUtils.getName(fileName);
                }

                File uploadedFile = new File(Utils.UPLOAD_DIRECTORY, fileName);

                // first clean-up the folder; we want no clutter on the server :-)
                String[] ls = new File(Utils.UPLOAD_DIRECTORY).list();

                for (int idx = 0; idx < ls.length; idx++) {

                    File file = new File(Utils.UPLOAD_DIRECTORY, ls[idx]);
                    file.delete();
                }

                if (uploadedFile.createNewFile()) {

                    item.write(uploadedFile);
                    resp.setStatus(HttpServletResponse.SC_CREATED);
                    resp.getWriter().print("The file was created successfully.");
                    resp.flushBuffer();

                } else {

                    throw new IOException("The file already exists in repository.");
                }
            }
        } catch (Exception e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while creating the file : " + e.getMessage());
        }

    } else {
        resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

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

@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_COMMENT_ADD })
@RequestMapping(value = "", method = RequestMethod.POST)
public ModelAndView createComment(@RequestBody final String data, final HttpServletRequest request,
        final HttpServletResponse response) {
    final User user = (User) request.getAttribute(Constants.USER);

    final ActionResponseDTO<Comment> comment = getCommentService()
            .createComment(this.buildCommentFromInputParameters(data), user);
    if (comment.getErrors().getErrorCount() > ZERO) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else {//from   ww  w.  j  a v  a 2  s  .  c o m
        response.setStatus(HttpServletResponse.SC_CREATED);
    }
    final String includes[] = (String[]) ArrayUtils.addAll(COMMENT_INCLUDES, ERROR_INCLUDE);
    return toModelAndViewWithIoFilter(comment.getModelData(), RESPONSE_FORMAT_JSON, EXCLUDE_ALL, true,
            includes);
}

From source file:org.ednovo.gooru.controllers.v1.api.TaxonomyCourseRestController.java

@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_COURSE_ADD })
@RequestMapping(method = RequestMethod.POST)
public ModelAndView createCourse(@RequestBody String data, HttpServletRequest request,
        HttpServletResponse response) {//from  w  ww . j a v  a  2s.  c  o  m
    final User user = (User) request.getAttribute(Constants.USER);
    ActionResponseDTO<TaxonomyCourse> responseDTO = getTaxonomyCourseService()
            .createTaxonomyCourse(buildCourseFromInputParameters(data), user);
    if (responseDTO.getErrors().getErrorCount() > 0) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else {
        response.setStatus(HttpServletResponse.SC_CREATED);
        responseDTO.getModel().setUri(RequestMappingUri.TAXONOMY_COURSE + RequestMappingUri.SEPARATOR
                + responseDTO.getModel().getCourseId());
    }
    String includes[] = (String[]) ArrayUtils.addAll(CREATE_INCLUDES, ERROR_INCLUDE);
    return toModelAndViewWithIoFilter(responseDTO.getModelData(), RESPONSE_FORMAT_JSON, EXCLUDE_ALL, true,
            includes);
}

From source file:com.thinkberg.webdav.CopyMoveBase.java

/**
 * Handle a COPY or MOVE request.//from ww  w .  j  a  v  a  2 s  . c o  m
 *
 * @param request  the servlet request
 * @param response the servlet response
 * @throws IOException if there is an error executing this request
 */
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    boolean overwrite = getOverwrite(request);
    FileObject object = VFSBackend.resolveFile(request.getPathInfo());
    FileObject targetObject = getDestination(request);

    try {
        final LockManager lockManager = LockManager.getInstance();
        LockManager.EvaluationResult evaluation = lockManager.evaluateCondition(targetObject, getIf(request));
        if (!evaluation.result) {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }
        if ("MOVE".equals(request.getMethod())) {
            evaluation = lockManager.evaluateCondition(object, getIf(request));
            if (!evaluation.result) {
                response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return;
            }
        }
    } catch (LockException e) {
        response.sendError(SC_LOCKED);
        return;
    } catch (ParseException e) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    if (null == targetObject) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    if (object.equals(targetObject)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    if (targetObject.exists()) {
        if (!overwrite) {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else {
        FileObject targetParent = targetObject.getParent();
        if (!targetParent.exists() || !FileType.FOLDER.equals(targetParent.getType())) {
            response.sendError(HttpServletResponse.SC_CONFLICT);
        }
        response.setStatus(HttpServletResponse.SC_CREATED);
    }

    // delegate the actual execution to a sub class
    copyOrMove(object, targetObject, getDepth(request));
}

From source file:nl.fontys.fhict.jea.gwt.jee7.server.bus.FileUploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    System.out.println("working?");
    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {

        // 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 ww  .  j  ava2  s.c  o  m
            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                // process only file upload - discard other form item types
                if (item.isFormField()) {
                    continue;
                }

                String fileName = item.getName();
                // get only the file name not whole path
                if (fileName != null) {
                    fileName = FilenameUtils.getName(fileName);
                }

                File uploadedFile = new File(UPLOAD_DIRECTORY, fileName);
                uploadedFile.delete();
                if (uploadedFile.createNewFile()) {
                    item.write(uploadedFile);
                } else {
                    throw new IOException("The file already exists in repository.");
                }

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                BufferedImage in = ImageIO.read(uploadedFile);
                try {
                    ImageIO.write(in, "png", baos);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String imageString = "data:image/png;base64,"
                        + DatatypeConverter.printBase64Binary(baos.toByteArray());
                serviceBean.setPicture(req.getRemoteUser(), imageString);

                resp.setStatus(HttpServletResponse.SC_CREATED);
                resp.setContentType("image/png");
                resp.getWriter().print(imageString);
                resp.flushBuffer();

            }
        } catch (Exception e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while creating the file : " + e.getMessage());
        }

    } else {
        resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

From source file:org.wiredwidgets.cow.server.web.TasksController.java

/**
 * Create a new ad-hoc task, i.e. one not associated with any process
 * instance Note: ad-hoc tasks are considered experimental and may not
 * function as expected in all cases. The HTTP response Location header
 * provides the URL of the new task./*  w w  w. j  ava2 s.c om*/
 *
 * @param task a task object in XML sent as the request body
 * @param request
 * @param response
 */
@RequestMapping(method = RequestMethod.POST)
public void createTask(@RequestBody Task task, HttpServletRequest request, HttpServletResponse response) {
    String id = this.taskService.createAdHocTask(task);
    response.setStatus(HttpServletResponse.SC_CREATED); // 201
    response.setHeader("Location", request.getRequestURL() + "/active/" + id);
}

From source file:fr.ybonnel.simpleweb4j.MultipartIntegrationTest.java

@Before
public void startServer() {
    resetDefaultValues();//from  w w  w  .  j  av a  2s .  c o m
    port = Integer.getInteger("test.http.port", random.nextInt(10000) + 10000);
    setPort(port);

    resource(new RestResource<TestUploadImage>("multipart", TestUploadImage.class) {
        @Override
        public TestUploadImage getById(String id) throws HttpErrorException {
            return null;
        }

        @Override
        public List<TestUploadImage> getAll() throws HttpErrorException {
            return Collections.emptyList();
        }

        @Override
        public void update(String id, TestUploadImage resource) throws HttpErrorException {
            resource.id = id;
            lastCall = resource;
        }

        @Override
        public TestUploadImage create(TestUploadImage resource) throws HttpErrorException {
            lastCall = resource;
            return resource;
        }

        @Override
        public Route<TestUploadImage, TestUploadImage> routeCreate() {
            return new Route<TestUploadImage, TestUploadImage>("multipart", TestUploadImage.class) {
                @Override
                public Response<TestUploadImage> handle(TestUploadImage param, RouteParameters routeParams)
                        throws HttpErrorException {
                    return new Response<>(create(param), HttpServletResponse.SC_CREATED);
                }

                @Override
                protected TestUploadImage getRouteParam(HttpServletRequest request) throws IOException {
                    try {
                        Part dataPart = request.getPart("data");
                        TestUploadImage data = ContentType.GSON
                                .fromJson(new InputStreamReader(dataPart.getInputStream()), getParamType());

                        Part imagePart = request.getPart("image");
                        if (null != imagePart) {
                            data.imageName = ((MultiPartInputStreamParser.MultiPart) imagePart)
                                    .getContentDispositionFilename();
                            data.image = IOUtils.toByteArray(imagePart.getInputStream());
                        }
                        return data;
                    } catch (ServletException e) {
                        e.printStackTrace();
                        return null;
                    }
                }
            };
        }

        @Override
        public Route<TestUploadImage, Void> routeUpdate() {
            return new Route<TestUploadImage, Void>("multipart/:id", TestUploadImage.class) {
                @Override
                public Response<Void> handle(TestUploadImage param, RouteParameters routeParams)
                        throws HttpErrorException {
                    update(routeParams.getParam("id"), param);
                    return new Response<>(null);
                }

                @Override
                protected TestUploadImage getRouteParam(HttpServletRequest request) throws IOException {
                    try {
                        Part dataPart = request.getPart("data");
                        InputStreamReader dataReader = new InputStreamReader(dataPart.getInputStream());
                        TestUploadImage data = ContentType.GSON.fromJson(dataReader, getParamType());
                        dataReader.close();

                        Part imagePart = request.getPart("image");
                        if (null != imagePart) {
                            data.imageName = ((MultiPartInputStreamParser.MultiPart) imagePart)
                                    .getContentDispositionFilename();
                            data.image = IOUtils.toByteArray(imagePart.getInputStream());
                        }
                        return data;
                    } catch (ServletException e) {
                        e.printStackTrace();
                        return null;
                    }
                }
            };
        }

        @Override
        public void delete(String id) throws HttpErrorException {
        }
    });

    start(false);
}

From source file:org.fcrepo.server.management.UploadServlet.java

public void sendResponse(int status, String message, HttpServletResponse response) {
    try {/*from   ww w . j  a v  a 2 s.com*/
        if (status == HttpServletResponse.SC_CREATED) {
            logger.info("Successful upload, id=" + message);
        } else {
            logger.error("Failed upload: " + message);
        }
        response.setStatus(status);
        response.setContentType("text/plain");
        PrintWriter w = response.getWriter();
        w.println(message);
    } catch (Exception e) {
        logger.error("Unable to send response", e);
    }
}

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

@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_EVENT_ADD })
@RequestMapping(method = { RequestMethod.POST }, value = "")
public ModelAndView createEvent(@RequestBody String data, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    User user = (User) request.getAttribute(Constants.USER);
    Event event = getEventService().createEvent(this.buildEventFromInputParameters(data), user);
    response.setStatus(HttpServletResponse.SC_CREATED);
    String includes[] = (String[]) ArrayUtils.addAll(EVENT_INCLUDES, ERROR_INCLUDE);
    return toModelAndViewWithIoFilter(event, RESPONSE_FORMAT_JSON, EXCLUDE_ALL, true, includes);
}