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.GitRemoteHandlerV1.java
private boolean addRemote(HttpServletRequest request, HttpServletResponse response, String path) throws IOException, JSONException, ServletException, CoreException, URISyntaxException { // expected path: /git/remote/file/{path} Path p = new Path(path); JSONObject toPut = OrionServlet.readJSONRequest(request); String remoteName = toPut.optString(GitConstants.KEY_REMOTE_NAME, null); // remoteName is required if (remoteName == null || remoteName.isEmpty()) { return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Remote name must be provided", null)); }/*from w w w . jav a 2s . c om*/ String remoteURI = toPut.optString(GitConstants.KEY_REMOTE_URI, null); // remoteURI is required if (remoteURI == null || remoteURI.isEmpty()) { return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Remote URI must be provided", null)); } try { URIish uri = new URIish(remoteURI); if (GitUtils.isForbiddenGitUri(uri)) { statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, NLS.bind("Remote URI {0} does not appear to be a git repository", remoteURI), //$NON-NLS-1$ null)); return false; } } catch (URISyntaxException e) { statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, NLS.bind("Invalid remote URI: {0}", remoteURI), e)); //$NON-NLS-1$ return false; } String fetchRefSpec = toPut.optString(GitConstants.KEY_REMOTE_FETCH_REF, null); String remotePushURI = toPut.optString(GitConstants.KEY_REMOTE_PUSH_URI, null); String pushRefSpec = toPut.optString(GitConstants.KEY_REMOTE_PUSH_REF, null); File gitDir = GitUtils.getGitDir(p); Repository db = FileRepositoryBuilder.create(gitDir); StoredConfig config = db.getConfig(); RemoteConfig rc = new RemoteConfig(config, remoteName); rc.addURI(new URIish(remoteURI)); // FetchRefSpec is required, but default version can be generated // if it isn't provided if (fetchRefSpec == null || fetchRefSpec.isEmpty()) { fetchRefSpec = String.format("+refs/heads/*:refs/remotes/%s/*", remoteName); //$NON-NLS-1$ } rc.addFetchRefSpec(new RefSpec(fetchRefSpec)); // pushURI is optional if (remotePushURI != null && !remotePushURI.isEmpty()) rc.addPushURI(new URIish(remotePushURI)); // PushRefSpec is optional if (pushRefSpec != null && !pushRefSpec.isEmpty()) rc.addPushRefSpec(new RefSpec(pushRefSpec)); rc.update(config); config.save(); URI cloneLocation = BaseToCloneConverter.getCloneLocation(getURI(request), BaseToCloneConverter.REMOTE_LIST); Remote remote = new Remote(cloneLocation, db, remoteName); JSONObject result = new JSONObject(); result.put(ProtocolConstants.KEY_LOCATION, remote.getLocation()); OrionServlet.writeJSONResponse(request, response, result); response.setHeader(ProtocolConstants.HEADER_LOCATION, result.getString(ProtocolConstants.KEY_LOCATION)); response.setStatus(HttpServletResponse.SC_CREATED); return true; }
From source file:smartrics.rest.test.fitnesse.fixture.ResourcesServlet.java
private void generateResponse(HttpServletResponse resp, String type, String content) { Resource newResource = new Resource(content); resources.add(type, newResource);//w w w . j a v a 2 s . com // TODO: should put the ID in resp.setStatus(HttpServletResponse.SC_CREATED); resp.addHeader("Location", type + "/" + newResource.getId()); }
From source file:com.imaginary.home.device.hue.HueMethod.java
public JSONObject post(@Nonnull String resource, JSONObject body) throws HueException { Logger std = Hue.getLogger(HueMethod.class); Logger wire = Hue.getWireLogger(HueMethod.class); if (std.isTraceEnabled()) { std.trace("enter - " + HueMethod.class.getName() + ".post(" + resource + ")"); }/*from www . j av a 2 s.co m*/ if (wire.isDebugEnabled()) { wire.debug(""); wire.debug(">>> [POST (" + (new Date()) + ")] -> " + hue.getAPIEndpoint() + resource); } try { HttpClient client = getClient(); HttpPost method = new HttpPost(hue.getAPIEndpoint() + resource); method.addHeader("Content-Type", "application/json"); try { if (body != null) { //noinspection deprecation method.setEntity(new StringEntity(body.toString(), "application/json", "UTF-8")); } } catch (UnsupportedEncodingException e) { throw new HueException(e); } if (wire.isDebugEnabled()) { wire.debug(method.getRequestLine().toString()); for (Header header : method.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); if (body != null) { try { wire.debug(EntityUtils.toString(method.getEntity())); } catch (IOException ignore) { } wire.debug(""); } } HttpResponse response; StatusLine status; try { 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 HueException(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 CREATED or OK or ACCEPTED for POST request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); if (entity == null) { throw new HueException(status.getStatusCode(), "An error was returned without explanation"); } String json; try { json = EntityUtils.toString(entity); } catch (IOException e) { throw new HueException(status.getStatusCode(), e.getMessage()); } if (wire.isDebugEnabled()) { wire.debug(json); wire.debug(""); } throw new HueException(status.getStatusCode(), json); } else { try { String json = EntityUtils.toString(response.getEntity()); if (wire.isDebugEnabled()) { wire.debug(json); wire.debug(""); } if (json.startsWith("[")) { JSONArray arr = new JSONArray(json); if (arr.length() > 0) { JSONObject ob = arr.getJSONObject(0); if (ob.has("error")) { ob = ob.getJSONObject("error"); if (ob.has("description")) { throw new HueException(ob.getString("description")); } } return ob; } return null; } return new JSONObject(json); } catch (IOException e) { throw new HueException(status.getStatusCode(), e.getMessage()); } catch (JSONException e) { throw new HueException(status.getStatusCode(), e.getMessage()); } } } finally { if (std.isTraceEnabled()) { std.trace("exit - " + HueMethod.class.getName() + ".post()"); } if (wire.isDebugEnabled()) { wire.debug("<<< [POST (" + (new Date()) + ")] -> " + hue.getAPIEndpoint() + resource + " <--------------------------------------------------------------------------------------"); wire.debug(""); } } }
From source file:com.sun.faban.harness.webclient.Uploader.java
/** * Responsible for uploading the runs./*from w w w. ja va 2s . c o m*/ * @param request * @param response * @return String * @throws java.io.IOException * @throws javax.servlet.ServletException * @throws java.lang.ClassNotFoundException */ public String uploadRuns(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, ClassNotFoundException { // 3. Upload the run HashSet<String> duplicateSet = new HashSet<String>(); HashSet<String> replaceSet = new HashSet<String>(); String host = null; String key = null; boolean origin = false; // Whether the upload is to the original // run requestor. If so, key is needed. DiskFileUpload fu = new DiskFileUpload(); // No maximum size fu.setSizeMax(-1); // maximum size that will be stored in memory fu.setSizeThreshold(4096); // the location for saving data that is larger than // getSizeThreshold() fu.setRepositoryPath(Config.TMP_DIR); List fileItems = null; try { fileItems = fu.parseRequest(request); } catch (FileUploadException e) { throw new ServletException(e); } // assume we know there are two files. The first file is a small // text file, the second is unknown and is written to a file on // the server for (Iterator i = fileItems.iterator(); i.hasNext();) { FileItem item = (FileItem) i.next(); String fieldName = item.getFieldName(); if (item.isFormField()) { if ("host".equals(fieldName)) { host = item.getString(); } else if ("replace".equals(fieldName)) { replaceSet.add(item.getString()); } else if ("key".equals(fieldName)) { key = item.getString(); } else if ("origin".equals(fieldName)) { String value = item.getString(); origin = Boolean.parseBoolean(value); } continue; } if (host == null) { logger.warning("Host not received on upload request!"); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } // The host, origin, key info must be here before we receive // any file. if (origin) { if (Config.daemonMode != Config.DaemonModes.POLLEE) { logger.warning("Origin upload requested. Not pollee!"); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } if (key == null) { logger.warning("Origin upload requested. No key!"); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } if (!RunRetriever.authenticate(host, key)) { logger.warning("Origin upload requested. " + "Host/key mismatch: " + host + '/' + key + "!"); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } } if (!"jarfile".equals(fieldName)) // ignore continue; String fileName = item.getName(); if (fileName == null) // We don't process files without names continue; // Now, this name may have a path attached, dependent on the // source browser. We need to cover all possible clients... char[] pathSeparators = { '/', '\\' }; // Well, if there is another separator we did not account for, // just add it above. for (int j = 0; j < pathSeparators.length; j++) { int idx = fileName.lastIndexOf(pathSeparators[j]); if (idx != -1) { fileName = fileName.substring(idx + 1); break; } } // Ignore all non-jarfiles. if (!fileName.toLowerCase().endsWith(".jar")) continue; File uploadFile = new File(Config.TMP_DIR, host + '.' + fileName); try { item.write(uploadFile); } catch (Exception e) { throw new ServletException(e); } int runIdx = fileName.lastIndexOf("."); String runName = host + '.' + fileName.substring(0, runIdx); File runTmp = unjarTmp(uploadFile); //Check if archived recently if (checkIfArchived(runName) && !(replaceSet.contains(fileName.substring(0, runIdx)))) { //Now check if timestamps are same //Get the timestamp of run being uploaded at this point //ts is timestamp of run being uploaded String ts = getRunIdTimestamp(runName, Config.TMP_DIR); l1: while (true) { //reposTs is timestamp of run being compared in the //repository String reposTs = getRunIdTimestamp(runName, Config.OUT_DIR); if (reposTs.equals(ts)) { duplicateSet.add(fileName.substring(0, runIdx)); } else { runName = getNextRunId(runName); if (checkIfArchived(runName)) continue l1; File newRunNameFile = new File(Config.OUT_DIR, runName); if (newRunNameFile.exists()) { recursiveDelete(newRunNameFile); } if (recursiveCopy(runTmp, newRunNameFile)) { newRunNameFile.setLastModified(runTmp.lastModified()); uploadTags(runName); uploadFile.delete(); recursiveDelete(runTmp); } else { logger.warning("Origin upload requested. " + "Copy error!"); response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE); break; } response.setStatus(HttpServletResponse.SC_CREATED); } break; } } else { //File runTmp = unjarTmp(uploadFile); String runId = null; if (origin) { // Change origin file to know where this run came from. File metaInf = new File(runTmp, "META-INF"); File originFile = new File(metaInf, "origin"); if (!originFile.exists()) { logger.warning("Origin upload requested. " + "Origin file does not exist!"); response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Origin file does not exist!"); break; } RunId origRun; try { origRun = new RunId(readStringFromFile(originFile).trim()); } catch (IndexOutOfBoundsException e) { response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Origin file error. " + e.getMessage()); break; } runId = origRun.getBenchName() + '.' + origRun.getRunSeq(); String localHost = origRun.getHostName(); if (!localHost.equals(Config.FABAN_HOST)) { logger.warning("Origin upload requested. Origin " + "host" + localHost + " does not match this host " + Config.FABAN_HOST + '!'); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } writeStringToFile(runTmp.getName(), originFile); } else { runId = runTmp.getName(); } File newRunFile = new File(Config.OUT_DIR, runId); if (newRunFile.exists()) { recursiveDelete(newRunFile); } if (recursiveCopy(runTmp, newRunFile)) { newRunFile.setLastModified(runTmp.lastModified()); uploadFile.delete(); uploadTags(runId); recursiveDelete(runTmp); } else { logger.warning("Origin upload requested. Copy error!"); response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE); break; } } response.setStatus(HttpServletResponse.SC_CREATED); //break; } request.setAttribute("duplicates", duplicateSet); return "/duplicates.jsp"; }
From source file:com.portfolio.security.LTIv2Servlet.java
protected void doRegister(HttpServletResponse response, Map<String, Object> payload, ServletContext application, String toolProxyPath, StringBuffer outTrace) { String launch_url = (String) payload.get("launch_url"); response.setContentType("text/html"); outTraceFormattedMessage(outTrace, "doRegister() - launch_url: " + launch_url); outTraceFormattedMessage(outTrace, "payload: " + payload); String key = null;/*from w w w . ja v a2 s. c o m*/ String passwd = null; if (BasicLTIConstants.LTI_MESSAGE_TYPE_TOOLPROXYREGISTRATIONREQUEST .equals(payload.get(BasicLTIConstants.LTI_MESSAGE_TYPE))) { key = (String) payload.get(LTI2Constants.REG_KEY); passwd = (String) payload.get(LTI2Constants.REG_PASSWORD); } else if (BasicLTIConstants.LTI_MESSAGE_TYPE_TOOLPROXY_RE_REGISTRATIONREQUEST .equals(payload.get(BasicLTIConstants.LTI_MESSAGE_TYPE))) { key = (String) payload.get(LTIServletUtils.OAUTH_CONSUMER_KEY); final String configPrefix = "basiclti.provider." + key + "."; passwd = (String) application.getAttribute(configPrefix + "secret"); } else { //TODO BOOM outTraceFormattedMessage(outTrace, "BOOM"); } String returnUrl = (String) payload.get(BasicLTIConstants.LAUNCH_PRESENTATION_RETURN_URL); String tcProfileUrl = (String) payload.get(LTI2Constants.TC_PROFILE_URL); //Lookup tc profile if (tcProfileUrl != null && !"".equals(tcProfileUrl)) { InputStream is = null; try { URL url = new URL(tcProfileUrl); is = url.openStream(); JSONParser parser = new JSONParser(); JSONObject obj = (JSONObject) parser.parse(new InputStreamReader(is)); // is.close(); outTraceFormattedMessage(outTrace, obj.toJSONString()); JSONArray services = (JSONArray) obj.get("service_offered"); String regUrl = null; for (int i = 0; i < services.size(); i++) { JSONObject service = (JSONObject) services.get(i); JSONArray formats = (JSONArray) service.get("format"); if (formats.contains("application/vnd.ims.lti.v2.toolproxy+json")) { regUrl = (String) service.get("endpoint"); outTraceFormattedMessage(outTrace, "RegEndpoint: " + regUrl); } } if (regUrl == null) { //TODO BOOM throw new RuntimeException("Need an endpoint"); } JSONObject toolProxy = getToolProxy(toolProxyPath); //TODO do some replacement on stock values that need specifics from us here // Tweak the stock profile toolProxy.put("tool_consumer_profile", tcProfileUrl); //LTI2Constants. // BasicLTIConstants. // // Re-register JSONObject toolProfile = (JSONObject) toolProxy.get("tool_profile"); JSONArray messages = (JSONArray) toolProfile.get("message"); JSONObject message = (JSONObject) messages.get(0); message.put("path", launch_url); String baseUrl = (String) payload.get("base_url"); JSONObject pi = (JSONObject) toolProfile.get("product_instance"); JSONObject pInfo = (JSONObject) pi.get("product_info"); JSONObject pFamily = (JSONObject) pInfo.get("product_family"); JSONObject vendor = (JSONObject) pFamily.get("vendor"); vendor.put("website", baseUrl); // vendor.put("timestamp", new Date().toString()); // $tp_profile->tool_profile->product_instance->product_info->product_family->vendor->website = $cur_base; // $tp_profile->tool_profile->product_instance->product_info->product_family->vendor->timestamp = "2013-07-13T09:08:16-04:00"; // // // I want this *not* to be unique per instance // $tp_profile->tool_profile->product_instance->guid = "urn:sakaiproject:unit-test"; // // $tp_profile->tool_profile->product_instance->service_provider->guid = "http://www.sakaiproject.org/"; // // // Launch Request // $tp_profile->tool_profile->resource_handler[0]->message[0]->path = "tool.php"; // $tp_profile->tool_profile->resource_handler[0]->resource_type->code = "sakai-api-test-01"; // $tp_profile->tool_profile->base_url_choice[0]->secure_base_url = $cur_base; // $tp_profile->tool_profile->base_url_choice[0]->default_base_url = $cur_base; JSONObject choice = (JSONObject) ((JSONArray) toolProfile.get("base_url_choice")).get(0); choice.put("secure_base_url", baseUrl); choice.put("default_base_url", baseUrl); JSONObject secContract = (JSONObject) toolProxy.get("security_contract"); secContract.put("shared_secret", passwd); JSONArray toolServices = (JSONArray) secContract.get("tool_service"); JSONObject service = (JSONObject) toolServices.get(0); service.put("service", regUrl); outTraceFormattedMessage(outTrace, "ToolProxyJSON: " + toolProxy.toJSONString()); /// From the Implementation Guid Version 2.0 Final (http://www.imsglobal.org/lti/ltiv2p0/ltiIMGv2p0.html) /// Section 10.1 /// Get data JSONObject dataService = getData(tcProfileUrl); /// find endpoint with format: application/vnd.ims.lti.v2.toolproxy+json WITH POST action JSONArray offered = (JSONArray) dataService.get("service_offered"); String registerAddress = ""; for (int i = 0; i < offered.size(); ++i) { JSONObject offer = (JSONObject) offered.get(i); JSONArray offerFormat = (JSONArray) offer.get("format"); String format = (String) offerFormat.get(0); JSONArray offerAction = (JSONArray) offer.get("action"); String action = (String) offerAction.get(0); if ("application/vnd.ims.lti.v2.toolproxy+json".equals(format) && "POST".equals(action)) { registerAddress = (String) offer.get("endpoint"); break; } } /// FIXME: Sakai return server name as "localhost", could be my configuration String[] serverAddr = tcProfileUrl.split("/"); String addr = serverAddr[2]; registerAddress = registerAddress.substring(registerAddress.indexOf("/", 8)); registerAddress = "http://" + addr + registerAddress; /// Send POST to specified URL as signed request with given values int responseCode = postData(registerAddress, toolProxy.toJSONString(), key, passwd); if (responseCode != HttpServletResponse.SC_CREATED) { //TODO BOOM! throw new RuntimeException("Bad response code. Got " + responseCode + " but expected " + HttpServletResponse.SC_CREATED); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } String output = "<a href='" + returnUrl + "'>Continue to launch presentation url</a>"; try { PrintWriter out = response.getWriter(); out.println(output); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.opendatakit.aggregate.servlet.SubmissionServlet.java
/** * Handler for HTTP post request that processes a form submission Currently * supports plain/xml and multipart/*w w w . j ava2 s.com*/ * * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { CallingContext cc = ContextFactory.getCallingContext(this, req); Double openRosaVersion = getOpenRosaVersion(req); boolean isIncomplete = false; try { SubmissionParser submissionParser = null; if (ServletFileUpload.isMultipartContent(req)) { MultiPartFormData uploadedSubmissionItems = new MultiPartFormData(req); String isIncompleteFlag = uploadedSubmissionItems .getSimpleFormField(ServletConsts.TRANSFER_IS_INCOMPLETE); isIncomplete = (isIncompleteFlag != null && isIncompleteFlag.compareToIgnoreCase("YES") == 0); submissionParser = new SubmissionParser(uploadedSubmissionItems, isIncomplete, cc); } else { // TODO: check that it is the proper types we can deal with // XML received, we hope... submissionParser = new SubmissionParser(req.getInputStream(), cc); } IForm form = submissionParser.getForm(); // Only trigger uploads if this submission was not already // marked as complete before this interaction and if it is // now complete. AND... // Issue a publish request only if we haven't issued one recently. // use BackendActionsTable to mediate that decision. // This test ONLY OCCURS during submissions, not during Watchdog // firings, so we don't have to worry about bugs here affecting Watchdog. if (!submissionParser.wasPreexistingComplete() && submissionParser.getSubmission().isComplete() && BackendActionsTable.triggerPublisher(form.getUri(), cc)) { // send information to remote servers that need to be notified List<ExternalService> tmp = FormServiceCursor.getExternalServicesForForm(form, cc); UploadSubmissions uploadTask = (UploadSubmissions) cc.getBean(BeanDefs.UPLOAD_TASK_BEAN); // publication failures should not fail the submission... try { CallingContext ccDaemon = ContextFactory.getCallingContext(this, req); ccDaemon.setAsDaemon(true); for (ExternalService rs : tmp) { // only create upload tasks for active publishers if (rs.getFormServiceCursor().getOperationalStatus() == OperationalStatus.ACTIVE) { uploadTask.createFormUploadTask(rs.getFormServiceCursor(), false, ccDaemon); } } } catch (ODKExternalServiceException e) { logger.info("Publishing enqueue failure (this is recoverable) - " + e.getMessage()); e.printStackTrace(); } } // form full url including scheme... String serverUrl = cc.getServerURL(); String url = serverUrl + BasicConsts.FORWARDSLASH + ADDR; resp.setHeader("Location", url); resp.setStatus(HttpServletResponse.SC_CREATED); if (openRosaVersion == null) { logger.info("Successful non-OpenRosa submission"); resp.setContentType(HtmlConsts.RESP_TYPE_HTML); resp.setCharacterEncoding(HtmlConsts.UTF8_ENCODE); PrintWriter out = resp.getWriter(); out.write(HtmlConsts.HTML_OPEN); out.write(HtmlConsts.BODY_OPEN); out.write("Successful submission upload. Click "); out.write(HtmlUtil.createHref(cc.getWebApplicationURL(ADDR), "here", false)); out.write(" to return to upload submissions page."); out.write(HtmlConsts.BODY_CLOSE); out.write(HtmlConsts.HTML_CLOSE); } else { logger.info("Successful OpenRosa submission"); addOpenRosaHeaders(resp); resp.setContentType(HtmlConsts.RESP_TYPE_XML); resp.setCharacterEncoding(HtmlConsts.UTF8_ENCODE); PrintWriter out = resp.getWriter(); out.write("<OpenRosaResponse xmlns=\"http://openrosa.org/http/response\">"); if (isIncomplete) { out.write("<message>partial submission upload was successful!</message>"); } else { out.write("<message>full submission upload was successful!</message>"); } // for Briefcase2, use the attributes on a <submissionMetadata> tag to // update the local copy of the data (if these attributes are // available). { XmlAttributeFormatter attributeFormatter = new XmlAttributeFormatter(); Submission sub = submissionParser.getSubmission(); Row attributeRow = new Row(sub.constructSubmissionKey(null)); // // add what could be considered the form's metadata... // attributeRow.addFormattedValue("id=\"" + StringEscapeUtils.escapeXml10(form.getFormId() .replace(ParserConsts.FORWARD_SLASH_SUBSTITUTION, ParserConsts.FORWARD_SLASH)) + "\""); if (form.isEncryptedForm()) { attributeRow.addFormattedValue("encrypted=\"yes\""); } sub.getFormattedNamespaceValuesForRow(attributeRow, Collections.singletonList(FormElementNamespace.METADATA), attributeFormatter, false, cc); out.write("<submissionMetadata xmlns=\"" + StringEscapeUtils.escapeXml10(ParserConsts.NAMESPACE_ODK) + "\""); Iterator<String> itrAttributes = attributeRow.getFormattedValues().iterator(); while (itrAttributes.hasNext()) { out.write(" "); out.write(itrAttributes.next()); } out.write("/>"); } out.write("</OpenRosaResponse>"); } } catch (ODKFormNotFoundException e) { e.printStackTrace(); logger.warn("Form not found - " + e.getMessage()); odkIdNotFoundError(resp); } catch (ODKParseException e) { logger.warn("Parsing failure - " + e.getMessage()); e.printStackTrace(); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ErrorConsts.PARSING_PROBLEM); } catch (ODKEntityPersistException e) { logger.error("Persist failure - " + e.getMessage()); e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ErrorConsts.PARSING_PROBLEM); } catch (ODKIncompleteSubmissionData e) { logger.warn("Incomplete submission failure - " + e.getMessage()); e.printStackTrace(); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ErrorConsts.PARSING_PROBLEM); } catch (ODKConversionException e) { logger.warn("Datatype casting failure - " + e.getMessage()); e.printStackTrace(); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ErrorConsts.PARSING_PROBLEM); } catch (ODKDatastoreException e) { logger.error("Datastore failure - " + e.getMessage()); e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ErrorConsts.PARSING_PROBLEM); } catch (FileUploadException e) { logger.warn("Attachments parsing failure - " + e.getMessage()); e.printStackTrace(); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ErrorConsts.PARSING_PROBLEM); } catch (ODKFormSubmissionsDisabledException e) { logger.warn("Form submission disabled - " + e.getMessage()); e.printStackTrace(); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ErrorConsts.FORM_DOES_NOT_ALLOW_SUBMISSIONS); } catch (Exception e) { logger.error("Unexpected exception: " + e.getMessage()); e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unexpected exception"); } }
From source file:com.imaginary.home.cloud.CloudTest.java
private void setupToken() throws Exception { if (relayKeyId == null) { setupRelay();// www . j av a 2 s . c o m } HttpClient client = getClient(); HttpPost method = new HttpPost(cloudAPI + "/token"); long timestamp = System.currentTimeMillis(); method.addHeader("Content-Type", "application/json"); method.addHeader("x-imaginary-version", VERSION); method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp)); method.addHeader("x-imaginary-api-key", relayKeyId); method.addHeader("x-imaginary-signature", CloudService.sign(relayKeyId.getBytes("utf-8"), "post:/token:" + relayKeySecret + ":" + timestamp + ":" + VERSION)); 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 t = new JSONObject(json); token = (t.has("token") && !t.isNull("token")) ? t.getString("token") : null; } else { Assert.fail("Failed to generate token (" + status.getStatusCode() + ": " + EntityUtils.toString(response.getEntity())); } }
From source file:es.logongas.ix3.web.controllers.CrudRestController.java
@RequestMapping(value = { "{path}/{entityName}" }, method = RequestMethod.POST, consumes = "application/json", produces = "application/json") public void insert(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, @PathVariable("entityName") String entityName, @RequestBody String jsonIn) { try (DataSession dataSession = dataSessionFactory.getDataSession()) { Principal principal = controllerHelper.getPrincipal(httpServletRequest, httpServletResponse, dataSession);/* w w w .ja v a 2 s. co m*/ MetaData metaData = metaDataFactory.getMetaData(entityName); if (metaData == null) { throw new RuntimeException("No existe la entidad " + entityName); } JsonReader jsonReader = jsonFactory.getJsonReader(metaData.getType()); Object entity = jsonReader.fromJson(jsonIn, controllerHelper.getBeanMapper(httpServletRequest), dataSession); CRUDBusinessProcess crudBusinessProcess = crudBusinessProcessFactory .getBusinessProcess(metaData.getType()); Object resultEntity = crudBusinessProcess .insert(new CRUDBusinessProcess.InsertArguments(principal, dataSession, entity)); controllerHelper.objectToHttpResponse( new HttpResult(metaData.getType(), resultEntity, HttpServletResponse.SC_CREATED), httpServletRequest, httpServletResponse); } catch (Exception ex) { controllerHelper.exceptionToHttpResponse(ex, httpServletResponse); } }
From source file:org.alfresco.module.vti.handler.alfresco.AlfrescoMethodHandler.java
/** * @see org.alfresco.module.vti.handler.MethodHandler#putResource(HttpServletRequest, HttpServletResponse) *//*from w w w . j ava2 s. co m*/ public void putResource(HttpServletRequest request, HttpServletResponse response) { // Office 2008/2011 for Mac specific header final String lockTimeOut = request.getHeader(DAV_EXT_LOCK_TIMEOUT); if (request.getContentLength() == 0 && lockTimeOut == null) { return; } String decodedUrl = URLDecoder.decode(request.getRequestURI()); if (decodedUrl.length() > getPathHelper().getAlfrescoContext().length()) { decodedUrl = decodedUrl.substring(getPathHelper().getAlfrescoContext().length() + 1); } FileInfo resourceFileInfo = getPathHelper().resolvePathFileInfo(decodedUrl); NodeRef resourceNodeRef = null; if (resourceFileInfo != null) { resourceNodeRef = resourceFileInfo.getNodeRef(); } if (logger.isDebugEnabled()) { logger.debug("The request lock timeout from response is " + lockTimeOut); logger.debug("The resource nodeRef is " + resourceNodeRef); } // Does the file already exist (false), or has it been created by this request? boolean newlyCreated = false; // Office 2008/2011 for Mac if (resourceNodeRef == null && lockTimeOut != null) { try { final Pair<String, String> parentChild = VtiPathHelper.splitPathParentChild(decodedUrl); final FileInfo parent = getPathHelper().resolvePathFileInfo(parentChild.getFirst()); RetryingTransactionCallback<NodeRef> cb = new RetryingTransactionCallback<NodeRef>() { @Override public NodeRef execute() throws Throwable { NodeRef result = getFileFolderService() .create(parent.getNodeRef(), parentChild.getSecond(), ContentModel.TYPE_CONTENT) .getNodeRef(); int timeout = Integer.parseInt(lockTimeOut.substring(WebDAV.SECOND.length())); getLockService().lock(result, getUserName(), timeout); return result; } }; resourceNodeRef = getTransactionService().getRetryingTransactionHelper().doInTransaction(cb); if (resourceNodeRef != null) { newlyCreated = true; } if (logger.isDebugEnabled()) { logger.debug("Created new node " + resourceNodeRef); } response.setStatus(HttpServletResponse.SC_CREATED); response.setHeader(WebDAV.HEADER_LOCK_TOKEN, WebDAV.makeLockToken(resourceNodeRef, getUserName())); response.setHeader(DAV_EXT_LOCK_TIMEOUT, lockTimeOut); } catch (AccessDeniedException e) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } } // Check we managed to find the node one way or another if (resourceNodeRef == null) { if (logger.isInfoEnabled()) { logger.info("No node found for resource " + decodedUrl); } // TODO Is this the correct status code to return if they've // tried to query for something that doesn't exist? // Or should we return something else, or even create it? response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } // Get the working copy of it final NodeRef workingCopyNodeRef = getCheckOutCheckInService().getWorkingCopy(resourceNodeRef); // ALF-15984 if (!expectedETagForNode(request, resourceNodeRef)) { response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // updates changes on the server final BufferedHttpServletRequest bufferedRequest = new BufferedHttpServletRequest(request, streamFactory); final NodeRef finalResourceNodeRef = resourceNodeRef; final String finalDecodedUrl = decodedUrl; final boolean finalNewlyCreated = newlyCreated; final String siteId = davHelper.determineSiteId(getPathHelper().getRootNodeRef(), finalDecodedUrl); RetryingTransactionCallback<Void> work = new RetryingTransactionCallback<Void>() { @SuppressWarnings("deprecation") @Override public Void execute() throws Throwable { ContentWriter writer; boolean newlyCreated = finalNewlyCreated; FileFolderService fileFolderService = getFileFolderService(); if (workingCopyNodeRef != null) { if (logger.isDebugEnabled()) { logger.debug("Writing to the workung copy " + workingCopyNodeRef); } if (fileFolderService.isHidden(workingCopyNodeRef)) { fileFolderService.setHidden(workingCopyNodeRef, false); } // working copy writer writer = getContentService().getWriter(workingCopyNodeRef, ContentModel.PROP_CONTENT, true); } else { // ALF-17662, hidden node is the same as non-existed node for SPP if (fileFolderService.isHidden(finalResourceNodeRef)) { // make it visible for client fileFolderService.setHidden(finalResourceNodeRef, false); } if (logger.isDebugEnabled()) { logger.debug("Writing to the node " + finalResourceNodeRef); } // original document writer writer = getContentService().getWriter(finalResourceNodeRef, ContentModel.PROP_CONTENT, true); } String documentName = getNodeService().getProperty(finalResourceNodeRef, ContentModel.PROP_NAME) .toString(); String mimetype = getMimetypeService().guessMimetype(documentName); writer.setMimetype(mimetype); writer.putContent(bufferedRequest.getInputStream()); // If needed, mark the node as having now had its content supplied if (getNodeService().hasAspect(finalResourceNodeRef, ContentModel.ASPECT_WEBDAV_NO_CONTENT)) { // CLOUD-2209: newly created documents not shown in activity feed. newlyCreated = true; getNodeService().removeAspect(finalResourceNodeRef, ContentModel.ASPECT_WEBDAV_NO_CONTENT); } // If we actually have content, it's time to add the versionable aspect and save the current version ContentData contentData = writer.getContentData(); if (workingCopyNodeRef == null && !getNodeService().hasAspect(finalResourceNodeRef, ContentModel.ASPECT_VERSIONABLE) && ContentData.hasContent(contentData) && contentData.getSize() > 0) { if (logger.isDebugEnabled()) { logger.debug("Creating a new major version for " + finalResourceNodeRef); } getVersionService().createVersion(finalResourceNodeRef, Collections .<String, Serializable>singletonMap(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR)); } if (siteId != null) { String tenantDomain = davHelper.determineTenantDomain(); long fileSize = contentData.getSize(); reportUploadEvent(finalDecodedUrl, siteId, tenantDomain, newlyCreated, mimetype, fileSize); } return null; } }; try { getTransactionService().getRetryingTransactionHelper().doInTransaction(work); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("An exception occurred during writing the content.", e); } response.setStatus(HttpServletResponse.SC_CONFLICT); return; } finally { if (bufferedRequest != null) { bufferedRequest.close(); } } // original document properties Map<QName, Serializable> props = getNodeService().getProperties(resourceNodeRef); if (workingCopyNodeRef != null) { String workingCopyOwner = getNodeService() .getProperty(workingCopyNodeRef, ContentModel.PROP_WORKING_COPY_OWNER).toString(); if (workingCopyOwner.equals(getAuthenticationService().getCurrentUserName())) { // working copy properties props = getNodeService().getProperties(workingCopyNodeRef); } } String guid = resourceNodeRef.getId().toUpperCase(); Date lastModified = (Date) props.get(ContentModel.PROP_MODIFIED); response.setHeader("Repl-uid", VtiUtils.constructRid(guid)); response.setHeader("ResourceTag", VtiUtils.constructResourceTag(guid, lastModified)); response.setHeader("Last-Modified", VtiUtils.formatBrowserDate(lastModified)); response.setHeader("ETag", VtiUtils.constructETag(guid, lastModified)); ContentReader reader = getContentService().getReader(resourceNodeRef, ContentModel.PROP_CONTENT); String mimetype = reader == null ? null : reader.getMimetype(); if (mimetype != null) { response.setContentType(mimetype); } }