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.tsugi.lti2.LTI2Servlet.java
@SuppressWarnings({ "unchecked", "unused", "rawtypes" }) public void registerToolProviderProfile(HttpServletRequest request, HttpServletResponse response, String profile_id) throws java.io.IOException { // Normally we would look up the deployment descriptor if (!TEST_KEY.equals(profile_id)) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return;/* w ww. j ava 2 s. co m*/ } String key = TEST_KEY; String secret = TEST_SECRET; IMSJSONRequest jsonRequest = new IMSJSONRequest(request); if (!jsonRequest.valid) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, "Request is not in a valid format", null); return; } System.out.println(jsonRequest.getPostBody()); // Lets check the signature if (key == null || secret == null) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); doErrorJSON(request, response, jsonRequest, "Deployment is missing credentials", null); return; } jsonRequest.validateRequest(key, secret, request); if (!jsonRequest.valid) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); doErrorJSON(request, response, jsonRequest, "OAuth signature failure", null); return; } ToolProxy toolProxy = null; try { toolProxy = new ToolProxy(jsonRequest.getPostBody()); // System.out.println("OBJ:"+toolProxy); } catch (Throwable t) { t.printStackTrace(); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, "JSON parse failed", null); return; } JSONObject default_custom = toolProxy.getCustom(); JSONObject security_contract = toolProxy.getSecurityContract(); if (security_contract == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, "JSON missing security_contract", null); return; } String shared_secret = (String) security_contract.get(LTI2Constants.SHARED_SECRET); System.out.println("shared_secret=" + shared_secret); if (shared_secret == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, "JSON missing shared_secret", null); return; } // Make sure that the requested services are a subset of the offered services ToolConsumer consumer = buildToolConsumerProfile(request, null, profile_id); JSONArray tool_services = (JSONArray) security_contract.get(LTI2Constants.TOOL_SERVICE); String retval = toolProxy.validateServices(consumer); if (retval != null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, retval, null); return; } // Parse the tool profile bit and extract the tools with error checking retval = toolProxy.validateCapabilities(consumer); if (retval != null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, retval, null); return; } // Pass the profile to the launch process PERSIST.put("profile", toolProxy.toString()); // Share our happiness with the Tool Provider Map jsonResponse = new TreeMap(); jsonResponse.put(LTI2Constants.CONTEXT, StandardServices.TOOLPROXY_ID_CONTEXT); jsonResponse.put(LTI2Constants.TYPE, StandardServices.TOOLPROXY_ID_TYPE); jsonResponse.put(LTI2Constants.JSONLD_ID, getServiceURL(request) + SVC_tc_registration + "/" + profile_id); jsonResponse.put(LTI2Constants.TOOL_PROXY_GUID, profile_id); jsonResponse.put(LTI2Constants.CUSTOM_URL, getServiceURL(request) + SVC_Settings + "/" + LTI2Util.SCOPE_ToolProxy + "/" + profile_id); response.setContentType(StandardServices.TOOLPROXY_ID_FORMAT); response.setStatus(HttpServletResponse.SC_CREATED); String jsonText = JSONValue.toJSONString(jsonResponse); M_log.debug(jsonText); PrintWriter out = response.getWriter(); out.println(jsonText); }
From source file:org.dasein.cloud.ibm.sce.SCEMethod.java
public @Nullable String post(@Nonnull String resource, @Nonnull List<NameValuePair> parameters) 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 + ")"); }//www .j av a 2s. co m if (wire.isDebugEnabled()) { wire.debug("POST --------------------------------------------------------> " + endpoint + resource); wire.debug(""); } try { HttpClient client = getClient(); HttpPost post = new HttpPost(endpoint + resource); post.addHeader("Content-Type", "application/x-www-form-urlencoded"); post.addHeader("Accept", "text/xml"); if (wire.isDebugEnabled()) { wire.debug(post.getRequestLine().toString()); for (Header header : post.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); if (parameters != null) { Iterator<NameValuePair> it = parameters.iterator(); StringBuilder str = new StringBuilder(); while (it.hasNext()) { NameValuePair p = it.next(); str.append(p.getName()).append("=").append(p.getValue()); if (it.hasNext()) { str.append("&"); } } wire.debug(str.toString()); wire.debug(""); } } if (parameters != null) { try { post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8")); } catch (UnsupportedEncodingException e) { throw new InternalException(e); } } HttpResponse response; StatusLine status; try { APITrace.trace(provider, resource); response = client.execute(post); 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(); String body; if (entity == null) { throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } 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); } else if (status.getStatusCode() == HttpServletResponse.SC_NO_CONTENT) { return null; } else { HttpEntity entity = response.getEntity(); if (entity == null) { return null; } try { return EntityUtils.toString(entity); } catch (IOException e) { throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } } } finally { if (std.isTraceEnabled()) { std.trace("exit - " + SCEMethod.class.getName() + ".post()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("POST --------------------------------------------------------> " + endpoint + resource); } } }
From source file:org.eclipse.orion.internal.server.servlets.workspace.WorkspaceResourceHandler.java
/** * Implementation of project copy/* w w w.j av a2s . co m*/ * Returns <code>false</code> if this method doesn't know how to interpret the request. */ private boolean handleCopyProject(HttpServletRequest request, HttpServletResponse response, WorkspaceInfo workspace, ProjectInfo sourceProject, String destinationName) throws IOException, ServletException { //first create the destination project JSONObject projectObject = new JSONObject(); try { projectObject.put(ProtocolConstants.KEY_NAME, destinationName); } catch (JSONException e) { //should never happen throw new RuntimeException(e); } //copy the project data from source ProjectInfo destinationProject = handleAddProject(request, response, workspace, projectObject); String sourceName = sourceProject.getFullName(); try { copyProjectContents(sourceProject, destinationProject); } catch (CoreException e) { handleError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, NLS.bind("Error copying project {0} to {1}", sourceName, destinationName)); return true; } URI baseLocation = getURI(request); JSONObject result = WebProjectResourceHandler.toJSON(workspace, destinationProject, baseLocation); OrionServlet.writeJSONResponse(request, response, result); response.setHeader(ProtocolConstants.HEADER_LOCATION, result.optString(ProtocolConstants.KEY_LOCATION, "")); //$NON-NLS-1$ response.setStatus(HttpServletResponse.SC_CREATED); return true; }
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(method = RequestMethod.POST, value = { "/{id}/associate" }) public ModelAndView createTaskAssoc(@PathVariable(ID) String taskId, @RequestBody String data, HttpServletRequest request, HttpServletResponse response) throws Exception { request.setAttribute(PREDICATE, TASK_CREATE_TASK_ASSOC); User user = (User) request.getAttribute(Constants.USER); JSONObject json = requestData(data); ActionResponseDTO<TaskAssoc> responseDTO = getTaskService() .createTaskAssoc(this.buildTaskAssocFromInputParameters(getValue(TASK_ASSOC, json)), taskId, user); if (responseDTO.getErrors().getErrorCount() > 0) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else {//from www. j av a2 s . 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 ? TASK_ASSOC_INCLUDES : includeFields, ERROR_INCLUDE); SessionContextSupport.putLogParameter(EVENTNAME, CREATE_TASK_ASSOC); SessionContextSupport.putLogParameter(TASK_ASSOC_UID, responseDTO.getModel().getTaskAssocUid()); SessionContextSupport.putLogParameter(TASK_DESCENDANT_ID, responseDTO.getModel().getTaskDescendant() != null ? responseDTO.getModel().getTaskDescendant().getGooruOid() : null); SessionContextSupport.putLogParameter(TASK_PARENT_ID, responseDTO.getModel().getTaskParent() != null ? responseDTO.getModel().getTaskParent().getGooruOid() : null); return toModelAndViewWithIoFilter(responseDTO.getModelData(), RESPONSE_FORMAT_JSON, EXCLUDE_ALL, includes); }
From source file:org.dasein.cloud.azure.AzureMethod.java
public String post(@Nonnull String account, @Nonnull String resource, @Nonnull String body) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("enter - " + AzureMethod.class.getName() + ".post(" + account + "," + resource + ")"); }/*from w w w . jav a 2 s .c o m*/ if (wire.isDebugEnabled()) { wire.debug("POST --------------------------------------------------------> " + endpoint + account + resource); wire.debug(""); } String requestId = null; try { HttpClient client = getClient(); String url = endpoint + account + resource; HttpPost post = new HttpPost(url); post.addHeader("x-ms-version", "2012-03-01"); //If it is networking configuration services if (url.endsWith("/services/networking/media")) { post.addHeader("Content-Type", "text/plain;charset=UTF-8"); } else { post.addHeader("Content-Type", "application/xml;charset=UTF-8"); } if (wire.isDebugEnabled()) { wire.debug(post.getRequestLine().toString()); for (Header header : post.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); if (body != null) { wire.debug(body); wire.debug(""); } } if (body != null) { try { if (url.endsWith("/services/networking/media")) { post.setEntity(new StringEntity(body, "text/plain", "utf-8")); } else { post.setEntity(new StringEntity(body, "application/xml", "utf-8")); } } catch (UnsupportedEncodingException e) { throw new InternalException(e); } } HttpResponse response; StatusLine status; try { response = client.execute(post); status = response.getStatusLine(); } catch (IOException e) { logger.error("post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); if (logger.isTraceEnabled()) { e.printStackTrace(); } throw new CloudException(e); } if (logger.isDebugEnabled()) { logger.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()); if (h.getName().equalsIgnoreCase("x-ms-request-id")) { requestId = 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) { logger.error("post(): Expected OK for GET request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); if (entity == null) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } try { body = EntityUtils.toString(entity); } catch (IOException e) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } if (wire.isDebugEnabled()) { wire.debug(body); } wire.debug(""); AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body); if (items == null) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), "Unknown", "Unknown"); } logger.error("post(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details); throw new AzureException(items); } } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + AzureMethod.class.getName() + ".post()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("POST --------------------------------------------------------> " + endpoint + account + resource); } } return requestId; }
From source file:com.imaginary.home.cloud.CloudTest.java
@Test public void createUser() throws Exception { HashMap<String, Object> user = new HashMap<String, Object>(); long key = (System.currentTimeMillis() % 100000); user.put("firstName", "Test " + key); user.put("lastName", "User"); user.put("email", "test" + key + "@example.com"); user.put("password", "ABC" + random.nextInt(1000000)); HttpClient client = getClient();/*w ww. ja va 2s . com*/ HttpPost method = new HttpPost(cloudAPI + "/user"); long timestamp = System.currentTimeMillis(); method.addHeader("Content-Type", "application/json"); method.addHeader("x-imaginary-version", VERSION); method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp)); //noinspection deprecation method.setEntity(new StringEntity((new JSONObject(user)).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); String userId = (u.has("userId") && !u.isNull("userId")) ? u.getString("userId") : null; String email = (u.has("email") && !u.isNull("email")) ? u.getString("email") : null; String firstName = (u.has("firstName") && !u.isNull("firstName")) ? u.getString("firstName") : null; String lastName = (u.has("lastName") && !u.isNull("lastName")) ? u.getString("lastName") : null; JSONObject keys = (u.has("apiKeys") && !u.isNull("apiKeys")) ? u.getJSONObject("apiKeys") : null; String apiKeyId = null, apiKeySecret = null; if (keys != null) { apiKeyId = (keys.has("apiKeyId") && !keys.isNull("apiKeyId")) ? keys.getString("apiKeyId") : null; apiKeySecret = (keys.has("apiKeySecret") && !keys.isNull("apiKeySecret")) ? keys.getString("apiKeySecret") : null; } out("ID: " + userId); out("Email: " + email); out("First Name: " + firstName); out("Last Name: " + lastName); out("API Key ID: " + apiKeyId); out("API Key Secret: " + apiKeySecret); Assert.assertNotNull("User ID may not be null", userId); Assert.assertNotNull("Email may not be null", email); Assert.assertNotNull("First name may not be null", firstName); Assert.assertNotNull("Last name may not be null", lastName); Assert.assertNotNull("API key ID may not be null", apiKeyId); Assert.assertNotNull("API key secret may not be null", apiKeySecret); if (CloudTest.apiKeyId == null) { CloudTest.apiKeyId = apiKeyId; CloudTest.apiKeySecret = apiKeySecret; } } else { Assert.fail("Failed to create user (" + status.getStatusCode() + ": " + EntityUtils.toString(response.getEntity())); } }
From source file:org.openmrs.module.webservices.rest.web.RestUtil.java
/** * Sets the HTTP status for CREATED and (if 'created' has a uri) the Location header attribute * // ww w.ja va 2 s . com * @param response * @param created * @return the object passed in */ public static Object created(HttpServletResponse response, Object created) { response.setStatus(HttpServletResponse.SC_CREATED); try { String uri = (String) PropertyUtils.getProperty(created, "uri"); response.addHeader("Location", uri); } catch (Exception ex) { } return created; }
From source file:com.googlecode.noweco.calendar.CaldavServlet.java
@Override public void doPut(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { String requestURI = req.getRequestURI(); String[] split = requestURI.split("/"); MemoryFile memoryFile = ROOT;/*from w ww . ja va 2 s . co m*/ for (int i = 0; i < split.length - 1; i++) { String name = split[i]; MemoryFile locate = MemoryFileUtils.locate(memoryFile, name); if (locate == null) { memoryFile = new MemoryFile(memoryFile, name, true); } else { memoryFile = locate; } } String name = split[split.length - 1]; MemoryFile locate = MemoryFileUtils.locate(memoryFile, name); if (locate == null) { memoryFile = new MemoryFile(memoryFile, name, false); } else { memoryFile = locate; } CalendarBuilder builder = new CalendarBuilder(); net.fortuna.ical4j.model.Calendar calendar; try { calendar = builder.build(req.getInputStream()); } catch (ParserException e) { throw new RuntimeException(e); } for (Iterator i = calendar.getComponents().iterator(); i.hasNext();) { Component component = (Component) i.next(); System.out.println("Component [" + component.getName() + "]"); if (component instanceof VEvent) { VEvent event = (VEvent) component; LOGGER.info("Create event " + event.getSummary().getValue() + " in " + event.getLocation().getValue() + " from " + event.getStartDate().getDate() + " to " + event.getEndDate().getDate()); } } CalendarOutputter outputter = new CalendarOutputter(); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { outputter.output(calendar, out); } catch (ValidationException e) { throw new RuntimeException(e); } memoryFile.setContent(out.toByteArray()); Getcontenttype getcontenttype = new Getcontenttype(); getcontenttype.getContent().add(req.getHeader("Content-Type")); memoryFile.getProp().setGetcontenttype(getcontenttype); Prop prop = memoryFile.getProp(); prop.setResourcetype(new Resourcetype()); Getetag getetag = new Getetag(); getetag.getContent().add("\"" + System.currentTimeMillis() + "\""); prop.setGetetag(getetag); resp.setHeader("ETag", prop.getGetetag().getContent().get(0)); resp.setStatus(HttpServletResponse.SC_CREATED); }
From source file:org.clothocad.phagebook.controllers.OrdersController.java
@RequestMapping(value = "/newOrder", method = RequestMethod.POST) public void newOrder(@RequestParam Map<String, String> params, HttpServletResponse response) throws IOException, ServletException { //params.get RETURNS NULL IF IT DOESN'T EXIST!!! Object pOrderName = params.get("name"); String orderName = pOrderName != null ? (String) pOrderName : ""; //WEBSITE WILL SEND THE ID Object pCreatedBy = params.get("createdBy"); String createdBy = pCreatedBy != null ? (String) pCreatedBy : ""; //WEBSITE WILL SEND THIS Object pLabId = params.get("labId"); String labId = pLabId != null ? (String) pLabId : ""; // Object pTaxRate = params.get("tax"); // String taxRateString = pTaxRate != null ? (String) pTaxRate : ""; // Double taxRate = Double.parseDouble(taxRateString) / 100; Object pAssociatedProject = params.get("associatedProjectId"); String associatedProjectId = pAssociatedProject != null ? (String) pAssociatedProject : ""; // Object pBudget = params.get("budget"); // String strBudget = pBudget != null ? (String) pBudget : ""; // Double budget = Double.parseDouble(strBudget); ///*from w w w. java 2 s .co m*/ // Object pOrderLimit = params.get("orderLimit"); // String strOrderLimit = pOrderLimit != null ? (String) pOrderLimit : ""; // Integer orderLimit = Integer.parseInt(strOrderLimit); Date date = new Date(); boolean isValid = false; //All parameters needed to create a new order as per the wire frame. if (!orderName.equals("") && !createdBy.equals("") && !labId.equals("") && !associatedProjectId.equals("")) { // && !strBudget.equals("") // && !strOrderLimit.equals("")) { isValid = true; } if (isValid) { //login ClothoConnection conn = new ClothoConnection(Args.clothoLocation); Clotho clothoObject = new Clotho(conn); String username = this.backendPhagebookUser; String password = this.backendPhagebookPassword; /* DIRECT ASSUMPTION THAT USER: phagebook exists and their PASSWORD: backend */ Map loginMap = new HashMap(); loginMap.put("username", username); loginMap.put("credentials", password); clothoObject.login(loginMap); Order order = new Order(); order.setName(orderName); order.setCreatedById(createdBy); order.setDateCreated(date); // order.setBudget(budget); // order.setMaxOrderSize(orderLimit); // if (!taxRateString.equals("")) { // order.setTaxRate((1 + taxRate)); // } else { // order.setTaxRate(1.07d); // } // // Added order.setTaxRate(0.0); order.setAffiliatedLabId(labId); order.setRelatedProjectId(associatedProjectId); order.setStatus(OrderStatus.INPROGRESS); ClothoAdapter.createOrder(order, clothoObject); // CREATED THE ORDER // BUT I NOW NEED TO LINK IT TO THE USER Person creator = ClothoAdapter.getPerson(order.getCreatedById(), clothoObject); List<String> createdOrders = creator.getCreatedOrders(); createdOrders.add(order.getId()); System.out.println("I am still on this part"); clothoObject.logout(); ClothoAdapter.setPerson(creator, clothoObject); // LINK CREATED response.setStatus(HttpServletResponse.SC_CREATED); PrintWriter writer = response.getWriter(); response.setContentType("application/JSON"); JSONObject responseJSON = new JSONObject(); responseJSON.put("message", "order created"); responseJSON.put("orderId", order.getId()); writer.println(responseJSON); writer.flush(); writer.close(); conn.closeConnection(); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); PrintWriter writer = response.getWriter(); response.setContentType("application/JSON"); JSONObject responseJSON = new JSONObject(); responseJSON.put("message", "Missing Required Parameters."); writer.println(responseJSON.toString()); writer.flush(); writer.close(); } }