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.ednovo.gooru.controllers.v2.api.EventRestV2Controller.java
@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_EVENT_MAPPING_ADD }) @RequestMapping(method = { RequestMethod.POST }, value = "/{id}/template-mapping") public ModelAndView createEventMapping(@PathVariable(value = ID) String id, @RequestBody String data, HttpServletRequest request, HttpServletResponse response) throws Exception { User user = (User) request.getAttribute(Constants.USER); EventMapping eventMapping = getEventService() .createEventMapping(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.odk.aggregate.servlet.SubmissionServlet.java
/** * Handler for HTTP post request that processes a form submission Currently * supports plain/xml and multipart//from ww w.j a v a 2 s .co m * * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType(ServletConsts.RESP_TYPE_HTML); PrintWriter out = resp.getWriter(); Key submissionKey = null; String odkId = null; EntityManager em = EMFactory.get().createEntityManager(); try { SubmissionParser submissionParser = null; if (ServletFileUpload.isMultipartContent(req)) { try { submissionParser = new SubmissionParser(new MultiPartFormData(req), em); odkId = submissionParser.getOdkId(); } catch (FileUploadException e) { e.printStackTrace(); } } else { // TODO: check that it is the proper types we can deal with // XML received submissionParser = new SubmissionParser(req.getInputStream(), em); } if (submissionParser == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ErrorConsts.INPUTSTREAM_ERROR); return; } Form form = submissionParser.getForm(); String appName = this.getServletContext().getInitParameter("application_name"); Submission submission = submissionParser.getSubmission(); List<RemoteServer> tmp = form.getExternalRepos(); // send information to remote servers that need to be notified for (RemoteServer rs : tmp) { rs.sendSubmissionToRemoteServer(form, req.getServerName(), em, appName, submission); } } catch (ODKFormNotFoundException e) { odkIdNotFoundError(resp); return; } catch (ODKParseException e) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ErrorConsts.PARSING_PROBLEM); return; } em.close(); if (ServletConsts.DEBUG) { out.println("QUERYING FROM DATASTORE"); em = EMFactory.get().createEntityManager(); DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); try { if (odkId == null) { // TODO: make better error decision return; } Entity subEntity = ds.get(submissionKey); Form form = Form.retrieveForm(em, odkId); Submission test = new Submission(subEntity, form); test.printSubmission(out); } catch (EntityNotFoundException e) { e.printStackTrace(); } catch (ODKFormNotFoundException e) { e.printStackTrace(); } catch (ODKIncompleteSubmissionData e) { e.printStackTrace(); } em.close(); } else { resp.setStatus(HttpServletResponse.SC_CREATED); resp.setHeader("Location", getServerURL(req)); // TODO: get an auto redirect going // resp.getWriter().print("<html><head><meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=http://" // + getServerURL(req) + "\"></head><body></body></html>"); } }
From source file:org.dasein.cloud.ibm.sce.SCEMethod.java
public void delete(@Nonnull String resource) throws CloudException, InternalException { Logger std = SCE.getLogger(SCEMethod.class, "std"); Logger wire = SCE.getLogger(SCEMethod.class, "wire"); if (std.isTraceEnabled()) { std.trace("enter - " + SCEMethod.class.getName() + ".post(" + resource + ")"); }/*from w ww . j a v a 2 s .c o m*/ if (wire.isDebugEnabled()) { wire.debug("POST --------------------------------------------------------> " + endpoint + resource); wire.debug(""); } try { HttpClient client = getClient(); HttpDelete method = new HttpDelete(endpoint + resource); method.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); if (wire.isDebugEnabled()) { wire.debug(method.getRequestLine().toString()); for (Header header : method.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } HttpResponse response; StatusLine status; try { APITrace.trace(provider, resource); response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { std.error("post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); if (std.isTraceEnabled()) { e.printStackTrace(); } throw new CloudException(e); } if (std.isDebugEnabled()) { std.debug("post(): HTTP Status " + status); } Header[] headers = response.getAllHeaders(); if (wire.isDebugEnabled()) { wire.debug(status.toString()); for (Header h : headers) { if (h.getValue() != null) { wire.debug(h.getName() + ": " + h.getValue().trim()); } else { wire.debug(h.getName() + ":"); } } wire.debug(""); } if (status.getStatusCode() != HttpServletResponse.SC_OK && status.getStatusCode() != HttpServletResponse.SC_CREATED && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) { std.error("post(): Expected OK for GET request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); if (entity == null) { throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } String body; try { body = EntityUtils.toString(entity); } catch (IOException e) { throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } if (wire.isDebugEnabled()) { wire.debug(body); } wire.debug(""); throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), body); } } finally { if (std.isTraceEnabled()) { std.trace("exit - " + SCEMethod.class.getName() + ".post()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("POST --------------------------------------------------------> " + endpoint + resource); } } }
From source file:com.imaginary.home.cloud.api.call.LocationCall.java
static public void main(String... args) throws Exception { if (args.length < 1) { System.err.println("You must specify an action"); System.exit(-1);/*ww w.j a va 2 s . com*/ return; } String action = args[0]; if (action.equalsIgnoreCase("initializePairing")) { if (args.length < 5) { System.err.println("You must specify a location ID"); System.exit(-2); return; } String endpoint = args[1]; String locationId = args[2]; String apiKeyId = args[3]; String apiKeySecret = args[4]; HashMap<String, Object> act = new HashMap<String, Object>(); act.put("action", "initializePairing"); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); //noinspection deprecation HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUserAgent(params, "Imaginary Home"); HttpClient client = new DefaultHttpClient(params); HttpPut method = new HttpPut(endpoint + "/location/" + locationId); long timestamp = System.currentTimeMillis(); method.addHeader("Content-Type", "application/json"); method.addHeader("x-imaginary-version", CloudService.VERSION); method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp)); method.addHeader("x-imaginary-api-key", apiKeyId); method.addHeader("x-imaginary-signature", CloudService.sign(apiKeySecret.getBytes("utf-8"), "put:/location/" + locationId + ":" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION)); //noinspection deprecation method.setEntity(new StringEntity((new JSONObject(act)).toString(), "application/json", "UTF-8")); 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_OK) { String json = EntityUtils.toString(response.getEntity()); JSONObject u = new JSONObject(json); System.out.println((u.has("pairingCode") && !u.isNull("pairingCode")) ? u.getString("pairingCode") : "--no code--"); } else { System.err.println("Failed to initialize pairing (" + status.getStatusCode() + ": " + EntityUtils.toString(response.getEntity())); System.exit(status.getStatusCode()); } } else if (action.equalsIgnoreCase("create")) { if (args.length < 7) { System.err.println("create ENDPOINT NAME DESCRIPTION TIMEZONE API_KEY_ID API_KEY_SECRET"); System.exit(-2); return; } String endpoint = args[1]; String name = args[2]; String description = args[3]; String tz = args[4]; String apiKeyId = args[5]; String apiKeySecret = args[6]; HashMap<String, Object> lstate = new HashMap<String, Object>(); lstate.put("name", name); lstate.put("description", description); lstate.put("timeZone", tz); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); //noinspection deprecation HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUserAgent(params, "Imaginary Home"); HttpClient client = new DefaultHttpClient(params); HttpPost method = new HttpPost(endpoint + "/location"); long timestamp = System.currentTimeMillis(); System.out.println( "Signing: " + "post:/location:" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION); method.addHeader("Content-Type", "application/json"); method.addHeader("x-imaginary-version", CloudService.VERSION); method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp)); method.addHeader("x-imaginary-api-key", apiKeyId); method.addHeader("x-imaginary-signature", CloudService.sign(apiKeySecret.getBytes("utf-8"), "post:/location:" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION)); //noinspection deprecation method.setEntity(new StringEntity((new JSONObject(lstate)).toString(), "application/json", "UTF-8")); 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) { String json = EntityUtils.toString(response.getEntity()); JSONObject u = new JSONObject(json); System.out.println((u.has("locationId") && !u.isNull("locationId")) ? u.getString("locationId") : "--no location--"); } else { System.err.println("Failed to create location (" + status.getStatusCode() + ": " + EntityUtils.toString(response.getEntity())); System.exit(status.getStatusCode()); } } else { System.err.println("No such action: " + action); System.exit(-3); } }
From source file:ge.taxistgela.servlet.RegistrationServlet.java
private void registerSuper(SuperUserManager man, SuperDaoUser obj, HttpServletRequest request, HttpServletResponse response) throws IOException { SmsQueue smsQueue = (SmsQueue) request.getServletContext().getAttribute(SmsQueue.class.getName()); if (man == null || smsQueue == null) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } else {/*from ww w . j a va 2s . c o m*/ ErrorCode errorCode = new ErrorCode(); errorCode.union(man.register(obj)); if (errorCode.errorNotAccrued()) { response.setStatus(HttpServletResponse.SC_CREATED); EmailSender.verifyEmail(obj); smsQueue.addSms(obj); return; } response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().print(errorCode.toJson()); } }
From source file:org.egov.restapi.web.rest.ContractorController.java
@RequestMapping(value = "/egworks/contractor", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE) public String createContractor(@RequestBody final String requestJson, final HttpServletResponse response) throws IOException { List<RestErrors> errors = new ArrayList<>(); final RestErrors restErrors = new RestErrors(); ApplicationThreadLocals.setUserId(2L); if (StringUtils.isBlank(requestJson)) { restErrors.setErrorCode(RestApiConstants.THIRD_PARTY_ERR_CODE_NO_JSON_REQUEST); restErrors.setErrorMessage(RestApiConstants.THIRD_PARTY_ERR_MSG_NO_JSON_REQUEST); errors.add(restErrors);//from w w w .ja va 2 s . c om return JsonConvertor.convert(errors); } final ContractorHelper contractorHelper = (ContractorHelper) getObjectFromJSONRequest(requestJson, ContractorHelper.class); errors = externalContractorService.validateContactorToCreate(contractorHelper); if (!errors.isEmpty()) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return JsonConvertor.convert(errors); } else { final Contractor contractor = externalContractorService.populateContractorToCreate(contractorHelper); final Contractor savedContractor = externalContractorService.saveContractor(contractor); final StringBuilder successMessage = new StringBuilder(); successMessage.append("Contractor data saved successfully with code ") .append(savedContractor.getCode()); response.setStatus(HttpServletResponse.SC_CREATED); return JsonConvertor.convert(successMessage.toString()); } }
From source file:org.eclipse.orion.internal.server.servlets.site.SiteConfigurationResourceHandler.java
/** * Creates a new site configuration, and possibly starts it. * @param site <code>null</code> */// w w w . ja v a2 s. c o m private boolean handlePost(HttpServletRequest req, HttpServletResponse resp, SiteInfo site) throws CoreException, IOException, JSONException { if (site != null) throw new IllegalArgumentException("Can't POST to an existing site"); UserInfo user = OrionConfiguration.getMetaStore().readUser(getUserName(req)); JSONObject requestJson = getRequestJson(req); try { site = doCreateSiteConfiguration(req, requestJson, user); changeHostingStatus(req, resp, requestJson, user, site); } catch (CoreException e) { // If starting it failed, try to clean up if (site != null) { // Remove site config site.delete(user); } throw e; } URI baseLocation = getURI(req); JSONObject result = toJSON(site, baseLocation); OrionServlet.writeJSONResponse(req, resp, result, JsonURIUnqualificationStrategy.LOCATION_ONLY); resp.setStatus(HttpServletResponse.SC_CREATED); resp.addHeader(ProtocolConstants.HEADER_LOCATION, result.getString(ProtocolConstants.KEY_LOCATION)); return true; }
From source file:org.sprintapi.api.http.HttpServlet.java
protected void doService(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ErrorException, IOException { final RequestHolder<Object> request = new RequestHolder<Object>(getUri(httpRequest)); request.setContext(httpRequest.getContextPath()); // Resolve incoming URL and get resource descriptor final ResourceDescriptor resourceDsc = resolve(request.getUri()); // Does the requested resource exist? if (resourceDsc == null) { throw new ErrorException(request.getUri(), HttpServletResponse.SC_NOT_FOUND); }// ww w . j av a2 s.c o m // Is requested method supported? if (httpRequest.getMethod() == null) { throw new ErrorException(request.getUri(), HttpServletResponse.SC_BAD_REQUEST); } try { request.setMethod(Method.valueOf(httpRequest.getMethod().toUpperCase(Locale.US))); } catch (IllegalArgumentException ex) { throw new ErrorException(request.getUri(), HttpServletResponse.SC_NOT_IMPLEMENTED); } if (request.getMethod() == null) { throw new ErrorException(request.getUri(), HttpServletResponse.SC_NOT_IMPLEMENTED); } // Get supported methods for requested resource Map<Method, MethodDescriptor<?, ?>> methods = resourceDsc.methods(); // Get requested method descriptors for the resource MethodDescriptor<?, ?> methodDsc = (methods != null) ? methods.get(request.getMethod()) : null; // Is requested method supported? if ((methodDsc == null)) { throw new ErrorException(request.getUri(), HttpServletResponse.SC_METHOD_NOT_ALLOWED); } ContentAdapter<InputStream, ?> inputContentAdapter = null; // Is request body expected? if (request.getMethod().isRequestBody()) { String requestContentType = httpRequest.getContentType(); inputContentAdapter = (methodDsc.consumes() != null) ? methodDsc.consumes().get(requestContentType) : null; if (inputContentAdapter == null) { throw new ErrorException(request.getUri(), HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); } } else if (httpRequest.getContentLength() > 0) { // Unexpected request body throw new ErrorException(request.getUri(), HttpServletResponse.SC_BAD_REQUEST); } ContentAdapter<?, InputStream> outputContentAdapter = null; String responseContentType = null; // Is response body expected? if (request.getMethod().isResponseBody()) { // Check Accept header HttpAcceptHeader acceptHeader = HttpAcceptHeader .read(httpRequest.getHeader(ContentDescriptor.META_ACCEPT)); if (acceptHeader != null) { Map<String, ?> produces = methodDsc.produces(); // Response content negotiation if (produces != null) { int weight = 0; for (String ct : produces.keySet()) { int tw = acceptHeader.accept(ct); if (tw > weight) { weight = tw; responseContentType = ct; outputContentAdapter = (ContentAdapter<?, InputStream>) produces.get(ct); } } } if (outputContentAdapter == null) { throw new ErrorException(request.getUri(), HttpServletResponse.SC_NOT_ACCEPTABLE); } } } if (inputContentAdapter != null) { ContentHolder<Object> lc = new ContentHolder<Object>(); lc.setBody(inputContentAdapter.transform(request.getUri(), httpRequest.getInputStream())); request.setContent(lc); } // Invoke resource method Response response = methodDsc.invoke((Request) request); if (response == null) { throw new ErrorException(request.getUri(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } // Write response status int responseStatus = (response.getStatus() > 0) ? response.getStatus() : HttpServletResponse.SC_OK; httpResponse.setStatus(responseStatus); if (response.getContent() == null) { return; } // Write response headers if (response.getContent().getMetaNames() != null) { for (String metaName : response.getContent().getMetaNames()) { Object metaValue = response.getContent().getMeta(metaName); if (metaValue != null) { if (metaValue instanceof Date) { httpResponse.setHeader(metaName, HttpDate.RFC1123_FORMAT.format(((Date) metaValue))); } else { httpResponse.setHeader(metaName, metaValue.toString()); } } } } if ((HttpServletResponse.SC_CREATED == responseStatus)) { httpResponse.setHeader(ContentDescriptor.META_LOCATION, response.getContext() + response.getUri()); } if ((response.getContent().getBody() == null) || (HttpServletResponse.SC_NOT_MODIFIED == responseStatus)) { return; } // Write response body if (outputContentAdapter != null) { httpResponse.setHeader(ContentDescriptor.META_CONTENT_TYPE, responseContentType); InputStream is = ((ContentAdapter<Object, InputStream>) outputContentAdapter) .transform(request.getUri(), response.getContent().getBody()); if (is != null) { CopyUtils.copy(is, httpResponse.getOutputStream()); } } }
From source file:com.tasktop.c2c.server.common.service.tests.ajp.AjpProtocolTest.java
@Test public void testMultipleSuccessiveRequestsOnOneConnection() throws IOException { GenericKeyedObjectPool uniSocketPool = new GenericKeyedObjectPool(new AjpPoolableConnectionFactory()); uniSocketPool.setLifo(true);//from w w w .j av a 2 s. c o m uniSocketPool.setMaxIdle(1); uniSocketPool.setMaxTotal(1); uniSocketPool.setMinIdle(1); protocol.setSocketPool(uniSocketPool); final int numRequests = 50; for (int x = 0; x < numRequests; ++x) { System.out.println("request: " + x); Payload payload = new Payload(); MockHttpServletRequest request = new MockHttpServletRequest(); if (x % 3 == 0) { payload.setResponseCode(HttpServletResponse.SC_CREATED); payload.setCharacterContent("some content " + x); payload.getResponseHeaders().put("foo", "bar"); TestServlet.setResponsePayload(payload); String formContent = "a=b&c=def"; byte[] requestContent = formContent.getBytes(); request.setMethod("PUT"); request.setRequestURI("/testPostData" + x); request.addHeader("Content-Type", "application/x-www-form-urlencoded"); request.addHeader("Content-Length", requestContent.length); request.setContent(requestContent); } else { payload.setResponseCode(HttpServletResponse.SC_OK); payload.setBinaryContent(createData((x * 1024) + 3)); payload.getResponseHeaders().put("Content-Length", Integer.toString(payload.getBinaryContent().length)); payload.getResponseHeaders().put("Content-Type", "unknown"); payload.getResponseHeaders().put("TestPayloadNumber", Integer.toHexString(x) + '/' + Integer.toHexString(numRequests)); TestServlet.setResponsePayload(payload); request.setMethod("GET"); request.setRequestURI("/test" + x); } MockHttpServletResponse response = new MockHttpServletResponse(); protocol.forward(request, response); assertRequestIsExpected(request, TestServlet.getLastRequest()); assertResponseIsExpected(payload, response); } }
From source file:org.apache.hadoop.hbase.rest.Status.java
public void setCreated() { this.statusCode = HttpServletResponse.SC_CREATED; this.setOK(); }