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.ednovo.gooru.controllers.v2.api.InstitutionRestV2Controller.java

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

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

@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_ORGANIZATION_ADD })
@RequestMapping(method = RequestMethod.POST)
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public ModelAndView createOrganization(HttpServletRequest request, HttpServletResponse response,
        @RequestBody String data) throws Exception {
    JSONObject json = requestData(data);
    User user = (User) request.getAttribute(Constants.USER);
    ActionResponseDTO<Organization> responseDTO = getOrganizationService().saveOrganization(
            buildOrganizationFromInputParameters(getValue(ORGANIZATION, json)), user, request);
    if (responseDTO.getErrors().getErrorCount() > 0) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else {/*from w ww.j a v  a  2s  . c om*/
        response.setStatus(HttpServletResponse.SC_CREATED);
    }
    String includes[] = (String[]) ArrayUtils.addAll(ORGANIZATION_INCLUDES_ADD, ERROR_INCLUDE);

    return toModelAndViewWithInFilter(responseDTO.getModelData(), RESPONSE_FORMAT_JSON, includes);
}

From source file:fr.gael.dhus.server.http.webapp.api.controller.UploadController.java

@PreAuthorize("hasRole('ROLE_UPLOAD')")
@RequestMapping(value = "/upload", method = { RequestMethod.POST })
public void upload(Principal principal, HttpServletRequest req, HttpServletResponse res) throws 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 w w  .jav a  2 s  .co  m*/
            ArrayList<String> collectionIds = new ArrayList<>();
            FileItem product = null;

            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                if (COLLECTIONSKEY.equals(item.getFieldName())) {
                    if (item.getString() != null && !item.getString().isEmpty()) {
                        for (String cid : item.getString().split(",")) {
                            collectionIds.add(cid);
                        }
                    }
                } else if (PRODUCTKEY.equals(item.getFieldName())) {
                    product = item;
                }
            }
            if (product == null) {
                res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Your request is missing a product file to upload.");
                return;
            }
            productUploadService.upload(product, collectionIds);
            res.setStatus(HttpServletResponse.SC_CREATED);
            res.getWriter().print("The file was created successfully.");
            res.flushBuffer();
        } catch (FileUploadException e) {
            LOGGER.error("An error occurred while parsing request.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while parsing request : " + e.getMessage());
        } catch (UserNotExistingException e) {
            LOGGER.error("You need to be connected to upload a product.", e);
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You need to be connected to upload a product.");
        } catch (UploadingException e) {
            LOGGER.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (RootNotModifiableException e) {
            LOGGER.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (ProductNotAddedException e) {
            LOGGER.error("Your product can not be read by the system.", e);
            res.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Your product can not be read by the system.");
        }
    } else {
        res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

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

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

    //get all necessary fields to create 
    //REQUIRING NAME & DESCRIPTION & CONTACT 
    boolean isValid = false;

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

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

    String contact = params.get("contact") != null ? params.get("contact") : "";

    String phone = params.get("phone") != null ? params.get("phone") : "";
    String url = params.get("url") != null ? params.get("url") : "";

    if (!name.isEmpty() && !description.isEmpty() && !contact.isEmpty()) {
        isValid = true;/*from   w  w  w.j a va2  s  .c  o m*/

    } else {

    }
    if (isValid) {
        ClothoConnection conn = new ClothoConnection(Args.clothoLocation);
        Clotho clothoObject = new Clotho(conn);
        //TODO: we need to have an authentication token at some point

        String username = this.backendPhagebookUser;
        String password = this.backendPhagebookPassword;
        Map loginMap = new HashMap();
        loginMap.put("username", username);
        loginMap.put("credentials", password);
        clothoObject.login(loginMap);

        Vendor vendor = new Vendor();
        vendor.setName(name);
        vendor.setDescription(description);
        vendor.setContact(contact);

        if (!phone.isEmpty()) {
            vendor.setPhone(phone);
        }
        if (!url.isEmpty()) {
            vendor.setUrl(url);
        }

        //everything is set for that product
        ClothoAdapter.createVendor(vendor, clothoObject);
        JSONObject vendorJSON = new JSONObject();
        vendorJSON.put("id", vendor.getId());
        conn.closeConnection();
        response.setStatus(HttpServletResponse.SC_CREATED);
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        out.print(vendorJSON);
        out.flush();
        out.close();

        clothoObject.logout();

    } else {
        JSONObject msg = new JSONObject();
        msg.put("message", "Need to send name, description, and contact");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        out.print(msg);
        out.flush();
        out.close();
    }

}

From source file:com.imaginary.home.cloud.api.call.RelayCall.java

@Override
public void post(@Nonnull String requestId, @Nullable String userId, @Nonnull String[] path,
        @Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp,
        @Nonnull Map<String, Object> headers, @Nonnull Map<String, Object> parameters)
        throws RestException, IOException {
    try {/*from w w w .  j  ava  2 s.co m*/
        BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
        StringBuilder source = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            source.append(line);
            source.append(" ");
        }
        JSONObject object = new JSONObject(source.toString());

        if (!object.has("pairingCode") || object.isNull("pairingCode")) {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.MISSING_PAIRING_CODE,
                    "Pairing code is missing");
        }
        String code = object.getString("pairingCode");

        if (code.equalsIgnoreCase("null")) {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.MISSING_PAIRING_CODE,
                    "Pairing code is missing");
        }
        Location location = Location.findForPairing(code);

        if (location == null) {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_PAIRING_CODE,
                    "Invalid pairing code; pairing did not occur");
        }
        String relayName;

        if (object.has("name") && !object.isNull("name")) {
            relayName = object.getString("name");
        } else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.MISSING_DATA,
                    "Missing relay name from JSON");
        }
        ControllerRelay relay = location.pair(code, relayName);

        if (relay == null) {
            throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.PAIRING_FAILURE,
                    "Pairing failed due to an invalid pairing code or expired pairing code");
        }
        HashMap<String, Object> json = new HashMap<String, Object>();

        json.put("apiKeyId", relay.getControllerRelayId());
        json.put("apiKeySecret", Configuration.decrypt(location.getLocationId(), relay.getApiKeySecret()));
        resp.setStatus(HttpServletResponse.SC_CREATED);
        resp.getWriter().println((new JSONObject(json)).toString());
        resp.getWriter().flush();
    } catch (JSONException e) {
        throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_JSON,
                "Invalid JSON in body");
    } catch (PersistenceException e) {
        e.printStackTrace();
        throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR,
                "Internal database error");
    }
}

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

/**
 * Starts execution of a new process instance.  The processInstance representation
 * must contain, at minimum, a processDefinitionKey element to identify the process,
 * as well as any variables.  Note that if variables are not needed, it may be more
 * convenient to use startExecutionSimple.
 *
 * The response Location header will contain the URL of the newly created instance
 * @param pi/*  w w w . j a  va  2s.c  om*/
 * @param initVars set to 'true' to trigger initialization of variables with default values taken 
 * from the workflow Process element
 * @param response
 * @param req 
 */
@RequestMapping(value = "/active", method = RequestMethod.POST, params = "!execute")
public void startExecution(@RequestBody org.wiredwidgets.cow.server.api.service.ProcessInstance pi,
        @RequestParam(value = "init-vars", required = false) boolean initVars, HttpServletResponse response,
        HttpServletRequest req) {
    log.debug("startExecution: " + pi.getProcessDefinitionKey());

    // option to initialize the process instance with variables / values set in the master process
    /*if (initVars) {
    org.wiredwidgets.cow.server.api.model.v2.Process process = processService.getV2Process(pi.getProcessDefinitionKey());
    for (org.wiredwidgets.cow.server.api.model.v2.Variable var : process.getVariables().getVariables()) {
        addVariable(pi, var.getName(), var.getValue());
    }
    }*/

    String id = processInstanceService.executeProcess(pi);

    //Map<String, Object> params = new HashMap<String, Object>();
    /*if (pi.getVariables() != null) {
    for (Variable variable : pi.getVariables().getVariables()) {
        params.put(variable.getName(), variable.getValue());
    }
    }*/
    // COW-65 save history for all variables
    // org.jbpm.api.ProcessInstance pi = executionService.startProcessInstanceByKey(instance.getProcessDefinitionKey(), vars);

    //params.put("content", new HashMap<String,Object>());
    //org.drools.runtime.process.ProcessInstance pi2 = kSession.startProcess(pi.getProcessDefinitionKey(), params);

    System.out.println("STARTED PROCESS ID " + id);
    response.setStatus(HttpServletResponse.SC_CREATED); // 201
    response.setHeader("Location", req.getRequestURL() + "/" + id);
}

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

@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_V2_SESSION_ADD })
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
@RequestMapping(value = "", method = RequestMethod.POST)
public ModelAndView createSession(@RequestBody String data, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    request.setAttribute(PREDICATE, TAG_ADD_RESOURCE);
    User user = (User) request.getAttribute(Constants.USER);
    final JSONObject json = requestData(data);
    final ActionResponseDTO<Session> session = getSessionService()
            .createSession(this.buildSessionFromInputParameters(getValue(SESSION, json)), user);
    if (session.getErrors().getErrorCount() > 0) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else {//from   w w  w  .  j  a v a2 s  .co  m
        response.setStatus(HttpServletResponse.SC_CREATED);
    }
    SessionContextSupport.putLogParameter(EVENT_NAME, "create-session");
    SessionContextSupport.putLogParameter(USER_ID, user.getUserId());
    SessionContextSupport.putLogParameter(GOORU_UID, user.getPartyUid());
    String[] includeFields = getValue(FIELDS, json) != null ? getFields(getValue(FIELDS, json)) : null;
    String includes[] = (String[]) ArrayUtils.addAll(includeFields == null ? SESSION_INCLUDES : includeFields,
            ERROR_INCLUDE);
    return toModelAndViewWithIoFilter(session.getModelData(), RESPONSE_FORMAT_JSON, EXCLUDE_ALL, includes);
}

From source file:fr.gael.dhus.api.UploadController.java

@SuppressWarnings("unchecked")
@PreAuthorize("hasRole('ROLE_UPLOAD')")
@RequestMapping(value = "/upload", method = { RequestMethod.POST })
public void upload(Principal principal, HttpServletRequest req, HttpServletResponse res) throws IOException {
    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {
        User user = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal();
        // 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 .  ja  va  2s  .  com*/
            ArrayList<Long> collectionIds = new ArrayList<>();
            FileItem product = null;

            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                if (COLLECTIONSKEY.equals(item.getFieldName())) {
                    if (item.getString() != null && !item.getString().isEmpty()) {
                        for (String cid : item.getString().split(",")) {
                            collectionIds.add(new Long(cid));
                        }
                    }
                } else if (PRODUCTKEY.equals(item.getFieldName())) {
                    product = item;
                }
            }
            if (product == null) {
                res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Your request is missing a product file to upload.");
                return;
            }
            productUploadService.upload(user.getId(), product, collectionIds);
            res.setStatus(HttpServletResponse.SC_CREATED);
            res.getWriter().print("The file was created successfully.");
            res.flushBuffer();
        } catch (FileUploadException e) {
            logger.error("An error occurred while parsing request.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while parsing request : " + e.getMessage());
        } catch (UserNotExistingException e) {
            logger.error("You need to be connected to upload a product.", e);
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You need to be connected to upload a product.");
        } catch (UploadingException e) {
            logger.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (RootNotModifiableException e) {
            logger.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (ProductNotAddedException e) {
            logger.error("Your product can not be read by the system.", e);
            res.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Your product can not be read by the system.");
        }
    } else {
        res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

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

@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_TAG_ADD })
@RequestMapping(value = "", method = RequestMethod.POST)
public ModelAndView createTag(@RequestBody final String data, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    request.setAttribute(PREDICATE, TAG_ADD_RESOURCE);
    final User user = (User) request.getAttribute(Constants.USER);
    final ActionResponseDTO<Tag> tag = getTagService().createTag(this.buildTagFromInputParameters(data), user);
    if (tag.getErrors().getErrorCount() > 0) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else {//from   ww  w  .  ja v a2s .co m
        response.setStatus(HttpServletResponse.SC_CREATED);
    }

    String includes[] = (String[]) ArrayUtils.addAll(TAG_INCLUDES, ERROR_INCLUDE);
    return toModelAndViewWithIoFilter(tag.getModelData(), RESPONSE_FORMAT_JSON, EXCLUDE_ALL, true, includes);
}

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

@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_QUIZ_V2_ADD })
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
@RequestMapping(value = "", method = RequestMethod.POST)
public ModelAndView createQuiz(@RequestBody String data, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    User user = (User) request.getAttribute(Constants.USER);
    JSONObject json = requestData(data);
    ActionResponseDTO<Quiz> responseDTO = this.getQuizSerivce().createQuiz(
            this.buildQuizFromInputParameters(getValue(QUIZ, json), user), true,
            this.quizSerivce.buildOptionsParameter(getValue("options", json)));
    if (responseDTO.getErrors().getErrorCount() > 0) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else {/*w  ww  .ja  v  a 2s. c om*/
        response.setStatus(HttpServletResponse.SC_CREATED);
    }
    String[] includeFields = getValue(FIELDS, json) != null ? getFields(getValue(FIELDS, json)) : null;
    String includesDefault[] = (String[]) ArrayUtils.addAll(QUIZ_INCLUDES, COLLECTION_INCLUDE_FIELDS);
    String includes[] = (String[]) ArrayUtils.addAll(includeFields == null ? includesDefault : includeFields,
            ERROR_INCLUDE);
    return toModelAndView(serialize(responseDTO.getModelData(), RESPONSE_FORMAT_JSON, EXCLUDE_ALL, includes));
}