Java Code Examples for java.io.StringWriter

The following are top voted examples for showing how to use java.io.StringWriter. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: sphereMiners   File: ErrorPopup.java View source code Vote up 10 votes
public static void create(String titleText, String longMessage, @Nullable Throwable t) {
    Alert alert = new Alert(AlertType.ERROR);
    alert.setTitle("A Problem occured while running Sphere Miners");
    alert.setHeaderText(titleText);
    alert.setContentText(longMessage);

    if (t != null) {
        Label label = new Label("The exception stacktrace was:");

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        t.printStackTrace(pw);
        TextArea textArea = new TextArea(sw.toString());
        textArea.setEditable(false);
        textArea.setWrapText(true);

        textArea.setMaxWidth(Double.MAX_VALUE);
        textArea.setMaxHeight(Double.MAX_VALUE);
        GridPane.setVgrow(textArea, Priority.ALWAYS);
        GridPane.setHgrow(textArea, Priority.ALWAYS);

        GridPane expContent = new GridPane();
        expContent.setMaxWidth(Double.MAX_VALUE);
        expContent.add(label, 0, 0);
        expContent.add(textArea, 0, 1);

        // Set expandable Exception into the dialog pane.
        alert.getDialogPane().setExpandableContent(expContent);
    }
    alert.showAndWait();
}
 
Example 2
Project: phonegap-plugin-wizPurchase   File: Util.java View source code Vote up 10 votes
/** Returns the remainder of 'reader' as a string, closing it when done. */
public static String readFully(Reader reader) throws IOException {
  try {
    StringWriter writer = new StringWriter();
    char[] buffer = new char[1024];
    int count;
    while ((count = reader.read(buffer)) != -1) {
      writer.write(buffer, 0, count);
    }
    return writer.toString();
  } finally {
    reader.close();
  }
}
 
Example 3
Project: netlib   File: Encryption.java View source code Vote up 8 votes
/**
 * Converts RSA private key to PEM string.
 * 
 * @param rsaKeyPair
 * 
 * @return PEM string
 */
public static String getPEMStringFromRSAKeyPair(RSAKeyPair rsaKeyPair) {
    StringWriter pemStrWriter = new StringWriter();
    PEMWriter pemWriter = new PEMWriter(pemStrWriter);
    try {
        KeyPair keyPair = new KeyPair(rsaKeyPair.getPublic(), rsaKeyPair.getPrivate());
        //pemWriter.writeObject(keyPair);
        pemWriter.writeObject(keyPair.getPrivate());
        //pemWriter.flush();
        pemWriter.close();

    } catch (IOException e) {
        log.warning("Caught exception:" + e.getMessage());
        return "";
    }

    return pemStrWriter.toString();
}
 
Example 4
Project: angularjs-navigation-master-detail   File: Util.java View source code Vote up 8 votes
/** Returns the remainder of 'reader' as a string, closing it when done. */
public static String readFully(Reader reader) throws IOException {
  try {
    StringWriter writer = new StringWriter();
    char[] buffer = new char[1024];
    int count;
    while ((count = reader.read(buffer)) != -1) {
      writer.write(buffer, 0, count);
    }
    return writer.toString();
  } finally {
    reader.close();
  }
}
 
Example 5
Project: jentrata-msh   File: IOHandler.java View source code Vote up 7 votes
/**
 * Reads a string from a reader.
 * 
 * @param reader the reader to be read.
 * @return a string read from the specified reader.
 * @throws IOException if there is IO error occurred during the operation.
 */
public static String readString(Reader reader) throws IOException {
    StringWriter writer = new StringWriter();
    pipe(reader, writer);
    String s = writer.toString();
    writer.close();
    return s;
}
 
Example 6
Project: jboss-dmr   File: ListModelValue.java View source code Vote up 7 votes
@Override
String asString() {
    final StringWriter stringWriter = new StringWriter();
    final PrintWriter writer = new PrintWriter(stringWriter, true);
    format(writer, 0, false);
    return stringWriter.toString();
}
 
Example 7
Project: aws-toolkit-eclipse   File: CodeTemplateManager.java View source code Vote up 7 votes
public static String processTemplateWithData(Template template,
        Object templateData) throws TemplateException, IOException {
    StringWriter sw = new StringWriter();
    template.process(templateData, sw);
    sw.flush();
    return sw.toString();
}
 
Example 8
Project: iswc2012metadata   File: ToolJena.java View source code Vote up 7 votes
public static String printModelToString(Model m, String sz_rdfsyntax, String sz_namespace) {
	try {
		StringWriter sw = new StringWriter();
		printModelToWriter(m, sz_rdfsyntax, sz_namespace, sw);
		return sw.toString();
	} catch (IOException e) {
		e.printStackTrace();
		return "";
	}
}
 
Example 9
Project: dlna   File: FixedAndroidHandler.java View source code Vote up 7 votes
@Override
public String format(LogRecord r) {
    Throwable thrown = r.getThrown();
    if (thrown != null) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        sw.write(r.getMessage());
        sw.write("\n");
        thrown.printStackTrace(pw);
        pw.flush();
        return sw.toString();
    } else {
        return r.getMessage();
    }
}
 
Example 10
Project: virgo.kernel   File: ManifestUtils.java View source code Vote up 7 votes
/**
 * Creates a [email protected] Reader} for the manifest in the supplied JAR file.
 * 
 * @param file the JAR file.
 * @return the <code>Reader</code> or <code>null</code> if the manifest cannot be found.
 */
public static final Reader manifestReaderFromJar(File file) {
    JarFile jar = null;
    try {
        jar = new JarFile(file);
        JarEntry entry = jar.getJarEntry(MANIFEST_ENTRY);
        if (entry != null) {
            StringWriter writer = new StringWriter();
            FileCopyUtils.copy(new InputStreamReader(jar.getInputStream(entry)), writer);
            jar.close();
            return new StringReader(writer.toString());
        } else {
            return null;
        }
    } catch (Exception e) {
        throw new RuntimeException("Cannot read MANIFEST.MF from jar '" + file.getAbsolutePath() + "'.", e);
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException ioe) {
                throw new RuntimeException("Failed to close jar '" + file.getAbsolutePath() + "'.", ioe);
            }
        }
    }
}
 
Example 11
Project: richfaces   File: Test.java View source code Vote up 7 votes
static void testStandardReaders() throws IOException {
    String s = "This is a senseless text to test readers.\n";

    for (int i = 0; i < 10; i++) {
        s = s + s; // repeated 16 times
    }

    char[] bytes = s.toCharArray();
    StringWriter output = new StringWriter(16);

    // write it several times.
    for (int i = 0; i < 4; i++) {
        output.write(bytes);
    }

    // write it one more time by one byte
    for (int i = 0; i < bytes.length; i++) {
        output.write(bytes[i]);
    }

    StringReader input = new StringReader(output.toString());
    StringBuffer sb = new StringBuffer();

    // use for reading unconvenient array length.
    char[] bs = new char[ARRAY_LENGTH];
    int l = 0;

    while ((l = input.read(bs, READ_OFF, READ_LENGTH)) >= 0) {
        if (BUILD_STRING) {
            sb.append(new String(bs, READ_OFF, l));
        }
    }

    if (BUILD_STRING && OUT_STRING) {
        System.out.println(sb);
    }
}
 
Example 12
Project: CaptureJSP   File: SwallowingJspRenderer.java View source code Vote up 7 votes
public String render(String viewName, Map<String,Object> modelMap, Locale locale) throws IOException {
	String result = null;
	
	if(locale == null) {
		locale = Locale.getDefault();
	}
	
	// These String objects are used to capture the output
	// of SwallowingHttpServletResponse
	StringWriter sout = new StringWriter();
	StringBuffer sbuffer = sout.getBuffer();
	
	// Set up a fake request and response.  We need the mock response
	// so that we can create the Swallowing response
	HttpServletRequest request = new MockIncludedHttpServletRequest();		
	HttpServletResponse response = new MockHttpServletResponse();
	HttpServletResponse swallowingResponse = new SwallowingHttpServletResponse(response, sout, "UTF-8");

	// Use our own LocaleResolver here, or Spring will try to meddle with it
	LocaleResolver localeResolver = new JspLocaleResolver();
	localeResolver.setLocale(request, swallowingResponse, locale);
	
	try {			
		//Add the modelMap to the request as attributes
		addModelAsRequestAttributes(request, modelMap);
		
		// Push our LocaleResolver into the request
		request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, localeResolver);			
		
		// Push our Locale into the request
		LocalizationContext localizationContext = new LocalizationContext(null, locale);
		request.setAttribute(Config.FMT_LOCALIZATION_CONTEXT+".request", localizationContext);
		request.setAttribute(Config.FMT_LOCALE, locale);
		
		// Make sure we are using UTF-8 for the rendered JSP
		swallowingResponse.setContentType("text/html; charset=utf-8");
		
		// "include" the file (but not really an include) with the dispatcher
		// The resulting rendering will come out in swallowing response,
		// via sbuffer
		RequestDispatcher dispatcher = servletContext.getRequestDispatcher(viewResolver.urlForView(viewName));
		
		dispatcher.include(request, swallowingResponse);
		
		result = sbuffer.toString();
	} catch(Exception e) {
		throw new IOException(e);
	}
	
	return result;
}
 
Example 13
Project: jasper-xml-to-pdf-generator   File: JasperPdfGenerator.java View source code Vote up 7 votes
private String applyVelocityTemplate(String templateData) throws Exception {
    Properties properties = new Properties();
    properties.setProperty("resource.loader", "string");
    properties.setProperty("string.resource.loader.class", "org.apache.velocity.runtime.resource.loader.StringResourceLoader");
    properties.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem");
    properties.setProperty("userdirective",
            "com.github.xmltopdf.MoneyUAHDirective,"
            + "com.github.xmltopdf.MoneyToStrDirective,"
            + "com.github.xmltopdf.DateDirective,"
            + "com.github.xmltopdf.UkrToLatinDirective");
    Velocity.init(properties);

    StringResourceRepository repo = StringResourceLoader.getRepository();
    repo.putStringResource("template", templateData);
    Template template = Velocity.getTemplate("template", "UTF-8");
    StringWriter writer = new StringWriter();
    VelocityContext context = new VelocityContext();
    context.put("xml", xmlTag);
    template.merge(context, writer);
    writer.flush();
    writer.close();
    return writer.toString();
}
 
Example 14
Project: Desktop   File: MapStyle.java View source code Vote up 7 votes
public void writeContent(final ITreeWriter writer, final Object object, final IExtension extension)
        throws IOException {
	final MapStyleModel mapStyleModel = (MapStyleModel) extension;
	final MapModel styleMap = mapStyleModel.getStyleMap();
	final String el = System.getProperty("line.separator");
	if (styleMap == null) {
		return;
	}
	final MapWriter mapWriter = Controller.getCurrentModeController().getMapController().getMapWriter();
	final StringWriter sw = new StringWriter();
	sw.append(el);
	sw.append("<map_styles>");
	sw.append(el);
	final NodeModel rootNode = styleMap.getRootNode();
	final boolean forceFormatting = Boolean.TRUE.equals(writer.getHint(MapWriter.WriterHint.FORCE_FORMATTING));
	try {
		mapWriter.writeNodeAsXml(sw, rootNode, Mode.STYLE, true, true, forceFormatting);
	}
	catch (final IOException e) {
		e.printStackTrace();
	}
	sw.append("</map_styles>");
	sw.append(el);
	final XMLElement element = new XMLElement("hook");
	saveExtension(extension, element);
	writer.addElement(sw.toString(), element);
}
 
Example 15
Project: appengine-java-vm-runtime   File: VmRuntimeWebAppContext.java View source code Vote up 7 votes
/**
 * [email protected]}
 *
 * @param throwable an exception associated with this log message,
 * or [email protected] null}.
 */
@Override
public void log(String message, Throwable throwable) {
  StringWriter writer = new StringWriter();
  writer.append("javax.servlet.ServletContext log: ");
  writer.append(message);

  if (throwable != null) {
    writer.append("\n");
    throwable.printStackTrace(new PrintWriter(writer));
  }

  LogRecord.Level logLevel = throwable == null ? LogRecord.Level.info : LogRecord.Level.error;
  ApiProxy.log(new ApiProxy.LogRecord(logLevel, System.currentTimeMillis() * 1000L,
      writer.toString()));
}
 
Example 16
Project: i2p.android.base   File: PeersFragment.java View source code Vote up 7 votes
public void update() {
    WebView wv = (WebView) getActivity().findViewById(R.id.peers_webview);
    wv.clearHistory(); // fixes having to hit back.
    CommSystemFacade comm = getCommSystem();
    String data;
    if (comm != null) {
        StringWriter out = new StringWriter(32*1024);
        out.append(HEADER);
        try {
            comm.renderStatusHTML(out, "http://thiswontwork.i2p/peers", 0);
            out.append(FOOTER);
            data = out.toString().replaceAll("/themes", "themes");
        } catch (IOException ioe) {
            data = HEADER + "Error: " + ioe + FOOTER;
        }
    } else {
        data = HEADER + "No peer data available. The router is not running." + FOOTER;
    }
    try {
        // wv.loadData(data, "text/html", "UTF-8");
        // figure out a way to get /themes/console/images/outbound.png to load
        // String url = "file://" + _myDir + "/docs/";
        String url = "file:///android_asset/";
        wv.loadDataWithBaseURL(url, data, "text/html", "UTF-8", url);
    } catch (Exception e) {
    }
}
 
Example 17
Project: Curators-Workbench   File: MdSecTypePropertySection.java View source code Vote up 7 votes
String getXMLText(MdSecType mdSec) {
	StringWriter sw = new StringWriter();
	try {
		EObject o = (EObject) mdSec.getMdWrap().getXmlData().getAny().getValue(0);
		Map<Object, Object> options = new HashMap<Object, Object>();
		options.put(XMLResource.OPTION_ENCODING, "utf-8");
		options.put(XMLResource.OPTION_LINE_WIDTH, new Integer(80));
		options.put(XMLResource.OPTION_ROOT_OBJECTS, Collections.singletonList(o));
		((XMLResource) o.eResource()).save(sw, options);
	} catch (Exception ignored) {
		sw.append("failed to serialize XML for model object");
	}
	return sw.toString();
}
 
Example 18
Project: jentrata-msh   File: Headers.java View source code Vote up 6 votes
/**
 * Gets the headers as an input stream from the underlying request object.
 * 
 * @return an input stream of the headers.
 */
public InputStream getInputStreamHeaders() {
    StringWriter headers = new StringWriter();
    addHeaders(headers);
    headers.write("\r\n");
    return new ByteArrayInputStream(headers.toString().getBytes());
}
 
Example 19
Project: phonegap-geolocation   File: Util.java View source code Vote up 6 votes
/** Returns the remainder of 'reader' as a string, closing it when done. */
public static String readFully(Reader reader) throws IOException {
  try {
    StringWriter writer = new StringWriter();
    char[] buffer = new char[1024];
    int count;
    while ((count = reader.read(buffer)) != -1) {
      writer.write(buffer, 0, count);
    }
    return writer.toString();
  } finally {
    reader.close();
  }
}
 
Example 20
Project: webstart   File: JarDiff.java View source code Vote up 6 votes
/**
 * Writes the index file out to <code>jos</code>.
 * <code>oldEntries</code> gives the names of the files that were removed,
 * <code>movedMap</code> maps from the new name to the old name.
 */
private static void createIndex( JarOutputStream jos, List oldEntries, Map movedMap )
    throws IOException
{
    StringWriter writer = new StringWriter();

    writer.write( VERSION_HEADER );
    writer.write( "\r\n" );

    // Write out entries that have been removed
    for ( Object oldEntry : oldEntries )
    {
        String name = (String) oldEntry;

        writer.write( REMOVE_COMMAND );
        writer.write( " " );
        writeEscapedString( writer, name );
        writer.write( "\r\n" );
    }

    // And those that have moved

    for ( Object o : movedMap.keySet() )
    {
        String newName = (String) o;
        String oldName = (String) movedMap.get( newName );

        writer.write( MOVE_COMMAND );
        writer.write( " " );
        writeEscapedString( writer, oldName );
        writer.write( " " );
        writeEscapedString( writer, newName );
        writer.write( "\r\n" );
    }

    JarEntry je = new JarEntry( INDEX_NAME );
    byte[] bytes = writer.toString().getBytes( "UTF-8" );

    writer.close();
    jos.putNextEntry( je );
    jos.write( bytes, 0, bytes.length );
}
 
Example 21
Project: appstatus   File: BatchDao.java View source code Vote up 6 votes
private String clobToString(Clob clob) throws SQLException, IOException {
	if (clob == null)
		return null;

	InputStream in = clob.getAsciiStream();
	Reader read = new InputStreamReader(in);
	StringWriter w = new StringWriter();

	int c = -1;
	while ((c = read.read()) != -1) {
		w.write(c);
	}
	w.flush();
	return StringUtils.trim(w.toString());
}
 
Example 22
Project: fiji   File: Clojure_Interpreter.java View source code Vote up 6 votes
private StringBuffer parse() throws Throwable {
	// prepare input for parser
	final LineNumberingPushbackReader lnpr = new LineNumberingPushbackReader(input_reader);
	// storage for readout
	final StringWriter sw = new StringWriter();

	Object ret = null;

	final Thread thread = Thread.currentThread();

	while (!thread.isInterrupted()) {
		// read one token from the pipe
		Object r = LispReader.read(lnpr, false, EOF, false);
		if (EOF == r) {
			break;
		}
		// evaluate the tokens returned by the LispReader
		ret = Compiler.eval(r);
		// print the result in a lispy way
		RT.print(ret, sw);
		sw.write('\n');
	}

	if (thread.isInterrupted()) {
		// cleanup:
		Var.popThreadBindings();
		return null;
	}

	// update *1, *2, *3, even if null
	Object ob = star2.get();
	Var.pushThreadBindings(RT.map(star3, ob));
	ob = star1.get();
	Var.pushThreadBindings(RT.map(star2, ob));
	// The last returned object of whatever was executed gets set to star1
	Var.pushThreadBindings(RT.map(star1, ret));

	return sw.getBuffer();
}
 
Example 23
Project: eclipse-integration-commons   File: ArrayEncoder.java View source code Vote up 6 votes
public static String encode(String[] strings) {
	StringWriter out = new StringWriter(BUFFER_SIZE);
	for (String string : strings) {
		for (int i = 0; i < string.length(); i++) {
			char c = string.charAt(i);
			if (c==ESCAPE_CHAR || c==TERMINATOR_CHAR) {
				out.write(ESCAPE_CHAR);
			}
			out.write(c);
		}
		out.write(TERMINATOR_CHAR);
	};
	return out.toString();
}
 
Example 24
Project: xface-android   File: Util.java View source code Vote up 6 votes
/** Returns the remainder of 'reader' as a string, closing it when done. */
public static String readFully(Reader reader) throws IOException {
  try {
    StringWriter writer = new StringWriter();
    char[] buffer = new char[1024];
    int count;
    while ((count = reader.read(buffer)) != -1) {
      writer.write(buffer, 0, count);
    }
    return writer.toString();
  } finally {
    reader.close();
  }
}
 
Example 25
Project: hivemall   File: UDTFWithOptions.java View source code Vote up 6 votes
protected final CommandLine parseOptions(String optionValue) throws UDFArgumentException {
    String[] args = optionValue.split("\\s+");
    Options opts = getOptions();
    opts.addOption("help", false, "Show function help");
    CommandLine cl = CommandLineUtils.parseOptions(args, opts);

    if(cl.hasOption("help")) {
        Description funcDesc = getClass().getAnnotation(Description.class);
        final String cmdLineSyntax;
        if(funcDesc == null) {
            cmdLineSyntax = getClass().getSimpleName();
        } else {
            String funcName = funcDesc.name();
            cmdLineSyntax = funcName == null ? getClass().getSimpleName()
                    : funcDesc.value().replace("_FUNC_", funcDesc.name());
        }
        StringWriter sw = new StringWriter();
        sw.write('\n');
        PrintWriter pw = new PrintWriter(sw);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(pw, HelpFormatter.DEFAULT_WIDTH, cmdLineSyntax, null, opts, HelpFormatter.DEFAULT_LEFT_PAD, HelpFormatter.DEFAULT_DESC_PAD, null, true);
        pw.flush();
        String helpMsg = sw.toString();
        throw new UDFArgumentException(helpMsg);
    }

    return cl;
}
 
Example 26
Project: SOLR   File: DocumentAnalysisRequest.java View source code Vote up 6 votes
/**
 * Returns the xml be be set as the request body.
 *
 * @return The xml be be set as the request body.
 *
 * @throws IOException When constructing the xml fails
 */
String getXML() throws IOException {
  StringWriter writer = new StringWriter();
  writer.write("<docs>");
  for (SolrInputDocument document : documents) {
    ClientUtils.writeXML(document, writer);
  }
  writer.write("</docs>");
  writer.flush();

  String xml = writer.toString();
  return (xml.length() > 0) ? xml : null;
}
 
Example 27
Project: pg-twit   File: Util.java View source code Vote up 6 votes
/** Returns the remainder of 'reader' as a string, closing it when done. */
public static String readFully(Reader reader) throws IOException {
  try {
    StringWriter writer = new StringWriter();
    char[] buffer = new char[1024];
    int count;
    while ((count = reader.read(buffer)) != -1) {
      writer.write(buffer, 0, count);
    }
    return writer.toString();
  } finally {
    reader.close();
  }
}
 
Example 28
Project: HugeCollections   File: OSResizesMain.java View source code Vote up 6 votes
static String run(String... cmd) throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder(cmd);
    pb.redirectErrorStream(true);
    Process p = pb.start();
    InputStreamReader reader = new InputStreamReader(p.getInputStream());
    StringWriter sw = new StringWriter();
    char[] chars = new char[512];
    for (int len; (len = reader.read(chars)) > 0; )
        sw.write(chars, 0, len);
    int exitValue = p.waitFor();
    if (exitValue != 0)
        sw.write("\nexit=" + exitValue);
    p.destroy();
    return sw.toString();
}
 
Example 29
Project: Developing-with-Cordova   File: Util.java View source code Vote up 6 votes
/** Returns the remainder of 'reader' as a string, closing it when done. */
public static String readFully(Reader reader) throws IOException {
  try {
    StringWriter writer = new StringWriter();
    char[] buffer = new char[1024];
    int count;
    while ((count = reader.read(buffer)) != -1) {
      writer.write(buffer, 0, count);
    }
    return writer.toString();
  } finally {
    reader.close();
  }
}
 
Example 30
Project: JAME   File: JXTANetworkService.java View source code Vote up 6 votes
@SuppressWarnings("unchecked")
private static void printAdvertisement(final Advertisement adv) {
	try {
		final StructuredTextDocument doc = (StructuredTextDocument) adv.getDocument(MimeMediaType.XMLUTF8);
		final StringWriter out = new StringWriter();
		doc.sendToWriter(out);
		logger.fine(out.toString());
		out.close();
	}
	catch (final Exception e) {
	}
}
 
Example 31
Project: wso2-synapse   File: JsonXMLMapperTest.java View source code Vote up 6 votes
@Test
public void testWriteXmlRootElement() throws Exception {
    JsonXMLMapper<SampleRootElement> mapper = new JsonXMLMapper<SampleRootElement>(SampleRootElement.class);
    StringWriter writer = new StringWriter();
    SampleRootElement value = new SampleRootElement();
    mapper.writeObject(writer, value);
    writer.close();
    Assert.assertEquals("{\"sampleRootElement\":null}", writer.toString());
}
 
Example 32
Project: koubei-mongo   File: MongoUtil.java View source code Vote up 6 votes
/**
 * 
 * @param object
 * @return
 * @throws IOException
 */
public static String objectToJson(Object object) throws IOException {

	String json = null;

	ObjectMapper mapper = MongoMapper.getInstance();
	StringWriter writer = new StringWriter();
	JsonGenerator generator = new JsonFactory().createJsonGenerator(writer);
	mapper.writeValue(generator, object);
	generator.close();
	json = writer.toString();
	writer.close();

	return json;
}
 
Example 33
Project: sw606f13   File: StationConfiguration.java View source code Vote up 6 votes
/**
 * Write the station to a string.<br />
 * Example format: category,pictogram,pictogram
 * @return String representation of the station.
 * @throws IOException
 */
public String writeStation() throws IOException {
	StringWriter sWriter = new StringWriter(1024);
	
	sWriter.write(String.valueOf(this.category));
	
	for(Long pictogram : acceptPictograms) {
		sWriter.append(",");
		sWriter.write(String.valueOf(pictogram));
	}
	
	String result = sWriter.toString();
	sWriter.close();
	
	return result;
}
 
Example 34
Project: pentaho-metadata-editor   File: Const.java View source code Vote up 6 votes
/**
 * Returns a string of the stack trace of the specified exception
 */
public static final String getStackTracker(Throwable e)
{
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    e.printStackTrace(printWriter);
    String string = stringWriter.getBuffer().toString();
    try { stringWriter.close(); } catch(IOException ioe) {} // is this really required?
    return string;
}
 
Example 35
Project: violetumleditor   File: XHTMLPersistenceService.java View source code Vote up 6 votes
@Override
public IGraph read(InputStream in) throws IOException
{
    InputStreamReader reader = new InputStreamReader(in, "UTF-8");
	XHTMLPersistenceServiceParserGetter kit = new XHTMLPersistenceServiceParserGetter();
    HTMLEditorKit.Parser parser = kit.getParser();
    StringWriter writer = new StringWriter();
    HTMLEditorKit.ParserCallback callback = new XHTMLPersistenceServiceParserCallback(writer);
    parser.parse(reader, callback, true);
    String xmlContent = writer.toString();
    InputStream xmlContentStream = new ByteArrayInputStream(xmlContent.getBytes());
    IGraph graph = this.xstreamService.read(xmlContentStream);
    reader.close();
    xmlContentStream.close();
    reader.close();
    writer.close();
    return graph;
}
 
Example 36
Project: JFugue-for-Android   File: TransformerImpl.java View source code Vote up 6 votes
/**
 * Take the contents of a template element, process it, and
 * convert it to a string.
 *
 * @param elem The parent element whose children will be output
 * as a string.
 *
 * @return The stringized result of executing the elements children.
 *
 * @throws javax.xml.transform.TransformerException
 * @xsl.usage advanced
 */
public String transformToString(ElemTemplateElement elem)
        throws TransformerException
{
  ElemTemplateElement firstChild = elem.getFirstChildElem();
  if(null == firstChild)
    return "";
  if(elem.hasTextLitOnly() && m_optimizer)
  {
    return ((ElemTextLiteral)firstChild).getNodeValue();
  }

  // Save the current result tree handler.
  SerializationHandler savedRTreeHandler = this.m_serializationHandler;

  // Create a Serializer object that will handle the SAX events 
  // and build the ResultTreeFrag nodes.
  StringWriter sw = (StringWriter) m_stringWriterObjectPool.getInstance();

  m_serializationHandler =
      (ToTextStream) m_textResultHandlerObjectPool.getInstance();

    if (null == m_serializationHandler)
    {
      // if we didn't get one from the pool, go make a new one

      
      Serializer serializer = org.apache.xml.serializer.SerializerFactory.getSerializer(
          m_textformat.getProperties());
      m_serializationHandler = (SerializationHandler) serializer;
    } 

      m_serializationHandler.setTransformer(this);
      m_serializationHandler.setWriter(sw);
 
 
  String result;

  try
  {
      /* Don't call startDocument, the SerializationHandler  will
       * generate its own internal startDocument call anyways
       */
    // this.m_serializationHandler.startDocument();

    // Do the transformation of the child elements.
    executeChildTemplates(elem, true);
      this.m_serializationHandler.endDocument();

    result = sw.toString();
  }
  catch (SAXException se)
  {
    throw new TransformerException(se);
  }
  finally
  {
    sw.getBuffer().setLength(0);

    try
    {
      sw.close();
    }
    catch (Exception ioe){}

    m_stringWriterObjectPool.freeInstance(sw);
    m_serializationHandler.reset();
    m_textResultHandlerObjectPool.freeInstance(m_serializationHandler);

    // Restore the previous result tree handler.
    m_serializationHandler = savedRTreeHandler;
  }

  return result;
}
 
Example 37
Project: dswarm-graph-neo4j   File: MaintainResource.java View source code Vote up 6 votes
/**
 * note utilise this endpoint with care, because it cleans your complete db!
 *
 * @param database the graph database
 */
@DELETE
@Path("/delete")
@Produces("application/json")
public Response cleanGraph(@Context final GraphDatabaseService database) throws IOException, DMPGraphException {

	MaintainResource.LOG.debug("start cleaning up the db");

	final long deleted = deleteSomeStatements(database);

	MaintainResource.LOG.debug("finished delete-all-entities TXs");

	MaintainResource.LOG.debug("start legacy indices clean-up");

	// TODO: maybe separate index clean-up + observe index clean-up
	// => maybe we also need to do a label + relationship types clean-up ... => this is not supported right now ...

	deleteSomeLegacyIndices(database);

	MaintainResource.LOG.debug("finished legacy indices clean-up");

	MaintainResource.LOG.debug("start schema indices clean-up");

	deleteSomeSchemaIndices(database);

	MaintainResource.LOG.debug("finished schema indices clean-up");

	MaintainResource.LOG.debug("finished cleaning up the db");

	final StringWriter out = new StringWriter();
	final JsonGenerator generator = simpleObjectMapper.getFactory().createGenerator(out);

	generator.writeStartObject();
	generator.writeNumberField("deleted", deleted);
	generator.writeEndObject();
	generator.flush();
	generator.close();

	final String result = out.toString();

	out.flush();
	out.close();

	return Response.ok(result, MediaType.APPLICATION_JSON_TYPE).build();
}
 
Example 38
Project: org.openscience.cdk   File: RModel.java View source code Vote up 6 votes
private void loadRFunctionsAsStrings(Rengine evaluator) {
    String[] scripts = {
            "helper.R",
    };
    String scriptPrefix = "org/openscience/cdk/qsar/model/data/";
    for (int i = 0; i < scripts.length; i++) {

        String scriptLocator = scriptPrefix + scripts[i];
        try {
            InputStreamReader reader = new InputStreamReader(
                    this.getClass().getClassLoader().getResourceAsStream(scriptLocator));
            BufferedReader inFile = new BufferedReader(reader);

            StringWriter sw = new StringWriter();
            String inputLine;
            while ((inputLine = inFile.readLine()) != null) {
                sw.write(inputLine);
                sw.write("\n");
            }
            sw.close();

            evaluator.eval("eval(parse(text=\"" + sw.toString() + "\"))");

        } catch (Exception exception) {
            logger.error("Could not load CDK-rJava R scripts: ", scriptLocator);
            logger.debug(exception);
        }

    }
}
 
Example 39
Project: dbfound   File: TreeGrid.java View source code Vote up 6 votes
public void executeFreemarker(Writer out) {
	try {
		Configuration cfg = FreemarkFactory.getConfig(pageContext
				.getServletContext());
		// ??Template??
		Template template = cfg.getTemplate(templateName);
		// ????
		Map<String, Object> root = new HashMap<String, Object>();

		if (id == null || "".equals(id)) {
			id = "TG" + UUIDUtil.getRandomString(6);
		}
		root.put("tree", this);
		root.put("columns", getColumns().getColumns());

		ToolBar toolBar = getToolBar();
		if (toolBar != null) {
			List<GridButton> buttons = toolBar.getButtons();
			if (buttons != null) {
				root.put("buttons", buttons);
			}
		}

		String div = "<div style='margin-left:5px;margin-right:5px;margin-top:5px;margin-bottom:5px;"
				+ style + "' id='" + id + "_div'></div>";
		Tag t = findAncestorWithClass(this, Panel.class);
		if (t != null && findAncestorWithClass(this, Div.class) == null) {
			Panel parent = (Panel) t;
			if (parent.contentCmp == null) {
				parent.contentCmp = "'" + id + "'";
			} else {
				parent.contentCmp += ",'" + id + "'";
			}
			try {
				out = new StringWriter();
				parent.html += div;
				template.process(root, out);
				parent.content.append(out);
			} finally {
				out.close();
			}
		} else {
			root.put("div", div);
			template.process(root, out);
		}
	} catch (Exception e) {
		LogUtil.error(e.getMessage(), e);
	}
}
 
Example 40
Project: MinecraftSecondScreenMod   File: JSONArray.java View source code Vote up 6 votes
/**
 * Make a prettyprinted JSON text of this JSONArray. Warning: This method
 * assumes that the data structure is acyclical.
 * 
 * @param indentFactor
 *            The number of spaces to add to each level of indentation.
 * @return a printable, displayable, transmittable representation of the
 *         object, beginning with <code>[</code>&nbsp;<small>(left
 *         bracket)</small> and ending with <code>]</code>
 *         &nbsp;<small>(right bracket)</small>.
 * @throws JSONException
 */
public String toString(int indentFactor) throws JSONException {
	StringWriter sw = new StringWriter();
	synchronized (sw.getBuffer()) {
		return this.write(sw, indentFactor, 0).toString();
	}
}
 
Example 41
Project: SOLR   File: TestHarness.java View source code Vote up 6 votes
/**
 * A helper that creates an xml &lt;doc&gt; containing all of the
 * fields and values specified
 *
 * @param fieldsAndValues 0 and Even numbered args are fields names odds are field values.
 */
public static StringBuffer makeSimpleDoc(String... fieldsAndValues) {

  try {
    StringWriter w = new StringWriter();
    w.append("<doc>");
    for (int i = 0; i < fieldsAndValues.length; i+=2) {
      XML.writeXML(w, "field", fieldsAndValues[i+1], "name",
                   fieldsAndValues[i]);
    }
    w.append("</doc>");
    return w.getBuffer();
  } catch (IOException e) {
    throw new RuntimeException
      ("this should never happen with a StringWriter", e);
  }
}
 
Example 42
Project: r2015   File: JSONArray.java View source code Vote up 6 votes
/**
 * Make a prettyprinted JSON text of this JSONArray. Warning: This method
 * assumes that the data structure is acyclical.
 *
 * @param indentFactor
 *            The number of spaces to add to each level of indentation.
 * @return a printable, displayable, transmittable representation of the
 *         object, beginning with <code>[</code>&nbsp;<small>(left
 *         bracket)</small> and ending with <code>]</code>
 *         &nbsp;<small>(right bracket)</small>.
 * @throws JSONException
 */
public String toString(int indentFactor) throws JSONException {
    StringWriter sw = new StringWriter();
    synchronized (sw.getBuffer()) {
        return this.write(sw, indentFactor, 0).toString();
    }
}
 
Example 43
Project: Jorum-DSpace   File: LicenseCleanup.java View source code Vote up 6 votes
/**
 * Process Item, correcting CC-License if encountered.
 * @param item
 * @throws SQLException
 * @throws AuthorizeException
 * @throws IOException
 */
protected static void handleItem(Item item) throws SQLException,
        AuthorizeException, IOException
{
    Bundle[] bundles = item.getBundles("CC-LICENSE");

    if (bundles == null || bundles.length == 0)
        return;

    Bundle bundle = bundles[0];

    Bitstream bitstream = bundle.getBitstreamByName("license_rdf");

    String license_rdf = new String(copy(bitstream));

    /* quickly fix xml by ripping out offensive parts */
    license_rdf = license_rdf.replaceFirst("<license", "");
    license_rdf = license_rdf.replaceFirst("</license>", "");

    StringWriter result = new StringWriter();

    try
    {
        templates.newTransformer().transform(
                new StreamSource(new ByteArrayInputStream(license_rdf
                        .getBytes())), new StreamResult(result));
    }
    catch (TransformerException e)
    {
        throw new RuntimeException(e.getMessage(), e);
    }

    StringBuffer buffer = result.getBuffer();

    Bitstream newBitstream = bundle
            .createBitstream(new ByteArrayInputStream(buffer.toString()
                    .getBytes()));

    newBitstream.setName(bitstream.getName());
    newBitstream.setDescription(bitstream.getDescription());
    newBitstream.setFormat(bitstream.getFormat());
    newBitstream.setSource(bitstream.getSource());
    newBitstream.setUserFormatDescription(bitstream
            .getUserFormatDescription());
    newBitstream.update();

    bundle.removeBitstream(bitstream);

    bundle.update();

}
 
Example 44
Project: processing-shellmaker   File: JSONArray.java View source code Vote up 6 votes
/**
 * Make a pretty-printed JSON text of this JSONArray.
 * Warning: This method assumes that the data structure is acyclical.
 * @param indentFactor The number of spaces to add to each level of
 *  indentation. Use -1 to specify no indentation and no newlines.
 * @return a printable, displayable, transmittable
 *  representation of the object, beginning
 *  with <code>[</code>&nbsp;<small>(left bracket)</small> and ending
 *  with <code>]</code>&nbsp;<small>(right bracket)</small>.
 */
public String format(int indentFactor) {
  StringWriter sw = new StringWriter();
  synchronized (sw.getBuffer()) {
    return this.write(sw, indentFactor, 0).toString();
  }
}
 
Example 45
Project: gpu-garbage-collection   File: OptimizingCompilerException.java View source code Vote up 6 votes
/**
 * Return a string that is the printout of level stackframes in the stacktrace.
 * @param level the number of levels to print
 * @return n-level dump of stacktrace
 */
public String trace(int level) {
  StringWriter sw = new StringWriter();
  PrintWriter pw = new PrintWriter(sw);
  printStackTrace(pw);
  int count = 0, i = 0;
  StringBuffer sb = sw.getBuffer();
  for (; i < sb.length() && count < level + 1; i++) {
    if (sb.charAt(i) == '\n') {
      count++;
    }
  }
  sb.setLength(i);
  return sb.toString();
}
 
Example 46
Project: dragome-sdk   File: TwoColumnOutput.java View source code Vote up 6 votes
/**
 * Constructs an instance.
 * 
 * @param out [email protected] non-null;} writer to send final output to
 * @param leftWidth [email protected] > 0;} width of the left column, in characters
 * @param rightWidth [email protected] > 0;} width of the right column, in characters
 * @param spacer [email protected] non-null;} spacer string to sit between the two columns
 */
public TwoColumnOutput(Writer out, int leftWidth, int rightWidth,
                       String spacer) {
    if (out == null) {
        throw new NullPointerException("out == null");
    }

    if (leftWidth < 1) {
        throw new IllegalArgumentException("leftWidth < 1");
    }

    if (rightWidth < 1) {
        throw new IllegalArgumentException("rightWidth < 1");
    }

    if (spacer == null) {
        throw new NullPointerException("spacer == null");
    }

    StringWriter leftWriter = new StringWriter(1000);
    StringWriter rightWriter = new StringWriter(1000);

    this.out = out;
    this.leftWidth = leftWidth;
    this.leftBuf = leftWriter.getBuffer();
    this.rightBuf = rightWriter.getBuffer();
    this.leftColumn = new IndentingWriter(leftWriter, leftWidth);
    this.rightColumn =
        new IndentingWriter(rightWriter, rightWidth, spacer);
}
 
Example 47
Project: jeboorker   File: JSONArray.java View source code Vote up 6 votes
/**
 * Make a prettyprinted JSON text of this JSONArray.
 * Warning: This method assumes that the data structure is acyclical.
 * @param indentFactor The number of spaces to add to each level of
 *  indentation.
 * @return a printable, displayable, transmittable
 *  representation of the object, beginning
 *  with <code>[</code>&nbsp;<small>(left bracket)</small> and ending
 *  with <code>]</code>&nbsp;<small>(right bracket)</small>.
 * @throws JSONException
 */
public String toString(int indentFactor) throws JSONException {
    StringWriter sw = new StringWriter();
    synchronized (sw.getBuffer()) {
        return this.write(sw, indentFactor, 0).toString();
    }
}
 
Example 48
Project: OpenClinica   File: SecureController.java View source code Vote up 6 votes
public static String getStackTrace(Throwable t) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw, true);
    t.printStackTrace(pw);
    pw.flush();
    sw.flush();
    return sw.toString();
}
 
Example 49
Project: sql-layer   File: MultipleCauseException.java View source code Vote up 6 votes
@Override
public String toString() {
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    printWriter.printf("%d cause%s%n", causes.size(), causes.size() == 1 ? ":" : "s:");
    for (Enumerated<Throwable> cause : EnumeratingIterator.of(causes)) {
        printWriter.printf("%d:%n----------------------------%n", cause.count());
        cause.get().printStackTrace(printWriter);
    }
    printWriter.flush();
    stringWriter.flush();
    return stringWriter.toString();
}
 
Example 50
Project: jeboorker   File: IOUtil.java View source code Vote up 6 votes
/**
 * Gets the contents of the Reader as a byte[], with the given character encoding.
 * 
 * @param in
 * @param encoding
 * @return
 * @throws IOException
 */
public static byte[] toByteArray(Reader in, String encoding) throws IOException {
	StringWriter out = new StringWriter();
	copy(in, out);
	out.flush();
	return out.toString().getBytes(encoding);
}
 
Example 51
Project: aws-sdk-android   File: XMLWriterTests.java View source code Vote up 6 votes
@Test
public void testEscapeXMLEntitiesProperlyEscapedFromString() {

    String expectedString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Test>quote &quot;&quot; apostrophe &apos;&apos; lessthan &lt;&lt; greaterthan &gt;&gt; ampersand &amp;&amp;</Test>";
    StringWriter sw = new StringWriter();
    XMLWriter xw = new XMLWriter(sw);
    xw.startElement("Test");
    xw.value("quote &quot;\" apostrophe &apos;' lessthan &lt;< greaterthan &gt;> ampersand &amp;&");
    xw.endElement();
    sw.flush();

    assertEquals(sw.toString(), expectedString);
}
 
Example 52
Project: hise   File: DOMUtils.java View source code Vote up 6 votes
/**
 * Convert a DOM node to a stringified XML representation.
 */
static public String domToString(Node node) {
    if (node == null) {
        throw new IllegalArgumentException("Cannot stringify null Node!");
    }

    String value = null;
    short nodeType = node.getNodeType();
    if (nodeType == Node.ELEMENT_NODE || nodeType == Node.DOCUMENT_NODE) {
        // serializer doesn't handle Node type well, only Element
        DOMSerializerImpl ser = new DOMSerializerImpl();
        ser.setParameter(Constants.DOM_NAMESPACES, Boolean.TRUE);
        ser.setParameter(Constants.DOM_WELLFORMED, Boolean.FALSE );
        ser.setParameter(Constants.DOM_VALIDATE, Boolean.FALSE);

        // create a proper XML encoding header based on the input document;
        // default to UTF-8 if the parent document's encoding is not accessible
        String usedEncoding = "UTF-8";
        Document parent = node.getOwnerDocument();
        if (parent != null) {
            String parentEncoding = parent.getXmlEncoding();
            if (parentEncoding != null) {
                usedEncoding = parentEncoding;
            }
        }

        // the receiver of the DOM
        DOMOutputImpl out = new DOMOutputImpl();
        out.setEncoding(usedEncoding);

        // we write into a String
        StringWriter writer = new StringWriter(4096);
        out.setCharacterStream(writer);

        // out, ye characters!
        ser.write(node, out);
        writer.flush();

        // finally get the String
        value = writer.toString();
    } else {
        value = node.getNodeValue();
    }
    return value;
}
 
Example 53
Project: extdirectspring   File: ExtDirectSpringUtil.java View source code Vote up 6 votes
/**
 * Converts a stacktrace into a String
 *
 * @param t a Throwable
 * @return the whole stacktrace in a String
 */
public static String getStackTrace(Throwable t) {
	StringWriter sw = new StringWriter();
	PrintWriter pw = new PrintWriter(sw, true);
	t.printStackTrace(pw);
	pw.flush();
	sw.flush();
	return sw.toString();
}
 
Example 54
Project: octarine   File: Serialiser.java View source code Vote up 6 votes
default String toString(T value) {
    StringWriter writer = new StringWriter();
    try {
        toWriter(writer, value);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    writer.flush();
    return writer.toString();
}
 
Example 55
Project: nuxeo-jsf   File: UICellExcel.java View source code Vote up 6 votes
/**
 * Helper method for rendering a component (usually on a facescontext with
 * a caching reponsewriter)
 *
 * @param facesContext The faces context to render to
 * @param component The component to render
 * @return The textual representation of the component
 * @throws IOException If the JSF helper class can't render the component
 */
public static String cmp2String(FacesContext facesContext,
        UIComponent component) throws IOException {
    ResponseWriter oldResponseWriter = facesContext.getResponseWriter();
    String contentType = oldResponseWriter != null ? oldResponseWriter.getContentType()
            : DEFAULT_CONTENT_TYPE;
    String characterEncoding = oldResponseWriter != null ? oldResponseWriter.getCharacterEncoding()
            : DEFAULT_CHARACTER_ENCODING;
    StringWriter cacheingWriter = new StringWriter();

    // XXX: create a response writer by hand, to control html escaping of
    // iso characters
    // take default values for these confs
    Boolean scriptHiding = Boolean.FALSE;
    Boolean scriptInAttributes = Boolean.TRUE;
    // force escaping to true
    WebConfiguration.DisableUnicodeEscaping escaping = WebConfiguration.DisableUnicodeEscaping.True;
    ResponseWriter newResponseWriter = new NXHtmlResponseWriter(
            cacheingWriter, contentType, characterEncoding, scriptHiding,
            scriptInAttributes, escaping);
    // ResponseWriter newResponseWriter = renderKit.createResponseWriter(
    // cacheingWriter, contentType, characterEncoding);

    facesContext.setResponseWriter(newResponseWriter);
    JSF.renderChild(facesContext, component);
    if (oldResponseWriter != null) {
        facesContext.setResponseWriter(oldResponseWriter);
    }
    cacheingWriter.flush();
    cacheingWriter.close();
    return cacheingWriter.toString();
}
 
Example 56
Project: bigtable-sql   File: OverviewCtrl.java View source code Vote up 6 votes
private void onReport()
{
   try
   {
      DataScaleTableModel dstm = _overviewHolder.getDataScaleTable().getDataScaleTableModel();

      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);


      pw.println("<html>");
      pw.println("<body>");

      for( int i = 0; i < dstm.getRowCount(); i++ )
      {

         DataScale dataScale = dstm.getDataScaleAt(i);

         pw.println("<h1>Column name " + dataScale.getColumn() +":</h1>");
         pw.println("<table border=\"1\">");
         pw.println("<tr>");

         ArrayList<String> intervalReports = dataScale.getIntervalReports();

         for( String toolTip : intervalReports )
         {
            pw.println("<td>" + toolTip + "</td>");
         }
         pw.println("<tr>");
         pw.println("</table>");

         pw.println();
      }

      pw.println("</body>");
      pw.println("</html>");
      pw.flush();
      sw.flush();
      pw.close();
      sw.close();

      Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
      StringSelection data = new StringSelection(sw.getBuffer().toString());
      clip.setContents(data, data);
   }
   catch(IOException e)
   {
      throw new RuntimeException(e);
   }
}
 
Example 57
Project: HR-WebServices-Examples-Java   File: EchoBlockingWsaBasedClient.java View source code Vote up 6 votes
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.setTo(targetEPR);
    options.setTransportInProtocol(Constants.TRANSPORT_HTTP);

    //Blocking invocation via wsa mapping
    options.setAction("urn:echo");

    ServiceClient sender = new ServiceClient();
    sender.setOptions(options);
    OMElement result = sender.sendReceive(getBody());

    StringWriter writer = new StringWriter();
    result.serialize(writer);
    writer.flush();

    System.out.println(writer.toString());

}
 
Example 58
Project: nmonvisualizer   File: BasicFormatter.java View source code Vote up 6 votes
@Override
public String format(LogRecord record) {
    StringWriter buffer = new StringWriter(256);

    buffer.append(format.format(record.getMillis()));
    buffer.append(" ");
    buffer.append(record.getLevel().getName());
    buffer.append(" ");
    buffer.append(record.getSourceClassName());
    buffer.append(".");
    buffer.append(record.getSourceMethodName());
    buffer.append(": ");
    buffer.append(record.getMessage());
    buffer.append("\n");

    if (record.getThrown() != null) {
        PrintWriter pw = new PrintWriter(buffer);
        record.getThrown().printStackTrace(pw);

        pw.close();
    }
    // else nothing since StringWriter.close() is a no-op

    return buffer.toString();
}
 
Example 59
Project: genome-weaver-align   File: SequenceBoundary.java View source code Vote up 6 votes
public String toSAMHeader() {
    StringWriter buf = new StringWriter();
    for (SequenceIndex each : index) {
        buf.append(String.format("@SQ\tSN:%s\tLN:%d\n", each.name, each.length));
    }
    return buf.toString();
}
 
Example 60
Project: airlift   File: StaticFormatter.java View source code Vote up 6 votes
@Override
public String format(LogRecord record)
{
    ZonedDateTime timestamp = ZonedDateTime.ofInstant(Instant.ofEpochMilli(record.getMillis()), SYSTEM_ZONE);

    StringWriter stringWriter = new StringWriter()
            .append(TIMESTAMP_FORMATTER.format(timestamp))
            .append('\t')
            .append(Level.fromJulLevel(record.getLevel()).name())
            .append('\t')
            .append(Thread.currentThread().getName())
            .append('\t')
            .append(record.getLoggerName())
            .append('\t')
            .append(record.getMessage());

    if (record.getThrown() != null) {
        stringWriter.append('\n');
        record.getThrown().printStackTrace(new PrintWriter(stringWriter));
        stringWriter.append('\n');
    }

    stringWriter.append('\n');
    return stringWriter.toString();
}
 
Example 61
Project: JerseyTest   File: FormDataMultiPartReaderWriterTest.java View source code Vote up 6 votes
private void checkEntity(String expected, BodyPartEntity entity) throws IOException {
    // Convert the raw bytes into a String
    InputStreamReader sr = new InputStreamReader(entity.getInputStream());
    StringWriter sw = new StringWriter();
    while (true) {
        int ch = sr.read();
        if (ch < 0) {
            break;
        }
        sw.append((char) ch);
    }
    // Perform the comparison
    assertEquals(expected, sw.toString());
}
 
Example 62
Project: galen   File: XmlBuilder.java View source code Vote up 6 votes
public void toXml(String indentation, StringWriter sw) {
    if (type == XmlNodeType.TEXT) {
        sw.append(StringEscapeUtils.escapeXml(name));
    }
    else if (type == XmlNodeType.TEXT_UNESCAPED) {
        sw.append(name);
    }
    else {
        if (parent != null) {
            sw.append("\n");
        }
        sw.append(indentation);
        sw.append("<");
        sw.append(name);
        writeAttributes(sw);
        sw.append(">");
        
        writeChildren(indentation + INDENTATION, sw);
        
        if (childNodes != null && childNodes.size() > 0 && !containsOnlyText()) {
            sw.append("\n");
            sw.append(indentation);
        }
        
        sw.append("</");
        sw.append(name);
        sw.append(">");
    }
}
 
Example 63
Project: tapestry-facebook   File: FBAsyncSupportImpl.java View source code Vote up 6 votes
String initString() {		
	String sep = "";
	StringWriter s = new StringWriter();
	//s.append("({");
	if ( fbinit.getAppID() != null ) {
		s.append(sep);
		sep = ",";
		s.append("appId: '");
		s.append(fbinit.getAppID());
		s.append("'");
	}
	if ( fbinit.getCookie() != null ) {
		s.append(sep);
		sep = ",";
		s.append("cookie: " + fbinit.getCookie());
	}
	if ( fbinit.getLogging() != null ) {
		s.append(sep);
		sep = ",";
		s.append("logging: " + fbinit.getLogging());
	}
	if ( fbinit.getStatus() != null ) {
		s.append(sep);
		sep = ",";
		s.append("status: " + fbinit.getStatus());
	}
	if ( fbinit.getXfbml() != null ) {
		s.append(sep);
		sep = ",";
		s.append("xfbml: " + fbinit.getXfbml());
	}
	
	return s.toString();
	
}
 
Example 64
Project: android-platform-tools-base   File: JarFileIssueRegistryTest.java View source code Vote up 6 votes
public void testCached() throws Exception {
    File targetDir = Files.createTempDir();
    File file1 = getTestfile(targetDir, "rules/appcompat.jar.data");
    File file2 = getTestfile(targetDir, "apicheck/unsupported.jar.data");
    assertTrue(file1.getPath(), file1.exists());
    final StringWriter mLoggedWarnings = new StringWriter();
    TestLintClient client = new TestLintClient() {
        @Override
        public void log(@NonNull Severity severity, @Nullable Throwable exception,
                @Nullable String format, @Nullable Object... args) {
            if (format != null) {
                mLoggedWarnings.append(String.format(format, args));
            }
        }

    };
    IssueRegistry registry1 = JarFileIssueRegistry.get(client, file1);
    IssueRegistry registry2 = JarFileIssueRegistry.get(client, new File(file1.getPath()));
    assertSame(registry1, registry2);
    IssueRegistry registry3 = JarFileIssueRegistry.get(client, file2);
    assertNotSame(registry1, registry3);

    assertEquals(1, registry1.getIssues().size());
    assertEquals("AppCompatMethod", registry1.getIssues().get(0).getId());

    assertEquals(
            "Custom lint rule jar " + file2.getPath() + " does not contain a valid "
                    + "registry manifest key (Lint-Registry).\n"
                    + "Either the custom jar is invalid, or it uses an outdated API not "
                    + "supported this lint client", mLoggedWarnings.toString());
}
 
Example 65
Project: AdminCMD-Bukkit   File: LogFormatter.java View source code Vote up 6 votes
@Override
public String format(final LogRecord record) {
        final String[] arguments = new String[9];
        // %L
        arguments[0] = record.getLevel().toString();
        arguments[1] = record.getMessage();
        // sometimes the message is empty, but there is a throwable
        if (arguments[1] == null || arguments[1].length() == 0) {
                final Throwable thrown = record.getThrown();
                if (thrown != null) {
                        arguments[1] = thrown.getMessage();
                }
        }
        // %m
        arguments[1] = record.getMessage();
        // %M
        if (record.getSourceMethodName() != null) {
                arguments[2] = record.getSourceMethodName();
        } else {
                arguments[2] = "?";
        }
        // %t
        final Date date = new Date(record.getMillis());
        synchronized (dateFormat) {
                arguments[3] = dateFormat.format(date);
        }
        // %c
        if (record.getSourceClassName() != null) {
                arguments[4] = record.getSourceClassName();
        } else {
                arguments[4] = "?";
        }
        // %T
        arguments[5] = Integer.valueOf(record.getThreadID()).toString();
        // %n
        arguments[6] = record.getLoggerName();
        // %C
        final int start = arguments[4].lastIndexOf(".") + 1;
        if (start > 0 && start < arguments[4].length()) {
                arguments[7] = arguments[4].substring(start);
        } else {
                arguments[7] = arguments[4];
        }
        // %E
        final Throwable throwable = record.getThrown();
        if (throwable != null) {
                final StringWriter stringwriter = new StringWriter();
                stringwriter.append("\n");
                throwable.printStackTrace(new PrintWriter(stringwriter));
                arguments[8] = stringwriter.toString();
        } else {
                arguments[8] = "";
        }
        synchronized (messageFormat) {
                return messageFormat.format(arguments);
        }
}
 
Example 66
Project: keycloak   File: StackoverflowIdentityProvider.java View source code Vote up 6 votes
public static final String unescapeHtml3(final String input) {
	if (input == null)
		return null;
	StringWriter writer = null;
	int len = input.length();
	int i = 1;
	int st = 0;
	while (true) {
		// look for '&'
		while (i < len && input.charAt(i - 1) != '&')
			i++;
		if (i >= len)
			break;

		// found '&', look for ';'
		int j = i;
		while (j < len && j < i + MAX_ESCAPE + 1 && input.charAt(j) != ';')
			j++;
		if (j == len || j < i + MIN_ESCAPE || j == i + MAX_ESCAPE + 1) {
			i++;
			continue;
		}

		// found escape
		if (input.charAt(i) == '#') {
			// numeric escape
			int k = i + 1;
			int radix = 10;

			final char firstChar = input.charAt(k);
			if (firstChar == 'x' || firstChar == 'X') {
				k++;
				radix = 16;
			}

			try {
				int entityValue = Integer.parseInt(input.substring(k, j), radix);

				if (writer == null)
					writer = new StringWriter(input.length());
				writer.append(input.substring(st, i - 1));

				if (entityValue > 0xFFFF) {
					final char[] chrs = Character.toChars(entityValue);
					writer.write(chrs[0]);
					writer.write(chrs[1]);
				} else {
					writer.write(entityValue);
				}

			} catch (NumberFormatException ex) {
				i++;
				continue;
			}
		} else {
			// named escape
			CharSequence value = lookupMap.get(input.substring(i, j));
			if (value == null) {
				i++;
				continue;
			}

			if (writer == null)
				writer = new StringWriter(input.length());
			writer.append(input.substring(st, i - 1));

			writer.append(value);
		}

		// skip escape
		st = j + 1;
		i = st;
	}

	if (writer != null) {
		writer.append(input.substring(st, len));
		return writer.toString();
	}
	return input;
}