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:fedora.server.management.UploadServlet.java

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

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

@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_FEEDBACK_ADD })
@RequestMapping(method = RequestMethod.POST, value = "")
public ModelAndView createFeedback(@RequestBody final String data, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    final User user = (User) request.getAttribute(Constants.USER);
    final Feedback newFeedback = this.buildFeedbackFromInputParameters(data, request);
    final boolean list = newFeedback.getTypes() == null ? false : true;
    final List<Feedback> feedbacks = getFeedbackService().createFeedbacks(newFeedback, user);
    final Feedback feedback = feedbacks.get(0);
    response.setStatus(HttpServletResponse.SC_CREATED);
    final String includes[] = (String[]) ArrayUtils.addAll(FEEDBACK_INCLUDE_FIELDS, ERROR_INCLUDE);
    return toModelAndViewWithIoFilter(list ? feedbacks : feedback, RESPONSE_FORMAT_JSON, EXCLUDE_ALL, true,
            includes);//from   w  w w .  jav  a  2s . c om
}

From source file:org.efaps.webdav4vfs.handler.AbstractCopyMoveBaseHandler.java

/**
 * Handle a COPY or MOVE request.//www .  j a v a 2  s  . c o m
 *
 * @param _request      HTTP servlet request
 * @param _response     HTTP servlet response
 * @throws IOException if there is an error executing this request
 */
@Override
public void service(final HttpServletRequest _request, final 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
    this.copyOrMove(object, targetObject, getDepth(_request));
}

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

@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_PARTY_CUSTOM_FIELD_ADD })
@RequestMapping(method = RequestMethod.POST, value = "/{id}/custom-field")
public ModelAndView createPartyCustomField(@RequestBody String data, @PathVariable(value = ID) String partyId,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    User user = (User) request.getAttribute(Constants.USER);
    JSONObject json = requestData(data);
    ActionResponseDTO<PartyCustomField> responseDTO = getPartyservice().createPartyCustomField(partyId,
            buildPartyCustomFieldFromInputParameters(getValue(PARTY_CUSTOM_FIELD, json)), user);
    if (responseDTO.getErrors().getErrorCount() > 0) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else {//from  w ww  . ja  v a2s.c om
        response.setStatus(HttpServletResponse.SC_CREATED);
    }
    String[] includeFields = getValue(FIELDS, json) != null ? getFields(getValue(FIELDS, json)) : null;
    String includes[] = (String[]) ArrayUtils
            .addAll(includeFields == null ? PARTY_CUSTOM_INCLUDES : includeFields, ERROR_INCLUDE);
    return toModelAndViewWithIoFilter(responseDTO.getModelData(), RESPONSE_FORMAT_JSON, EXCLUDE_ALL, includes);
}

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

@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_OAUTH_ADD })
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
@RequestMapping(method = { RequestMethod.POST }, value = "/client")
public ModelAndView createOAuthClient(@RequestBody String data, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    User user = (User) request.getAttribute(Constants.USER);
    ActionResponseDTO<OAuthClient> responseDTO = getOAuthService()
            .createOAuthClient(buildOAuthClientFromInputParameters(data), user);
    if (responseDTO.getErrors().getErrorCount() > 0) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else {/*from w  w w.  j a v a2s  .co m*/
        response.setStatus(HttpServletResponse.SC_CREATED);
        // To capture activity log
        SessionContextSupport.putLogParameter(EVENT_NAME, "OauthClient-Register");
        SessionContextSupport.putLogParameter("OAuthClientId", responseDTO.getModel().getKey());
    }
    String[] includes = (String[]) ArrayUtils.addAll(ERROR_INCLUDE, OAUTH_CLIENT_INCLUDES);
    return toModelAndView(serialize(responseDTO.getModel(), RESPONSE_FORMAT_JSON, EXCLUDE_ALL, includes));
}

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

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    try {/* w w w.  j a  va 2  s .  c  o m*/
        String userName = restUtils.getFullUserName(restUtils.extractResourceName(req.getPathInfo()));
        @SuppressWarnings("unchecked")
        JAXBList<ProfileAttribute> atts = (JAXBList<ProfileAttribute>) restUtils.unmarshal(req.getInputStream(),
                JAXBList.class, ProfileAttributeImpl.class);

        for (int i = 0; i < atts.size(); i++) {
            attributesRemoteService.putAttribute(userName, atts.get(i));
        }

        restUtils.setStatusAndBody(HttpServletResponse.SC_CREATED, resp, "");
    } catch (IOException e) {
        throw new ServiceException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (JAXBException e) {
        throw new ServiceException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}

From source file:cf.spring.servicebroker.ServiceBrokerHandler.java

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!authenticator.authenticate(request, response)) {
        return;// w  ww  . j a  v  a  2s.  c o m
    }
    ApiVersionValidator.validateApiVersion(request);
    try {
        response.setContentType(Constants.JSON_CONTENT_TYPE);
        final Matcher matcher = URI_PATTERN.matcher(request.getRequestURI());
        if (!matcher.matches()) {
            throw new NotFoundException("Resource not found");
        }
        final String instanceId = matcher.group(1);
        final String bindingId = matcher.group(3);
        if ("put".equalsIgnoreCase(request.getMethod())) {
            if (bindingId == null) {
                final ProvisionBody provisionBody = mapper.readValue(request.getInputStream(),
                        ProvisionBody.class);
                final String serviceId = provisionBody.getServiceId();
                final BrokerServiceAccessor accessor = getServiceAccessor(serviceId);
                final ProvisionRequest provisionRequest = new ProvisionRequest(UUID.fromString(instanceId),
                        provisionBody.getPlanId(), provisionBody.getOrganizationGuid(),
                        provisionBody.getSpaceGuid());
                final ProvisionResponse provisionResponse = accessor.provision(provisionRequest);
                if (provisionResponse.isCreated()) {
                    response.setStatus(HttpServletResponse.SC_CREATED);
                }
                mapper.writeValue(response.getOutputStream(), provisionResponse);
            } else {
                final BindBody bindBody = mapper.readValue(request.getInputStream(), BindBody.class);
                final String serviceId = bindBody.getServiceId();
                final BrokerServiceAccessor accessor = getServiceAccessor(serviceId);

                final BindRequest bindRequest = new BindRequest(UUID.fromString(instanceId),
                        UUID.fromString(bindingId), bindBody.applicationGuid, bindBody.getPlanId());
                final BindResponse bindResponse = accessor.bind(bindRequest);
                if (bindResponse.isCreated()) {
                    response.setStatus(HttpServletResponse.SC_CREATED);
                }
                mapper.writeValue(response.getOutputStream(), bindResponse);
            }
        } else if ("delete".equalsIgnoreCase(request.getMethod())) {
            final String serviceId = request.getParameter(SERVICE_ID_PARAM);
            final String planId = request.getParameter(PLAN_ID_PARAM);
            final BrokerServiceAccessor accessor = getServiceAccessor(serviceId);
            try {
                if (bindingId == null) {
                    // Deprovision
                    final DeprovisionRequest deprovisionRequest = new DeprovisionRequest(
                            UUID.fromString(instanceId), planId);
                    accessor.deprovision(deprovisionRequest);
                } else {
                    // Unbind
                    final UnbindRequest unbindRequest = new UnbindRequest(UUID.fromString(bindingId),
                            UUID.fromString(instanceId), planId);
                    accessor.unbind(unbindRequest);
                }
            } catch (MissingResourceException e) {
                response.setStatus(HttpServletResponse.SC_GONE);
            }
            response.getWriter().write("{}");
        } else {
            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }
    } catch (ConflictException e) {
        response.setStatus(HttpServletResponse.SC_CONFLICT);
        response.getWriter().write("{}");
    } catch (ServiceBrokerException e) {
        LOGGER.warn("An error occurred processing a service broker request", e);
        response.setStatus(e.getHttpResponseCode());
        mapper.writeValue(response.getOutputStream(), new ErrorBody(e.getMessage()));
    } catch (Throwable e) {
        LOGGER.error(e.getMessage(), e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        mapper.writeValue(response.getOutputStream(), new ErrorBody(e.getMessage()));
    }
}

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

@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_APPLICATION_ADD })
@RequestMapping(method = RequestMethod.POST)
public ModelAndView createApplication(@RequestBody String data, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    User user = (User) request.getAttribute(Constants.USER);
    ActionResponseDTO<Application> responseDTO = getApplicationService()
            .createApplication(buildApplicationFromInputParameters(data), user);
    if (responseDTO.getErrors().getErrorCount() > 0) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else {//w  w w .  j a  va2  s.  c  o m
        response.setStatus(HttpServletResponse.SC_CREATED);
    }
    String includes[] = (String[]) ArrayUtils.addAll(APPLICATION_INCLUDES, ERROR_INCLUDE);
    return toModelAndViewWithIoFilter(responseDTO.getModelData(), RESPONSE_FORMAT_JSON, EXCLUDE_ALL, true,
            includes);
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.servlets.post.PostServletCopyTest.java

public void testCopyNodeAbsoluteBelowDest() throws IOException {
    final String testPath = TEST_BASE_PATH + "/abs/" + System.currentTimeMillis();
    Map<String, String> props = new HashMap<String, String>();
    props.put("text", "Hello");
    testClient.createNode(HTTP_BASE_URL + testPath + "/src", props);

    // first test: failure because dest (parent) does not exist
    List<NameValuePair> nvPairs = new ArrayList<NameValuePair>();
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_OPERATION, SlingPostConstants.OPERATION_COPY));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_DEST, testPath + "/dest/"));
    assertPostStatus(HTTP_BASE_URL + testPath + "/src", HttpServletResponse.SC_PRECONDITION_FAILED, nvPairs,
            "Expecting Copy Failure (dest must exist)");

    // create dest as parent
    testClient.createNode(HTTP_BASE_URL + testPath + "/dest", null);

    // copy now succeeds to below dest
    assertPostStatus(HTTP_BASE_URL + testPath + "/src", HttpServletResponse.SC_CREATED, nvPairs,
            "Expecting Copy Success");

    // assert content at new location
    String content = getContent(HTTP_BASE_URL + testPath + "/dest.-1.json", CONTENT_TYPE_JSON);
    assertJavascript("Hello", content, "out.println(data.src.text)");

    // assert content at old location
    content = getContent(HTTP_BASE_URL + testPath + "/src.json", CONTENT_TYPE_JSON);
    assertJavascript("Hello", content, "out.println(data.text)");
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.servlets.post.PostServletMoveTest.java

public void testMoveNodeAbsoluteBelowDest() throws IOException {
    final String testPath = TEST_BASE_PATH + "/abs/" + System.currentTimeMillis();
    Map<String, String> props = new HashMap<String, String>();
    props.put("text", "Hello");
    testClient.createNode(HTTP_BASE_URL + testPath + "/src", props);

    // first test: failure because dest (parent) does not exist
    List<NameValuePair> nvPairs = new ArrayList<NameValuePair>();
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_OPERATION, SlingPostConstants.OPERATION_MOVE));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_DEST, testPath + "/dest/"));
    assertPostStatus(HTTP_BASE_URL + testPath + "/src", HttpServletResponse.SC_PRECONDITION_FAILED, nvPairs,
            "Expecting Move Failure (dest must exist)");

    // create dest as parent
    testClient.createNode(HTTP_BASE_URL + testPath + "/dest", null);

    // move now succeeds to below dest
    assertPostStatus(HTTP_BASE_URL + testPath + "/src", HttpServletResponse.SC_CREATED, nvPairs,
            "Expecting Move Success");

    // assert content at new location
    String content = getContent(HTTP_BASE_URL + testPath + "/dest.-1.json", CONTENT_TYPE_JSON);
    assertJavascript("Hello", content, "out.println(data.src.text)");

    // assert content at old location
    assertHttpStatus(HTTP_BASE_URL + testPath + "/src.json", HttpServletResponse.SC_NOT_FOUND);
}