List of usage examples for javax.servlet.http HttpServletResponse SC_CREATED
int SC_CREATED
To view the source code for javax.servlet.http HttpServletResponse SC_CREATED.
Click Source Link
From source file:org.eclipse.orion.server.git.servlets.GitBranchHandlerV1.java
@Override protected boolean handlePost(RequestInfo requestInfo) throws ServletException { String gitSegment = requestInfo.gitSegment; HttpServletRequest request = requestInfo.request; HttpServletResponse response = requestInfo.response; Repository db = requestInfo.db;/*w ww.j a v a2 s . c o m*/ IPath filePath = requestInfo.filePath; JSONObject toCreate = requestInfo.getJSONRequest(); try { if (gitSegment == null) { // expected path /gitapi/branch/file/{filePath} String branchName = toCreate.optString(ProtocolConstants.KEY_NAME, null); String startPoint = toCreate.optString(GitConstants.KEY_BRANCH_NAME, null); if (branchName == null || branchName.isEmpty()) { if (startPoint == null || startPoint.isEmpty()) return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Branch name must be provided", null)); else { String shortName = Repository.shortenRefName(startPoint); branchName = shortName.substring(shortName.indexOf("/") + 1); //$NON-NLS-1$ } } CreateBranchCommand cc = new Git(db).branchCreate(); cc.setName(branchName); if (startPoint != null && !startPoint.isEmpty()) { cc.setStartPoint(startPoint); cc.setUpstreamMode(SetupUpstreamMode.TRACK); } Ref ref = cc.call(); URI cloneLocation = BaseToCloneConverter.getCloneLocation(getURI(request), BaseToCloneConverter.BRANCH_LIST); JSONObject result = new Branch(cloneLocation, db, ref).toJSON(); OrionServlet.writeJSONResponse(request, response, result); response.setHeader(ProtocolConstants.HEADER_LOCATION, result.getString(ProtocolConstants.KEY_LOCATION)); response.setStatus(HttpServletResponse.SC_CREATED); return true; } String msg = NLS.bind("Failed to create a branch for {0}", filePath); //$NON-NLS-1$ return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); } catch (Exception e) { return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occured when creating a branch.", e)); } }
From source file:org.openo.auth.common.CommonMockUp.java
/** * <br/>// w w w . ja v a 2 s .c o m * * @param value * @since */ public ClientResponse mockTokenClientDoLogin() { final ClientResponse resp = new ClientResponse(); new MockUp<TokenServiceClient>() { @Mock public ClientResponse doLogin(String json) { resp.setStatus(HttpServletResponse.SC_CREATED); resp.setBody("body"); resp.setHeader("header"); return resp; } }; return resp; }
From source file:org.opendatakit.aggregate.servlet.OdkTablesUploadTableFromCSVServlet.java
/** * Handler for HTTP Post request that takes a CSV file, uses that file to add * a new OdkTables table to the datastore. *//* w ww . j av a 2s. c o m*/ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { ServiceUtils.examineRequest(getServletContext(), req); // TODO here do I need to handle the log stuff? CallingContext cc = ContextFactory.getCallingContext(this, req); if (!ServletFileUpload.isMultipartContent(req)) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ErrorConsts.NO_MULTI_PART_CONTENT); return; } try { MultiPartFormData uploadedFormItems = new MultiPartFormData(req); MultiPartFormItem csvFile = uploadedFormItems.getFormDataByFieldName("table_file"); String tableName = uploadedFormItems.getSimpleFormField("table_name"); addOpenDataKitHeaders(resp); resp.setStatus(HttpServletResponse.SC_CREATED); resp.setContentType(HtmlConsts.RESP_TYPE_PLAIN); resp.setCharacterEncoding(HtmlConsts.UTF8_ENCODE); CsvUtil csvUtil = new CsvUtil(); byte[] bytes = csvFile.getStream().toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, CharEncoding.UTF_8)); boolean success = csvUtil.importNewTable(br, tableName, cc); PrintWriter out = resp.getWriter(); if (success) { out.write("The table was created successfully."); } else { // something went wrong while uploading. out.write("There was a problem uploading the table."); } } catch (FileUploadException e) { logger.error("error uploading csv: " + e.getMessage()); e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ErrorConsts.PERSISTENCE_LAYER_PROBLEM + "\n" + e.getMessage()); } catch (BadColumnNameExceptionClient e) { logger.error("bad column name: " + e.getMessage()); e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ErrorConsts.PERSISTENCE_LAYER_PROBLEM); } catch (ImportFromCSVExceptionClient e) { logger.error("problem importing from CSV: " + e.getMessage()); e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ErrorConsts.PARSING_PROBLEM); } catch (ETagMismatchExceptionClient e) { logger.error("etag mismatch while importing: " + e.getMessage()); e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ErrorConsts.PERSISTENCE_LAYER_PROBLEM); } catch (PermissionDeniedExceptionClient e) { logger.error("permission denied while uploading: " + e.getMessage()); e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ErrorConsts.PERSISTENCE_LAYER_PROBLEM); } catch (EntityNotFoundExceptionClient e) { logger.error("entity not found while uploading: " + e.getMessage()); e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ErrorConsts.PERSISTENCE_LAYER_PROBLEM); } }
From source file:com.basetechnology.s0.agentserver.appserver.HandlePost.java
public boolean handlePost() throws IOException, ServletException, AgentAppServerException, SymbolException, RuntimeException, AgentServerException, JSONException, TokenizerException, ParserException { // Extract out commonly used info String path = httpInfo.path;//from ww w .j av a 2 s. c om String[] pathParts = httpInfo.pathParts; Request request = httpInfo.request; HttpServletResponse response = httpInfo.response; AgentServer agentServer = httpInfo.agentServer; String lcPath = path.toLowerCase(); if (path.equalsIgnoreCase("/users")) { // User can specify parameters in JSON or as query parameters // Query overrides JSON if query parameter is non-null JSONObject userJson = getJsonRequest(httpInfo); String id = request.getParameter("id"); if (id == null) id = userJson.optString("id"); else userJson.put("id", id); String password = request.getParameter("password"); if (password == null) password = userJson.optString("password"); else userJson.put("password", password); String passwordHint = request.getParameter("password_hint"); if (passwordHint == null) passwordHint = userJson.optString("password_hint"); else userJson.put("password_hint", passwordHint); String fullName = request.getParameter("full_name"); if (fullName == null) fullName = userJson.optString("full_name"); else userJson.put("full_name", fullName); String displayName = request.getParameter("display_name"); if (displayName == null) displayName = userJson.optString("display_name"); else userJson.put("display_name", displayName); String nickName = request.getParameter("nick_name"); if (nickName == null) nickName = userJson.optString("nick_name"); else userJson.put("nick_name", nickName); String organization = request.getParameter("organization"); if (organization == null) organization = userJson.optString("organization"); else userJson.put("organization", organization); String bio = request.getParameter("bio"); if (bio == null) bio = userJson.optString("bio"); else userJson.put("bio", bio); String interests = request.getParameter("interests"); if (interests == null) interests = userJson.optString("interests"); else userJson.put("interests", interests); String incognitoString = request.getParameter("incognito"); boolean incognito = incognitoString != null && (incognitoString.equalsIgnoreCase("true") || incognitoString.equalsIgnoreCase("yes") || incognitoString.equalsIgnoreCase("on")); if (incognitoString == null) incognito = userJson.optBoolean("incognito"); else userJson.put("incognito", incognito ? "true" : false); String email = request.getParameter("email"); if (email == null) email = userJson.optString("email"); else userJson.put("email", email); String comment = request.getParameter("comment"); if (comment == null) comment = userJson.optString("comment"); else userJson.put("comment", comment); if (id == null) { throw new AgentAppServerBadRequestException("Missing id query parameter"); } else if (id.trim().length() == 0) { throw new AgentAppServerBadRequestException("Empty id query parameter"); } else if (id.trim().length() < User.MIN_ID_LENGTH) { throw new AgentAppServerBadRequestException("Id must be at least 4 characters"); } else if (password == null) { throw new AgentAppServerBadRequestException("Missing password query parameter"); } else if (password.trim().length() == 0) { throw new AgentAppServerBadRequestException("Empty password query parameter"); } else if (password.trim().length() < User.MIN_ID_LENGTH) { throw new AgentAppServerBadRequestException("Password must be at least 4 characters"); } else if (agentServer.users.containsKey(id.trim())) { throw new AgentAppServerBadRequestException("User with that id already exists"); } else { id = id.trim(); password = password.trim(); log.info("Adding new user: " + id); Boolean approved = !agentServer.config.getBoolean("admin_approve_user_create"); User newUser = new User(id, password, passwordHint, fullName, displayName, nickName, organization, bio, interests, email, incognito, comment, approved, true, true, null, null); newUser.generateSha(); agentServer.addUser(newUser); response.setStatus(HttpServletResponse.SC_CREATED); // TODO: Set Location header with URL return true; } } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-]*/agent_definitions$")) { User user = checkUserAccess(true); JSONObject agentDefinitionJson = getJsonRequest(httpInfo); if (agentDefinitionJson == null) throw new AgentAppServerBadRequestException("Invalid agent definition JSON object"); log.info("Adding new agent definition for user: " + user.id); // Parse and add the agent definition AgentDefinition agentDefinition = agentServer.addAgentDefinition(user, agentDefinitionJson); // Done response.setStatus(HttpServletResponse.SC_CREATED); } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-]*/agents$")) { User user = checkUserAccess(true); JSONObject agentInstanceJson = getJsonRequest(httpInfo); if (agentInstanceJson == null) throw new AgentAppServerBadRequestException("Invalid agent instance JSON object"); log.info("Adding new agent instance for user: " + user.id); // Parse and add the agent instance AgentInstance agentInstance = agentServer.addAgentInstance(user, agentInstanceJson); // Done response.setStatus(HttpServletResponse.SC_CREATED); } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-*]*/website_access$")) { User user = checkAdminUserAccess(); JSONObject accessControlsJson = getJsonRequest(httpInfo); if (accessControlsJson == null) throw new AgentAppServerBadRequestException("Invalid website access JSON object"); log.info("Adding web site access controls for user: " + user.id); // Add the web site access controls for the user agentServer.addWebSiteAccessControls(user, accessControlsJson); // Done response.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { throw new AgentAppServerException(HttpServletResponse.SC_NOT_FOUND, "Path does not address any existing object"); } return true; }
From source file:com.jaspersoft.jasperserver.rest.services.RESTReport.java
/** * The get method get resources of a produced report * Urls in this case look like /reports/samples/myreport;uniqueidentifier?file=filename *//* www .j av a 2s. com*/ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServiceException { // Get the uri of the resource String uuid = restUtils.extractRepositoryUri(req.getPathInfo()); if (uuid.startsWith("/")) uuid = uuid.substring(1); // Add all the options... Map<String, String> options = new HashMap<String, String>(); // Add as option all the GET parameters... Enumeration en = req.getParameterNames(); while (en.hasMoreElements()) { String key = (String) en.nextElement(); options.put(key, req.getParameter(key)); } // Find the report in session... HttpSession session = req.getSession(); Report report = (Report) session.getAttribute(uuid); if (report == null) { restUtils.setStatusAndBody(HttpServletResponse.SC_NOT_FOUND, resp, "Report not found (uuid not found in session)"); return; } JasperPrint jp = report.getJasperPrint(); // highcharts report for REST v1 is by default noninteractive. if (!options.containsKey(Argument.PARAM_INTERACTIVE)) { options.put(Argument.PARAM_INTERACTIVE, Boolean.FALSE.toString()); } OperationResult or = runReportService.exportReport(report.getOriginalUri(), jp, options, report.getAttachments()); if (or.getReturnCode() != 0) { restUtils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, or.getMessage()); return; } else { // If the jasperprint is present as attribute, it means it has been modified // in some way (i.e. using a RUN_TRANSFORMER_KEY). if (runReportService.getAttributes().get("jasperPrint") != null) { jp = (JasperPrint) runReportService.getAttributes().get("jasperPrint"); report.setJasperPrint(jp); } // Send out the xml... resp.setContentType("text/xml; charset=UTF-8"); restUtils.setStatusAndBody(HttpServletResponse.SC_CREATED, resp, report.toXml()); } }
From source file:org.ednovo.gooru.controllers.v2.api.EventRestV2Controller.java
@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_EVENT_MAPPING_UPDATE }) @RequestMapping(method = { RequestMethod.PUT }, value = "/{id}/template-mapping") public ModelAndView updateEventMapping(@PathVariable(value = ID) String id, @RequestBody String data, HttpServletRequest request, HttpServletResponse response) throws Exception { User user = (User) request.getAttribute(Constants.USER); EventMapping eventMapping = getEventService() .updateEventMapping(this.buildEventMappingFromInputParameters(data, id), user); response.setStatus(HttpServletResponse.SC_CREATED); String includes[] = (String[]) ArrayUtils.addAll(EVENT_MAPPING_INCLUDES, ERROR_INCLUDE); return toModelAndViewWithIoFilter(eventMapping, RESPONSE_FORMAT_JSON, EXCLUDE_ALL, true, includes); }
From source file:org.opencastproject.adminui.endpoint.TasksEndpoint.java
@POST @Path("/new") @RestQuery(name = "createNewTask", description = "Creates a new task by the given metadata as JSON", returnDescription = "The task identifiers", restParameters = { @RestParameter(name = "metadata", isRequired = true, description = "The metadata as JSON", type = RestParameter.Type.TEXT) }, reponses = { @RestResponse(responseCode = HttpServletResponse.SC_CREATED, description = "Task sucessfully added"), @RestResponse(responseCode = SC_NOT_FOUND, description = "If the workflow definition is not found"), @RestResponse(responseCode = SC_BAD_REQUEST, description = "If the metadata is not set or couldn't be parsed") }) public Response createNewTask(@FormParam("metadata") String metadata) throws NotFoundException { if (StringUtils.isBlank(metadata)) { logger.warn("No metadata set"); return RestUtil.R.badRequest("No metadata set"); }/*from w ww . j a v a 2 s. c om*/ JSONObject metadataJson; try { metadataJson = (JSONObject) parser.parse(metadata); } catch (Exception e) { logger.warn("Unable to parse metadata {}", metadata); return RestUtil.R.badRequest("Unable to parse metadata"); } String workflowId = (String) metadataJson.get("workflow"); if (StringUtils.isBlank(workflowId)) return RestUtil.R.badRequest("No workflow set"); JSONArray eventIds = (JSONArray) metadataJson.get("eventIds"); if (eventIds == null) return RestUtil.R.badRequest("No eventIds set"); JSONObject configuration = (JSONObject) metadataJson.get("configuration"); Stream<Entry<String, String>> options = Stream.empty(); if (configuration != null) { try { options = options.append(JSONUtils .toMap(new org.codehaus.jettison.json.JSONObject(configuration.toJSONString())).entrySet()); } catch (JSONException e) { logger.warn("Unable to parse workflow options to map: {}", ExceptionUtils.getStackTrace(e)); return RestUtil.R.badRequest("Unable to parse workflow options to map"); } } Map<String, String> optionsMap = options.filter(new Fn<Map.Entry<String, String>, Boolean>() { @Override public Boolean ap(Entry<String, String> a) { if ("eventIds".equalsIgnoreCase(a.getKey())) return false; return true; } }).foldl(new HashMap<String, String>(), TasksEndpoint.<String, String>mapFold()); WorkflowDefinition wfd; try { wfd = workflowService.getWorkflowDefinitionById(workflowId); } catch (WorkflowDatabaseException e) { logger.error("Unable to get workflow definition {}: {}", workflowId, ExceptionUtils.getStackTrace(e)); return RestUtil.R.serverError(); } List<WorkflowInstance> instances = archive.applyWorkflow(workflow(wfd, optionsMap), httpMediaPackageElementProvider.getUriRewriter(), IteratorUtils.toList(eventIds.iterator())); return Response.status(Status.CREATED) .entity(StringUtils.join(Stream.$(instances).map(getWorkflowIds).toList(), ",")).build(); }
From source file:com.imaginary.home.cloud.api.call.LocationCall.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 {// w w w.j av a 2 s . c o m if (userId == null) { throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.RELAY_NOT_ALLOWED, "A relay cannot add locations"); } User user = User.getUserByUserId(userId); if (user == null) { throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.NO_SUCH_USER, "An error occurred identifying the user record for this key"); } BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream())); StringBuilder source = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { source.append(line); source.append(" "); } String name = null, description = null, tz = null; JSONObject object = new JSONObject(source.toString()); if (object.has("name") && !object.isNull("name")) { name = object.getString("name"); } if (object.has("description") && !object.isNull("description")) { description = object.getString("description"); } if (object.has("timeZone") && !object.isNull("timeZone")) { tz = object.getString("timeZone"); } if (name == null || description == null) { throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.MISSING_DATA, "Required fields: name, description"); } TimeZone timeZone = (tz == null ? TimeZone.getTimeZone("UTC") : TimeZone.getTimeZone(tz)); Location location = Location.create(userId, name, description, timeZone); user.grant(location); resp.setStatus(HttpServletResponse.SC_CREATED); resp.getWriter().println((new JSONObject(toJSON(location))).toString()); resp.getWriter().flush(); } catch (JSONException e) { throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_JSON, "Invalid JSON in request"); } catch (PersistenceException e) { throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR, e.getMessage()); } }
From source file:com.lp.webapp.cc.CCOrderResponseServlet.java
private void processOrder(HttpServletRequest req, HttpServletResponse response, FileItem file) { authHeader.setToken(req.getParameter(PARAM_TOKEN)); CreateOrderResult result = processEjbOrder(response, file); int httpStatus = getHttpStatusforEjbStatus(result); response.setStatus(httpStatus);/*from www .j a v a 2 s . co m*/ myLogger.info("Returning httpStatus '" + httpStatus + "' for request '" + file.getName() + "'. Status (" + result.getRc() + ")"); if (!(httpStatus == HttpServletResponse.SC_CREATED || httpStatus == HttpServletResponse.SC_OK)) { saveXmlFile(file); } }
From source file:org.ednovo.gooru.controllers.v2.api.UserManagementRestV2Controller.java
@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_USER_ADD }) @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @RequestMapping(method = { RequestMethod.POST }, value = "") public ModelAndView createUser(HttpServletRequest request, @RequestBody String data, @RequestParam(value = SESSIONTOKEN, required = false) String sessionToken, @RequestParam(value = SHARED_SECRETKEY, required = false) String sharedSecretKey, @RequestParam(value = ORG_ADMIN, required = false, defaultValue = "false") Boolean orgAdmin, @RequestParam(value = ADMIN_ORGANIZATION_UID, required = false) String adminOrganizationUid, HttpServletResponse response) throws Exception { JSONObject json = requestData(data); User creator = this.buildUserFromInputParameters((getValue(USER, json))); String sessionId = request.getSession().getId(); String dateOfBirth = getValue(DATEOFBIRTH, json); User apiCaller = (User) request.getAttribute(Constants.USER); if (getValue(CHILDFLAG, json) != null ? Boolean.parseBoolean(getValue(CHILDFLAG, json)) : false) { dateOfBirth = dateOfBirth != null ? dateOfBirth.replace("d", "/") : dateOfBirth; }//from w w w . j a v a 2 s. co m // Check user organization permission if (creator.getOrganization() != null && creator.getOrganization().getOrganizationCode() != null && apiCaller != null && !creator.getOrganization().getOrganizationCode().equalsIgnoreCase(GOORU)) { this.getUserManagementService() .validateUserOrganization(creator.getOrganization().getOrganizationCode(), sharedSecretKey); } User user = this.getUserManagementService().createUserWithValidation(creator, getValue(PASSWORD, json), null, getValue(CONFIRM_STATUS, json) != null ? Integer.parseInt(getValue(CONFIRM_STATUS, json)) : null, getValue(USEGENERATEDPASSWORD, json) != null ? Boolean.parseBoolean(getValue(USEGENERATEDPASSWORD, json)) : false, getValue(SENDCONFIRMATIONMAIL, json) != null ? Boolean.parseBoolean(getValue(SENDCONFIRMATIONMAIL, json)) : true, apiCaller, getValue(ACCOUNTTYPE, json), dateOfBirth, getValue(USERPARENTID, json), sessionId, getValue(GENDER, json), getValue(CHILDDOB, json), getValue(GOORU_BASE_URL, json), getValue(TOKEN, json) != null ? Boolean.parseBoolean(getValue(TOKEN, json)) : false, request, getValue(ROLE, json), getValue(MAIL_CONFIRMATION_URL, json) != null ? getValue(MAIL_CONFIRMATION_URL, json) : null); if (user != null) { if (orgAdmin && adminOrganizationUid != null) { this.getUserManagementService().updateOrgAdminCustomField(adminOrganizationUid, user); } response.setStatus(HttpServletResponse.SC_CREATED); indexProcessor.index(user.getPartyUid(), IndexProcessor.INDEX, USER); } return toModelAndViewWithIoFilter(user, RESPONSE_FORMAT_JSON, EXCLUDE_ALL, true, USER_INCLUDES); }