List of usage examples for java.io PrintWriter append
public PrintWriter append(char c)
From source file:serposcope.controllers.google.GoogleGroupController.java
public Result jsonSearches(Context context) { List<GoogleSearch> searches = context.getAttribute("searches", List.class); if (searches.isEmpty()) { return Results.json().renderRaw("[]"); }/*from ww w . ja va 2s .c om*/ return Results.ok().json().render((Context context0, Result result) -> { PrintWriter writer = null; OutputStream os = null; try { String acceptEncoding = context0.getHeader("Accept-Encoding"); if (acceptEncoding != null && acceptEncoding.contains("gzip")) { result.addHeader("Content-Encoding", "gzip"); } ResponseStreams response = context0.finalizeHeaders(result); os = response.getOutputStream(); if (acceptEncoding != null && acceptEncoding.contains("gzip")) { os = new GZIPOutputStream(os); } writer = new PrintWriter(os); writer.append("["); for (int i = 0; i < searches.size(); i++) { GoogleSearch search = searches.get(i); writer.append("{"); writer.append("\"id\":").append(Integer.toString(search.getId())).append(","); writer.append("\"keyword\":\"").append(StringEscapeUtils.escapeJson(search.getKeyword())) .append("\","); writer.append("\"tld\":\"") .append(search.getTld() == null ? "" : StringEscapeUtils.escapeJson(search.getTld())) .append("\","); writer.append("\"device\":\"").append(SMARTPHONE.equals(search.getDevice()) ? 'M' : 'D') .append("\","); writer.append("\"local\":\"").append( search.getLocal() == null ? "" : StringEscapeUtils.escapeJson(search.getLocal())) .append("\","); writer.append("\"datacenter\":\"").append(search.getDatacenter() == null ? "" : StringEscapeUtils.escapeJson(search.getDatacenter())).append("\","); writer.append("\"custom\":\"").append(search.getCustomParameters() == null ? "" : StringEscapeUtils.escapeJson(search.getCustomParameters())).append("\""); writer.append("}"); if (i != searches.size() - 1) { writer.append(","); } } writer.append("]"); } catch (Exception ex) { LOG.warn("HTTP error", ex); } finally { if (os != null) { try { writer.close(); os.close(); } catch (Exception ex) { } } } }); }
From source file:org.commoncrawl.io.NIODNSCache.java
void dumpNode(PrintWriter printWriter, Node node, NodeDumpFilter filter) throws IOException { if (node.isTerminalNode()) { if (filter == null || filter.dumpTerminalNode(node)) { printWriter.append(node.getFullName()); printWriter.append(","); try { printWriter.append((IPAddressUtils.IntegerToInetAddress(node.getIPAddress()).toString())); } catch (UnknownHostException e) { LOG.error(StringUtils.stringifyException(e)); }//from w w w.ja va2s . c om printWriter.append(","); printWriter.append(Long.toString(node.getTimeToLive())); printWriter.append(","); if (node._cannonicalName != null) { printWriter.append(node._cannonicalName); } else { printWriter.append("null"); } printWriter.append(","); printWriter.append(Long.toString(node.getLastTouchedTime())); printWriter.append("\n"); } } for (int i = 0; i < node.getChildCount(); ++i) { dumpNode(printWriter, node.getChildAt(i), filter); } }
From source file:org.jbpm.designer.server.StencilSetJSONPServlet.java
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("application/json"); String resource = req.getParameter("resource"); String type = req.getParameter("type"); String jsonp = req.getParameter("jsonp"); String embedSvg = req.getParameter("embedsvg"); try {/*from www . j av a 2 s. com*/ PrintWriter out = res.getWriter(); // also allow to request stencil set extensions (specified by namespace) if (type != null && type.equals("ssextension")) { File extensionsFile = new File( getServletContext().getRealPath("/stencilsets/extensions/extensions.json")); BufferedReader reader = new BufferedReader(new FileReader(extensionsFile)); String line = null; String jsonString = ""; while ((line = reader.readLine()) != null) { jsonString += line; } JSONObject jsonObj = new JSONObject(jsonString); JSONArray extArr = jsonObj.getJSONArray("extensions"); for (int i = 0; i < extArr.length(); i++) { if (extArr.getJSONObject(i).getString("namespace").equals(resource)) { String definition = extArr.getJSONObject(i).getString("definition"); File jsonFile = new File( getServletContext().getRealPath("/stencilsets/extensions/" + definition)); if (jsonp != null) out.append(jsonp + "("); BufferedReader reader2 = new BufferedReader(new FileReader(jsonFile)); String line2 = null; while ((line2 = reader2.readLine()) != null) { out.append(line2); out.append(System.getProperty("line.separator")); } if (jsonp != null) out.append(");"); } } } else { // standard stencil set requested (specified by path) resource = resource.replace("..", ""); // don't allow to leave stencilset dir if (resource.startsWith("/")) resource = resource.substring(1); if (resource.startsWith("stencilsets/")) // ignore stencilset/ at beginning of path reference resource = resource.substring(12); File jsonFile; if (embedSvg != null && embedSvg.equals("true")) { // SVG embedding jsonFile = new File(getServletContext().getRealPath("/stencilsets/" + resource)); } else { // no SVG embedding (default) // try to find stencilset nosvg representation int pIdx = resource.lastIndexOf('.'); jsonFile = new File(getServletContext().getRealPath( "/stencilsets/" + resource.substring(0, pIdx) + "-nosvg" + resource.substring(pIdx))); if (!jsonFile.exists()) jsonFile = new File(getServletContext().getRealPath("/stencilsets/" + resource)); } if (!jsonFile.exists()) { if (jsonp != null) out.write(jsonp + "({ \"error\":\"resource not found\" })"); else out.write("{ \"error\":\"resource not found\" }"); } if (jsonp != null) out.append(jsonp + "("); BufferedReader reader = new BufferedReader(new FileReader(jsonFile)); String line = null; while ((line = reader.readLine()) != null) { out.append(line); out.append(System.getProperty("line.separator")); } if (jsonp != null) out.append(");"); } } catch (Exception e) { e.printStackTrace(); } }
From source file:serposcope.controllers.google.GoogleTargetController.java
public Result jsonVariation(Context context, @PathParam("targetId") Integer targetId, @Param("endDate") String endDateStr) { GoogleTarget target = getTarget(context, targetId); List<GoogleSearch> searches = context.getAttribute("searches", List.class); Group group = context.getAttribute("group", Group.class); final LocalDate endDate; try {/*w ww . j a va 2 s . c o m*/ endDate = LocalDate.parse(endDateStr); } catch (Exception ex) { return Results.json().renderRaw("[[],[],[]]"); } Run lastRun = baseDB.run.findLast(group.getModule(), RunDB.STATUSES_DONE, endDate); List<TargetVariation> ranksUp = new ArrayList<>(); List<TargetVariation> ranksDown = new ArrayList<>(); List<TargetVariation> ranksSame = new ArrayList<>(); Map<Integer, GoogleSearch> searchesById = searches.stream() .collect(Collectors.toMap(GoogleSearch::getId, Function.identity())); List<GoogleRank> ranks = googleDB.rank.list(lastRun.getId(), group.getId(), target.getId()); for (GoogleRank rank : ranks) { GoogleSearch search = searchesById.get(rank.googleSearchId); if (search == null) { continue; } if (rank.diff > 0) { ranksDown.add(new TargetVariation(search, rank)); } else if (rank.diff < 0) { ranksUp.add(new TargetVariation(search, rank)); } else { ranksSame.add(new TargetVariation(search, rank)); } } Collections.sort(ranksUp, (TargetVariation o1, TargetVariation o2) -> Integer.compare(o1.rank.diff, o2.rank.diff)); Collections.sort(ranksDown, (TargetVariation o1, TargetVariation o2) -> -Integer.compare(o1.rank.diff, o2.rank.diff)); Collections.sort(ranksSame, (TargetVariation o1, TargetVariation o2) -> Integer.compare(o1.rank.rank, o2.rank.rank)); return Results.ok().json().render((Context context0, Result result) -> { PrintWriter writer = null; OutputStream os = null; try { String acceptEncoding = context0.getHeader("Accept-Encoding"); if (acceptEncoding != null && acceptEncoding.contains("gzip")) { result.addHeader("Content-Encoding", "gzip"); } ResponseStreams response = context0.finalizeHeaders(result); os = response.getOutputStream(); if (acceptEncoding != null && acceptEncoding.contains("gzip")) { os = new GZIPOutputStream(os); } writer = new PrintWriter(os); writer.append("["); int id = 0; writer.append("["); for (int i = 0; i < ranksUp.size(); i++) { TargetVariation var = ranksUp.get(i); writer.append("{").append("\"id\":").append(Integer.toString(id++)).append(",\"search\":") .append(searchToJson(var.search)).append(",\"now\":") .append(Integer.toString(var.rank.rank)).append(",\"prv\":") .append(Integer.toString(var.rank.previousRank)).append(",\"diff\":") .append(Integer.toString(var.rank.diff)).append("}"); if (i != ranksUp.size() - 1) { writer.append(','); } } writer.append("],["); for (int i = 0; i < ranksDown.size(); i++) { TargetVariation var = ranksDown.get(i); writer.append("{").append("\"id\":").append(Integer.toString(id++)).append(",\"search\":") .append(searchToJson(var.search)).append(",\"now\":") .append(Integer.toString(var.rank.rank)).append(",\"prv\":") .append(Integer.toString(var.rank.previousRank)).append(",\"diff\":") .append(Integer.toString(var.rank.diff)).append("}"); if (i != ranksDown.size() - 1) { writer.append(','); } } writer.append("],["); for (int i = 0; i < ranksSame.size(); i++) { TargetVariation var = ranksSame.get(i); writer.append("{").append("\"id\":").append(Integer.toString(id++)).append(",\"search\":") .append(searchToJson(var.search)).append(",\"now\":") .append(Integer.toString(var.rank.rank)).append("}"); if (i != ranksSame.size() - 1) { writer.append(','); } } writer.append("]]"); } catch (Exception ex) { LOG.warn("HTTP error", ex); } finally { if (os != null) { try { writer.close(); os.close(); } catch (Exception ex) { } } } }); }
From source file:org.openhealthtools.mdht.uml.cda.core.util.CDAModelUtil.java
private static void appendPropertyComments(PrintWriter writer, Property property, boolean markup) { if (markup) { } else {/*from w w w . j a v a 2s. c o m*/ } // INLINE Association association = property.getAssociation(); if (association != null && association.getOwnedComments().size() > 0) { if (markup) { writer.append("<p><lines><i>"); } for (Comment comment : association.getOwnedComments()) { writer.append(CDAModelUtil.fixNonXMLCharacters(comment.getBody())); } if (markup) { writer.append("</i></lines></p>"); } } if (property.getOwnedComments().size() > 0) { if (markup) { writer.append("<p><lines><i>"); } for (Comment comment : property.getOwnedComments()) { writer.append(CDAModelUtil.fixNonXMLCharacters(comment.getBody())); } if (markup) { writer.append("</i></lines></p>"); } } }
From source file:org.exoplatform.shareextension.service.UploadAction.java
@Override protected boolean doExecute() { String id = uploadInfo.uploadId; String boundary = "----------------------------" + id; String CRLF = "\r\n"; int status = -1; OutputStream output = null;// w w w . j a v a 2 s . co m PrintWriter writer = null; try { // Open a connection to the upload web service StringBuffer stringUrl = new StringBuffer(postInfo.ownerAccount.serverUrl).append("/portal") .append(ExoConstants.DOCUMENT_UPLOAD_PATH_REST).append("?uploadId=").append(id); URL uploadUrl = new URL(stringUrl.toString()); HttpURLConnection uploadReq = (HttpURLConnection) uploadUrl.openConnection(); uploadReq.setDoOutput(true); uploadReq.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); // Pass the session cookies for authentication CookieStore store = ExoConnectionUtils.cookiesStore; if (store != null) { StringBuffer cookieString = new StringBuffer(); for (Cookie cookie : store.getCookies()) { cookieString.append(cookie.getName()).append("=").append(cookie.getValue()).append("; "); } uploadReq.addRequestProperty("Cookie", cookieString.toString()); } ExoConnectionUtils.setUserAgent(uploadReq); // Write the form data output = uploadReq.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true); writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + uploadInfo.fileToUpload.documentName + "\"").append(CRLF); writer.append("Content-Type: " + uploadInfo.fileToUpload.documentMimeType).append(CRLF); writer.append(CRLF).flush(); byte[] buf = new byte[1024]; while (uploadInfo.fileToUpload.documentData.read(buf) != -1) { output.write(buf); } output.flush(); writer.append(CRLF).flush(); writer.append("--" + boundary + "--").append(CRLF).flush(); // Execute the connection and retrieve the status code status = uploadReq.getResponseCode(); } catch (Exception e) { Log.e(LOG_TAG, "Error while uploading " + uploadInfo.fileToUpload, e); } finally { if (uploadInfo != null && uploadInfo.fileToUpload != null && uploadInfo.fileToUpload.documentData != null) try { uploadInfo.fileToUpload.documentData.close(); } catch (IOException e1) { Log.e(LOG_TAG, "Error while closing the upload stream", e1); } if (output != null) try { output.close(); } catch (IOException e) { Log.e(LOG_TAG, "Error while closing the connection", e); } if (writer != null) writer.close(); } if (status < HttpURLConnection.HTTP_OK || status >= HttpURLConnection.HTTP_MULT_CHOICE) { // Exit if the upload went wrong return listener.onError("Could not upload the file " + uploadInfo.fileToUpload.documentName); } status = -1; try { // Prepare the request to save the file in JCR String stringUrl = postInfo.ownerAccount.serverUrl + "/portal" + ExoConstants.DOCUMENT_CONTROL_PATH_REST; Uri moveUri = Uri.parse(stringUrl); moveUri = moveUri.buildUpon().appendQueryParameter("uploadId", id) .appendQueryParameter("action", "save") .appendQueryParameter("workspaceName", DocumentHelper.getInstance().workspace) .appendQueryParameter("driveName", uploadInfo.drive) .appendQueryParameter("currentFolder", uploadInfo.folder) .appendQueryParameter("fileName", uploadInfo.fileToUpload.documentName).build(); HttpGet moveReq = new HttpGet(moveUri.toString()); // Execute the request and retrieve the status code HttpResponse move = ExoConnectionUtils.httpClient.execute(moveReq); status = move.getStatusLine().getStatusCode(); } catch (Exception e) { Log.e(LOG_TAG, "Error while saving " + uploadInfo.fileToUpload + " in JCR", e); } boolean ret = false; if (status >= HttpStatus.SC_OK && status < HttpStatus.SC_MULTIPLE_CHOICES) { ret = listener.onSuccess("File " + uploadInfo.fileToUpload.documentName + "uploaded successfully"); } else { ret = listener.onError("Could not save the file " + uploadInfo.fileToUpload.documentName); } return ret; }
From source file:sos.Sos.java
/**provides sensor metadata in SensorML. The sensor description can contain information about the sensor in general, * the identifier and classification,position and observed phenomena, but also details such as calibration data. * /*from ww w . j a va 2 s. c o m*/ * @param request Http Servlet Request * @param response Http Servlet Response * @param out PrintWriter for Http Servlet Response * @param snannySostServerConfig the sos server configuration * @throws SnannySostServerException (I/O or conversion problem) */ private void describeSensor(HttpServletRequest request, HttpServletResponse response, PrintWriter out, SnannySostServerConfig snannySostServerConfig) throws SnannySostServerException { String uuid = getSosProcedureUuid(request); SOSFORMAT sosresponseformat = getResponseFormatParameter(request); if (snannySostServerConfig.isCouchbase()) { try { JsonDocument jsonDocument = CouchbaseManager.getSystemBucket().get(uuid); if (jsonDocument == null) { throw new SnannySostServerException(SnannySostServerMessages.ERROR_NO_UUID_RECORD_1of2 + uuid + SnannySostServerMessages.ERROR_NO_UUID_RECORD_2of2, Status.NOT_FOUND); } response.setContentType(SosFormat.getContentType(sosresponseformat)); switch (sosresponseformat) { case JSON: if (snannySostServerConfig.isJsonObject()) { out.append(new JsonTranscoder().jsonObjectToString( jsonDocument.content().getObject(SnannySostServerConfig.FilejsonField))); } else { out.append(new JsonArrayTranscoder().jsonArrayToString( jsonDocument.content().getArray(SnannySostServerConfig.FilejsonField))); } break; case XML: if (snannySostServerConfig.isJsonObject()) { JSONObject jSONObject = new JSONObject( StringEscapeUtils.unescapeXml(new JsonTranscoder().jsonObjectToString( jsonDocument.content().getObject(SnannySostServerConfig.FilejsonField)))); out.append(JSONML.toString(jSONObject)); } else { JSONArray jsonArray = new JSONArray( StringEscapeUtils.unescapeXml(new JsonArrayTranscoder().jsonArrayToString( jsonDocument.content().getArray(SnannySostServerConfig.FilejsonField)))); out.append(JSONML.toString(jsonArray)); } break; } } catch (Exception ex) { throw new SnannySostServerException( SnannySostServerMessages.ERROR_COUCHBASE_ERROR + ex.getMessage(), Status.SERVICE_UNAVAILABLE); } } else { File uuidFile = snannySostServerConfig.getSensorMlFile(uuid); try { byte[] encoded = Files.readAllBytes(Paths.get(uuidFile.toURI())); String uuidFileContent = new String(encoded, snannySostServerConfig.getCharset()); response.setContentType(SosFormat.getContentType(sosresponseformat)); switch (sosresponseformat) { case JSON: if (snannySostServerConfig.isJsonObject()) { JSONObject jSONObject = JSONML.toJSONObject(uuidFileContent); out.append(jSONObject.toString()); } else { JSONArray jsonArray = JSONML.toJSONArray(uuidFileContent); out.append(jsonArray.toString()); } break; case XML: out.append(uuidFileContent); break; } } catch (IOException io) { throw new SnannySostServerException(SnannySostServerMessages.ERROR_describeSensor, Status.SERVICE_UNAVAILABLE); } catch (JSONException je) { throw new SnannySostServerException( SnannySostServerMessages.ERROR_XML_JSON_CONVERSION + je.getMessage(), Status.SERVICE_UNAVAILABLE); } } }
From source file:sos.Sos.java
/**allows to query a specific observation using an identifier returned by the service as response to an InsertObservation operation. * /* www. ja v a 2s .c o m*/ * @param request Http Servlet Request * @param response Http Servlet Response * @param out PrintWriter for Http Servlet Response * @param snannySostServerConfig the sos server configuration * @throws SnannySostServerException */ private void getObservationById(HttpServletRequest request, HttpServletResponse response, PrintWriter out, SnannySostServerConfig snannySostServerConfig) throws SnannySostServerException { String uuid = getSosObservationUuid(request); SOSFORMAT sosresponseformat = getResponseFormatParameter(request); if (snannySostServerConfig.isCouchbase()) { try { JsonDocument jsonDocument = CouchbaseManager.getObservationBucket().get(uuid); if (jsonDocument == null) { throw new SnannySostServerException(SnannySostServerMessages.ERROR_NO_UUID_RECORD_1of2 + uuid + SnannySostServerMessages.ERROR_NO_UUID_RECORD_2of2, Status.NOT_FOUND); } response.setContentType(SosFormat.getContentType(sosresponseformat)); switch (sosresponseformat) { case JSON: if (snannySostServerConfig.isJsonObject()) { out.append(new JsonTranscoder().jsonObjectToString( jsonDocument.content().getObject(SnannySostServerConfig.FilejsonField))); } else { out.append(new JsonArrayTranscoder().jsonArrayToString( jsonDocument.content().getArray(SnannySostServerConfig.FilejsonField))); } break; case XML: if (snannySostServerConfig.isJsonObject()) { JSONObject jSONObject = new JSONObject( StringEscapeUtils.unescapeXml(new JsonTranscoder().jsonObjectToString( jsonDocument.content().getObject(SnannySostServerConfig.FilejsonField)))); out.append(JSONML.toString(jSONObject)); } else { JSONArray jsonArray = new JSONArray( StringEscapeUtils.unescapeXml(new JsonArrayTranscoder().jsonArrayToString( jsonDocument.content().getArray(SnannySostServerConfig.FilejsonField)))); out.append(JSONML.toString(jsonArray)); } break; } } catch (Exception ex) { throw new SnannySostServerException( SnannySostServerMessages.ERROR_COUCHBASE_ERROR + ex.getMessage(), Status.SERVICE_UNAVAILABLE); } } else { File uuidFile = SnannySostServerConfig.singleton(request.getServletContext()).getOemFile(uuid); try { byte[] encoded = Files.readAllBytes(Paths.get(uuidFile.toURI())); String uuidFileContent = new String(encoded, snannySostServerConfig.getCharset()); response.setContentType(SosFormat.getContentType(sosresponseformat)); switch (sosresponseformat) { case JSON: if (snannySostServerConfig.isJsonObject()) { JSONObject jsonObject = JSONML.toJSONObject(uuidFileContent); out.append(jsonObject.toString()); } else { JSONArray jsonArray = JSONML.toJSONArray(uuidFileContent); out.append(jsonArray.toString()); } break; case XML: out.append(uuidFileContent); break; } } catch (Exception ex) { throw new SnannySostServerException(SnannySostServerMessages.ERROR_describeSensor, Status.SERVICE_UNAVAILABLE); } } }
From source file:com.ifeng.computing.service.impl.DataFactoryServiceTest.java
@Test public void buildPushDataWithNormal() { File file = null;/*from w w w .j a v a2 s . co m*/ PrintWriter pw = null; try { file = new File("F:/HUGE_FILE_NORMAL.txt"); pw = new PrintWriter(file); int start = 0; List<NewsItem> newsList = new ArrayList<NewsItem>(); List<LogData> logList = new ArrayList<LogData>(); Map<String, Object> map = new HashMap<String, Object>(); map.put("limit", LIMIT_SIZE); int steps = (MAX_USER_SIZE % LIMIT_SIZE == 0) ? (MAX_USER_SIZE / LIMIT_SIZE) : (MAX_USER_SIZE / LIMIT_SIZE + 1); Map<String, Object> newsMap = new HashMap<String, Object>(); newsMap.put("start", 0); newsMap.put("limit", NEWS_ITEM_SIZE); ObjectMapper mapper = new ObjectMapper(); for (int i = 0; i < steps; i++) { start = i * LIMIT_SIZE; map.put("start", start); log.info("Step {} loading ... , Start index is [{}]", i, start); logList = dataFactoryService.readLogData(map); for (int j = 0, length = logList.size(); j < length; j++) { LogData data = logList.get(j); newsMap.put("pId", data.getpId()); newsList = dataFactoryService.readNewsByUserId(newsMap); data.setNewsItem(newsList); pw.append(mapper.writeValueAsString(data)); pw.println(); if (j % 50 == 0) pw.flush(); } } } catch (JsonGenerationException e) { log.error(e.getMessage(), e); } catch (JsonMappingException e) { log.error(e.getMessage(), e); } catch (FileNotFoundException e) { log.error(e.getMessage(), e); } catch (IOException e) { log.error(e.getMessage(), e); } finally { if (pw != null) { pw.flush(); pw.close(); } } }
From source file:org.lockss.servlet.DisplayContentStatus.java
private void doXmlStatusTable() throws Exception { // By default, XmlDomBuilder will produce UTF-8. Must set content type // *before* calling getWriter() resp.setContentType("text/xml; charset=UTF-8"); PrintWriter wrtr = resp.getWriter(); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); org.w3c.dom.Element rootElement = doc.createElement("root"); doc.appendChild(rootElement);//from w w w. j a va2 s . c o m org.w3c.dom.Element notImplemented = doc.createElement("notImplemented"); rootElement.appendChild(notImplemented); TransformerFactory transformerFactory = TransformerFactory.newInstance(); javax.xml.transform.Transformer transformer = transformerFactory.newTransformer(); DOMSource domSource = new DOMSource(doc); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); transformer.transform(domSource, streamResult); wrtr.append(stringWriter.toString()); }