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.jahia.bin.Render.java
private boolean checkForUploadedFiles(HttpServletRequest req, HttpServletResponse resp, String workspace, Locale locale, Map<String, List<String>> parameters, URLResolver urlResolver) throws RepositoryException, IOException { if (isMultipartRequest(req)) { // multipart is processed only if it's not a portlet request. // otherwise it's the task the portlet if (!isPortletRequest(req)) { final String savePath = getSettingsBean().getTmpContentDiskPath(); final File tmp = new File(savePath); if (!tmp.exists()) { tmp.mkdirs();/*from w w w .j av a 2 s . c o m*/ } try { final FileUpload fileUpload = new FileUpload(req, savePath, Integer.MAX_VALUE); req.setAttribute(FileUpload.FILEUPLOAD_ATTRIBUTE, fileUpload); if (fileUpload.getFileItems() != null && fileUpload.getFileItems().size() > 0) { boolean isTargetDirectoryDefined = fileUpload.getParameterNames().contains(TARGETDIRECTORY); boolean isAction = urlResolver.getPath().endsWith(".do"); boolean isContributePost = fileUpload.getParameterNames().contains(CONTRIBUTE_POST); final String requestWith = req.getHeader("x-requested-with"); boolean isAjaxRequest = req.getHeader("accept") != null && req.getHeader("accept").contains("application/json") && requestWith != null && requestWith.equals("XMLHttpRequest") || fileUpload.getParameterMap().isEmpty(); List<String> uuids = new LinkedList<String>(); List<String> files = new ArrayList<String>(); List<String> urls = new LinkedList<String>(); // If target directory is defined or if it is an ajax request then save the file now // otherwise we delay the save of the file to the node creation if (!isAction && (isContributePost || isTargetDirectoryDefined || isAjaxRequest)) { JCRSessionWrapper session = jcrSessionFactory.getCurrentUserSession(workspace, locale); String target; if (isTargetDirectoryDefined) { target = (fileUpload.getParameterValues(TARGETDIRECTORY))[0]; } else if (isContributePost) { String path = urlResolver.getPath(); path = (path.endsWith("*") ? StringUtils.substringBeforeLast(path, "/") : path); JCRNodeWrapper sessionNode = session.getNode(path); JCRSiteNode siteNode = sessionNode.getResolveSite(); if (siteNode != null) { String s = sessionNode.getResolveSite().getPath() + "/files/contributed/"; String name = JCRContentUtils.replaceColon(sessionNode.getPrimaryNodeTypeName()) + "_" + sessionNode.getName(); target = s + name; try { session.getNode(target); } catch (RepositoryException e) { JCRNodeWrapper node = session.getNode(s); session.checkout(node); node.addNode(name, "jnt:folder"); session.save(); } } else { target = sessionNode.getPath() + "/files"; if (!sessionNode.hasNode("files")) { session.checkout(sessionNode); sessionNode.addNode("files", "jnt:folder"); session.save(); } } } else { String path = urlResolver.getPath(); target = (path.endsWith("*") ? StringUtils.substringBeforeLast(path, "/") : path); } final JCRNodeWrapper targetDirectory = session.getNode(target); boolean isVersionActivated = fileUpload.getParameterNames().contains(VERSION) ? (fileUpload.getParameterValues(VERSION))[0].equals("true") : false; final Map<String, DiskFileItem> stringDiskFileItemMap = fileUpload.getFileItems(); for (Map.Entry<String, DiskFileItem> itemEntry : stringDiskFileItemMap.entrySet()) { //if node exists, do a checkout before String name = itemEntry.getValue().getName(); if (fileUpload.getParameterNames().contains(TARGETNAME)) { name = (fileUpload.getParameterValues(TARGETNAME))[0]; } name = JCRContentUtils.escapeLocalNodeName(FilenameUtils.getName(name)); JCRNodeWrapper fileNode = targetDirectory.hasNode(name) ? targetDirectory.getNode(name) : null; if (fileNode != null && isVersionActivated) { session.checkout(fileNode); } // checkout parent directory session.checkout(targetDirectory); InputStream is = null; JCRNodeWrapper wrapper = null; try { is = itemEntry.getValue().getInputStream(); wrapper = targetDirectory.uploadFile(name, is, JCRContentUtils.getMimeType(name, itemEntry.getValue().getContentType())); } finally { IOUtils.closeQuietly(is); } uuids.add(wrapper.getIdentifier()); urls.add(wrapper.getAbsoluteUrl(req)); files.add(itemEntry.getValue().getName()); if (isVersionActivated) { if (!wrapper.isVersioned()) { wrapper.versionFile(); } session.save(); // Handle potential move of the node after save wrapper = session.getNodeByIdentifier(wrapper.getIdentifier()); wrapper.checkpoint(); } } fileUpload.disposeItems(); fileUpload.markFilesAsConsumed(); session.save(); } if (isAction || (!isAjaxRequest && !isContributePost)) { parameters.putAll(fileUpload.getParameterMap()); if (isTargetDirectoryDefined) { parameters.put(NODE_NAME, files); } return true; } else { try { resp.setStatus(HttpServletResponse.SC_CREATED); Map<String, Object> map = new LinkedHashMap<String, Object>(); map.put("uuids", uuids); map.put("urls", urls); JSONObject nodeJSON = new JSONObject(map); nodeJSON.write(resp.getWriter()); return true; } catch (JSONException e) { logger.error(e.getMessage(), e); } } } if (fileUpload.getParameterMap() != null && !fileUpload.getParameterMap().isEmpty()) { parameters.putAll(fileUpload.getParameterMap()); } } catch (IOException e) { logger.error("Cannot parse multipart data !", e); } } else { logger.debug("Mulipart request is not processed. It's the task of the portlet"); } } return false; }
From source file:de.mendelson.comm.as2.send.MessageHttpUploader.java
/**Uploads the data, returns the HTTP result code*/ public int performUpload(HttpConnectionParameter connectionParameter, AS2Message message, Partner sender, Partner receiver, URL receiptURL) { String ediintFeatures = "multiple-attachments, CEM"; //set the http connection/routing/protocol parameter HttpParams httpParams = new BasicHttpParams(); if (connectionParameter.getConnectionTimeoutMillis() != -1) { HttpConnectionParams.setConnectionTimeout(httpParams, connectionParameter.getConnectionTimeoutMillis()); }/*from w ww .jav a2 s . c o m*/ if (connectionParameter.getSoTimeoutMillis() != -1) { HttpConnectionParams.setSoTimeout(httpParams, connectionParameter.getSoTimeoutMillis()); } HttpConnectionParams.setStaleCheckingEnabled(httpParams, connectionParameter.isStaleConnectionCheck()); if (connectionParameter.getHttpProtocolVersion() == null) { //default settings: HTTP 1.1 HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); } else if (connectionParameter.getHttpProtocolVersion().equals(HttpConnectionParameter.HTTP_1_0)) { HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_0); } else if (connectionParameter.getHttpProtocolVersion().equals(HttpConnectionParameter.HTTP_1_1)) { HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); } HttpProtocolParams.setUseExpectContinue(httpParams, connectionParameter.isUseExpectContinue()); HttpProtocolParams.setUserAgent(httpParams, connectionParameter.getUserAgent()); if (connectionParameter.getLocalAddress() != null) { ConnRouteParams.setLocalAddress(httpParams, connectionParameter.getLocalAddress()); } int status = -1; HttpPost filePost = null; DefaultHttpClient httpClient = null; try { ClientConnectionManager clientConnectionManager = this.createClientConnectionManager(httpParams); httpClient = new DefaultHttpClient(clientConnectionManager, httpParams); //some ssl implementations have problems with a session/connection reuse httpClient.setReuseStrategy(new NoConnectionReuseStrategy()); //disable SSL hostname verification. Do not confuse this with SSL trust verification! SSLSocketFactory sslFactory = (SSLSocketFactory) httpClient.getConnectionManager().getSchemeRegistry() .get("https").getSocketFactory(); sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); //determine the receipt URL if it is not set if (receiptURL == null) { //async MDN requested? if (message.isMDN()) { if (this.runtimeConnection == null) { throw new IllegalArgumentException( "MessageHTTPUploader.performUpload(): A MDN receipt URL is not set, unable to determine where to send the MDN"); } MessageAccessDB messageAccess = new MessageAccessDB(this.configConnection, this.runtimeConnection); AS2MessageInfo relatedMessageInfo = messageAccess .getLastMessageEntry(((AS2MDNInfo) message.getAS2Info()).getRelatedMessageId()); receiptURL = new URL(relatedMessageInfo.getAsyncMDNURL()); } else { receiptURL = new URL(receiver.getURL()); } } filePost = new HttpPost(receiptURL.toExternalForm()); filePost.addHeader("as2-version", "1.2"); filePost.addHeader("ediint-features", ediintFeatures); filePost.addHeader("mime-version", "1.0"); filePost.addHeader("recipient-address", receiptURL.toExternalForm()); filePost.addHeader("message-id", "<" + message.getAS2Info().getMessageId() + ">"); filePost.addHeader("as2-from", AS2Message.escapeFromToHeader(sender.getAS2Identification())); filePost.addHeader("as2-to", AS2Message.escapeFromToHeader(receiver.getAS2Identification())); String originalFilename = null; if (message.getPayloads() != null && message.getPayloads().size() > 0) { originalFilename = message.getPayloads().get(0).getOriginalFilename(); } if (originalFilename != null) { String subject = this.replace(message.getAS2Info().getSubject(), "${filename}", originalFilename); filePost.addHeader("subject", subject); //update the message infos subject with the actual content if (!message.isMDN()) { ((AS2MessageInfo) message.getAS2Info()).setSubject(subject); //refresh this in the database if it is requested if (this.runtimeConnection != null) { MessageAccessDB access = new MessageAccessDB(this.configConnection, this.runtimeConnection); access.updateSubject((AS2MessageInfo) message.getAS2Info()); } } } else { filePost.addHeader("subject", message.getAS2Info().getSubject()); } filePost.addHeader("from", sender.getEmail()); filePost.addHeader("connection", "close, TE"); //the data header must be always in english locale else there would be special //french characters (e.g. 13 dc. 2011 16:28:56 CET) which is not allowed after //RFC 4130 DateFormat format = new SimpleDateFormat("EE, dd MMM yyyy HH:mm:ss zz", Locale.US); filePost.addHeader("date", format.format(new Date())); String contentType = null; if (message.getAS2Info().getEncryptionType() != AS2Message.ENCRYPTION_NONE) { contentType = "application/pkcs7-mime; smime-type=enveloped-data; name=smime.p7m"; } else { contentType = message.getContentType(); } filePost.addHeader("content-type", contentType); //MDN header, this is always the way for async MDNs if (message.isMDN()) { if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("sending.mdn.async", new Object[] { message.getAS2Info().getMessageId(), receiptURL }), message.getAS2Info()); } filePost.addHeader("server", message.getAS2Info().getUserAgent()); } else { AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info(); //outbound AS2/CEM message if (messageInfo.requestsSyncMDN()) { if (this.logger != null) { if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_CEM) { this.logger.log(Level.INFO, this.rb.getResourceString("sending.cem.sync", new Object[] { messageInfo.getMessageId(), receiver.getURL() }), messageInfo); } else if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_AS2) { this.logger.log(Level.INFO, this.rb.getResourceString("sending.msg.sync", new Object[] { messageInfo.getMessageId(), receiver.getURL() }), messageInfo); } } } else { //Message with ASYNC MDN request if (this.logger != null) { if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_CEM) { this.logger.log(Level.INFO, this.rb.getResourceString("sending.cem.async", new Object[] { messageInfo.getMessageId(), receiver.getURL(), sender.getMdnURL() }), messageInfo); } else if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_AS2) { this.logger.log(Level.INFO, this.rb.getResourceString("sending.msg.async", new Object[] { messageInfo.getMessageId(), receiver.getURL(), sender.getMdnURL() }), messageInfo); } } //The following header indicates that this requests an asnc MDN. //When the header "receipt-delivery-option" is present, //the header "disposition-notification-to" serves as a request //for an asynchronous MDN. //The header "receipt-delivery-option" must always be accompanied by //the header "disposition-notification-to". //When the header "receipt-delivery-option" is not present and the header //"disposition-notification-to" is present, the header "disposition-notification-to" //serves as a request for a synchronous MDN. filePost.addHeader("receipt-delivery-option", sender.getMdnURL()); } filePost.addHeader("disposition-notification-to", sender.getMdnURL()); //request a signed MDN if this is set up in the partner configuration if (receiver.isSignedMDN()) { filePost.addHeader("disposition-notification-options", messageInfo.getDispositionNotificationOptions().getHeaderValue()); } if (messageInfo.getSignType() != AS2Message.SIGNATURE_NONE) { filePost.addHeader("content-disposition", "attachment; filename=\"smime.p7m\""); } else if (messageInfo.getSignType() == AS2Message.SIGNATURE_NONE && message.getAS2Info().getSignType() == AS2Message.ENCRYPTION_NONE) { filePost.addHeader("content-disposition", "attachment; filename=\"" + message.getPayload(0).getOriginalFilename() + "\""); } } int port = receiptURL.getPort(); if (port == -1) { port = receiptURL.getDefaultPort(); } filePost.addHeader("host", receiptURL.getHost() + ":" + port); InputStream rawDataInputStream = message.getRawDataInputStream(); InputStreamEntity postEntity = new InputStreamEntity(rawDataInputStream, message.getRawDataSize()); postEntity.setContentType(contentType); filePost.setEntity(postEntity); if (connectionParameter.getProxy() != null) { this.setProxyToConnection(httpClient, message, connectionParameter.getProxy()); } this.setHTTPAuthentication(httpClient, receiver, message.getAS2Info().isMDN()); this.updateUploadHttpHeader(filePost, receiver); HttpHost targetHost = new HttpHost(receiptURL.getHost(), receiptURL.getPort(), receiptURL.getProtocol()); BasicHttpContext localcontext = new BasicHttpContext(); // Generate BASIC scheme object and stick it to the local // execution context. Without this a HTTP authentication will not be sent BasicScheme basicAuth = new BasicScheme(); localcontext.setAttribute("preemptive-auth", basicAuth); HttpResponse httpResponse = httpClient.execute(targetHost, filePost, localcontext); rawDataInputStream.close(); this.responseData = this.readEntityData(httpResponse); if (httpResponse != null) { this.responseStatusLine = httpResponse.getStatusLine(); status = this.responseStatusLine.getStatusCode(); this.responseHeader = httpResponse.getAllHeaders(); } for (Header singleHeader : filePost.getAllHeaders()) { if (singleHeader.getValue() != null) { this.requestHeader.setProperty(singleHeader.getName(), singleHeader.getValue()); } } //accept all 2xx answers //SC_ACCEPTED Status code (202) indicating that a request was accepted for processing, but was not completed. //SC_CREATED Status code (201) indicating the request succeeded and created a new resource on the server. //SC_NO_CONTENT Status code (204) indicating that the request succeeded but that there was no new information to return. //SC_NON_AUTHORITATIVE_INFORMATION Status code (203) indicating that the meta information presented by the client did not originate from the server. //SC_OK Status code (200) indicating the request succeeded normally. //SC_RESET_CONTENT Status code (205) indicating that the agent SHOULD reset the document view which caused the request to be sent. //SC_PARTIAL_CONTENT Status code (206) indicating that the server has fulfilled the partial GET request for the resource. if (status != HttpServletResponse.SC_OK && status != HttpServletResponse.SC_ACCEPTED && status != HttpServletResponse.SC_CREATED && status != HttpServletResponse.SC_NO_CONTENT && status != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION && status != HttpServletResponse.SC_RESET_CONTENT && status != HttpServletResponse.SC_PARTIAL_CONTENT) { if (this.logger != null) { this.logger .severe(this.rb.getResourceString("error.httpupload", new Object[] { message.getAS2Info().getMessageId(), URLDecoder.decode( this.responseStatusLine == null ? "" : this.responseStatusLine.getReasonPhrase(), "UTF-8") })); } } } catch (Exception ex) { if (this.logger != null) { StringBuilder errorMessage = new StringBuilder(message.getAS2Info().getMessageId()); errorMessage.append(": MessageHTTPUploader.performUpload: ["); errorMessage.append(ex.getClass().getSimpleName()); errorMessage.append("]"); if (ex.getMessage() != null) { errorMessage.append(": ").append(ex.getMessage()); } this.logger.log(Level.SEVERE, errorMessage.toString(), message.getAS2Info()); } } finally { if (httpClient != null && httpClient.getConnectionManager() != null) { //shutdown the HTTPClient to release the resources httpClient.getConnectionManager().shutdown(); } } return (status); }
From source file:com.imaginary.home.cloud.CloudTest.java
@Test public void token() throws Exception { HttpClient client = getClient();/*from w w w . j ava 2s. c o m*/ 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(relayKeySecret.getBytes("utf-8"), "post:/token:" + relayKeyId + ":" + 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); String token = (t.has("token") && !t.isNull("token")) ? t.getString("token") : null; out("Token: " + token); Assert.assertNotNull("Token may not be null", token); CloudTest.token = token; } else { Assert.fail("Failed to generate token (" + status.getStatusCode() + ": " + EntityUtils.toString(response.getEntity())); } }
From source file:info.raack.appliancelabeler.web.MainController.java
/** * HTTP request handler for adding new appliance label for previously identified state transition * @throws IOException /*w ww. ja v a 2 s.co m*/ */ @RequestMapping(value = "/energy/transition/{id}/labels", method = RequestMethod.POST) public void addAnonymousUserApplianceLabel(@PathVariable(value = "id") int transitionId, @RequestParam(value = "userApplianceId") int userApplianceId, HttpServletRequest request, HttpServletResponse response) throws IOException { // get current energymonitor EnergyMonitor energyMonitor = getCurrentEnergyMonitor(request, response); // generate transition dataService.createUserGeneratedLabelsSurroundingAnonymousTransition(transitionId, userApplianceId); response.setStatus(HttpServletResponse.SC_CREATED); }
From source file:org.dasein.cloud.azure.AzureStorageMethod.java
public String getBlobProperty(@Nonnull String strMethod, @Nonnull String resource, @Nonnull Map<String, String> queries, String body, @Nullable Map<String, String> headerMap, boolean authorization, String propertyName) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("enter - " + AzureStorageMethod.class.getName() + "." + strMethod + "(" + getStorageAccount() + "," + resource + ")"); }//from ww w .j a v a2 s . co m String endpoint = getStorageEnpoint(); if (wire.isDebugEnabled()) { wire.debug(strMethod + "--------------------------------------------------------> " + endpoint + getStorageAccount() + resource); wire.debug(""); } try { HttpClient client = getClient(); if (headerMap == null) { headerMap = new HashMap<String, String>(); } HttpRequestBase method = getMethod(strMethod, buildUrl(resource, queries), queries, headerMap, authorization); if (wire.isDebugEnabled()) { wire.debug(method.getRequestLine().toString()); for (Header header : method.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); if (body != null) { wire.debug(body); wire.debug(""); } } // If it is post or put if (method instanceof HttpEntityEnclosingRequestBase) { HttpEntityEnclosingRequestBase entityEnclosingMethod = (HttpEntityEnclosingRequestBase) method; if (body != null) { entityEnclosingMethod.setEntity(new StringEntity(body, "application/xml", "utf-8")); } } HttpResponse response; StatusLine status; try { response = client.execute(method); 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("get(): HTTP Status " + status); } if (wire.isDebugEnabled()) { Header[] headers = response.getAllHeaders(); 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_NOT_FOUND) { return null; } if ((status.getStatusCode() != HttpServletResponse.SC_CREATED && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED && status.getStatusCode() != HttpServletResponse.SC_OK) && status.getStatusCode() != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION) { logger.error( strMethod + "(): Expected OK for " + strMethod + "request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); String result; if (entity == null) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } try { result = EntityUtils.toString(entity); int index = result.indexOf("<"); // The result may not be a stardard xml format if (index > 0) { result = result.substring(index); } } catch (IOException e) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } if (wire.isDebugEnabled()) { wire.debug(result); } wire.debug(""); AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), result); logger.error(strMethod + "(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details); throw new AzureException(items); } else { Header header = response.getFirstHeader(propertyName); if (header != null) { return header.getValue(); } else { return null; } } } catch (UnsupportedEncodingException e) { throw new CloudException(e); } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + AzureMethod.class.getName() + ".getStream()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("--------------------------------------------------------> "); } } }
From source file:info.raack.appliancelabeler.web.MainController.java
/** * HTTP request handler for adding new appliance labels * @throws IOException /*from w w w. j av a 2s .c om*/ */ @RequestMapping(value = "/energy/userappliances/labels", method = RequestMethod.POST) public void addUserApplianceLabel(@RequestParam(value = "userApplianceId") int applianceId, @RequestParam(value = "onTime") long onTime, @RequestParam(value = "offTime") long offTime, @RequestParam(value = "force") boolean force, HttpServletRequest request, HttpServletResponse response) throws IOException { // get current energymonitor EnergyMonitor energyMonitor = getCurrentEnergyMonitor(request, response); // TODO - set the forth argument back to 'force' once we can guarantee that the dataservice gets up to the second data for the ted on demand to correct detect current spikes LabelResult result = dataService.createUserGeneratedLabelsForUserApplianceId(energyMonitor, applianceId, new Date(onTime), new Date(offTime), true); if (result == LabelResult.OK) { logger.info("Found acceptable user labels"); response.setStatus(HttpServletResponse.SC_CREATED); } else { logger.info("Could not find acceptable user labels"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().write(result.toString()); } }
From source file:org.opencastproject.adminui.endpoint.SeriesEndpoint.java
@POST @Path("new") @RestQuery(name = "createNewSeries", description = "Creates a new series by the given metadata as JSON", returnDescription = "The created series id", restParameters = { @RestParameter(name = "metadata", isRequired = true, description = "The metadata as JSON", type = RestParameter.Type.TEXT) }, reponses = { @RestResponse(responseCode = HttpServletResponse.SC_CREATED, description = "Returns the created series id"), @RestResponse(responseCode = HttpServletResponse.SC_BAD_REQUEST, description = "he request could not be fulfilled due to the incorrect syntax of the request"), @RestResponse(responseCode = SC_UNAUTHORIZED, description = "If user doesn't have rights to create the series") }) public Response createNewSeries(@FormParam("metadata") String metadata) throws UnauthorizedException { String seriesId;/* www.j a v a 2 s. co m*/ try { seriesId = getIndexService().createSeries(metadata); return Response.created(getSeriesMetadataUrl(seriesId)).entity(seriesId).build(); } catch (IllegalArgumentException e) { return RestUtil.R.badRequest(e.getMessage()); } catch (InternalServerErrorException e) { return RestUtil.R.serverError(); } }
From source file:com.sitewhere.web.rest.controllers.AssignmentsController.java
/** * Adds data to an existing device stream. * /*from w ww .j a v a2 s . c o m*/ * @param token * @param streamId * @param sequenceNumber * @param svtRequest * @param svtResponse * @throws SiteWhereException */ @RequestMapping(value = "/{token}/streams/{streamId:.+}", method = RequestMethod.POST) @ResponseBody @ApiOperation(value = "Add data to device assignment data stream") @Secured({ SiteWhereRoles.REST }) @Documented public void addDeviceStreamData( @ApiParam(value = "Assignment token", required = true) @PathVariable String token, @ApiParam(value = "Stream Id", required = true) @PathVariable String streamId, @ApiParam(value = "Sequence Number", required = false) @RequestParam(required = false) Long sequenceNumber, HttpServletRequest servletRequest, HttpServletResponse svtResponse) throws SiteWhereException { Tracer.start(TracerCategory.RestApiCall, "addDeviceStreamData", LOGGER); try { ServletInputStream inData = servletRequest.getInputStream(); ByteArrayOutputStream byteData = new ByteArrayOutputStream(); int data; while ((data = inData.read()) != -1) { byteData.write(data); } byte[] payload = byteData.toByteArray(); DeviceStreamDataCreateRequest request = new DeviceStreamDataCreateRequest(); request.setStreamId(streamId); request.setSequenceNumber(sequenceNumber); request.setEventDate(new Date()); request.setUpdateState(false); request.setData(payload); SiteWhere.getServer().getDeviceEventManagement(getTenant(servletRequest)).addDeviceStreamData(token, request); svtResponse.setStatus(HttpServletResponse.SC_CREATED); } catch (SiteWhereSystemException e) { if (e.getCode() == ErrorCode.InvalidStreamId) { svtResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); } else { LOGGER.error("Unhandled SiteWhere exception.", e); svtResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } catch (IOException e) { LOGGER.error(e); svtResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { Tracer.stop(LOGGER); } }
From source file:org.openmrs.module.rheashradapter.web.controller.RHEApatientController.java
@RequestMapping(value = "/encounters", method = RequestMethod.POST) @ResponseBody// ww w. j a va 2 s . c o m public Object createEncounters(@RequestBody String hl7, @RequestParam(value = "patientId", required = true) String patientId, @RequestParam(value = "idType", required = true) String idType, @RequestParam(value = "notificationType", required = false) String notificationType, HttpServletRequest request, HttpServletResponse response) { log.info("RHEA HL7 Message Controller call detected..."); XmlMessageWriter xmlMessagewriter = new XmlMessageWriter(); Patient patient = null; String sourceKey = null; Encounter encounter = null; LogEncounterService service = Context.getService(LogEncounterService.class); PostEncounterLog postEncounterLog = new PostEncounterLog(); postEncounterLog.setPatientId(patientId); postEncounterLog.setHl7data(hl7); postEncounterLog.setDateCreated(new Date()); postEncounterLog.setUserId(Context.getUserContext().getAuthenticatedUser().getUserId()); if (!idType.equals("ECID")) { log.info("Error : Invalid ID Type"); postEncounterLog = util.postLogger(postEncounterLog, RequestOutcome.BAD_REQUEST.getResultType(), RHEAErrorCodes.ID_TYPE_DETAIL); service.savePostEncounterLog(postEncounterLog); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); try { xmlMessagewriter.parseMessage(response.getWriter(), RequestOutcome.BAD_REQUEST.getResultType(), RHEAErrorCodes.ID_TYPE_DETAIL); } catch (Exception e) { e.printStackTrace(); } return null; } if (notificationType != null) { if (!notificationType.equals("BIR") && !notificationType.equals("MAT") && !notificationType.equals("RISK")) { log.info("Error : Invalid notification type"); postEncounterLog = util.postLogger(postEncounterLog, RequestOutcome.BAD_REQUEST.getResultType(), RHEAErrorCodes.NOTIFICATION_TYPE_DETAIL); service.savePostEncounterLog(postEncounterLog); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); try { xmlMessagewriter.parseMessage(response.getWriter(), RequestOutcome.BAD_REQUEST.getResultType(), RHEAErrorCodes.NOTIFICATION_TYPE_DETAIL); } catch (Exception e) { e.printStackTrace(); } return null; } } SAXBuilder builder = new SAXBuilder(); Document document = null; try { document = builder.build(new ByteArrayInputStream(hl7.getBytes())); Element root = document.getRootElement(); List rows = root.getChildren("MSH"); Element child = (Element) document.getRootElement().getChildren().get(0); rows = child.getChildren(); for (int i = 0; i < rows.size(); i++) { Element row = (Element) rows.get(i); if (row.getName().equals("MSH.10")) { sourceKey = row.getValue(); } } } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } List<PatientIdentifierType> identifierTypeList = null; if (patientId != null) { PatientIdentifierType patientIdentifierType = Context.getPatientService() .getPatientIdentifierTypeByName("ECID"); identifierTypeList = new ArrayList<PatientIdentifierType>(); identifierTypeList.add(patientIdentifierType); List<Patient> patients = Context.getPatientService().getPatients(null, patientId, identifierTypeList, false); // I am not checking the identifier type here. Need to come back and // add a check for this if (patients.size() == 1) { patient = patients.get(0); PatientIdentifier identifier = patient.getPatientIdentifier("ECID"); identifier.setPreferred(true); Context.getPatientService().savePatient(patient); } } if (patient == null) { log.info("The specified patient was not found. A new patient wil be created.."); String givenName = null; String familyName = null; String birthDateString = null; Date birthDate = null; String gender = null; String nameSpace = "urn:hl7-org:v2xml"; Element root = document.getRootElement(); Element pidRows = root.getChild("ORU_R01.PATIENT_RESULT", Namespace.getNamespace(nameSpace)) .getChild("ORU_R01.PATIENT", Namespace.getNamespace(nameSpace)) .getChild("PID", Namespace.getNamespace(nameSpace)); List<Element> rows = pidRows.getChildren(); for (int i = 0; i < rows.size(); i++) { Element row = (Element) rows.get(i); if (row.getName().equals("PID.5")) { familyName = row.getChild("XPN.1", Namespace.getNamespace(nameSpace)) .getChild("FN.1", Namespace.getNamespace(nameSpace)).getValue().toString(); givenName = row.getChild("XPN.2", Namespace.getNamespace(nameSpace)).getValue().toString(); } if (row.getName().equals("PID.7")) { birthDateString = row.getChild("TS.1", Namespace.getNamespace(nameSpace)).getValue().toString(); SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd"); try { if (birthDateString != null) birthDate = format.parse(birthDateString); } catch (ParseException e) { } } if (row.getName().equals("PID.8")) { gender = row.getValue().toString(); } } patient = new Patient(); PersonName name = new PersonName(); name.setGivenName(givenName); name.setFamilyName(familyName); patient.addName(name); PatientIdentifier identifier = new PatientIdentifier(); identifier.setIdentifier(patientId); PatientIdentifierType pIdType = Context.getPatientService().getPatientIdentifierTypeByName(idType); if (pIdType == null) { pIdType = new PatientIdentifierType(); pIdType.setName("ECID"); pIdType.setDescription("Enterprise ID"); pIdType.setRequired(false); Context.getPatientService().savePatientIdentifierType(pIdType); } identifier.setIdentifierType(Context.getPatientService().getPatientIdentifierTypeByName(idType)); identifier.setLocation(Context.getLocationService().getLocation(1)); identifier.setDateCreated(new Date()); identifier.setVoided(false); identifier.setPreferred(true); patient.addIdentifier(identifier); if (gender != null) patient.setGender(gender); else patient.setGender("N/A"); patient.setBirthdate(birthDate); // Save newly created patient into database Context.getPatientService().savePatient(patient); } log.info("Source key : " + sourceKey); // log.info("Source : " + source); log.info("data :" + hl7); log.info("enterprise id :" + patientId); // For RHEA, should the source be a single static entity ? HL7Source hl7Source = Context.getHL7Service().getHL7SourceByName("LOCAL"); log.info("Creating HL7InQueue object..."); HL7InQueue hl7InQueue = new HL7InQueue(); hl7InQueue.setHL7Data(hl7); log.info("hl7 message is : " + hl7.toString()); hl7InQueue.setHL7Source(hl7Source); log.info("hl7 source is : " + hl7Source.toString()); hl7InQueue.setHL7SourceKey(sourceKey); log.info("hl7 source key is : " + sourceKey); Context.getHL7Service().saveHL7InQueue(hl7InQueue); String encId = null; try { // Call the processor method if (notificationType == null) { encId = processHL7InQueue(hl7InQueue, patientId); } else { encId = processNotification(hl7InQueue, patientId); } postEncounterLog.setResult(RequestOutcome.CREATED.getResultType()); postEncounterLog.setValid(true); service.savePostEncounterLog(postEncounterLog); response.setHeader("Location", request.getRequestURL() + "?enterpriseId=" + patientId + "&idType=" + idType + "&encounterId=" + encId); encounter = Context.getEncounterService().getEncounter(Integer.parseInt(encId)); response.setStatus(HttpServletResponse.SC_CREATED); } catch (HL7Exception e) { e.printStackTrace(); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String stackTrace = sw.toString(); postEncounterLog = util.postLogger(postEncounterLog, RequestOutcome.BAD_REQUEST.getResultType(), stackTrace); service.savePostEncounterLog(postEncounterLog); HL7InError error = new HL7InError(hl7InQueue); error.setError("ERROR"); error.setErrorDetails(ExceptionUtils.getFullStackTrace(e)); Context.getHL7Service().saveHL7InError(error); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); try { xmlMessagewriter.parseMessage(response.getWriter(), RequestOutcome.BAD_REQUEST.getResultType(), e.toString()); } catch (Exception e2) { e2.printStackTrace(); } return null; } catch (Exception e) { e.printStackTrace(); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String stackTrace = sw.toString(); postEncounterLog = util.postLogger(postEncounterLog, RequestOutcome.BAD_REQUEST.getResultType(), stackTrace); service.savePostEncounterLog(postEncounterLog); HL7InError error = new HL7InError(hl7InQueue); error.setError("Exception"); error.setErrorDetails(ExceptionUtils.getFullStackTrace(e)); Context.getHL7Service().saveHL7InError(error); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); try { xmlMessagewriter.parseMessage(response.getWriter(), RequestOutcome.SERVER_ERROR.getResultType(), e.toString()); } catch (Exception e2) { e2.printStackTrace(); } return null; } log.info("Returning persisted encounter to the ReferralAlerts module " + encounter.getId()); return encounter; }