List of usage examples for java.io StringWriter write
public void write(String str)
From source file:org.botlibre.util.Utils.java
public static String displayTimestamp(Date date) { if (date == null) { return ""; }/*from ww w. java 2s. c om*/ StringWriter writer = new StringWriter(); Calendar today = Calendar.getInstance(); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); if (calendar.get(Calendar.YEAR) == today.get(Calendar.YEAR) && calendar.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) { writer.write("Today"); } else if (calendar.get(Calendar.YEAR) == today.get(Calendar.YEAR) && calendar.get(Calendar.DAY_OF_YEAR) == (today.get(Calendar.DAY_OF_YEAR) - 1)) { writer.write("Yesterday"); } else { writer.write(calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.US)); writer.write(" "); writer.write(String.valueOf(calendar.get(Calendar.DAY_OF_MONTH))); if (calendar.get(Calendar.YEAR) != today.get(Calendar.YEAR)) { writer.write(" "); writer.write(String.valueOf(calendar.get(Calendar.YEAR))); } } writer.write(", "); writer.write(String.valueOf(calendar.get(Calendar.HOUR_OF_DAY))); writer.write(":"); if (calendar.get(Calendar.MINUTE) < 10) { writer.write("0"); } writer.write(String.valueOf(calendar.get(Calendar.MINUTE))); return writer.toString(); }
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(); }// w w w . j ava2s.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:com.google.acre.script.NHttpAsyncUrlfetch.java
private Scriptable callback_result(long start_time, URL url, HttpResponse res, boolean system, boolean log_to_user, String response_encoding) { BrowserCompatSpecFactory bcsf = new BrowserCompatSpecFactory(); CookieSpec cspec = bcsf.newInstance(null); String protocol = url.getProtocol(); boolean issecure = ("https".equals(protocol)); int port = url.getPort(); if (port == -1) port = 80;/*w w w . ja v a 2 s . c o m*/ CookieOrigin origin = new CookieOrigin(url.getHost(), port, url.getPath(), issecure); Object body = ""; int status = res.getStatusLine().getStatusCode(); Context ctx = Context.getCurrentContext(); Scriptable out = ctx.newObject(_scope); Scriptable headers = ctx.newObject(_scope); Scriptable cookies = ctx.newObject(_scope); out.put("status", out, status); out.put("headers", out, headers); out.put("cookies", out, cookies); Header content_type_header = null; StringBuilder response_header_log = new StringBuilder(); for (Header h : res.getAllHeaders()) { if (h.getName().equalsIgnoreCase("set-cookie")) { String set_cookie = h.getValue(); Matcher m = Pattern.compile("\\s*(([^,]|(,\\s*\\d))+)").matcher(set_cookie); while (m.find()) { Header ch = new BasicHeader("Set-Cookie", set_cookie.substring(m.start(), m.end())); try { List<Cookie> pcookies = cspec.parse(ch, origin); for (Cookie c : pcookies) { cookies.put(c.getName(), cookies, new AcreCookie(c).toJsObject(_scope)); } } catch (MalformedCookieException e) { throw new RuntimeException(e); } } } else if (h.getName().equalsIgnoreCase("content-type")) { content_type_header = h; } response_header_log.append(h.getName() + ": " + h.getValue() + "\r\n"); headers.put(h.getName(), headers, h.getValue()); } String charset = null; if (content_type_header != null) { HeaderElement values[] = content_type_header.getElements(); if (values.length == 1) { NameValuePair param = values[0].getParameterByName("charset"); if (param != null) { charset = param.getValue(); } } } if (charset == null) charset = response_encoding; // read body HttpEntity ent = res.getEntity(); try { if (ent != null) { InputStream res_stream = ent.getContent(); Header cenc = ent.getContentEncoding(); if (cenc != null && res_stream != null) { HeaderElement[] codecs = cenc.getElements(); for (HeaderElement codec : codecs) { if (codec.getName().equalsIgnoreCase("gzip")) { res_stream = new GZIPInputStream(res_stream); } } } long first_byte_time = 0; long end_time = 0; if (content_type_header != null && (content_type_header.getValue().startsWith("image/") || content_type_header.getValue().startsWith("application/octet-stream") || content_type_header.getValue().startsWith("multipart/form-data"))) { // HttpClient's InputStream doesn't support mark/reset, so // wrap it with one that does. BufferedInputStream bufis = new BufferedInputStream(res_stream); bufis.mark(2); bufis.read(); first_byte_time = System.currentTimeMillis(); bufis.reset(); byte[] data = IOUtils.toByteArray(bufis); end_time = System.currentTimeMillis(); body = new JSBinary(); ((JSBinary) body).set_data(data); try { if (res_stream != null) res_stream.close(); } catch (IOException e) { // ignore } } else if (res_stream == null || charset == null) { first_byte_time = end_time = System.currentTimeMillis(); body = ""; } else { StringWriter writer = new StringWriter(); Reader reader = new InputStreamReader(res_stream, charset); int i = reader.read(); first_byte_time = System.currentTimeMillis(); writer.write(i); IOUtils.copy(reader, writer); end_time = System.currentTimeMillis(); body = writer.toString(); try { reader.close(); writer.close(); } catch (IOException e) { // ignore } } long reading_time = end_time - first_byte_time; long waiting_time = first_byte_time - start_time; String httprephdr = response_header_log.toString(); // XXX need to log start-time of request _logger.syslog4j("DEBUG", "urlfetch.response.async", "URL", url.toString(), "Status", Integer.toString(status), "Headers", httprephdr, "Reading time", reading_time, "Waiting time", waiting_time); if (system && log_to_user) { _response.userlog4j("DEBUG", "urlfetch.response.async", "URL", url.toString(), "Status", Integer.toString(status), "Headers", httprephdr); } // XXX seems like AcreResponse should be able to use // the statistics object to generate x-metaweb-cost // given a bit of extra information Statistics.instance().collectUrlfetchTime(start_time, first_byte_time, end_time); _costCollector.collect((system) ? "asuc" : "auuc").collect((system) ? "asuw" : "auuw", waiting_time); } } catch (IOException e) { throw new RuntimeException(e); } out.put("body", out, body); return out; }
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/*w w w . j a v a 2 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.checkmarx.jenkins.CxWebService.java
private Pair<byte[], byte[]> createScanSoapMessage(Object request, Class inputType, ProjectSettings projectSettings, LocalCodeContainer localCodeContainer, boolean visibleToOtherUsers, boolean isPublicScan) { final String soapMessageHead = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " + "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" + " <soap:Body>\n"; final String soapMessageTail = "\n </soap:Body>\n</soap:Envelope>"; final String zippedFileOpenTag = "<ZippedFile>"; final String zippedFileCloseTag = "</ZippedFile>"; try {/*www . ja v a 2 s . c o m*/ final JAXBContext context = JAXBContext.newInstance(inputType); final Marshaller marshaller = context.createMarshaller(); StringWriter scanMessage = new StringWriter(); scanMessage.write(soapMessageHead); // Nullify the zippedFile field, and save its old value for // restoring later final byte[] oldZippedFileValue = localCodeContainer.getZippedFile(); localCodeContainer.setZippedFile(new byte[] {}); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); marshaller.marshal(request, scanMessage); localCodeContainer.setZippedFile(oldZippedFileValue); // Restore the // old value scanMessage.write(soapMessageTail); // Here we split the message around <ZippedFile></ZippedFile> // substring. We know that the opening // and closing tag are adjacent because the zippedFile property was // set to empty byte array final String[] parts = scanMessage.toString().split(zippedFileOpenTag + zippedFileCloseTag); assert parts.length == 2; final String startPart = parts[0] + zippedFileOpenTag; final String endPart = zippedFileCloseTag + parts[1]; return Pair.of(startPart.getBytes("UTF-8"), endPart.getBytes("UTF-8")); } catch (JAXBException | UnsupportedEncodingException e) { // Getting here indicates a bug logger.error(e.getMessage(), e); throw new RuntimeException("Eror creating SOAP message", e); } }
From source file:com.espertech.esper.epl.variable.VariableServiceImpl.java
public String toString() { StringWriter writer = new StringWriter(); for (Map.Entry<String, VariableReader> entry : variables.entrySet()) { int variableNum = entry.getValue().getVariableNumber(); VersionedValueList<Object> list = variableVersions.get(variableNum); writer.write("Variable '" + entry.getKey() + "' : " + list.toString() + "\n"); }//w ww . j a va2s . c o m return writer.toString(); }
From source file:se.jguru.nazgul.tools.visualization.model.jaxb.PlainJaxbContextRule.java
/** * Marshals the supplied objects into an XML String, or throws an IllegalArgumentException * containing a wrapped JAXBException indicating why the marshalling was unsuccessful. * * @param loader The ClassLoader to use in order to load all classes previously added * by calls to the {@code add} method. * @param emitJSON if {@code true}, the method will attempt to output JSON instead of XML. * This requires the EclipseLink MOXy implementation as the JAXBContextFactory. * @param schema An optional (i.e. nullable) Schema, used to validate output from the Marshaller. * @param objects The objects to Marshal into XML. * @return An XML-formatted String containing * @throws IllegalArgumentException if the marshalling operation failed. * The {@code cause} field in the IllegalArgumentException contains * the JAXBException thrown by the JAXB framework. * @see #add(Class[])/*from www . j a va 2 s .c om*/ */ @SuppressWarnings("all") public String marshal(final ClassLoader loader, final boolean emitJSON, final Schema schema, final Object... objects) throws IllegalArgumentException { // Use EclipseLink? if (emitJSON) { setUseEclipseLinkMOXyIfAvailable(true); } if (useEclipseLinkMOXyIfAvailable) { System.setProperty(JAXB_CONTEXTFACTORY_PROPERTY, ECLIPSELINK_JAXB_CONTEXT_FACTORY); } else { System.clearProperty(JAXB_CONTEXTFACTORY_PROPERTY); } // Create the JAXBContext try { jaxbContext = JAXBContext.newInstance(getClasses(loader, null)); } catch (JAXBException e) { throw new IllegalArgumentException("Could not create JAXB context.", e); } // Create the JAXB Marshaller Marshaller marshaller = null; try { marshaller = jaxbContext.createMarshaller(); // Should we validate the output using the supplied Schema? if (schema != null) { marshaller.setSchema(schema); } } catch (Exception e) { throw new IllegalStateException("Could not create JAXB Marshaller", e); } // Should we emit JSON instead of XML? if (emitJSON) { try { marshaller.setProperty(ECLIPSELINK_MEDIA_TYPE, JSON_CONTENT_TYPE); marshaller.setProperty(ECLIPSELINK_JSON_WRAPPER_AS_ARRAY_NAME, Boolean.TRUE); marshaller.setProperty(ECLIPSELINK_JSON_MARSHAL_EMPTY_COLLECTIONS, Boolean.FALSE); } catch (PropertyException e) { // This is likely not the EclipseLink Marshaller. } } // Assign all other Marshaller properties. try { for (Map.Entry<String, Object> current : marshallerProperties.entrySet()) { marshaller.setProperty(current.getKey(), current.getValue()); } } catch (PropertyException e) { final StringBuilder builder = new StringBuilder("Could not assign Marshaller properties."); marshallerProperties.entrySet().stream() .forEach(c -> builder.append("\n [" + c.getKey() + "]: " + c.getValue())); throw new IllegalStateException(builder.toString(), e); } // Marshal the objects final StringWriter result = new StringWriter(); for (int i = 0; i < objects.length; i++) { final StringWriter tmp = new StringWriter(); try { marshaller.marshal(objects[i], tmp); result.write(tmp.toString()); } catch (JAXBException e) { final String currentTypeName = objects[i] == null ? "<null>" : objects[i].getClass().getName(); throw new IllegalArgumentException( "Could not marshalToXML object [" + i + "] of type [" + currentTypeName + "].", e); } catch (Exception e) { throw new IllegalArgumentException("Could not marshalToXML object [" + i + "]: " + objects[i], e); } } // All done. return result.toString(); }
From source file:edu.cornell.mannlib.semservices.service.impl.AgrovocService.java
/** * The code here utilizes the SKOSMOS REST API for Agrovoc * This returns JSON LD so we would parse JSON instead of RDF * The code above can still be utilized if we need to employ the web services directly */// w w w .jav a 2 s. co m //Get search results for a particular term and language code private String getSKOSMosSearchResults(String term, String lang) { String urlEncodedTerm = URLEncoder.encode(term); //Utilize 'starts with' using the * operator at the end String searchUrlString = this.conceptsSkosMosSearch + "query=" + urlEncodedTerm + "*" + "&lang=" + lang; URL searchURL = null; try { searchURL = new URL(searchUrlString); } catch (Exception e) { logger.error("Exception occurred in instantiating URL for " + searchUrlString, e); // If the url is having trouble, just return null for the concept return null; } String results = null; try { StringWriter sw = new StringWriter(); BufferedReader in = new BufferedReader(new InputStreamReader(searchURL.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { sw.write(inputLine); } in.close(); results = sw.toString(); logger.debug(results); } catch (Exception ex) { logger.error("Error occurred in getting concept from the URL " + searchUrlString, ex); return null; } return results; }
From source file:PSOResultFileReader.java
/** * Returns the next population in the file; or {@code null} if the end of * the file is reached. If the last entry in the file is incomplete, * {@code null} is returned./*from www .ja va2 s . c o m*/ * * @return the next population in the file; or {@code null} if the end of * the file is reached * @throws NumberFormatException if an error occurred parsing the objectives * @throws IOException if an I/O error occurred */ private ResultEntry readNextEntry() throws NumberFormatException, IOException { NondominatedPopulation population = new NondominatedPopulation(); StringWriter stringBuffer = new StringWriter(); // ignore any comment lines separating entries while ((line != null) && (line.startsWith("#"))) { line = reader.readLine(); } // if line is null here, kick out if ((line == null)) return null; // read next entry, terminated by # while ((line != null) && !line.startsWith("#")) { if (line.startsWith("//")) { stringBuffer.write(line.substring(2)); stringBuffer.write('\n'); } else { Solution solution = parseSolution(line); if (solution == null) { System.out.println("Null SOln found"); return null; } else { population.add(solution); } } line = reader.readLine(); } Properties properties = new Properties(); properties.load(new StringReader(stringBuffer.toString())); //JDH: only one population per file, so just use the damn thing // return population only if non-empty and terminated by a # //if ((line == null)) { || !line.startsWith("#")) { // System.out.println("Returnnig null from readnextentry"); // return null; //} else { return new ResultEntry(population, properties); //} }
From source file:org.botlibre.util.Utils.java
/** * Get the contents of the stream to a .self file and parse it. */// w ww . j a v a2s .c om public static String loadTextFile(InputStream stream, String encoding, int maxSize) { if (encoding.trim().isEmpty()) { encoding = "UTF-8"; } // FEFF because this is the Unicode char represented by the UTF-8 byte order mark (EF BB BF). String UTF8_BOM = "\uFEFF"; StringWriter writer = new StringWriter(); InputStreamReader reader = null; try { reader = new InputStreamReader(stream, encoding); int size = 0; int next = reader.read(); boolean first = true; while (next >= 0) { if (first && next == UTF8_BOM.charAt(0)) { // skip } else { writer.write(next); } next = reader.read(); if (size > maxSize) { throw new BotException( "File size limit exceeded: " + size + " > " + maxSize + " token: " + next); } size++; } } catch (IOException exception) { throw new BotException("IO Error: " + exception.getMessage(), exception); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignore) { } } if (stream != null) { try { stream.close(); } catch (IOException ignore) { } } } return writer.toString(); }