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.tasktop.c2c.server.common.service.tests.ajp.AjpProtocolTest.java

@Test
public void testPostData() throws IOException {
    Payload payload = new Payload(HttpServletResponse.SC_CREATED, "some content\none two three\n\nfour");
    payload.getResponseHeaders().put("foo", "bar");
    TestServlet.setResponsePayload(payload);

    String formContent = "a=b&c=def";
    byte[] requestContent = formContent.getBytes();

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("GET");
    request.setRequestURI("/testPostData");
    request.addHeader("Content-Type", "application/x-www-form-urlencoded");
    request.addHeader("Content-Length", requestContent.length);
    request.setContent(requestContent);/*from  ww  w.ja  va2 s  .c o  m*/

    MockHttpServletResponse response = new MockHttpServletResponse();
    protocol.forward(request, response);

    assertRequestIsExpected(request, TestServlet.getLastRequest());
    assertResponseIsExpected(payload, response);
}

From source file:ch.entwine.weblounge.test.harness.rest.PagesEndpointTest.java

/**
 * Tests the creation of a page.//from  w  ww  .j  av a2 s  .co  m
 * 
 * @param serverUrl
 *          the server url
 * @throws Exception
 *           if page creation fails
 */
private void testCreate(String serverUrl) throws Exception {
    String requestUrl = UrlUtils.concat(serverUrl, "system/weblounge/pages");
    HttpPost createPageRequest = new HttpPost(requestUrl);
    String[][] params = new String[][] { { "path", pagePath } };
    logger.debug("Creating new page at {}", createPageRequest.getURI());
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpResponse response = TestUtils.request(httpClient, createPageRequest, params);
        assertEquals(HttpServletResponse.SC_CREATED, response.getStatusLine().getStatusCode());
        assertEquals(0, response.getEntity().getContentLength());

        // Extract the id of the new page
        assertNotNull(response.getHeaders("Location"));
        String locationHeader = response.getHeaders("Location")[0].getValue();
        assertTrue(locationHeader.startsWith(serverUrl));
        pageId = locationHeader.substring(locationHeader.lastIndexOf("/") + 1);
        assertEquals("Identifier doesn't have correct length", 36, pageId.length());
        logger.debug("Id of the new page is {}", pageId);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    // Make sure the page is not yet publicly reachable
    String requestByIdUrl = UrlUtils.concat(serverUrl, "/weblounge-pages/", pageId);
    HttpGet getPageRequest = new HttpGet(requestByIdUrl);
    httpClient = new DefaultHttpClient();
    logger.info("Requesting published page at {}", requestByIdUrl);
    try {
        HttpResponse response = TestUtils.request(httpClient, getPageRequest, null);
        assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode());
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

}

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

@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_SCOLLECTION_ADD })
@RequestMapping(value = { " " }, method = RequestMethod.POST)
public ModelAndView createCollection(@RequestBody final String data, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    final User user = (User) request.getAttribute(Constants.USER);
    final JSONObject json = requestData(data);
    final ActionResponseDTO<Collection> responseDTO = getCollectionService().createCollection(
            this.buildCollectionFromInputParameters(getValue(COLLECTION, json), user, request),
            Boolean.parseBoolean(
                    json != null && getValue(ADD_TO_SHELF, json) != null ? getValue(ADD_TO_SHELF, json)
                            : FALSE),/*from   w  ww .  j a va  2s  .  c  o  m*/
            getValue(RESOURCE_ID, json), getValue(PARENT_ID, json), user);
    if (responseDTO.getErrors().getErrorCount() > 0) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else {
        response.setStatus(HttpServletResponse.SC_CREATED);
    }
    String includes[] = (String[]) ArrayUtils.addAll(RESOURCE_INCLUDE_FIELDS, COLLECTION_INCLUDE_FIELDS);
    includes = (String[]) ArrayUtils.addAll(includes, COLLECTION_ITEM_INCLUDE_FILEDS);
    includes = (String[]) ArrayUtils.addAll(includes, ERROR_INCLUDE);
    return toModelAndViewWithIoFilter(responseDTO.getModelData(), RESPONSE_FORMAT_JSON, EXCLUDE_ALL, true,
            includes);
}

From source file:org.eclipse.orion.internal.server.servlets.file.DirectoryHandlerV1.java

private boolean handlePost(HttpServletRequest request, HttpServletResponse response, IFileStore dir)
        throws JSONException, CoreException, ServletException, IOException {
    //setup and precondition checks
    JSONObject requestObject = OrionServlet.readJSONRequest(request);
    String name = computeName(request, requestObject);
    if (name.length() == 0)
        return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST, "File name not specified.", null));
    IFileStore toCreate = dir.getChild(name);
    if (!name.equals(toCreate.getName()))
        return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST, "Bad file name: " + name, null));
    int options = getCreateOptions(request);
    boolean destinationExists = toCreate.fetchInfo(EFS.NONE, null).exists();
    if (!validateOptions(request, response, toCreate, destinationExists, options))
        return true;
    //perform the operation
    if (performPost(request, response, requestObject, toCreate, options)) {
        //write the response
        URI location = URIUtil.append(getURI(request), name);
        JSONObject result = ServletFileStoreHandler.toJSON(toCreate, toCreate.fetchInfo(EFS.NONE, null),
                location);//w w w. jav a  2 s .  c  om
        OrionServlet.writeJSONResponse(request, response, result);
        response.setHeader(ProtocolConstants.HEADER_LOCATION,
                ServletResourceHandler.resovleOrionURI(request, location).toString());
        //response code should indicate if a new resource was actually created or not
        response.setStatus(destinationExists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_CREATED);
    }
    return true;
}

From source file:com.cognitivabrasil.repositorio.web.FileControllerTest.java

@Test
public void testGetThumbnail() throws IOException {

    HttpServletResponse response = new MockHttpServletResponse();
    HttpServletResponse response2 = new MockHttpServletResponse();
    FileController fileController = mockFiles();

    // proves response and response2 are not comitted yet.
    Assert.assertFalse(response.isCommitted());
    Assert.assertFalse(response2.isCommitted());

    // tests id = null. 
    fileController.getThumbnail(null, response);
    Assert.assertTrue(response.isCommitted());
    assertThat(HttpServletResponse.SC_NOT_FOUND, equalTo(response.getStatus()));

    // tests id = 1      
    Long id = 1L;// w  ww  . j  a v  a2s.co m

    //proves response2 is only commited after flushbuffer.
    Assert.assertFalse(response2.isCommitted());
    fileController.getThumbnail(id, response2);
    Assert.assertTrue(response2.isCommitted());
    assertThat(HttpServletResponse.SC_CREATED, equalTo(response2.getStatus()));

}

From source file:org.syncope.core.rest.controller.TaskController.java

@PreAuthorize("hasRole('TASK_CREATE')")
@RequestMapping(method = RequestMethod.POST, value = "/create/sched")
public TaskTO createSchedTask(final HttpServletResponse response, @RequestBody final SchedTaskTO taskTO)
        throws NotFoundException {

    LOG.debug("Creating task " + taskTO);

    TaskUtil taskUtil = getTaskUtil(taskTO);

    SchedTask task = binder.createSchedTask(taskTO, taskUtil);
    task = taskDAO.save(task);/*  w  ww .  j a  va 2s .c o  m*/

    try {
        jobInstanceLoader.registerJob(task, task.getJobClassName(), task.getCronExpression());
    } catch (Exception e) {
        LOG.error("While registering quartz job for task " + task.getId(), e);

        SyncopeClientCompositeErrorException scce = new SyncopeClientCompositeErrorException(
                HttpStatus.BAD_REQUEST);
        SyncopeClientException sce = new SyncopeClientException(SyncopeClientExceptionType.Scheduling);
        sce.addElement(e.getMessage());
        scce.addException(sce);
        throw scce;
    }

    response.setStatus(HttpServletResponse.SC_CREATED);
    return binder.getTaskTO(task, taskUtil);
}

From source file:org.structr.web.resource.RegistrationResource.java

@Override
public RestMethodResult doPost(Map<String, Object> propertySet) throws FrameworkException {

    boolean existingUser = false;

    if (propertySet.containsKey(User.eMail.jsonName())) {

        final Principal user;

        final String emailString = (String) propertySet.get(User.eMail.jsonName());

        if (StringUtils.isEmpty(emailString)) {
            return new RestMethodResult(HttpServletResponse.SC_BAD_REQUEST);
        }//ww  w.j  av  a 2s.  c  o  m

        localeString = (String) propertySet.get(MailTemplate.locale.jsonName());
        confKey = UUID.randomUUID().toString();

        final Result result = StructrApp.getInstance().nodeQuery(User.class).and(User.eMail, emailString)
                .getResult();
        if (!result.isEmpty()) {

            user = (Principal) result.get(0);

            // For existing users, update confirmation key
            user.setProperty(User.confirmationKey, confKey);

            existingUser = true;

        } else {

            final Authenticator auth = securityContext.getAuthenticator();
            user = createUser(securityContext, User.eMail, emailString, propertySet, auth.getUserAutoCreate(),
                    auth.getUserClass());
        }

        if (user != null) {

            if (!sendInvitationLink(user, propertySet)) {

                // return 400 Bad request
                return new RestMethodResult(HttpServletResponse.SC_BAD_REQUEST);

            }

            // If we have just updated the confirmation key for an existing user,
            // return 200 to distinguish from new users
            if (existingUser) {

                // return 200 OK
                return new RestMethodResult(HttpServletResponse.SC_OK);

            } else {

                // return 201 Created
                return new RestMethodResult(HttpServletResponse.SC_CREATED);

            }

        } else {

            // return 400 Bad request
            return new RestMethodResult(HttpServletResponse.SC_BAD_REQUEST);

        }

    } else {

        // return 400 Bad request
        return new RestMethodResult(HttpServletResponse.SC_BAD_REQUEST);

    }

}

From source file:org.openmrs.module.webservices.rest.web.v1_0.controller.openmrs1_9.FormResourceController1_9Test.java

@Test
public void shouldPostFormResourceValue() throws Exception {
    byte[] fileData = IOUtils.toByteArray(
            getClass().getClassLoader().getResourceAsStream(RestTestConstants1_9.TEST_RESOURCE_FILE));

    String valueReferenceBefore = formService.getFormResourceByUuid(getUuid()).getValueReference();

    MockMultipartFile toUpload = new MockMultipartFile("value", "formresource.txt", "text/plain", fileData);

    MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();

    //Posting to uri of the form /ws/rest/v1/form/{uuid}/resource/{uuid}/value
    String uri = getBaseRestURI() + getURI() + "/" + getUuid() + "/value";
    request.setRequestURI(uri);//from   w w w  .  j  a  v a  2  s . co  m
    request.setMethod(RequestMethod.POST.name());
    request.addHeader("Content-Type", "multipart/form-data");

    request.addFile(toUpload);

    MockHttpServletResponse response = handle(request);

    String valueReferenceAfter = formService.getFormResourceByUuid(getUuid()).getValueReference();

    Assert.assertNotEquals(valueReferenceBefore, valueReferenceAfter);
    Assert.assertNotNull(datatypeService.getClobDatatypeStorageByUuid(valueReferenceAfter));
    Assert.assertEquals(HttpServletResponse.SC_CREATED, response.getStatus());
}

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

@Before
public void setupTest() throws IOException, Exception {
    nodesApi = applicationContext.getBean("Nodes", org.alfresco.rest.api.Nodes.class);

    setRequestContext(user1);/*from  w  w w. j a v a 2 s.c om*/

    Document zippableDoc1 = createTextFile(tDocLibNodeId, ZIPPABLE_DOC1_NAME, DUMMY_CONTENT);
    zippableDocId1 = zippableDoc1.getId();
    zippableDocId2 = createTextFile(tDocLibNodeId, "docTest2", DUMMY_CONTENT).getId();

    Folder zippableFolder1 = createFolder(tDocLibNodeId, FOLDER1_NAME);
    zippableFolderId1 = zippableFolder1.getId();
    zippableDocId3_InFolder1 = createTextFile(zippableFolderId1, DOC3_NAME, DUMMY_CONTENT).getId();

    Folder zippableFolder2_InFolder1 = createFolder(zippableFolderId1, SUB_FOLDER1_NAME);
    zippableFolderId2_InFolder1 = zippableFolder2_InFolder1.getId();

    zippableDocId4_InFolder2 = createTextFile(zippableFolderId2_InFolder1, DOC4_NAME, DUMMY_CONTENT).getId();

    Folder zippableFolder3 = createFolder(tDocLibNodeId, FOLDER3_NAME);
    zippableFolderId3 = zippableFolder3.getId();

    setRequestContext(user2);
    String user2Site = createSite("TestSite B - " + RUNID, SiteVisibility.PRIVATE).getId();
    String user2DocLib = getSiteContainerNodeId(user2Site, "documentLibrary");
    zippableDoc_user2 = createTextFile(user2DocLib, "user2doc", DUMMY_CONTENT).getId();

    setRequestContext(user1);
    AssocChild secChild = new AssocChild(zippableDoc1.getId(), ASSOC_TYPE_CM_CONTAINS);
    post(format(NODES_SECONDARY_CHILDREN, zippableFolder3.getId()), toJsonAsStringNonNull(secChild),
            HttpServletResponse.SC_CREATED);
}

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

@RequestMapping(value = "/createProduct", method = RequestMethod.POST)
protected void createProduct(@RequestParam Map<String, String> params, HttpServletResponse response)
        throws ServletException, IOException {

    ClothoConnection conn = new ClothoConnection(Args.clothoLocation);
    Clotho clothoObject = new Clotho(conn);
    Map createUserMap = new HashMap();
    String username = "test" + System.currentTimeMillis();
    createUserMap.put("username", username);
    createUserMap.put("password", "password");
    clothoObject.createUser(createUserMap);
    clothoObject.logout();/*  w w  w . j a va2  s  .  com*/
    Map loginMap = new HashMap();
    loginMap.put("username", username);
    loginMap.put("credentials", "password");
    clothoObject.login(loginMap);
    //

    Object pProductUrl = params.get("productUrl");
    String productUrl = pProductUrl != null ? (String) pProductUrl : "";

    Object pCompanyId = params.get("company");
    String companyId = pCompanyId != null ? (String) pCompanyId : "";

    Object pGoodType = params.get("goodType");
    String goodType = pGoodType != null ? (String) pGoodType : "";

    Object pCost = params.get("cost");
    Double cost = pCost != null ? Double.parseDouble((String) pCost) : -1.0d;

    Object pQuantity = params.get("quantity");
    Integer quantity = pQuantity != null ? Integer.parseInt((String) pQuantity) : -1;

    Object pName = params.get("name");
    String name = pName != null ? (String) pName : "";

    Object pDescription = params.get("description");
    String description = pDescription != null ? (String) pDescription : "";

    Vendor comp = new Vendor();
    boolean isValidRequest = false;
    if ((!name.isEmpty() && (cost > 0) && (quantity > 0) && !companyId.isEmpty())) {

        isValidRequest = true;
        comp = ClothoAdapter.getVendor(companyId, clothoObject);
        if (comp.getId().equals("")) {
            isValidRequest = false;
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.setContentType("application/json");
            PrintWriter out = response.getWriter();
            JSONObject responseJSON = new JSONObject();
            responseJSON.put("message", "No Company with that id exists");
            out.print(responseJSON.toString());
            out.flush();
            out.close();
            clothoObject.logout();

            return;
        }
    }

    if (isValidRequest) {
        Product prod = new Product();
        prod.setName(name);
        prod.setCost(cost);
        prod.setInventory(quantity);
        prod.setCompanyId(comp.getId());
        prod.setDescription(description);
        prod.setProductURL(productUrl);
        prod.setGoodType(GoodType.valueOf((!goodType.equals("")) ? goodType : "INSTRUMENT"));

        //everything is set for that product
        ClothoAdapter.createProduct(prod, clothoObject);
        JSONObject product = new JSONObject();
        product.put("id", prod.getId());
        product.put("name", prod.getName());
        response.setStatus(HttpServletResponse.SC_CREATED);
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        out.print(product);
        out.flush();
        out.close();

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

    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}