List of usage examples for java.io StringWriter close
public void close() throws IOException
From source file:ubc.pavlab.aspiredb.server.util.JSONUtil.java
/** * Converts a collection of objects to a json string * /*from w w w . j a va 2 s. c o m*/ * @param collection * @return * @throws JSONException */ public String collectionToJson(Collection<?> collection) throws JSONException { StringWriter jsonText = new StringWriter(); jsonText.write("["); try { Iterator<?> it = collection.iterator(); while (it.hasNext()) { Object obj = it.next(); String delim = it.hasNext() ? "," : ""; jsonText.append(new JSONObject(obj).toString() + delim); } jsonText.append("]"); jsonText.flush(); } catch (Exception e) { log.error(e.getLocalizedMessage(), e); JSONObject json = new JSONObject(); json.put("success", false); json.put("message", e.getLocalizedMessage()); jsonText.write(json.toString()); log.info(jsonText); } try { jsonText.close(); } catch (Exception e) { log.error(e.getLocalizedMessage(), e); JSONObject json = new JSONObject(); json.put("success", false); json.put("message", e.getLocalizedMessage()); jsonText.write(json.toString()); log.info(jsonText); } return jsonText.toString(); }
From source file:com.webtide.jetty.load.generator.jenkins.LoadGeneratorBuilder.java
protected ArgumentListBuilder getArgsProcess(Resource resource, Computer computer, TaskListener taskListener, Run<?, ?> run, String statsResultFilePath) throws Exception { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); StringWriter stringWriter = new StringWriter(); objectMapper.writeValue(stringWriter, resource); stringWriter.close(); final String tmpFilePath = getCurrentNode(computer) // .getChannel().call(new CopyResource(stringWriter.toString())); ArgumentListBuilder cmdLine = new ArgumentListBuilder(); cmdLine.add("--resource-json-path").add(tmpFilePath) // .add("--host").add(expandTokens(taskListener, host, run)) // .add("--port").add(expandTokens(taskListener, port, run)) // .add("--transport").add(StringUtils.lowerCase(this.getTransport().toString())) // .add("--users").add(expandTokens(taskListener, users, run)) // .add("--resource-rate").add(expandTokens(taskListener, resourceRate, run)) // .add("--stats-file").add(statsResultFilePath) // .add("--threads").add(threadsNumber < 1 ? 1 : threadsNumber) // .add("--scheme").add(isSecureProtocol() ? "https" : "http"); int iterationRuns = NumberUtils.toInt(expandTokens(taskListener, runIteration, run), 0); if (iterationRuns > 0) { cmdLine.add("--iterations").add(Integer.toString(iterationRuns)); } else {//from w ww. j a v a 2 s. c o m cmdLine.add("--running-time").add(expandTokens(taskListener, runningTime, run)); cmdLine.add("--running-time-unit"); switch (this.runningTimeUnit) { case HOURS: cmdLine.add("h"); break; case MINUTES: cmdLine.add("m"); break; case SECONDS: cmdLine.add("s"); break; case MILLISECONDS: cmdLine.add("ms"); break; default: throw new IllegalArgumentException(runningTimeUnit + " is not recognized"); } } int warmupNumber = StringUtils.isNotEmpty(getWarmupNumber()) ? // Integer.parseInt(expandTokens(taskListener, this.getWarmupNumber(), run)) : -1; if (warmupNumber > 0) { cmdLine.add("--warmup-iterations").add(warmupNumber); } // FIXME deleting tmp file // getCurrentNode().getChannel().call( new DeleteTmpFile( tmpFilePath ) ); LOGGER.debug("finish"); LOGGER.info("load generator starter args:" + cmdLine.toString()); return cmdLine; }
From source file:translate.TRanslate.java
public void post(String input) throws IOException { String response = ""; BufferedReader br = null;//from w w w. java2 s. c o m br = new BufferedReader(new FileReader("c:\\test.txt")); while ((input = br.readLine()) != null) { String body = "text=" + input + "&itc=te-t-i0-und&num=13"; input = input.replace(" ", "+"); input = input.replace(" ", "+"); input = input.replace(",", "+"); String starting = "\",[\""; String ending = "\"],[],{\""; PostMethod Postmethod = new PostMethod("https://inputtools.google.com/request"); Postmethod.addRequestHeader("Host", " inputtools.google.com"); Postmethod.addRequestHeader("User-Agent", " Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36"); Postmethod.addRequestHeader("Accept", "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,*/*;q=0.5"); Postmethod.addRequestHeader("Accept-Language", "en-US,en;q=0.8"); Postmethod.addRequestHeader("Accept-Encoding", "gzip,deflate,sdch"); Postmethod.addRequestHeader("X-Client-Data", "CKK2yQEIxLbJAQj9lcoB"); Postmethod.addRequestHeader("Connection", "keepalive,Keep-Alive"); Postmethod.addRequestHeader("Referer", "http://www.google.com/intl/te/inputtools/try/"); Postmethod.addRequestHeader("Cookie", " GMAIL_RTT=732; HSID=AGUw587xCPSUIaDxj; SSID=AkkKuZaUGVqvz06y7; APISID=Ih-jSJ5j_auXMle3/A8M2u_3miTXEymzjb; SAPISID=ejtl9SxGbj105_1t/Ak0S2KFfQxDfzHxmH; SID=DQAAADcCAAA267hpyJDVmhZXfBKMci856rC5Bt20M4X52m9JnFgK_cqo-_tIsepRyfGNIxjXd5KnchoxbIojLNAegGge80QA3iIH7l6RgYRCFC0NUHGNwTge61j3ATgH7WopBDw_V7PDCSXDV82TzvuXc7s0_ryI7UyWCW9pVANyqNqcBPmFGZbFD4ES2s6VOYs6MW9rVsQyKxTgTnJjv9b0P6cUMvpwr1J-HBGX2mMFqup3wsylJ9Rp1sECSd_bdjunrLKoqcumaV_3XBayFBcn4BZhSYOj3PvA5om7YTL7zWXfYQZfC_i35gZ5VKnGVlSU-mfwZ1TJdztdkQWVAj4r6c2D2gBm6ZKl6P4WtZ9tt3UMq2F0Efh1I1tYGKEW-PCb7zSJI2zupoc63k5VNB4qI8eL-3OzAZoR9BitHnRRe2IKkXdpdaW8dUim-18qqaOeLjQYzFmBGAqxNw8cFEGtyuiUyZGZ6xKVHNAAoW1nFb4E9NGoJtlBo0nYf0kL4tg68g-kOc9GK5WD28pKQbHuFvlgieSRsvX1R3FftEZs-FMTU-KEZgniOssOeXLD7Qupnh37KbXRysPpkgNf72JdaIodIALUoM4k-6mHgUU-r0uLXNWYigGhvt72qVcuSH6uBHuoOUSee838n_k0E8-vg6bpPis_dg5A30Aq2wLGtFS5Q72Qw3hflukKGHvL64wW2vEvUZq3xtMS685Yx1_ZN72A8-YbB8lHEARnTLrm9ticp1q4X2Zsiz-wMtrq6qU4pRALEKE; OGP=-5061574:; OGPC=5061940-3:5061952-24:5061574-2:5061975-17:; NID=77=S4GVPPNrqG49rmLeZbOwlcNB_PTo1_UNBiv6k2q3RV1O_RY14vKc25tuRyt2IhIvd3ntYrgMgb1WpPUeonBk3CMik5PuqeEYUkjOH6C0Sdg2Xgbl_DxAja0Z0o-gJBolOvyKBMo1YM8MYDVSBJl4dPVRxVvTyg68tGAUmP6Ic6EwDk25g5nA6DMH8nhiyQOT7cG3Zz1Irt2GRhMvqo6jYugcIUTNnogFDBY2Cy-hw9MbLvM8PX1_KRWhwvgKpnR4SwwcqMhQXDYUAPeYjlRGJysIBsS1E0OIPw8xhcKOAGLmN7Jyuwa9FZsHZlEPBXY; S=grandcentral=bhpk116omdw5GfDWh1bWOQ:billing-ui-v3=-hfCJx7YhccZsFolsRi1KA:billing-ui-v3-efe=-hfCJx7YhccZsFolsRi1KA"); Postmethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded"); Postmethod.setRequestBody(body); Postmethod.addRequestHeader("Content-Length", "" + body.length()); Postmethod.getFollowRedirects(); try { HttpClient client = new HttpClient(); client.executeMethod(Postmethod); Reader reader = null; StringWriter writer = null; String charset = "UTF-8"; // You should determine it based on response header. try { InputStream ungzippedResponse = null; ungzippedResponse = new GZIPInputStream(Postmethod.getResponseBodyAsStream()); reader = new InputStreamReader(ungzippedResponse, charset); writer = new StringWriter(); char[] buffer = new char[10240]; for (int length = 0; (length = reader.read(buffer)) > 0;) { writer.write(buffer, 0, length); } writer.close(); reader.close(); response = writer.toString(); } catch (Exception ex) { ex.printStackTrace(); } int pos = 0; int n1 = 0; int n2 = 0; while (n1 >= 0) { n1 = response.indexOf(starting, n2); n2 = response.indexOf(ending, n1); if (n1 > 0 && n2 > 0) System.out.println(response.substring(n1 + starting.length(), n2)); } } catch (Exception m) { m.printStackTrace(); } } }
From source file:de.tu_dortmund.ub.data.dswarm.Init.java
/** * uploads a file and creates a data resource with it * * @param filename//from w w w. jav a 2 s .co m * @param name * @param description * @return responseJson * @throws Exception */ private String uploadFileAndCreateResource(final String filename, final String name, final String description, final String serviceName, final String engineDswarmAPI) throws Exception { try (final CloseableHttpClient httpclient = HttpClients.createDefault()) { final HttpPost httpPost = new HttpPost(engineDswarmAPI + DswarmBackendStatics.RESOURCES_ENDPOINT); final File file1 = new File(filename); final FileBody fileBody = new FileBody(file1); final StringBody stringBodyForName = new StringBody(name, ContentType.TEXT_PLAIN); final StringBody stringBodyForDescription = new StringBody(description, ContentType.TEXT_PLAIN); final HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart(DswarmBackendStatics.NAME_IDENTIFIER, stringBodyForName) .addPart(DswarmBackendStatics.DESCRIPTION_IDENTIFIER, stringBodyForDescription) .addPart(FILE_IDENTIFIER, fileBody).build(); httpPost.setEntity(reqEntity); LOG.info(String.format("[%s][%d] request : %s", serviceName, cnt, httpPost.getRequestLine())); try (final CloseableHttpResponse httpResponse = httpclient.execute(httpPost)) { final int statusCode = httpResponse.getStatusLine().getStatusCode(); final HttpEntity httpEntity = httpResponse.getEntity(); final String message = String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode, httpResponse.getStatusLine().getReasonPhrase()); switch (statusCode) { case 201: { LOG.info(message); final StringWriter writer = new StringWriter(); IOUtils.copy(httpEntity.getContent(), writer, APIStatics.UTF_8); final String responseJson = writer.toString(); writer.flush(); writer.close(); LOG.debug(String.format("[%s][%d] responseJson : %s", serviceName, cnt, responseJson)); return responseJson; } default: { LOG.error(message); EntityUtils.consume(httpEntity); throw new Exception("something went wrong at resource upload: " + message); } } } } }
From source file:de.xplib.xdbm.util.Config.java
/** * // w w w . ja va 2 s . c om */ public void save() { Document doc = null; try { doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element config = (Element) doc.appendChild(doc.createElementNS(CONFIG_NS, "config")); config.setAttribute("xmlns", CONFIG_NS); Element ui = (Element) config.appendChild(doc.createElementNS(CONFIG_NS, "ui-settings")); Node lang = ui.appendChild(doc.createElementNS(CONFIG_NS, "language")); lang.appendChild(doc.createTextNode(this.locale.getLanguage())); Element drivers = (Element) config.appendChild(doc.createElementNS(CONFIG_NS, "drivers")); Iterator dIt = this.dbDrivers.keySet().iterator(); while (dIt.hasNext()) { String jar = (String) dIt.next(); Element driver = (Element) drivers.appendChild(doc.createElementNS(CONFIG_NS, "driver")); driver.setAttribute("jar", jar); driver.setAttribute("class", (String) this.dbDrivers.get(jar)); if (!this.dbUris.containsKey(jar)) { continue; } String value = ""; ArrayList uris = (ArrayList) this.dbUris.get(jar); for (int i = 0, l = uris.size(); i < l; i++) { value += uris.get(i) + "||"; } value = value.substring(0, value.length() - 2); driver.setAttribute("uris", value); } Element conns = (Element) config.appendChild(doc.createElementNS(CONFIG_NS, "connections")); for (int i = 0, s = this.connections.size(); i < s; i++) { Connection conn = (Connection) this.connections.get(i); Element conne = (Element) conns.appendChild(doc.createElementNS(CONFIG_NS, "connection")); conne.setAttribute("jar", conn.getJarFile()); conne.setAttribute("class", conn.getClassName()); conne.setAttribute("uri", conn.getUri()); } Element panels = (Element) config.appendChild(doc.createElementNS(CONFIG_NS, "plugins")); Iterator it = this.plugins.keySet().iterator(); while (it.hasNext()) { PluginFile pluginFile = (PluginFile) this.plugins.get(it.next()); Element elem = (Element) panels.appendChild(doc.createElementNS(CONFIG_NS, "plugin")); elem.setAttribute("jar", pluginFile.getJarFile()); elem.setAttribute("class", pluginFile.getClassName()); elem.setAttribute("id", pluginFile.getId()); elem.setAttribute("position", pluginFile.getPosition()); } } catch (ParserConfigurationException e) { e.printStackTrace(); } if (doc != null) { OutputFormat of = new OutputFormat(doc); of.setIndenting(true); of.setIndent(1); of.setStandalone(true); StringWriter sw = new StringWriter(); XMLSerializer xs = new XMLSerializer(sw, of); xs.setOutputCharStream(sw); try { xs.serialize(doc); sw.flush(); System.out.println(sw.toString()); sw.close(); } catch (IOException e1) { e1.printStackTrace(); } try { FileWriter fw = new FileWriter(this.cfgFile); fw.write(sw.toString()); fw.close(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:uk.ac.tgac.conan.core.service.impl.VelocityMergerServiceImpl.java
@Override public void merge(File template, VelocityContext context, File output) throws IOException { log.debug("Loading template data"); // Load the template String template_data = FileUtils.readFileToString(template); // Create the output writer StringWriter writer = new StringWriter(); log.debug("Merging template and exectx"); // Create Velocity properties Properties vp = new Properties(); vp.setProperty("resource.loader", "class"); vp.setProperty("class.resource.loader.description", "Velocity Classpath Resource Loader"); vp.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); vp.setProperty("runtime.log.logsystem.log4j.logger", VelocityMergerServiceImpl.class.getName()); // Merge the template and the exectx VelocityEngine ve = new VelocityEngine(vp); ve.init();/*ww w . ja v a 2 s. c om*/ ve.evaluate(context, writer, "LaTeX Report Builder", template_data); writer.flush(); writer.close(); log.debug("Writing merged file to disk"); // Output to file FileUtils.writeStringToFile(output, writer.toString()); log.debug("Velocity template and exectx merged and saved successfully"); }
From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java
/** * Evaluates a String property containing Velocity * /*from ww w. ja v a 2s . co m*/ * @param property The String property * @param context Context of the request * @return The evaluated String */ protected String evaluate(String property, Context context) throws Exception { String value = (String) context.get(property); StringWriter stringWriter = new StringWriter(); Velocity.evaluate(context, stringWriter, property, value); stringWriter.close(); return stringWriter.toString(); }
From source file:edu.cornell.mannlib.vitro.webapp.servlet.setup.UpdateKnowledgeBase.java
private void updateAddRemoveDataGetterStatements(OntModel displayModel, Model removeStatements, Model addStatements, Resource oldType, Resource newType) { log.debug("Old type: " + oldType.getURI() + " - newType: " + newType.getURI()); removeStatements.add(displayModel.listStatements(null, RDF.type, oldType)); StmtIterator oldStatements = displayModel.listStatements(null, RDF.type, oldType); while (oldStatements.hasNext()) { Statement stmt = oldStatements.nextStatement(); addStatements.add(stmt.getSubject(), RDF.type, newType); }// w w w . j a v a 2s. co m //Print out remove and add statements here StringWriter sw = new StringWriter(); try { log.debug( "Adding statements with old data getter types to remove statements, remove statements is now"); removeStatements.write(sw, "N3"); log.debug(sw.toString()); sw.close(); sw = new StringWriter(); log.debug("Adding statements with new data getter types to add statements, add statements is now"); addStatements.write(sw, "N3"); log.debug(sw.toString()); sw.close(); } catch (Exception ex) { log.error("Error occurred in writing out remove and statements for data getter types", ex); } }
From source file:org.hupo.psi.mi.psicquic.ws.IndexBasedPsicquicRestService.java
public Response getByQuery(String query, String format, String firstResultStr, String maxResultsStr, String compressed)//from w ww. ja va2 s. c o m throws PsicquicServiceException, NotSupportedMethodException, NotSupportedTypeException { boolean isCompressed = ("y".equalsIgnoreCase(compressed) || "true".equalsIgnoreCase(compressed)); int firstResult; int maxResults; try { firstResult = Integer.parseInt(firstResultStr); } catch (NumberFormatException e) { throw new PsicquicServiceException("firstResult parameter is not a number: " + firstResultStr); } try { if (maxResultsStr == null) { maxResults = Integer.MAX_VALUE; } else { maxResults = Integer.parseInt(maxResultsStr); } } catch (NumberFormatException e) { throw new PsicquicServiceException("maxResults parameter is not a number: " + maxResultsStr); } format = format.toLowerCase(); // if using mitab25-bin, set to mitab and compressed=y if (RETURN_TYPE_MITAB25_BIN.equalsIgnoreCase(format)) { format = RETURN_TYPE_MITAB25; isCompressed = true; } try { if (RETURN_TYPE_XML25.equalsIgnoreCase(format)) { final EntrySet entrySet = getByQueryXml(query, firstResult, maxResults); int count = 0; if (entrySet.getEntries() != null && !entrySet.getEntries().isEmpty()) { for (Entry entry : entrySet.getEntries()) { if (entry.getInteractionList() != null && entry.getInteractionList().getInteractions() != null && !entry.getInteractionList().getInteractions().isEmpty()) { count += entry.getInteractionList().getInteractions().size(); } } } return prepareResponse(Response.status(200).type(MediaType.APPLICATION_XML), entrySet, count, isCompressed).build(); } else if ((format.toLowerCase().startsWith("rdf") && format.length() > 5) || format.toLowerCase().startsWith("biopax") || format.toLowerCase().startsWith("biopax-L3") || format.toLowerCase().startsWith("biopax-L2")) { String rdfFormat = getRdfFormatName(format); String mediaType = (format.contains("xml") || format.toLowerCase().startsWith("biopax")) ? MediaType.APPLICATION_XML : MediaType.TEXT_PLAIN; psidev.psi.mi.xml.model.EntrySet entrySet = createEntrySet(query, firstResult, maxResults); StringWriter sw = new StringWriter(); String output = ""; PsimiRdfConverter rdfConverter = new PsimiRdfConverter(); try { rdfConverter.convert(entrySet, rdfFormat, sw); output = sw.toString(); } catch (Exception e) { return formatNotSupportedResponse(format); } finally { sw.close(); rdfConverter.close(); } int count = 0; if (entrySet.getEntries() != null && !entrySet.getEntries().isEmpty()) { for (psidev.psi.mi.xml.model.Entry entry : entrySet.getEntries()) { if (entry.getInteractions() != null && !entry.getInteractions().isEmpty()) { count += entry.getInteractions().size(); } } } return prepareResponse(Response.status(200).type(mediaType), output, count, isCompressed).build(); } else { int count = count(query); if (RETURN_TYPE_COUNT.equalsIgnoreCase(format)) { return prepareResponse(Response.status(200).type(MediaType.TEXT_PLAIN), count, count, false) .build(); } else if (RETURN_TYPE_XGMML.equalsIgnoreCase(format)) { XgmmlStreamingOutput xgmml = new XgmmlStreamingOutput(this.psicquicService, query, firstResult, maxResults); String fixedQuery = query; if (fixedQuery.contains("&")) { fixedQuery = query.substring(0, query.indexOf("&")); } fixedQuery = fixedQuery.replaceAll("q=", ""); fixedQuery = fixedQuery.replaceAll(":", "_"); fixedQuery = fixedQuery.replaceAll(" ", "_"); fixedQuery = fixedQuery.replaceAll("\\(", ""); fixedQuery = fixedQuery.replaceAll("\\)", ""); String name = fixedQuery.substring(0, Math.min(10, fixedQuery.length())) + ".xgmml"; return prepareResponse(Response.status(200).type(MediaType.APPLICATION_XML).header( "Content-Disposition", "attachment; filename=" + name), xgmml, count, isCompressed) .build(); } else if (RETURN_TYPE_MITAB25.equalsIgnoreCase(format) || format == null) { PsicquicStreamingOutput result = new PsicquicStreamingOutput(psicquicService, query, firstResult, maxResults, isCompressed); return prepareResponse(Response.status(200).type(MediaType.TEXT_PLAIN), result, result.countResults(), isCompressed).build(); } else { return formatNotSupportedResponse(format); } } } catch (Throwable e) { throw new PsicquicServiceException("Problem creating output", e); } }
From source file:org.eclipse.winery.repository.resources.entitytypes.relationshiptypes.ImplementationsOfOneRelationshipTypeResource.java
/** * required by implementations.jsp/*w ww .j a va 2 s . c om*/ * * Method similar top the one of ImplementationsOfOneNodeTypeResource * * @return for each node type implementation implementing the associated * node type */ @Override public String getImplementationsTableData() { String res; JsonFactory jsonFactory = new JsonFactory(); StringWriter tableDataSW = new StringWriter(); try { JsonGenerator jGenerator = jsonFactory.createGenerator(tableDataSW); jGenerator.writeStartArray(); Collection<RelationshipTypeImplementationId> allNTIids = BackendUtils .getAllElementsRelatedWithATypeAttribute(RelationshipTypeImplementationId.class, this.getTypeId().getQName()); for (RelationshipTypeImplementationId ntiID : allNTIids) { jGenerator.writeStartArray(); jGenerator.writeString(ntiID.getNamespace().getDecoded()); jGenerator.writeString(ntiID.getXmlId().getDecoded()); jGenerator.writeEndArray(); } jGenerator.writeEndArray(); jGenerator.close(); tableDataSW.close(); res = tableDataSW.toString(); } catch (Exception e) { ImplementationsOfOneRelationshipTypeResource.LOGGER.error(e.getMessage(), e); res = "[]"; } return res; }