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.apache.nifi.web.security.x509.X509AuthenticationFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    final HttpServletResponse httpResponse = (HttpServletResponse) response;

    // determine if this request is attempting to create a new account
    if (isNewAccountRequest((HttpServletRequest) request)) {
        // determine if this nifi supports new account requests
        if (properties.getSupportNewAccountRequests()) {
            // ensure there is a certificate in the request
            X509Certificate certificate = certificateExtractor
                    .extractClientCertificate((HttpServletRequest) request);
            if (certificate != null) {
                // extract the principal from the certificate
                Object certificatePrincipal = principalExtractor.extractPrincipal(certificate);
                String principal = certificatePrincipal.toString();

                // log the new user account request
                logger.info("Requesting new user account for " + principal);

                try {
                    // get the justification
                    String justification = request.getParameter("justification");
                    if (justification == null) {
                        justification = StringUtils.EMPTY;
                    }//  w  w w  . j  ava2s  .  com

                    // create the pending user account
                    userService.createPendingUserAccount(principal, justification);

                    // generate a response
                    httpResponse.setStatus(HttpServletResponse.SC_CREATED);
                    httpResponse.setContentType("text/plain");

                    // write the response message
                    PrintWriter out = response.getWriter();
                    out.println("Not authorized. User account created. Authorization pending.");
                } catch (IllegalArgumentException iae) {
                    handleUserServiceError((HttpServletRequest) request, httpResponse,
                            HttpServletResponse.SC_BAD_REQUEST, iae.getMessage());
                } catch (AdministrationException ae) {
                    handleUserServiceError((HttpServletRequest) request, httpResponse,
                            HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ae.getMessage());
                }
            } else {
                // can this really happen?
                handleMissingCertificate((HttpServletRequest) request, httpResponse);
            }
        } else {
            handleUserServiceError((HttpServletRequest) request, httpResponse, HttpServletResponse.SC_NOT_FOUND,
                    "This NiFi does not support new account requests.");
        }
    } else {
        try {
            // this not a request to create a user account - try to authorize
            super.doFilter(request, response, chain);
        } catch (AuthenticationException ae) {
            // continue the filter chain since anonymous access should be supported
            if (!properties.getNeedClientAuth()) {
                chain.doFilter(request, response);
            } else {
                // create an appropriate response for the given exception
                handleUnsuccessfulAuthentication((HttpServletRequest) request, httpResponse, ae);
            }
        }
    }
}

From source file:org.apache.wookie.BasicLTIServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //debugParameters(request);
    String userId = request.getParameter("user_id"); //$NON-NLS-1$
    String sharedDataKey = request.getParameter("resource_link_id"); //$NON-NLS-1$
    // We use this mapping as BasicLTI assumes one "tool provider" per endpoint URL
    // We map the value onto the actual widget id (IRI)
    String widgetId = Controller.getResourceId(request); //$NON-NLS-1$
    widgetId = getWidgetGuid(widgetId);//from  www  .ja  v a 2  s.c  om
    // TODO Get the oAuth token, for now just use the consumer key as a quick demo hack
    String token = request.getParameter("oauth_consumer_key");
    String locale = request.getParameter("launch_presentation_locale");//replace with real one
    // Construct the internal key
    sharedDataKey = SharedDataHelper.getInternalSharedDataKey(token, widgetId, sharedDataKey);

    HttpSession session = request.getSession(true);
    Messages localizedMessages = LocaleHandler.localizeMessages(request);

    if (userId == null || sharedDataKey == null || widgetId == null)
        error(500, request, response);

    // Construct a proxy URL for this instance
    checkProxy(request);

    // Get an instance
    IPersistenceManager persistenceManager = PersistenceManagerFactory.getPersistenceManager();
    IWidgetInstance instance = persistenceManager.findWidgetInstanceByGuid(token, userId, sharedDataKey,
            widgetId);

    // Widget instance exists?
    if (instance == null) {
        instance = WidgetInstanceFactory.getWidgetFactory(session, localizedMessages).newInstance(token, userId,
                sharedDataKey, "", widgetId, locale);
        response.setStatus(HttpServletResponse.SC_CREATED);
    }

    // Not a valid widget
    if (instance == null) {
        error(HttpServletResponse.SC_NOT_FOUND, request, response);
        return;
    }

    response.setStatus(HttpServletResponse.SC_OK);

    // Set some properties, e.g. participant info and roles
    setParticipant(instance, userId, request);

    boolean isModerator = false;
    if (request.getParameter("roles") != null) {
        for (String role : BASICLTI_ADMIN_ROLES) {
            if (StringUtils.containsIgnoreCase(request.getParameter("roles"), role))
                isModerator = true;
        }
    }
    if (isModerator)
        setOwner(instance, userId);
    // Set any other properties as preferences
    setPreferences(instance, request);

    // Redirect to the instance URL
    try {
        // Construct widget instance URL
        // For some reason this doesn't work:
        // String url = URLDecoder.decode(super.getUrl(request, instance),"UTF-8");
        String url = super.getUrl(request, instance).toString().replace("&", "&");
        response.sendRedirect(url);
    } catch (Exception e) {
        error(500, request, response);
        return;
    }

}

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

protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    try {//w w  w  .j av a  2s.  c  o  m
        String userName = restUtils.extractResourceName(req.getPathInfo());

        WSUser user = restUtils.populateServiceObject(restUtils.unmarshal(WSUser.class, req.getInputStream()));
        if (log.isDebugEnabled()) {
            log.debug("un Marshaling OK");
        }

        if (validateUserForPutOrUpdate(user)) {
            if (!isAlreadyAUser(user)) {
                userAndRoleManagementService.putUser(user);
                restUtils.setStatusAndBody(HttpServletResponse.SC_CREATED, resp, "");
            } else {
                throw new ServiceException(HttpServletResponse.SC_FORBIDDEN,
                        "user " + user.getUsername() + "already exists");
            }
        } else
            throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "check request parameters");

    } catch (AxisFault axisFault) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, axisFault.getLocalizedMessage());
    } catch (IOException e) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getLocalizedMessage());
    } catch (JAXBException e) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getLocalizedMessage());
    }

}

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

@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_TASK_MANAGEMENT_ADD })
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
@RequestMapping(value = { "" }, method = RequestMethod.POST)
public ModelAndView createTask(HttpServletRequest request, @RequestBody String data,
        HttpServletResponse response) throws Exception {
    request.setAttribute(PREDICATE, TASK_CREATE_TASK);
    User user = (User) request.getAttribute(Constants.USER);
    JSONObject json = requestData(data);
    ActionResponseDTO<Task> task = getTaskService().createTask(
            this.buildTaskFromInputParameters(getValue(TASK, json)),
            getValue(PLANNED_END_DATE, json) != null ? getValue(PLANNED_END_DATE, json) : null, user,
            this.buildAttachFromInputParameters(getValue(ATTACH_TO, json)));
    if (task.getErrors().getErrorCount() > 0) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else {//  ww  w.ja  v  a 2 s  .  c  o  m
        response.setStatus(HttpServletResponse.SC_CREATED);
    }
    String[] includeFields = getValue(FIELDS, json) != null ? getFields(getValue(FIELDS, json)) : null;
    String includes[] = (String[]) ArrayUtils.addAll(includeFields == null ? TASK_INCLUDES : includeFields,
            ERROR_INCLUDE);

    SessionContextSupport.putLogParameter(EVENTNAME, CREATE_TASK);
    SessionContextSupport.putLogParameter(TASK_UID, task.getModel().getGooruOid());
    SessionContextSupport.putLogParameter(CREATOR_UID,
            task.getModel().getCreatedOn() != null ? task.getModel().getCreator().getPartyUid() : null);
    SessionContextSupport.putLogParameter(TASK_CREATED_DATE, task.getModel().getCreatedOn());
    SessionContextSupport.putLogParameter(TASK_TITLE, task.getModel().getTitle());
    return toModelAndViewWithIoFilter(task.getModelData(), RESPONSE_FORMAT_JSON, EXCLUDE_ALL, includes);
}

From source file:org.ldp4j.apps.ldp4ro.servlets.FileUploaderServlet.java

/**
 * Upon receiving file upload submission, parses the request to read
 * upload data and saves the file on disk.
 *///  w ww . j  a v a 2s  .com
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    logger.debug("Received a POST request on '{}'", request.getRequestURL());

    // checks if the request actually contains upload file
    if (!ServletFileUpload.isMultipartContent(request)) {
        // if not, send an error message
        logger.error("Not a multipart request. The File Uploader only works with multipart requests ...");
        sendMessage("Not a multipart request", response);
        return;
    }

    // Configures upload settings
    ServletFileUpload upload = getFileItemFactory();

    // parses the request's content to extract file data
    @SuppressWarnings("unchecked")
    List<FileItem> formItems = null;
    try {
        formItems = upload.parseRequest(request);

        if (formItems != null && formItems.size() > 0) {
            // iterates over form's fields
            String fileName = null;
            File storeFile = null;

            for (FileItem item : formItems) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    fileName = new File(item.getName()).getName();

                    logger.trace("Processing the file upload '{}'", fileName);

                    String filePath = ConfigManager.getFileUploadDir().getAbsolutePath() + File.separator
                            + fileName;
                    storeFile = new File(filePath);

                    // We don't want to override existing files. If there is a file with the same name already,
                    // we will just prefix the file name with a number
                    int counter = 0;
                    String origFileName = fileName;
                    while (storeFile.exists()) {
                        fileName = counter++ + origFileName;
                        logger.trace("File with the name  '{}' already exists. Trying out the new name '{}'",
                                storeFile.getAbsolutePath(), fileName);
                        filePath = ConfigManager.getFileUploadDir().getAbsolutePath() + File.separator
                                + fileName;
                        storeFile = new File(filePath);
                    }
                    item.write(storeFile);
                    logger.trace("Successfully written the file at '{}'", storeFile.getAbsolutePath());
                }

            }

            if (fileName == null || storeFile == null) {
                sendMessage("Error occurred while uploading the file ...", response);
                return;
            }

            URL url = URLUtils.generateFileURL(fileName);

            // Preparing the response
            response.setStatus(HttpServletResponse.SC_CREATED);
            response.setHeader("Location", url.toExternalForm());
            sendMessage(url.toExternalForm(), response);

        }

    } catch (FileUploadException e) {
        throw new ServletException("Error parsing upload request ...", e);
    } catch (Exception e) {
        throw new ServletException("Error occurred while uploading the file ...", e);
    }
}

From source file:net.duckling.ddl.web.api.rest.TeamController.java

@RequestMapping(method = RequestMethod.POST)
public void create(@RequestParam("teamCode") String teamCode, @RequestParam("displayName") String displayName,
        @RequestParam("description") String description,
        @RequestParam(value = "accessType", required = false) String accessType,
        @RequestParam(value = "autoTeamCode", required = false) Boolean autoTeamCode,
        @RequestParam(value = "type", required = false) String type, HttpServletRequest request,
        HttpServletResponse response) {//from w ww . j a v a  2s .  c  o m
    String uid = getCurrentUid(request);
    accessType = StringUtils.defaultIfBlank(accessType, Team.ACCESS_PRIVATE);
    autoTeamCode = autoTeamCode == null ? false : autoTeamCode;
    teamCode = StringUtils.defaultString(teamCode).trim();

    LOG.info("create team start... {uid:" + uid + ",teamCode:" + teamCode + ",displayName:" + displayName
            + ",accessType:" + accessType + ",autoTeamCode:" + autoTeamCode + ",type:" + type + "}");

    //??
    if (!ClientValidator.validate(request)) {
        LOG.warn("client is not allowed. {teamCode:" + teamCode + ",type:" + type + ",host:"
                + ClientValidator.getRealIp(request) + ",pattern:" + ClientValidator.getClientIpPattern(request)
                + "}");

        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        JsonUtil.write(response, ErrorMsg.NEED_PERMISSION);
        return;
    }

    if (Team.CONFERENCE_TEAM.equals(type)) {
        //nothing
    } else {
        //
        type = Team.COMMON_TEAM;
    }

    if (autoTeamCode) {
        teamCode = tidyTeamCode(teamCode);
        if ("".equals(teamCode)) {
            teamCode = getRandomString(5);
        }
        teamCode = teamCodeIncrement(teamCode, 0);
    }
    if (!checkParams(teamCode, displayName, description, accessType, response)) {
        return;
    }

    Map<String, String> params = getParamsForCreate(uid, teamCode, displayName, description, accessType, type);
    int teamId = teamService.createAndStartTeam(uid, params);
    teamService.addTeamMembers(teamId, new String[] { uid }, new String[] { super.getCurrentUsername(request) },
            Team.AUTH_ADMIN);
    LOG.info("create team success. {uid:" + uid + ", tid:" + teamId + ", parmas:" + params + "}");

    response.setStatus(HttpServletResponse.SC_CREATED);
    JsonUtil.write(response, VoUtil.getTeamVo(teamService.getTeamByID(teamId)));
}

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

@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_PARTY_CUSTOM_FIELD_ADD })
@RequestMapping(method = RequestMethod.POST, value = "/default/{id}/custom-field")
public ModelAndView createDefaultPartyCustomField(
        @RequestParam(value = TYPE, required = true, defaultValue = USER_TYPE) String type,
        @PathVariable(value = ID) String partyId, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    User user = (User) request.getAttribute(Constants.USER);
    String includes[] = (String[]) ArrayUtils.addAll(PARTY_CUSTOM_INCLUDES, ERROR_INCLUDE);
    List<PartyCustomField> partyCustomFields = this.getPartyservice()
            .createPartyDefaultCustomAttributes(partyId, user, type);
    if (partyCustomFields != null) {
        response.setStatus(HttpServletResponse.SC_CREATED);
    }//  ww  w.  j  ava 2s  .c o m
    return toModelAndViewWithIoFilter(partyCustomFields, RESPONSE_FORMAT_JSON, EXCLUDE_ALL, includes);
}

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

@PreAuthorize("hasRole('REPORT_CREATE')")
@RequestMapping(method = RequestMethod.POST, value = "/create")
public ReportTO create(final HttpServletResponse response, @RequestBody final ReportTO reportTO) {

    LOG.debug("Creating report " + reportTO);

    Report report = new Report();
    binder.getReport(report, reportTO);// w ww .  j  a va 2  s. c  o m
    report = reportDAO.save(report);

    try {
        jobInstanceLoader.registerJob(report);
    } catch (Exception e) {
        LOG.error("While registering quartz job for report " + report.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.getReportTO(report);
}

From source file:ge.taxistgela.servlet.RegistrationServlet.java

public void registerDriver(HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (!verify(request, response))
        return;//from ww w  .  j a  va2 s  . co m

    DriverManagerAPI driverManager = (DriverManagerAPI) request.getServletContext()
            .getAttribute(DriverManagerAPI.class.getName());
    CompanyManagerAPI companyManager = (CompanyManagerAPI) request.getServletContext()
            .getAttribute(CompanyManagerAPI.class.getName());

    DriverPreference driverPreference = new DriverPreference(-1, 0.1, 0.0);

    ErrorCode code = driverManager.insertDriverPreference(driverPreference);
    if (code.errorAccrued()) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    Car car = new Car(RandomStringUtils.randomAlphanumeric(7), "Untitled", 1900, false, 0);

    code = driverManager.insertCar(car);
    if (code.errorAccrued()) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    Integer companyID = null;
    if (request.getParameter("drivercompanyCode") != "") {
        companyID = companyManager.getCompanyIDByCode(request.getParameter("drivercompanyCode"));
        if (companyID == null) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
    }

    Driver driver = new Driver(-1, request.getParameter("driverpersonalID"),
            request.getParameter("driveremail"), request.getParameter("driverpassword"), null,
            request.getParameter("driverfirstName"), request.getParameter("driverlastName"),
            getGender(request.getParameter("drivergender")), request.getParameter("driverphoneNumber"), car,
            filterSocialID(request.getParameter("driverfacebookId")),
            filterSocialID(request.getParameter("drivergoogleplusId")), 5.0, driverPreference, false, false,
            false);

    registerSuper(driverManager, driver, request, response);

    if (response.getStatus() == HttpServletResponse.SC_CREATED) {
        Company company = (Company) companyManager.getByID(companyID);
        driver = (Driver) driverManager.getByEmail(driver.getEmail());

        if (company != null && driver != null) {
            EmailSender.verifyCompany(driver, company);
        }
    }
}

From source file:org.structr.web.resource.ResetPasswordResource.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);
        }//from w  ww.j av  a2 s  .c o  m

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

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

            final App app = StructrApp.getInstance(securityContext);
            user = (Principal) result.get(0);

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

            existingUser = true;

        } else {

            // We only handle existing users but we don't want to disclose if this e-mail address exists,
            // so we're failing silently here
            return new RestMethodResult(HttpServletResponse.SC_OK);
        }

        if (user != null) {

            if (!sendResetPasswordLink(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);

    }

}