List of usage examples for java.io StringWriter close
public void close() throws IOException
From source file:fi.vm.kapa.identification.metadata.background.MetadataFilesGenerator.java
License:asdf
private String createXmlString(XMLObject content) throws Exception { Document xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(content); marshaller.marshall(content, xmlDocument); Transformer transformer = TransformerFactory.newInstance().newTransformer(); StringWriter writer = new StringWriter(); StreamResult streamResult = new StreamResult(writer); DOMSource source = new DOMSource(xmlDocument); transformer.transform(source, streamResult); writer.close(); return writer.toString(); }
From source file:com.thinkberg.webdav.data.DavResource.java
protected boolean setPropertyValue(Element root, Element propertyEl) { LogFactory.getLog(getClass()).debug(String.format("[%s].set('%s')", object.getName(), propertyEl.asXML())); if (!ALL_PROPERTIES.contains(propertyEl.getName())) { final String nameSpace = propertyEl.getNamespaceURI(); final String attributeName = getFQName(nameSpace, propertyEl.getName()); try {//from w ww . j a v a2 s .c o m FileContent objectContent = object.getContent(); final String command = propertyEl.getParent().getParent().getName(); if (TAG_PROP_SET.equals(command)) { StringWriter propertyValueWriter = new StringWriter(); propertyEl.write(propertyValueWriter); propertyValueWriter.close(); objectContent.setAttribute(attributeName, propertyValueWriter.getBuffer().toString()); } else if (TAG_PROP_REMOVE.equals(command)) { objectContent.setAttribute(attributeName, null); } root.addElement(propertyEl.getQName()); return true; } catch (IOException e) { LogFactory.getLog(getClass()).error(String.format("can't store attribute property '%s' = '%s'", attributeName, propertyEl.asXML()), e); } } return false; }
From source file:org.hawkular.apm.tests.dockerized.TestScenarioRunner.java
private String serialize(Object object) throws IOException { StringWriter out = new StringWriter(); JsonGenerator gen = objectMapper.getFactory().createGenerator(out); gen.writeObject(object);//from w w w .j a va2s .c o m gen.close(); out.close(); return out.toString(); }
From source file:org.metamorfosis.template.engine.FreemarkerEngine.java
@Override public void match(SingleTemplateMatch templateModel) { try {//from ww w. j a va 2 s. c om // create model root Map root = new HashMap(); // put directives root.putAll(directivesWrapped); // ${project} root.putAll(projectWrapped); // ${metapojos} List<MetaClass> metaPojos = templateModel.getMetaPojos(); if (metaPojos != null) { Object metaPojosWrapped = getEngineWrappersFactory().getMetaPojosWrapper().wrap(metaPojos); root.putAll((Map) metaPojosWrapped); } // ${metaproperty} MetaProperty metaProperty = templateModel.getMetaProperty(); if (metaProperty != null) { MetaPropertyWrapper metaPropertyWrapper = getEngineWrappersFactory().getMetaPropertyWrapper(); Object metaPropertyWrapped = metaPropertyWrapper.wrap(metaProperty); root.putAll((Map) metaPropertyWrapped); } // process template TemplateDef templateDef = templateModel.getTemplateDef(); InputStream is = templateDef.getLocation().getInputStream(); InputStreamReader reader = new InputStreamReader(is); Template template = new Template(templateDef.getName(), reader, cfg); StringWriter sw = new StringWriter(); Environment env = template.createProcessingEnvironment(root, sw); env.process(); // process the template sw.close(); } catch (TemplateException ex) { String templateName = templateModel.getTemplateDef().getName(); throw new MatchException("No se pudo hacer match del template '" + templateName + "' por un error en la definicin del template", ex); } catch (IOException ex) { String templateName = templateModel.getTemplateDef().getName(); throw new MatchException( "No se pudo hacer match del template '" + templateName + "' por un error de i/o", ex); } }
From source file:org.efaps.webdav4vfs.data.DavResource.java
@Override() protected boolean setPropertyValue(Element root, Element propertyEl) { LogFactory.getLog(getClass()).debug(String.format("[%s].set('%s')", object.getName(), propertyEl.asXML())); if (!ALL_PROPERTIES.contains(propertyEl.getName())) { final String nameSpace = propertyEl.getNamespaceURI(); final String attributeName = getFQName(nameSpace, propertyEl.getName()); try {// ww w . ja va2 s. c o m FileContent objectContent = object.getContent(); final String command = propertyEl.getParent().getParent().getName(); if (TAG_PROP_SET.equals(command)) { StringWriter propertyValueWriter = new StringWriter(); propertyEl.write(propertyValueWriter); propertyValueWriter.close(); objectContent.setAttribute(attributeName, propertyValueWriter.getBuffer().toString()); } else if (TAG_PROP_REMOVE.equals(command)) { objectContent.setAttribute(attributeName, null); } root.addElement(propertyEl.getQName()); return true; } catch (IOException e) { LogFactory.getLog(getClass()).error(String.format("can't store attribute property '%s' = '%s'", attributeName, propertyEl.asXML()), e); } } return false; }
From source file:com.imagesleuth.imagesleuthclient2.Poster.java
public String Post(final File imgFile) throws IOException, ImageReadException, InterruptedException { final ArrayList<String> idArray = new ArrayList<>(); final CountDownLatch latch = new CountDownLatch(1); try (CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultHeaders(harray) .setDefaultCredentialsProvider(credsProvider).setDefaultRequestConfig(requestConfig).build()) { httpclient.start();//from w w w. ja v a 2 s .com final byte[] imageAsBytes = IOUtils.toByteArray(new FileInputStream(imgFile)); final ImageInfo info = Imaging.getImageInfo(imageAsBytes); final HttpPost request = new HttpPost(urlval); String boundary = UUID.randomUUID().toString(); HttpEntity mpEntity = MultipartEntityBuilder.create().setBoundary("-------------" + boundary) .addBinaryBody("file", imageAsBytes, ContentType.create(info.getMimeType()), imgFile.getName()) .build(); ByteArrayOutputStream baoStream = new ByteArrayOutputStream(); mpEntity.writeTo(baoStream); request.setHeader("Content-Type", "multipart/form-data;boundary=-------------" + boundary); //equest.setHeader("Content-Type", "multipart/form-data"); NByteArrayEntity entity = new NByteArrayEntity(baoStream.toByteArray(), ContentType.MULTIPART_FORM_DATA); request.setEntity(entity); httpclient.execute(request, new FutureCallback<HttpResponse>() { @Override public void completed(final HttpResponse response) { int code = response.getStatusLine().getStatusCode(); //System.out.println(" response code: " + code + " for image: " + imgFile.getName()); if (response.getEntity() != null && code == 202) { StringWriter writer = new StringWriter(); try { IOUtils.copy(response.getEntity().getContent(), writer); idArray.add(writer.toString()); writer.close(); //System.out.println(" response id: " + id + " for image "+ img.getName()); latch.countDown(); } catch (Exception ex) { ex.printStackTrace(); } } else { System.out.println(" response code: " + code + " for image: " + imgFile.getName() + " reason " + response.getStatusLine().getReasonPhrase()); } } @Override public void failed(final Exception ex) { System.out.println(request.getRequestLine() + imgFile.getName() + "->" + ex); latch.countDown(); } @Override public void cancelled() { System.out.println(request.getRequestLine() + " cancelled"); latch.countDown(); } }); latch.await(); } if (idArray.isEmpty()) { return null; } else { return idArray.get(0); } }
From source file:org.metamorfosis.template.engine.FreemarkerEngine.java
@Override public void match(GroupTemplatesMatch groupTemplatesMatch) { // create model Map root = new HashMap(); // put directives root.putAll(directivesWrapped);/*from w ww . jav a 2 s . c om*/ // ${project} root.putAll(projectWrapped); // ${metapojos} List<MetaClass> metaPojos = groupTemplatesMatch.getMetaPojos(); if (metaPojos != null) { Object metaPojosWrapped = getEngineWrappersFactory().getMetaPojosWrapper().wrap(metaPojos); root.putAll((Map) metaPojosWrapped); } // ${metaproperty} MetaProperty metaProperty = groupTemplatesMatch.getMetaProperty(); if (metaProperty != null) { MetaPropertyWrapper metaPropertyWrapper = getEngineWrappersFactory().getMetaPropertyWrapper(); Object metaPropertyWrapped = metaPropertyWrapper.wrap(metaProperty); root.putAll((Map) metaPropertyWrapped); } // process templates GroupTemplatesDef groupTemplatesDef = groupTemplatesMatch.getGroupTemplatesDef(); List<TemplateDef> templatesDef = groupTemplatesDef.getTemplatesDef(); for (TemplateDef templateDef : templatesDef) { try { InputStream is = templateDef.getLocation().getInputStream(); InputStreamReader reader = new InputStreamReader(is); Template template = new Template(templateDef.getName(), reader, cfg); StringWriter sw = new StringWriter(); Environment env = template.createProcessingEnvironment(root, sw); env.process(); // process the template sw.close(); } catch (TemplateException ex) { String templateName = templateDef.getName(); throw new MatchException("No se pudo procesar el grupo de templates '" + groupTemplatesDef.getGroupName() + "' ya que al hacer match del template '" + templateName + "' ocurrio error en la definicin", ex); } catch (IOException ex) { String templateName = templateDef.getName(); throw new MatchException("No se pudo procesar el grupo de templates '" + groupTemplatesDef.getGroupName() + "' ya que al hacer match del template '" + templateName + "' ocurrio error de i/o", ex); } } }
From source file:nl.ru.cmbi.vase.web.rest.JobRestResource.java
@MethodMapping(value = "/structure/{id}", httpMethod = HttpMethod.GET, produces = RestMimeTypes.TEXT_PLAIN) public String structure(String id) { try {/*w w w . j a va 2s. co m*/ Matcher mpdb = StockholmParser.pPDBAC.matcher(id); if (mpdb.matches()) { URL url = Utils.getRcsbURL(mpdb.group(1)); StringWriter pdbWriter = new StringWriter(); IOUtils.copy(url.openStream(), pdbWriter, "UTF-8"); pdbWriter.close(); return pdbWriter.toString(); } File xmlFile = new File(Config.getCacheDir(), id + ".xml.gz"); if (xmlFile.isFile()) { VASEDataObject data = VASEXMLParser.parse(new GZIPInputStream(new FileInputStream(xmlFile))); return Utils.getPdbContents(data.getPdbID()); } if (Config.hsspPdbCacheEnabled()) { File pdbFile = new File(Config.getHSSPCacheDir(), id + ".pdb.gz"); if (pdbFile.isFile()) { StringWriter pdbWriter = new StringWriter(); IOUtils.copy(new GZIPInputStream(new FileInputStream(pdbFile)), pdbWriter, "UTF-8"); pdbWriter.close(); return pdbWriter.toString(); } } log.error("no structure file for " + id); throw new AbortWithHttpErrorCodeException(HttpURLConnection.HTTP_NOT_FOUND); } catch (Exception e) { log.error("structure " + id + ": " + e.getMessage(), e); throw new AbortWithHttpErrorCodeException(HttpURLConnection.HTTP_INTERNAL_ERROR); } }
From source file:com.hypirion.io.PipeTest.java
/** * Test that basic reader/writer capabilities work as expected. *///from w w w.j a v a 2s . co m @Test(timeout = 1000) public void testBasicReaderCapabilities() throws Exception { String input = RandomStringUtils.random(3708); StringReader rdr = new StringReader(input); StringWriter wrt = new StringWriter(); Pipe p = new Pipe(rdr, wrt); p.start(); p.join(); String output = wrt.toString(); rdr.close(); wrt.close(); assertEquals(input, output); }
From source file:plugins.GerritTriggerTest.java
private String readJson(Process curl) throws InterruptedException, IOException { assertThat(curl.waitFor(), is(equalTo(0))); StringWriter writer = new StringWriter(); IOUtils.copy(curl.getInputStream(), writer); String[] lines = writer.toString().split(System.getProperty("line.separator")); writer.close(); // need to remove first line from JSON response // see: http://gerrit-documentation.googlecode.com/svn/Documentation/2.6/rest-api.html#output StringBuilder sb = new StringBuilder(); for (int i = 1; i < lines.length; i++) { sb.append(lines[i] + "\n"); }/* w w w.j av a2 s . c o m*/ return sb.toString(); }