List of usage examples for java.io StringWriter close
public void close() throws IOException
From source file:com.google.gwtjsonrpc.server.JsonServlet.java
private String formatResult(final ActiveCall call) throws UnsupportedEncodingException, IOException { final GsonBuilder gb = createGsonBuilder(); gb.registerTypeAdapter(call.getClass(), new JsonSerializer<ActiveCall>() { public JsonElement serialize(final ActiveCall src, final Type typeOfSrc, final JsonSerializationContext context) { if (call.callback != null) { if (src.externalFailure != null) { return new JsonNull(); }//from ww w. j av a 2s . c o m return context.serialize(src.result); } final JsonObject r = new JsonObject(); r.add(src.versionName, src.versionValue); if (src.id != null) { r.add("id", src.id); } if (src.xsrfKeyOut != null) { r.addProperty("xsrfKey", src.xsrfKeyOut); } if (src.externalFailure != null) { final JsonObject error = new JsonObject(); if ("jsonrpc".equals(src.versionName)) { final int code = to2_0ErrorCode(src); error.addProperty("code", code); error.addProperty("message", src.externalFailure.getMessage()); } else { error.addProperty("name", "JSONRPCError"); error.addProperty("code", 999); error.addProperty("message", src.externalFailure.getMessage()); } r.add("error", error); } else { r.add("result", context.serialize(src.result)); } return r; } }); final StringWriter o = new StringWriter(); if (call.callback != null) { o.write(call.callback); o.write("("); } gb.create().toJson(call, o); if (call.callback != null) { o.write(");"); } o.close(); return o.toString(); }
From source file:org.eclipse.winery.repository.resources.entitytypes.nodetypes.ImplementationsOfOneNodeTypeResource.java
/** * required by implementations.jsp/* w w w.j av a 2 s.c o m*/ * * @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<NodeTypeImplementationId> allNodeTypeImplementations = BackendUtils .getAllElementsRelatedWithATypeAttribute(NodeTypeImplementationId.class, this.getTypeId().getQName()); for (NodeTypeImplementationId ntiID : allNodeTypeImplementations) { 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) { ImplementationsOfOneNodeTypeResource.LOGGER.error(e.getMessage(), e); res = "[]"; } return res; }
From source file:com.palominolabs.crm.sf.rest.HttpApiClient.java
@Nonnull private String getSObjectFieldsAsJson(@Nonnull SObject sObject) throws IOException { StringWriter writer = new StringWriter(); JsonGenerator jsonGenerator = this.objectMapper.getFactory().createGenerator(writer); jsonGenerator.writeStartObject();/*from w w w .j a v a 2 s .c o m*/ for (Map.Entry<String, String> entry : sObject.getAllFields().entrySet()) { if (entry.getValue() == null) { jsonGenerator.writeNullField(entry.getKey()); } else { jsonGenerator.writeStringField(entry.getKey(), entry.getValue()); } } jsonGenerator.writeEndObject(); jsonGenerator.close(); writer.close(); return writer.toString(); }
From source file:org.rapla.server.jsonrpc.JsonServlet.java
private String formatResult(final ActiveCall call) throws UnsupportedEncodingException, IOException { final GsonBuilder gb = createGsonBuilder(); gb.registerTypeAdapter(call.getClass(), new JsonSerializer<ActiveCall>() { @Override//from ww w . ja v a2 s .com public JsonElement serialize(final ActiveCall src, final Type typeOfSrc, final JsonSerializationContext context) { if (call.callback != null) { if (src.externalFailure != null) { return new JsonNull(); } return context.serialize(src.result); } final JsonObject r = new JsonObject(); r.add(src.versionName, src.versionValue); if (src.id != null) { r.add("id", src.id); } if (src.xsrfKeyOut != null) { r.addProperty("xsrfKey", src.xsrfKeyOut); } if (src.externalFailure != null) { final JsonObject error = new JsonObject(); if ("jsonrpc".equals(src.versionName)) { final int code = to2_0ErrorCode(src); error.addProperty("code", code); error.addProperty("message", src.externalFailure.getMessage()); } else { error.addProperty("name", "JSONRPCError"); error.addProperty("code", 999); error.addProperty("message", src.externalFailure.getMessage()); } r.add("error", error); } else { r.add("result", context.serialize(src.result)); } return r; } }); final StringWriter o = new StringWriter(); if (call.callback != null) { o.write(call.callback); o.write("("); } gb.create().toJson(call, o); if (call.callback != null) { o.write(");"); } o.close(); return o.toString(); }
From source file:com.webcohesion.enunciate.modules.csharp_client.CSharpXMLClientModule.java
/** * Processes the specified template with the given model. * * @param templateURL The template URL./*ww w .j av a 2 s . c o m*/ * @param model The root model. */ public String processTemplate(URL templateURL, Object model) throws IOException, TemplateException { debug("Processing template %s.", templateURL); Configuration configuration = new Configuration(Configuration.VERSION_2_3_22); configuration.setTemplateLoader(new URLTemplateLoader() { protected URL getURL(String name) { try { return new URL(name); } catch (MalformedURLException e) { return null; } } }); configuration.setTemplateExceptionHandler(new TemplateExceptionHandler() { public void handleTemplateException(TemplateException templateException, Environment environment, Writer writer) throws TemplateException { throw templateException; } }); configuration.setLocalizedLookup(false); configuration.setDefaultEncoding("UTF-8"); configuration.setObjectWrapper(new CSharpXMLClientObjectWrapper()); Template template = configuration.getTemplate(templateURL.toString()); StringWriter unhandledOutput = new StringWriter(); template.process(model, unhandledOutput); unhandledOutput.close(); return unhandledOutput.toString(); }
From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java
public static XmlElement getAtomElement(final StartElement start, final XMLEventReader reader) throws Exception { final XmlElement res = new XmlElement(); res.setStart(start);/* w w w . j a v a 2s . c om*/ StringWriter content = new StringWriter(); int depth = 1; while (reader.hasNext() && depth > 0) { final XMLEvent event = reader.nextEvent(); if (event.getEventType() == XMLStreamConstants.START_ELEMENT && start.getName().getLocalPart().equals(event.asStartElement().getName().getLocalPart())) { depth++; } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT && start.getName().getLocalPart().equals(event.asEndElement().getName().getLocalPart())) { depth--; } if (depth == 0) { res.setEnd(event.asEndElement()); } else { event.writeAsEncodedUnicode(content); } } content.flush(); content.close(); res.setContent(new ByteArrayInputStream(content.toString().getBytes())); return res; }
From source file:fr.univlr.cri.planning.factory.HugICalendarFactory.java
/** * Lecture d'un fichier icalendar via l'API de la librairie ical4j. Les * occupations contenues dans la fenetre d'interrogation [dateDebut, dateFin] * sont retournees./*from w w w . ja v a2 s.co m*/ * * @param pathICalendar * : le chemin du fichier ICS * @param dateDebut * : date de debut de la periode d'interrogation * @param dateFin * : date de fin de la periode d'interrogation * @return * @throws CalendarNotFoundException */ private CalendarObject newCalendarObjectFromICalendarFileICal4J(String pathICalendar, NSTimestamp dateDebut, NSTimestamp dateFin) throws CalendarNotFoundException { CalendarObject oCal = null; InputStream in = null; try { // fin = new FileInputStream(pathICalendar); URL url = new URL(pathICalendar); URLConnection con = url.openConnection(); con.connect(); in = con.getInputStream(); } catch (FileNotFoundException e) { throw new CalendarNotFoundException("Calendar " + pathICalendar + " non trouv ou acc?s refus."); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } /* * CalendarBuilder calendarBuilder = new CalendarBuilder(); * * try { long l1 = System.currentTimeMillis(); Calendar calendar = * calendarBuilder.build(in); oCal = new CalendarObject(pathICalendar); l1 = * System.currentTimeMillis() - l1; CktlLog.log(">> parsing : " + l1 + * " ms ("+pathICalendar+")"); * * // on passe au evenements for (Iterator i = * calendar.getComponents().iterator(); i.hasNext();) { Component component * = (Component) i.next(); if (component.getName().equals(Component.VEVENT)) * { VEvent vEvent = (VEvent) component; oCal.addSPVEvent(new * SPVEvent(vEvent)); } } * * * * } catch (IOException e) { throw new * CalendarNotFoundException("Calendar "+ pathICalendar * +" erreur de lecture " + e.getMessage()); } catch (ParserException e) { * throw new CalendarNotFoundException("Calendar "+ pathICalendar * +" erreur de lecture " + e.getMessage()); } */ String string = null; try { long l1 = System.currentTimeMillis(); URL url = new URL(pathICalendar); URLConnection con = url.openConnection(); con.connect(); BufferedInputStream bin = new BufferedInputStream(con.getInputStream()); StringWriter out = new StringWriter(); int b; while ((b = bin.read()) != -1) out.write(b); out.flush(); out.close(); bin.close(); string = out.toString(); l1 = System.currentTimeMillis() - l1; System.out.println("converting calendar url to string : " + l1 + " ms (" + pathICalendar + ")"); } catch (IOException ie) { ie.printStackTrace(); } long l1 = System.currentTimeMillis(); StringReader sin = new StringReader(string); CalendarBuilder builder = new CalendarBuilder(); Calendar calendar = null; try { calendar = builder.build(sin); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } l1 = System.currentTimeMillis() - l1; System.out.println("parse calendar string : " + l1 + " ms (" + pathICalendar + ")"); oCal = new CalendarObject(pathICalendar); // on passe au evenements for (Iterator i = calendar.getComponents().iterator(); i.hasNext();) { Component component = (Component) i.next(); if (component.getName().equals(Component.VEVENT)) { VEvent vEvent = (VEvent) component; oCal.addSPVEvent(new SPVEvent(vEvent)); } } // on met en cache notre affaire if (oCal != null) { putCalendarInCache(pathICalendar, oCal); } return oCal; }
From source file:org.openo.client.cli.fw.output.print.OpenOCommandPrint.java
/** * Print output in csv format./* w w w. j a va2 s . c om*/ * * @return string * @throws OpenOCommandOutputPrintingFailed * exception */ public String printCsv() throws OpenOCommandOutputPrintingFailed { StringWriter writer = new StringWriter(); CSVPrinter printer = null; try { CSVFormat formattor = CSVFormat.DEFAULT.withRecordSeparator(System.getProperty("line.separator")); printer = new CSVPrinter(writer, formattor); List<List<Object>> rows = this.formRows(false); for (int i = 0; i < this.findMaxRows(); i++) { printer.printRecord(rows.get(i)); } return writer.toString(); } catch (IOException e) { throw new OpenOCommandOutputPrintingFailed(e); } finally { try { if (printer != null) { printer.close(); } writer.close(); } catch (IOException e) { throw new OpenOCommandOutputPrintingFailed(e); // NOSONAR } } }
From source file:edu.cornell.mannlib.vitro.webapp.servlet.setup.UpdateKnowledgeBase.java
private void replaceTboxAndDisplayMetadata(OntModel displayModel, Model addStatements, Model removeStatements, UpdateSettings settings) {//from w w w . j a v a 2 s .c o m OntModel oldDisplayModelTboxModel = settings.getOldDisplayModelTboxModel(); OntModel oldDisplayModelDisplayMetadataModel = settings.getOldDisplayModelDisplayMetadataModel(); OntModel newDisplayModelTboxModel = settings.getNewDisplayModelTboxModel(); OntModel newDisplayModelDisplayMetadataModel = settings.getNewDisplayModelDisplayMetadataModel(); OntModel loadedAtStartup = settings.getLoadedAtStartupDisplayModel(); OntModel oldVivoListView = settings.getVivoListViewConfigDisplayModel(); //Remove old display model tbox and display metadata statements from display model removeStatements.add(oldDisplayModelTboxModel); removeStatements.add(oldDisplayModelDisplayMetadataModel); //the old startup folder only contained by oldVivoListView removeStatements.add(oldVivoListView); StringWriter sw = new StringWriter(); try { log.debug( "Adding old display tbox model, display metadata model, and oldVivoListView to remove statements. Remove statements now include:"); removeStatements.write(sw, "N3"); log.debug(sw.toString()); sw.close(); } catch (Exception ex) { log.error("Exception occurred", ex); } //Add statements from new tbox and display metadata addStatements.add(newDisplayModelTboxModel); addStatements.add(newDisplayModelDisplayMetadataModel); //this should include the list view in addition to other files addStatements.add(loadedAtStartup); try { sw = new StringWriter(); log.debug( "Adding new display tbox model, display metadata model, and loaded at startup to add statements. Add statements now include:"); addStatements.write(sw, "N3"); log.debug(sw.toString()); sw.close(); } catch (Exception ex) { log.error("Exception occurred in adding new display model tbox/metadata info to add statements ", ex); } log.debug("Adding new display tbox model, display metadata model, and all models loaded at startup"); }
From source file:org.jetbrains.jet.grammar.GrammarGenerator.java
private static String generate(List<Token> tokens) throws IOException { StringWriter result = new StringWriter(); Set<String> declaredSymbols = new HashSet<String>(); Set<String> usedSymbols = new HashSet<String>(); Multimap<String, String> usages = Multimaps.newSetMultimap(Maps.<String, Collection<String>>newHashMap(), new Supplier<Set<String>>() { @Override// www . jav a 2 s. co m public Set<String> get() { return Sets.newHashSet(); } }); Declaration lastDeclaration = null; for (Token advance : tokens) { if (advance instanceof Declaration) { Declaration declaration = (Declaration) advance; lastDeclaration = declaration; declaredSymbols.add(declaration.getName()); } else if (advance instanceof Identifier) { Identifier identifier = (Identifier) advance; assert lastDeclaration != null; usages.put(identifier.getName(), lastDeclaration.getName()); usedSymbols.add(identifier.getName()); } } try { JAXBContext context = JAXBContext.newInstance(Annotation.class, Comment.class, Declaration.class, DocComment.class, Identifier.class, Other.class, StringToken.class, SymbolToken.class, Token.class, WhiteSpace.class, TokenList.class); Marshaller m = context.createMarshaller(); TokenList list = new TokenList(tokens); list.updateUsages(usedSymbols, usages); m.marshal(list, result); } catch (PropertyException e) { e.printStackTrace(); } catch (JAXBException e) { e.printStackTrace(); } result.flush(); result.close(); return result.toString(); }