List of usage examples for java.io PrintWriter write
public void write(String s)
From source file:eu.gloriaproject.tools.userreservations.UserReservationController.java
/** * To go to the Experiment Panel (Private Page) *///w w w . jav a 2 s. com @ResourceMapping(value = "goExperiment") public void goExperiment(ResourceRequest request, ResourceResponse response) throws PortletException, IOException { ResourceBundle rb = ResourceBundle.getBundle("Language", request.getLocale()); String reservationId = request.getParameter("reservationId"); // Get email and password of the current user ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); String emailUser = themeDisplay.getUser().getEmailAddress(); String passwordUser = themeDisplay.getUser().getPassword(); try { reservationsService.getExperimentInformation(emailUser, passwordUser, Integer.parseInt(reservationId)); // TODO Set the experiment selected String friendlyURL = renderExperiment(request, response, reservationId, "SOLAR"); JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", true); jsonObject.put("message", rb.getString("msg-experiment-created")); jsonObject.put("url", friendlyURL); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); } catch (NumberFormatException e) { JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); } catch (OnlineExperimentException e) { log.error("No reservation for " + reservationId + ":" + e.getMessage()); JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error-not-reservations")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); } catch (ExperimentNotInstantiatedException e) { JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error-not-instantiated")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); log.error("No reservation for " + reservationId + ":" + e.getMessage()); } catch (NoSuchReservationException e) { JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error-current-reservation")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); } catch (ConnectionException e) { JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); } catch (ExperimentOperationException e) { JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); } catch (NoSuchOperationException e) { JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); } catch (ExperimentParameterException e) { JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); } catch (NoSuchExperimentException e) { JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); } }
From source file:de.cebitec.guava.dockertest.Docker.java
public int run() throws Exception { if (repo.equals("")) { throw new Exception("No container defined."); }/* w w w .j a v a 2 s.com*/ if (!isImageAvailable(repo)) { pullImage(repo); } String[] command = cmd.toArray(new String[cmd.size()]); ContainerCreateResponse containerResp = dockerClient.createContainerCmd(repo).withCmd(command).exec(); if (binds.isEmpty()) { dockerClient.startContainerCmd(containerResp.getId()).exec(); } else { dockerClient.startContainerCmd(containerResp.getId()).withBinds(binds.toArray(new Bind[binds.size()])) .exec(); } int exit = dockerClient.waitContainerCmd(containerResp.getId()).exec(); if (exit != 0) { ClientResponse resp = dockerClient.logContainerCmd(containerResp.getId()).withStdErr().exec(); LineIterator itr = IOUtils.lineIterator(resp.getEntityInputStream(), "US-ASCII"); while (itr.hasNext()) { String line = itr.next(); //ugly hack because of java -docker bug System.out.println(line.replaceAll("[^\\x20-\\x7e]", "")); System.out.println(itr.hasNext() ? "\n" : ""); } throw new Exception("Command Exited with code " + exit); } if (!this.outputFile.isEmpty()) { new File(new File(this.outputFile).getParent()).mkdirs(); PrintWriter writer = new PrintWriter(this.outputFile, "UTF-8"); ClientResponse resp = dockerClient.logContainerCmd(containerResp.getId()).withStdOut().exec(); try { LineIterator itr = IOUtils.lineIterator(resp.getEntityInputStream(), "UTF-8"); while (itr.hasNext()) { String out = itr.next(); //ugly hack because of java -docker bug out = out.replaceAll("[\\p{Cc}&&[^\t]]", ""); writer.write(out); writer.write(itr.hasNext() ? "\n" : ""); } } finally { writer.close(); IOUtils.closeQuietly(resp.getEntityInputStream()); } } dockerClient.removeContainerCmd(containerResp.getId()).exec(); return exit; }
From source file:eu.gloriaproject.tools.userreservations.UserReservationController.java
/** * To get the current user's reservations (by AJAX) *//* www.ja va 2 s. c om*/ @ResourceMapping(value = "cancelReservation") public void cancelReservation(ResourceRequest request, ResourceResponse response) throws PortletException, IOException { ResourceBundle rb = ResourceBundle.getBundle("Language", request.getLocale()); String reservationId = request.getParameter("reservationId"); log.info("Cancelling reservationId = " + reservationId); // Get email and password of the current user ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); String emailUser = themeDisplay.getUser().getEmailAddress(); String passwordUser = themeDisplay.getUser().getPassword(); // Call to the Reservations Service try { reservationsService.cancelReservation(emailUser, passwordUser, Integer.parseInt(reservationId)); JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", true); jsonObject.put("message", rb.getString("msg-reservation-cancelled")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); } catch (NumberFormatException e) { log.error(rb.getString("msg-error-invalid-format")); JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error-invalid-format")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); return; } catch (OnlineExperimentException e) { log.error("OnlineExperimentError"); JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); return; } catch (NoSuchReservationException e) { JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); return; } catch (ConnectionException e) { JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); return; } catch (ExperimentOperationException e) { JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); return; } catch (NoSuchOperationException e) { JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); return; } catch (ExperimentParameterException e) { JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); return; } catch (ExperimentNotInstantiatedException e) { JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); return; } catch (NoSuchExperimentException e) { JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("success", false); jsonObject.put("message", rb.getString("msg-error")); PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); return; } }
From source file:com.tbodt.jswerve.maven.GenerateTemplatesMojo.java
/** * Executes the mojo./*w w w . j a v a 2 s . c o m*/ * * @throws MojoExecutionException if something really bad happens */ public void execute() throws MojoExecutionException { DirectoryScanner scanner = new DirectoryScanner(); scanner.addDefaultExcludes(); scanner.setBasedir(sourceDirectory); scanner.setIncludes(new String[] { "**/*.jtl" }); scanner.scan(); for (String templatePath : scanner.getIncludedFiles()) { File template = new File(sourceDirectory, templatePath); String templateClassName = StringUtils.removeEnd(templatePath, ".jtl").replace('.', '_') .replace(File.separatorChar, '.'); int lastDot = templateClassName.lastIndexOf('.'); String templatePackage = templateClassName.substring(0, lastDot); String templateName = templateClassName.substring(lastDot + 1); File outputFile = new File(outputDirectory, templateClassName.replace('.', File.separatorChar) + ".java"); Reader input = null; PrintWriter output = null; try { input = new FileReader(template); getLog().debug(String.valueOf(outputFile.getParentFile().mkdirs())); output = new PrintWriter(new FileWriter(outputFile)); output.println("package " + templatePackage + ";"); output.println(); output.println("public class " + templateName + " implements com.tbodt.jswerve.Template {"); output.println(" @Override"); output.println(" public String render() {"); output.write(Jtl.generateCode(input)); output.println(" }"); output.println("}"); } catch (IOException ioe) { throw new MojoExecutionException("IOException!", ioe); } finally { if (input != null) try { input.close(); } catch (IOException ex) { getLog().error(ex); // nothing else can be done } if (output != null) output.close(); } } // notify maven of the new output directory project.addCompileSourceRoot(outputDirectory.getPath()); }
From source file:edu.vt.vbi.patric.portlets.ExperimentListPortlet.java
@SuppressWarnings("unchecked") public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException, IOException { String sraction = request.getParameter("sraction"); if (sraction != null && sraction.equals("save_params")) { Map<String, String> key = new HashMap<>(); String genomeId = request.getParameter("genomeId"); String taxonId = ""; String cType = request.getParameter("context_type"); String cId = request.getParameter("context_id"); if (cType != null && cId != null && cType.equals("taxon") && !cId.equals("")) { taxonId = cId;// w ww . j a v a 2 s . c om } String keyword = request.getParameter("keyword"); String state = request.getParameter("state"); String ncbi_taxon_id = request.getParameter("ncbi_taxon_id"); if (genomeId != null && !genomeId.equalsIgnoreCase("")) { key.put("genomeId", genomeId); } if (!taxonId.equalsIgnoreCase("")) { key.put("taxonId", taxonId); } if (keyword != null) { key.put("keyword", keyword.trim()); } if (ncbi_taxon_id != null) { key.put("ncbi_taxon_id", ncbi_taxon_id); } if (state != null) { key.put("state", state); } long pk = (new Random()).nextLong(); SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key)); PrintWriter writer = response.getWriter(); writer.write("" + pk); writer.close(); } else { String need = request.getParameter("need"); JSONObject jsonResult = new JSONObject(); switch (need) { case "0": { // Experiments String pk = request.getParameter("pk"); Map data = processExperimentTab(request); Map<String, String> key = (Map) data.get("key"); int numFound = (Integer) data.get("numFound"); List<Map> experiments = (List<Map>) data.get("experiments"); JSONArray docs = new JSONArray(); for (Map item : experiments) { JSONObject doc = new JSONObject(); doc.putAll(item); docs.add(doc); } if (data.containsKey("facets")) { JSONObject facets = FacetHelper.formatFacetTree((Map) data.get("facets")); key.put("facets", facets.toJSONString()); SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key)); } jsonResult.put("results", docs); jsonResult.put("total", numFound); response.setContentType("application/json"); PrintWriter writer = response.getWriter(); writer.write(jsonResult.toString()); writer.close(); break; } case "1": { // Comparisons Map data = processComparisonTab(request); int numFound = (Integer) data.get("numFound"); List<Map> comparisons = (List<Map>) data.get("comparisons"); JSONArray docs = new JSONArray(); for (Map item : comparisons) { JSONObject doc = new JSONObject(); doc.putAll(item); docs.add(doc); } // key.put("keyword", orig_keyword); jsonResult.put("results", docs); jsonResult.put("total", numFound); response.setContentType("application/json"); PrintWriter writer = response.getWriter(); jsonResult.writeJSONString(writer); writer.close(); break; } case "tree": { String pk = request.getParameter("pk"); Map<String, String> key = jsonReader .readValue(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk)); String state; if (key.containsKey("state")) { state = key.get("state"); } else { state = request.getParameter("state"); } key.put("state", state); SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key)); JSONArray tree = new JSONArray(); try { if (key.containsKey("facets") && !key.get("facets").equals("{}")) { JSONObject facet_fields = (JSONObject) new JSONParser().parse(key.get("facets")); DataApiHandler dataApi = new DataApiHandler(request); tree = FacetHelper.processStateAndTree(dataApi, SolrCore.TRANSCRIPTOMICS_EXPERIMENT, key, need, facet_fields, key.get("facet"), state, null, 4); } } catch (ParseException e) { LOGGER.error(e.getMessage(), e); } response.setContentType("application/json"); PrintWriter writer = response.getWriter(); tree.writeJSONString(writer); writer.close(); break; } case "download": { List<String> tableHeader = new ArrayList<>(); List<String> tableField = new ArrayList<>(); JSONArray tableSource = new JSONArray(); String fileName = "Transcriptomics"; String fileFormat = request.getParameter("fileformat"); String aT = request.getParameter("aT"); switch (aT) { case "0": { // experiments Map data = processExperimentTab(request); List<Map> experiments = (List<Map>) data.get("experiments"); for (Map item : experiments) { JSONObject doc = new JSONObject(); doc.putAll(item); tableSource.add(doc); } tableHeader.addAll(DownloadHelper.getHeaderForTranscriptomicsExperiment()); tableField.addAll(DownloadHelper.getFieldsForTranscriptomicsExperiment()); break; } case "1": { // comparisons Map data = processComparisonTab(request); List<Map> comparisons = (List<Map>) data.get("comparisons"); for (Map item : comparisons) { JSONObject doc = new JSONObject(); doc.putAll(item); tableSource.add(doc); } tableHeader.addAll(DownloadHelper.getHeaderForTranscriptomicsComparison()); tableField.addAll(DownloadHelper.getFieldsForTranscriptomicsComparison()); break; } } ExcelHelper excel = new ExcelHelper("xssf", tableHeader, tableField, tableSource); excel.buildSpreadsheet(); if (fileFormat.equalsIgnoreCase("xlsx")) { response.setContentType("application/octetstream"); response.addProperty("Content-Disposition", "attachment; filename=\"" + fileName + "." + fileFormat + "\""); excel.writeSpreadsheettoBrowser(response.getPortletOutputStream()); } else if (fileFormat.equalsIgnoreCase("txt")) { response.setContentType("application/octetstream"); response.addProperty("Content-Disposition", "attachment; filename=\"" + fileName + "." + fileFormat + "\""); response.getPortletOutputStream().write(excel.writeToTextFile().getBytes()); } break; } } } }
From source file:eu.comvantage.dataintegration.SparulSimulationServlet.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) *//*from ww w . j a v a2 s . c o m*/ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String eventID = ""; if (request.getParameterMap().containsKey("eventID")) eventID = request.getParameter("eventID"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); String uri = request.getRequestURI(); ServletContext context = getServletContext(); String serverName = ""; if (request.getLocalName().startsWith("0")) { serverName = "localhost"; } else { serverName = request.getLocalName(); } simulateEvent(eventID, new String("http://" + serverName + ":" + request.getLocalPort() + request.getContextPath() + "/QueryDistributionServiceImpl/SPARUL")); out.write("'" + eventID + "' simulated. "); }
From source file:eu.stratosphere.nephele.jobmanager.web.JobmanagerInfoServlet.java
/** * Writes infos about archived job in Json format, including groupvertices and groupverticetimes * /* ww w.j a v a 2 s. c o m*/ * @param wrt * @param jobEvent */ private void writeJsonForArchivedJob(PrintWriter wrt, RecentJobEvent jobEvent) { try { wrt.write("["); ManagementGraph jobManagementGraph = jobmanager.getManagementGraph(jobEvent.getJobID()); //Serialize job to json wrt.write("{"); wrt.write("\"jobid\": \"" + jobEvent.getJobID() + "\","); wrt.write("\"jobname\": \"" + jobEvent.getJobName() + "\","); wrt.write("\"status\": \"" + jobEvent.getJobStatus() + "\","); wrt.write("\"SCHEDULED\": " + jobmanager.getArchive().getJobTime(jobEvent.getJobID(), JobStatus.SCHEDULED) + ","); wrt.write("\"RUNNING\": " + jobmanager.getArchive().getJobTime(jobEvent.getJobID(), JobStatus.RUNNING) + ","); wrt.write("\"FINISHED\": " + jobmanager.getArchive().getJobTime(jobEvent.getJobID(), JobStatus.FINISHED) + ","); wrt.write("\"FAILED\": " + jobmanager.getArchive().getJobTime(jobEvent.getJobID(), JobStatus.FAILED) + ","); wrt.write("\"CANCELED\": " + jobmanager.getArchive().getJobTime(jobEvent.getJobID(), JobStatus.CANCELED) + ","); wrt.write("\"CREATED\": " + jobmanager.getArchive().getJobTime(jobEvent.getJobID(), JobStatus.CREATED) + ","); if (jobEvent.getJobStatus() == JobStatus.FAILED) { ManagementGraphIterator managementGraphIterator = new ManagementGraphIterator(jobManagementGraph, true); wrt.write("\"failednodes\": ["); HashSet<String> map = new HashSet<String>(); boolean first = true; while (managementGraphIterator.hasNext()) { ManagementVertex managementVertex = managementGraphIterator.next(); String instanceName = managementVertex.getInstanceName(); if (managementVertex.getExecutionState() == ExecutionState.FAILED && !map.contains(instanceName)) { if (first) { first = false; } else { wrt.write(","); } wrt.write("{"); wrt.write("\"node\": \"" + instanceName + "\","); wrt.write("\"message\": \"" + StringUtils.escapeHtml(managementVertex.getOptMessage()) + "\""); wrt.write("}"); map.add(instanceName); } } wrt.write("],"); } // Serialize ManagementGraph to json wrt.write("\"groupvertices\": ["); boolean first = true; for (ManagementGroupVertex groupVertex : jobManagementGraph.getGroupVerticesInTopologicalOrder()) { //Write seperator between json objects if (first) { first = false; } else { wrt.write(","); } wrt.write(groupVertex.toJson()); } wrt.write("],"); // write accumulators AccumulatorEvent accumulators = jobmanager.getAccumulatorResults(jobEvent.getJobID()); Map<String, Object> accMap = AccumulatorHelper.toResultMap(accumulators.getAccumulators()); wrt.write("\n\"accumulators\": ["); int i = 0; for (Entry<String, Object> accumulator : accMap.entrySet()) { wrt.write( "{ \"name\": \"" + accumulator.getKey() + " (" + accumulator.getValue().getClass().getName() + ")\"," + " \"value\": \"" + accumulator.getValue().toString() + "\"}\n"); if (++i < accMap.size()) { wrt.write(","); } } wrt.write("],\n"); wrt.write("\"groupverticetimes\": {"); first = true; for (ManagementGroupVertex groupVertex : jobManagementGraph.getGroupVerticesInTopologicalOrder()) { if (first) { first = false; } else { wrt.write(","); } // Calculate start and end time for groupvertex long started = Long.MAX_VALUE; long ended = 0; // Take earliest running state and latest endstate of groupmembers for (int j = 0; j < groupVertex.getNumberOfGroupMembers(); j++) { ManagementVertex vertex = groupVertex.getGroupMember(j); long running = jobmanager.getArchive().getVertexTime(jobEvent.getJobID(), vertex.getID(), ExecutionState.RUNNING); if (running != 0 && running < started) { started = running; } long finished = jobmanager.getArchive().getVertexTime(jobEvent.getJobID(), vertex.getID(), ExecutionState.FINISHED); long canceled = jobmanager.getArchive().getVertexTime(jobEvent.getJobID(), vertex.getID(), ExecutionState.CANCELED); long failed = jobmanager.getArchive().getVertexTime(jobEvent.getJobID(), vertex.getID(), ExecutionState.FAILED); if (finished != 0 && finished > ended) { ended = finished; } if (canceled != 0 && canceled > ended) { ended = canceled; } if (failed != 0 && failed > ended) { ended = failed; } } wrt.write("\"" + groupVertex.getID() + "\": {"); wrt.write("\"groupvertexid\": \"" + groupVertex.getID() + "\","); wrt.write("\"groupvertexname\": \"" + groupVertex + "\","); wrt.write("\"STARTED\": " + started + ","); wrt.write("\"ENDED\": " + ended); wrt.write("}"); } wrt.write("}"); wrt.write("}"); wrt.write("]"); } catch (EofException eof) { // Connection closed by client LOG.info("Info server for jobmanager: Connection closed by client, EofException"); } catch (IOException ioe) { // Connection closed by client LOG.info("Info server for jobmanager: Connection closed by client, IOException"); } }
From source file:photosharing.api.conx.CommentsDefinition.java
/** * creates a new comment with a given library id and document id * //from www .j av a 2s. c om * @param bearer * the accesstoken used to make the request * @param pid * the document id * @param uid * the library id * @param body * the body of the comment * @param nonce * the nonce code * @param response * the http response that the results are sent to */ public void createComment(String bearer, String pid, String uid, String body, String nonce, HttpServletResponse response) { String apiUrl = getApiUrl() + "/library/" + uid + "/document/" + pid + "/feed"; logger.info(apiUrl); try { JSONObject obj = new JSONObject(body); String comment = generateComment(obj.getString("comment")); // Generate the Request post = Request.Post(apiUrl); post.addHeader("Authorization", "Bearer " + bearer); post.addHeader("X-Update-Nonce", nonce); post.addHeader("Content-Type", "application/atom+xml"); ByteArrayEntity entity = new ByteArrayEntity(comment.getBytes("UTF-8")); post.body(entity); Executor exec = ExecutorUtil.getExecutor(); Response apiResponse = exec.execute(post); HttpResponse hr = apiResponse.returnResponse(); /** * Check the status codes */ int code = hr.getStatusLine().getStatusCode(); // Process the Status Codes if (code == HttpStatus.SC_FORBIDDEN) { // Session is no longer valid or access token is expired response.setStatus(HttpStatus.SC_FORBIDDEN); } else if (code == HttpStatus.SC_UNAUTHORIZED) { // User is not authorized response.setStatus(HttpStatus.SC_UNAUTHORIZED); } else if (code == HttpStatus.SC_CREATED) { // Default to 201 response.setStatus(HttpStatus.SC_OK); InputStream in = hr.getEntity().getContent(); String jsonString = org.apache.wink.json4j.utils.XML.toJson(in); JSONObject base = new JSONObject(jsonString); JSONObject entry = base.getJSONObject("entry"); JSONObject author = entry.getJSONObject("author"); String name = author.getString("name"); String userid = author.getString("userid"); String date = entry.getString("modified"); String content = entry.getString("content"); String cid = entry.getString("uuid"); // Build the JSON object JSONObject commentJSON = new JSONObject(); commentJSON.put("uid", userid); commentJSON.put("author", name); commentJSON.put("date", date); commentJSON.put("content", content); commentJSON.put("cid", cid); // Flush the Object to the Stream with content type response.setHeader("Content-Type", "application/json"); PrintWriter out = response.getWriter(); out.write(commentJSON.toString()); out.flush(); out.close(); } } catch (IOException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("Issue with create comment " + e.toString()); } catch (JSONException e) { response.setHeader("X-Application-Error ", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("Issue with create comment " + e.toString()); e.printStackTrace(); } catch (SAXException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("Issue with create comment " + e.toString()); } }
From source file:com.aipo.container.protocol.AipoDataServiceServlet.java
/** * Handler for non-batch requests.//from www .j a v a 2s . co m */ protected void handleSingleRequest(HttpServletRequest servletRequest, HttpServletResponse servletResponse, SecurityToken token) throws IOException { // Always returns a non-null handler. RestHandler handler = getRestHandler(servletRequest); // Get Content-Type String contentType = null; try { // TODO: First implementation causes bug when Content-Type is // application/atom+xml. Fix is applied. contentType = ContentTypes.extractMimePart(servletRequest.getContentType()); } catch (Throwable t) { // this happens while testing if (LOG.isLoggable(Level.FINE)) { LOG.fine("Unexpected error : content type is null " + t.toString()); } } // Get BeanConverter for Request payload. BeanConverter requestConverter = getConverterForRequest(contentType, null); // Get BeanConverter for Response body. BeanConverter responseConverter = getConverterForFormat(null); // Execute the request Map<String, FormDataItem> formItems = Maps.newHashMap(); Map<String, String[]> parameterMap = loadParameters(servletRequest, formItems); Future<?> future = handler.execute(parameterMap, formItems, token, requestConverter); ResponseItem responseItem = getResponseItem(future); servletResponse.setContentType(responseConverter.getContentType()); if (responseItem.getErrorCode() >= 200 && responseItem.getErrorCode() < 400) { Object response = responseItem.getResponse(); if (response instanceof StreamContent) { InputStream is = null; OutputStream out = null; try { StreamContent content = (StreamContent) response; servletResponse.setContentType(content.getContentType()); if (content.getContentLength() != 0) { servletResponse.setContentLength(content.getContentLength()); } is = content.getInputStream(); out = servletResponse.getOutputStream(); int b; while ((b = is.read()) != -1) { out.write(b); } } finally { try { if (out != null) { out.close(); } } catch (IOException ignore) { // ignore } try { if (is != null) { is.close(); } } catch (IOException ignore) { // ignore } } return; } // TODO: ugliness resulting from not using RestfulItem if (!(response instanceof DataCollection) && !(response instanceof RestfulCollection)) { response = ImmutableMap.of("entry", response); } // JSONP style callbacks String callback = (HttpUtil.isJSONP(servletRequest) && ContentTypes.OUTPUT_JSON_CONTENT_TYPE.equals(responseConverter.getContentType())) ? servletRequest.getParameter("callback") : null; PrintWriter writer = servletResponse.getWriter(); if (callback != null) { writer.write(callback + '('); } writer.write(responseConverter.convertToString(response)); if (callback != null) { writer.write(");\n"); } } else { sendError(servletResponse, responseItem); } }
From source file:eu.stratosphere.nephele.jobmanager.web.JobmanagerInfoServlet.java
private void writeJsonForJob(PrintWriter wrt, RecentJobEvent jobEvent) throws IOException { ManagementGraph jobManagementGraph = jobmanager.getManagementGraph(jobEvent.getJobID()); //Serialize job to json wrt.write("{"); wrt.write("\"jobid\": \"" + jobEvent.getJobID() + "\","); wrt.write("\"jobname\": \"" + jobEvent.getJobName() + "\","); wrt.write("\"status\": \"" + jobEvent.getJobStatus() + "\","); wrt.write("\"time\": " + jobEvent.getTimestamp() + ","); // Serialize ManagementGraph to json wrt.write("\"groupvertices\": ["); boolean first = true; for (ManagementGroupVertex groupVertex : jobManagementGraph.getGroupVerticesInTopologicalOrder()) { //Write seperator between json objects if (first) { first = false;//from w w w .ja va2s.c o m } else { wrt.write(","); } wrt.write(groupVertex.toJson()); } wrt.write("]"); wrt.write("}"); }