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:org.egov.restapi.web.rest.ContractorController.java

@RequestMapping(value = "/egworks/contractors", method = GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String getContractors(@RequestParam(value = "code", required = false) final String code,
        final HttpServletResponse response) {
    if (StringUtils.isBlank(code)) {
        response.setStatus(HttpServletResponse.SC_CREATED);
        return JsonConvertor.convert(externalContractorService.populateContractor());
    } else {//from  w  w w  . ja va  2  s . c  o m
        final RestErrors restErrors = new RestErrors();
        final Contractor contractor = contractorService.getContractorByCode(code);
        if (contractor == null) {
            restErrors.setErrorCode(RestApiConstants.THIRD_PARTY_ERR_CODE_NOT_EXIST_CONTRACTOR);
            restErrors.setErrorMessage(RestApiConstants.THIRD_PARTY_ERR_MSG_NOT_EXIST_CONTRACTOR);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return JsonConvertor.convert(restErrors);
        } else {
            response.setStatus(HttpServletResponse.SC_CREATED);
            return JsonConvertor.convert(externalContractorService.populateContractorData(contractor));
        }
    }
}

From source file:it.geosolutions.geofence.gui.server.UploadServlet.java

@SuppressWarnings("unchecked")
@Override/*from w  w w .j  a v a  2  s. c o m*/
protected 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);

        File uploadedFile = null;
        // Parse the request
        try {
            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);
                }

                uploadedFile = File.createTempFile(fileName, "");
                // if (uploadedFile.createNewFile()) {
                item.write(uploadedFile);
                resp.setStatus(HttpServletResponse.SC_CREATED);
                resp.flushBuffer();

                // uploadedFile.delete();
                // } 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());
        }

        try {
            String wkt = calculateWKT(uploadedFile);
            resp.getWriter().print(wkt);
        } catch (Exception exc) {
            resp.getWriter().print("Error : " + exc.getMessage());
            logger.error("ERROR ********** " + exc);
        }

        uploadedFile.delete();

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

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

@PreAuthorize("hasRole('CONNECTOR_CREATE')")
@RequestMapping(method = RequestMethod.POST, value = "/create")
public ConnInstanceTO create(final HttpServletResponse response, @RequestBody final ConnInstanceTO connectorTO)
        throws SyncopeClientCompositeErrorException, NotFoundException {

    LOG.debug("ConnInstance create called with configuration {}", connectorTO);

    ConnInstance connInstance = binder.getConnInstance(connectorTO);

    try {//from   w  w w .j a va  2 s .c om
        connInstance = connInstanceDAO.save(connInstance);
    } catch (Throwable t) {
        SyncopeClientCompositeErrorException scce = new SyncopeClientCompositeErrorException(
                HttpStatus.BAD_REQUEST);

        SyncopeClientException invalidConnInstance = new SyncopeClientException(
                SyncopeClientExceptionType.InvalidConnInstance);
        invalidConnInstance.addElement(t.getMessage());

        scce.addException(invalidConnInstance);
        throw scce;
    }

    response.setStatus(HttpServletResponse.SC_CREATED);
    return binder.getConnInstanceTO(connInstance);
}

From source file:com.jaspersoft.jasperserver.rest.services.RESTRole.java

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    try {//from   w w  w.j  a  v  a 2s. c o m
        WSRole role = restUtils.unmarshal(WSRole.class, req.getInputStream());
        role = restUtils.populateServiceObject(role);

        if (userAndRoleManagementService.findRoles(wsRoleToWSRoleSearchCriteria(role)).length == 0) {
            userAndRoleManagementService.putRole(role);
            restUtils.setStatusAndBody(HttpServletResponse.SC_CREATED, resp, "");
        } else {
            throw new IllegalArgumentException(
                    "can not create new role: " + role.getRoleName() + ". it already exists");
        }
    } catch (Exception e) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getLocalizedMessage());
    }
}

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

@PreAuthorize("hasRole('RESOURCE_CREATE')")
@RequestMapping(method = RequestMethod.POST, value = "/create")
public ResourceTO create(final HttpServletResponse response, final @RequestBody ResourceTO resourceTO)
        throws SyncopeClientCompositeErrorException, NotFoundException {

    LOG.debug("Resource creation: {}", resourceTO);

    if (resourceTO == null) {
        LOG.error("Missing resource");

        throw new NotFoundException("Missing resource");
    }//from w w w  .  jav  a2  s .c  o  m

    SyncopeClientCompositeErrorException scce = new SyncopeClientCompositeErrorException(
            HttpStatus.BAD_REQUEST);

    LOG.debug("Verify that resource doesn't exist yet");
    if (resourceTO.getName() != null && resourceDAO.find(resourceTO.getName()) != null) {
        SyncopeClientException ex = new SyncopeClientException(
                SyncopeClientExceptionType.DataIntegrityViolation);

        ex.addElement("Existing " + resourceTO.getName());
        scce.addException(ex);

        throw scce;
    }

    ExternalResource resource = binder.create(resourceTO);
    if (resource == null) {
        LOG.error("Resource creation failed");

        SyncopeClientException ex = new SyncopeClientException(SyncopeClientExceptionType.Unknown);

        scce.addException(ex);

        throw scce;
    }

    resource = resourceDAO.save(resource);

    response.setStatus(HttpServletResponse.SC_CREATED);
    return binder.getResourceTO(resource);
}

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

/**
 * We have just received the final chunk of data for a file upload.
 * Complete the transfer by moving the uploaded content into the
 * workspace./*  ww  w  .j av  a 2 s  .  c  om*/
 * @throws IOException 
 */
private void completeTransfer(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    List<String> options = getOptions();
    boolean success;
    if (!options.contains("raw")) { //$NON-NLS-1$
        success = completeUnzip(req, resp);
    } else {
        success = completeMove(req, resp);
    }
    if (success) {
        resp.setHeader(ProtocolConstants.HEADER_LOCATION, req.getContextPath() + "/file" + getPath()); //$NON-NLS-1$
        resp.setStatus(HttpServletResponse.SC_CREATED);
        resp.setContentType(ProtocolConstants.CONTENT_TYPE_HTML);
    }
}

From source file:com.jaspersoft.jasperserver.rest.services.RESTJob.java

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    try {//w w w  .  jav a2s .  c  om
        StringWriter sw = new StringWriter();
        Job job = restUtils.unmarshal(Job.class, req.getInputStream());

        if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication()
                    .getPrincipal();
            job.setUsername(userDetails.getUsername());
        }
        try {

            job = reportSchedulerService.scheduleJob(job);
        } catch (AxisFault axisFault) {
            throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "could not schedule job to report: "
                    + job.getReportUnitURI() + ". check job parameters\n" + axisFault.getMessage());
        }

        restUtils.getMarshaller(Job.class).marshal(job, sw);
        restUtils.setStatusAndBody(HttpServletResponse.SC_CREATED, resp, sw.toString()); // job is a unique case where we return the descriptor

    } catch (AxisFault axisFault) {
        throw new ServiceException(HttpServletResponse.SC_NOT_FOUND, axisFault.getMessage());
    } catch (IOException e) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } catch (JAXBException e) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST,
                "please check the request job descriptor");
    }

}

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

@RequestMapping(value = "/egf/budgetgroups", method = GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String getAllActiveBudgetGroups(final HttpServletResponse response) {
    try {//from w  w w  .  j  av a 2 s .  co m
        response.setStatus(HttpServletResponse.SC_CREATED);
        return JsonConvertor.convert(financialMasterService.populateBudgetGroup());
    } catch (final Exception e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return JsonConvertor.convert(StringUtils.EMPTY);
    }
}

From source file:com.imaginary.home.controller.CloudService.java

static CloudService pair(@Nonnull String name, @Nonnull String endpoint, @Nullable String proxyHost,
        int proxyPort, @Nonnull String pairingToken) throws CommunicationException, ControllerException {
    HttpClient client = getClient(endpoint, proxyHost, proxyPort);
    HttpPost method = new HttpPost(endpoint + "/relay");

    method.addHeader("Content-Type", "application/json");
    method.addHeader("x-imaginary-version", VERSION);
    method.addHeader("x-imaginary-timestamp", String.valueOf(System.currentTimeMillis()));

    HashMap<String, Object> body = new HashMap<String, Object>();

    body.put("pairingCode", pairingToken);
    body.put("name", HomeController.getInstance().getName());
    try {/*from w  w w . j  a  va  2s . c  om*/
        //noinspection deprecation
        method.setEntity(new StringEntity((new JSONObject(body)).toString(), "application/json", "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new ControllerException(e);
    }
    HttpResponse response;
    StatusLine status;

    try {
        response = client.execute(method);
        status = response.getStatusLine();
    } catch (IOException e) {
        e.printStackTrace();
        throw new CommunicationException(e);
    }
    if (status.getStatusCode() == HttpServletResponse.SC_CREATED) {
        HttpEntity entity = response.getEntity();

        if (entity == null) {
            throw new CommunicationException(status.getStatusCode(), "No error, but no body");
        }
        String json;

        try {
            json = EntityUtils.toString(entity);
        } catch (IOException e) {
            throw new ControllerException(e);
        }
        try {
            JSONObject ob = new JSONObject(json);
            String apiKeyId = null, apiSecret = null;

            if (ob.has("apiKeyId") && !ob.isNull("apiKeyId")) {
                apiKeyId = ob.getString("apiKeyId");
            }
            if (ob.has("apiKeySecret") && !ob.isNull("apiKeySecret")) {
                apiSecret = ob.getString("apiKeySecret");
            }
            if (apiKeyId == null || apiSecret == null) {
                throw new CommunicationException(status.getStatusCode(),
                        "Invalid JSON response to pairing request");
            }
            return new CloudService(apiKeyId, apiSecret, name, endpoint, proxyHost, proxyPort);
        } catch (JSONException e) {
            throw new CommunicationException(e);
        }

    } else {
        HttpEntity entity = response.getEntity();

        if (entity == null) {
            throw new CommunicationException(status.getStatusCode(),
                    "An error was returned without explanation");
        }
        String json;

        try {
            json = EntityUtils.toString(entity);
        } catch (IOException e) {
            throw new ControllerException(e);
        }
        throw new CommunicationException(status.getStatusCode(), json);
    }
}

From source file:com.homesnap.webserver.GroupRestAPITest.java

@Test
public void test7OnStatus() {
    // Test to get a specific group
    JSONObject group = getRequestJSONObject("/house/groups/1?param=param");
    // Test group 1
    testGroup1Bis(group);/*from w  w  w .  j  a v  a 2s.co m*/

    group = getRequestJSONObject("/house/groups/group?id=10&param=param");
    // Test group 10
    testGroup10(group);

    putRequestJSONObject("/house/groups/1?param=param", createGroup1(), HttpServletResponse.SC_OK);
    putRequestJSONObject("/house/groups/group?id=1&param=param", createGroup1(), HttpServletResponse.SC_OK);

    postRequestJSONObject("/house/groups/1/21", createController21(), HttpServletResponse.SC_CREATED);
    JSONObject jo = getRequestJSONObject("/house/groups/1/controller?id=21&param=param");
    testController21(jo);

    jo = getRequestJSONObject("/house/groups/1/21?param=param");
    testController21(jo);

    testController21(jo);

    deleteRequestJSONObject("/house/groups/1?param=param", HttpServletResponse.SC_OK);
    deleteRequestJSONObject("/house/groups/group?id=1&param=param", HttpServletResponse.SC_NOT_ACCEPTABLE);
}