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 generate more good examples.
Example 1
Project: cas-server-4.2.1   File: CouchbaseServiceRegistryDao.java   View source code 6 votes vote down vote up
@Override
public RegisteredService save(final RegisteredService service) {
    logger.debug("Saving service {}", service);

    if (service.getId() == AbstractRegisteredService.INITIAL_IDENTIFIER_VALUE) {
        ((AbstractRegisteredService) service).setId(service.hashCode());
    }

    final StringWriter stringWriter = new StringWriter();
    registeredServiceJsonSerializer.toJson(stringWriter, service);

    couchbase.bucket().upsert(
            RawJsonDocument.create(
                    String.valueOf(service.getId()),
                    0, stringWriter.toString()));
    return service;
}
 
Example 2
Project: elastic-db-tools-for-java   File: StoreOperationRequestBuilder.java   View source code 6 votes vote down vote up
/**
 * Print the created XML to verify. Usage: return printLogAndReturn(new JAXBElement(rootElementName, StoreOperationInput.class, input));
 *
 * @return JAXBElement - same object which came as input.
 */
private static JAXBElement printLogAndReturn(JAXBElement jaxbElement) {
    try {
        // Create a String writer object which will be
        // used to write jaxbElment XML to string
        StringWriter writer = new StringWriter();

        // create JAXBContext which will be used to update writer
        JAXBContext context = JAXBContext.newInstance(StoreOperationInput.class);

        // marshall or convert jaxbElement containing student to xml format
        context.createMarshaller().marshal(jaxbElement, writer);

        // print XML string representation of Student object
        System.out.println(writer.toString());
    }
    catch (JAXBException e) {
        e.printStackTrace();
    }
    return jaxbElement;
}
 
Example 3
Project: Aurora   File: CharacterHandler.java   View source code 6 votes vote down vote up
/**
 * xml 格式化
 *
 * @param xml
 * @return
 */
public static String xmlFormat(String xml) {
    if (TextUtils.isEmpty(xml)) {
        return "Empty/Null xml content";
    }
    String message;
    try {
        Source xmlInput = new StreamSource(new StringReader(xml));
        StreamResult xmlOutput = new StreamResult(new StringWriter());
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(xmlInput, xmlOutput);
        message = xmlOutput.getWriter().toString().replaceFirst(">", ">\n");
    } catch (TransformerException e) {
        message = xml;
    }
    return message;
}
 
Example 4
Project: GitHub   File: SerializeWriterTest_17.java   View source code 6 votes vote down vote up
public void test_writer_1() throws Exception {
    StringWriter strOut = new StringWriter();
    SerializeWriter out = new SerializeWriter(strOut, 6);
    out.config(SerializerFeature.QuoteFieldNames, true);

    try {
        JSONSerializer serializer = new JSONSerializer(out);

        VO vo = new VO();
        vo.setValue(123456789);
        serializer.write(vo);
    } finally {
        out.close();
    }
    Assert.assertEquals("{\"value\":123456789}", strOut.toString());
}
 
Example 5
Project: hadoop   File: RLESparseResourceAllocation.java   View source code 6 votes vote down vote up
/**
 * Returns the JSON string representation of the current resources allocated
 * over time
 * 
 * @return the JSON string representation of the current resources allocated
 *         over time
 */
public String toMemJSONString() {
  StringWriter json = new StringWriter();
  JsonWriter jsonWriter = new JsonWriter(json);
  readLock.lock();
  try {
    jsonWriter.beginObject();
    // jsonWriter.name("timestamp").value("resource");
    for (Map.Entry<Long, Resource> r : cumulativeCapacity.entrySet()) {
      jsonWriter.name(r.getKey().toString()).value(r.getValue().toString());
    }
    jsonWriter.endObject();
    jsonWriter.close();
    return json.toString();
  } catch (IOException e) {
    // This should not happen
    return "";
  } finally {
    readLock.unlock();
  }
}
 
Example 6
Project: uavstack   File: ClobSeriliazer.java   View source code 6 votes vote down vote up
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
    try {
        if (object == null) {
            serializer.writeNull();
            return;
        }
        
        Clob clob = (Clob) object;
        Reader reader = clob.getCharacterStream();

        StringWriter writer = new StringWriter();
        char[] buf = new char[1024];
        int len = 0;
        while ((len = reader.read(buf)) != -1) {
            writer.write(buf, 0, len);
        }
        reader.close();
        
        String text = writer.toString();
        serializer.write(text);
    } catch (SQLException e) {
        throw new IOException("write clob error", e);
    }
}
 
Example 7
Project: hippo-groovy-updater   File: TestUpdaterTransforming.java   View source code 6 votes vote down vote up
@Test
public void generateHippoEcmExtensions() throws URISyntaxException, IOException, JAXBException {
    URI resourceURI = getClass().getResource("").toURI();
    File root = new File(resourceURI);
    List<ScriptClass> scriptClasses = ScriptClassFactory.getScriptClasses(root);
    Node node = XmlGenerator.getEcmExtensionNode(root, new File(root, "target"), scriptClasses, "my-updater-prefix-");

    StringWriter writer = new StringWriter();

    getMarshaller().marshal(node, writer);
    final String xml = writer.toString();
    URL testfileResultUrl = getClass().getResource("resulting-hippoecm-extension.xml");
    File resultFile = new File(testfileResultUrl.toURI());

    String expectedContent = FileUtils.fileRead(resultFile);
    assertEquals(expectedContent, xml);
}
 
Example 8
Project: incubator-netbeans   File: ErrorPanel.java   View source code 6 votes vote down vote up
private void btnStackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStackActionPerformed
    StringWriter sw = new StringWriter();
    exception.printStackTrace(new PrintWriter(sw));
    JPanel pnl = new JPanel();
    pnl.setLayout(new BorderLayout());
    pnl.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));
    JTextArea ta = new JTextArea();
    ta.setText(sw.toString());
    ta.setEditable(false);
    JScrollPane pane = new JScrollPane(ta);
    pnl.add(pane);
    pnl.setMaximumSize(new Dimension(600, 300));
    pnl.setPreferredSize(new Dimension(600, 300));
    NotifyDescriptor.Message nd = new NotifyDescriptor.Message(pnl);
    DialogDisplayer.getDefault().notify(nd);

}
 
Example 9
Project: raven   File: JaxbUtils.java   View source code 6 votes vote down vote up
public static String obj2xml(Object o, Class<?> clazz) throws JAXBException {
	
	if(null == o){
		throw new InvalidParameterException();
	}
	JAXBContext context = JAXBContext.newInstance(clazz);
	
	Marshaller marshaller = context.createMarshaller();
	
	// 
	marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
	marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
	
	// 是否去掉头部信息
	marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);

	StringWriter writer = new StringWriter();
	marshaller.marshal(o, writer);
	return writer.toString();
}
 
Example 10
Project: OpenJSharp   File: UnixPrintJob.java   View source code 6 votes vote down vote up
private void handleProcessFailure(final Process failedProcess,
        final String[] execCmd, final int result) throws IOException {
    try (StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw)) {
        pw.append("error=").append(Integer.toString(result));
        pw.append(" running:");
        for (String arg: execCmd) {
            pw.append(" '").append(arg).append("'");
        }
        try (InputStream is = failedProcess.getErrorStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr)) {
            while (br.ready()) {
                pw.println();
                pw.append("\t\t").append(br.readLine());
            }
        } finally {
            pw.flush();
            throw new IOException(sw.toString());
        }
    }
}
 
Example 11
Project: openjdk-jdk10   File: XMLSignatureInputDebugger.java   View source code 6 votes vote down vote up
/**
 * Method getHTMLRepresentation
 *
 * @return The HTML Representation.
 * @throws XMLSignatureException
 */
public String getHTMLRepresentation() throws XMLSignatureException {
    if ((this.xpathNodeSet == null) || (this.xpathNodeSet.size() == 0)) {
        return HTMLPrefix + "<blink>no node set, sorry</blink>" + HTMLSuffix;
    }

    // get only a single node as anchor to fetch the owner document
    Node n = this.xpathNodeSet.iterator().next();

    this.doc = XMLUtils.getOwnerDocument(n);

    try {
        this.writer = new StringWriter();

        this.canonicalizeXPathNodeSet(this.doc);
        this.writer.close();

        return this.writer.toString();
    } catch (IOException ex) {
        throw new XMLSignatureException("empty", ex);
    } finally {
        this.xpathNodeSet = null;
        this.doc = null;
        this.writer = null;
    }
}
 
Example 12
Project: retroxlibs   File: RetroBoxDialog.java   View source code 6 votes vote down vote up
public static void showException(final Activity activity, Exception e, SimpleCallback callback) {
	StringWriter sw = new StringWriter();
	PrintWriter pw = new PrintWriter(sw);
	Throwable cause = e.getCause();
	if (cause!=null) {
		cause.printStackTrace(pw);
	} else {
		e.printStackTrace(pw);
	}
	
	final TextView text = (TextView)activity.findViewById(R.id.txtDialogAction);
	text.setTextSize(12);
		
	String msg =  e.toString() + "\n" + e.getMessage() + "\n" + sw.toString();
	showAlert(activity, "Error", msg, callback);
}
 
Example 13
Project: java-debug   File: CompileUtils.java   View source code 6 votes vote down vote up
public static void compileFiles(File projectRoot, List<String> javaFiles) {
    DiagnosticCollector diagnosticCollector = new DiagnosticCollector();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticCollector, Locale.ENGLISH, Charset.forName("utf-8"));
    Iterable<? extends JavaFileObject> javaFileObjects = fileManager.getJavaFileObjects(javaFiles.toArray(new String[0]));
    File outputFolder = new File(projectRoot, "bin");
    if (!outputFolder.exists()) {
        outputFolder.mkdir();
    }
    String[] options = new String[] { "-d", outputFolder.getAbsolutePath() , "-g", "-proc:none"};
    final StringWriter output = new StringWriter();
    CompilationTask task = compiler.getTask(output, fileManager, diagnosticCollector, Arrays.asList(options), null, javaFileObjects);
    boolean result = task.call();
    if (!result) {
        throw new IllegalArgumentException(
            "Compilation failed:\n" + output);
    }
    List list = diagnosticCollector.getDiagnostics();
    for (Object object : list) {
        Diagnostic d = (Diagnostic) object;
        System.out.println(d.getMessage(Locale.ENGLISH));
    }
}
 
Example 14
Project: JavaRushTasks   File: Solution.java   View source code 6 votes vote down vote up
public static StringWriter getAllDataFromInputStream(InputStream is) throws IOException {
    StringWriter writer = new StringWriter();

    try {
        while (is.available() > 0) {
            byte[] buf = new byte[1024];
            int len = is.read(buf);
            String s = new String(buf, 0, len);
            writer.append(s);
        }
    } catch (Exception e) {
        return new StringWriter();
    }

    return writer;
}
 
Example 15
Project: ralasafe   File: UserCategory.java   View source code 6 votes vote down vote up
public UserCategoryTestResult test(User user, Map context,
		QueryManager queryManager) {
	UserCategoryTestResult result = new UserCategoryTestResult();
	Interpreter interpreter = new Interpreter();
	String script = toScript();
	try {
		eval(interpreter, user, context, queryManager);
		Boolean contain = (Boolean) interpreter
				.get(SystemConstant.DOES_USER_CATEGORY_CONTAIN);
		Map variableMap = (Map) interpreter
				.get(SystemConstant.VARIABLE_MAP);
		result.setValid(contain.booleanValue());
		result.setFailed(false);
		result.setScript(script);
		result.setVariableMap(variableMap);
	} catch (EvalError e) {
		result.setFailed(true);
		StringWriter sw=new StringWriter();
		PrintWriter pw=new PrintWriter( sw );
		e.printStackTrace( pw );
		result.setErrorMessage( sw.toString() );
		//result.setErrorMessage(StringUtil.getEvalError(e.getMessage()));
		result.setScript(script);
	}
	return result;
}
 
Example 16
Project: Android-DFU-App   File: UARTActivity.java   View source code 6 votes vote down vote up
/**
 * Saves the given configuration in the database.
 */
private void saveConfiguration() {
	final UartConfiguration configuration = mConfiguration;
	try {
		final Format format = new Format(new HyphenStyle());
		final Strategy strategy = new VisitorStrategy(new CommentVisitor());
		final Serializer serializer = new Persister(strategy, format);
		final StringWriter writer = new StringWriter();
		serializer.write(configuration, writer);
		final String xml = writer.toString();

		mDatabaseHelper.updateConfiguration(configuration.getName(), xml);
		mWearableSynchronizer.onConfigurationAddedOrEdited(mPreferences.getLong(PREFS_CONFIGURATION, 0), configuration);
	} catch (final Exception e) {
		Log.e(TAG, "Error while creating a new configuration", e);
	}
}
 
Example 17
Project: openjdk-jdk10   File: XSLTFunctionsTest.java   View source code 6 votes vote down vote up
/**
 * @bug 8165116
 * Verifies that redirect works properly when extension function is enabled
 *
 * @param xml the XML source
 * @param xsl the stylesheet that redirect output to a file
 * @param output the output file
 * @param redirect the redirect file
 * @throws Exception if the test fails
 **/
@Test(dataProvider = "redirect")
public void testRedirect(String xml, String xsl, String output, String redirect) throws Exception {

    TransformerFactory tf = TransformerFactory.newInstance();
    tf.setFeature(ORACLE_ENABLE_EXTENSION_FUNCTION, true);
    Transformer t = tf.newTransformer(new StreamSource(new StringReader(xsl)));

    //Transform the xml
    tryRunWithTmpPermission(
            () -> t.transform(new StreamSource(new StringReader(xml)), new StreamResult(new StringWriter())),
            new FilePermission(output, "write"), new FilePermission(redirect, "write"));

    // Verifies that the output is redirected successfully
    String userDir = getSystemProperty("user.dir");
    Path pathOutput = Paths.get(userDir, output);
    Path pathRedirect = Paths.get(userDir, redirect);
    Assert.assertTrue(Files.exists(pathOutput));
    Assert.assertTrue(Files.exists(pathRedirect));
    System.out.println("Output to " + pathOutput + " successful.");
    System.out.println("Redirect to " + pathRedirect + " successful.");
    Files.deleteIfExists(pathOutput);
    Files.deleteIfExists(pathRedirect);
}
 
Example 18
Project: fluentxml4j   File: FluentXmlSerializerIntegrationTest.java   View source code 6 votes vote down vote up
@Test
public void serializeCustomizedToWriter()
{
	StringWriter wr = new StringWriter();

	serialize(documentTestRule.asDocument())
			.withSerializer(new SerializerConfigurerAdapter()
			{
				@Override
				protected void configure(Transformer transformer)
				{
					super.configure(transformer);
					transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
				}
			})
			.to(wr);

	String serializedXml = wr.getBuffer().toString();
	assertThat(serializedXml, is("<foo:test xmlns:foo=\"bar\"/>\n"));
}
 
Example 19
Project: server-utility   File: JaxbXMLUtil.java   View source code 6 votes vote down vote up
/**
 * JavaBean转换成xml,默认编码UTF-8
 *
 * @param obj 待转换对象
 * @return 转换后的xml
 */
public static String convertToXml(Object obj) {
    String result = null;
    try {
        JAXBContext context = JAXBContext.newInstance(obj.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, CharsetConstant.UTF_8);

        StringWriter writer = new StringWriter();
        marshaller.marshal(obj, writer);
        result = writer.toString();
    } catch (Exception e) {
        logger.error(ExceptionUtil.parseException(e));
    }

    return result;
}
 
Example 20
Project: incubator-netbeans   File: ErrorManagerDelegatesToLoggingTest.java   View source code 6 votes vote down vote up
public void testThatWeNotifyAnException() throws Exception {
    Throwable t = new NullPointerException("npe");
    Throwable v = new ClassNotFoundException("cnf", t);

    Throwable a = new IOException();
    ErrorManager.getDefault().annotate(a, v);
    ErrorManager.getDefault().notify(a);

    assertEquals("Last throwable is a", a, MyHandler.lastThrowable);
    assertNotNull("And it has a cause", MyHandler.lastThrowable.getCause());

    StringWriter w = new StringWriter();
    MyHandler.lastThrowable.getCause().printStackTrace(new PrintWriter(w));
    String msg = w.toString();

    if (msg.indexOf("npe") == -1) fail("there should be npe: " + msg);
    if (msg.indexOf("cnf") == -1) fail("there should be cnf: " + msg);

}
 
Example 21
Project: marathonv5   File: ObjectMapNamingStrategy.java   View source code 6 votes vote down vote up
public void init() {
    runtimeLogger = RuntimeLogger.getRuntimeLogger();
    omapService = getObjectMapService();
    try {
        omapService.load();
        runtimeLogger.info(MODULE, "Loaded object map omapService");
    } catch (IOException e) {
        StringWriter w = new StringWriter();
        e.printStackTrace(new PrintWriter(w));
        runtimeLogger.error(MODULE, "Error in creating naming strategy:" + e.getMessage(), w.toString());
        FXUIUtils.showMessageDialog(null, "Error in creating naming strategy:" + e.getMessage(), "Error in NamingStrategy",
                Alert.AlertType.ERROR);
        e.printStackTrace();
        System.exit(1);
    }
}
 
Example 22
Project: xsharing-services-router   File: UraSerializerWrapperTest.java   View source code 6 votes vote down vote up
@Test
public void testSerialize() throws Exception {
    String expected = "{\"version\":null,\"status\":0,\"routeInstructions\":null,\"routeGeometry\":[[50.753,5.712],[50.653,6.012]]}";
    GeoCoordinates[] coords = new GeoCoordinates[2];
    coords[0] = new GeoCoordinates(50.753, 5.712);
    coords[1] = new GeoCoordinates(50.653, 6.012);
    PathData pathData = new PathData.Builder().withRouteGeometry(coords).build();

    ObjectMapper mapper = new ObjectMapper();
    mapper.addMixInAnnotations(PathData.class, UraPathDataMixIn.class);
    Writer stringWriter = new StringWriter();
    try {
        mapper.writeValue(stringWriter, pathData);
        String json = stringWriter.toString();
        assertNotNull(json);
        assertEquals(json, expected);
    } catch (Exception e) {
        fail();
    }
}
 
Example 23
Project: Open-DM   File: AbstractArcCli.java   View source code 6 votes vote down vote up
public String helpScreen() {
    StringBuffer usage = new StringBuffer();
    HelpFormatter formatter = new HelpFormatter();

    if (cliOrder != null && cliOrder.size() > 0) {
        formatter.setOptionComparator(new OptionComparator());
    }

    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    formatter.printHelp(pw,
                        HCPMoverProperties.CLI_WIDTH.getAsInt(),
                        getHelpUsageLine(),
                        null /* header */,
                        getOptions(),
                        HelpFormatter.DEFAULT_LEFT_PAD /* leftPad */,
                        HelpFormatter.DEFAULT_DESC_PAD /* descPad */,
                        null /* footer */,
                        false /* autoUsage */
    );

    usage.append(getHelpHeader());
    usage.append(sw.toString());
    usage.append(getHelpFooter());
    return usage.toString();
}
 
Example 24
Project: de.flapdoodle.solid   File: EscaperExtensionTest.java   View source code 6 votes vote down vote up
@Test()
public void testPrintBigDecimal() throws PebbleException, IOException {

    PebbleEngine pebble = new PebbleEngine.Builder().loader(new StringLoader()).strictVariables(true).build();

    String source = "{{ num }}";
    PebbleTemplate template = pebble.getTemplate(source);

    Map<String, Object> context = new HashMap<>();
    BigDecimal num = new BigDecimal("1234E+4");
    context.put("num", num);

    Writer writer = new StringWriter();
    template.evaluate(writer, context);
    assertEquals(num.toPlainString(), writer.toString());
    assertNotEquals(num.toString(), writer.toString());
}
 
Example 25
Project: alfresco-repository   File: ValueDataTypeValidatorImplTest.java   View source code 6 votes vote down vote up
@Test
public void testValueContentDataType() throws Exception
{
    // d:content tests
    {
        final String contentDataType = "d:content";
        validate_invalid("somePrefix:", "some very long text"); // invalid QName prefixed data type
        validate_invalid("unknownPrefix" + System.currentTimeMillis() + ":content", "some text"); // prefix is not mapped to a namespace URI

        validate_valid(contentDataType, null); // no validation
        validate_valid(contentDataType, ""); // no validation
        ByteArrayInputStream is = new ByteArrayInputStream("very long text".getBytes("UTF-8"));
        StringWriter writer = new StringWriter();
        IOUtils.copy(is, writer, "UTF-8");
        validate_valid(contentDataType,  writer.toString()); // valid value
    }
}
 
Example 26
Project: de.flapdoodle.solid   File: CoreTagsTest.java   View source code 6 votes vote down vote up
@Test
public void testForWithArray() throws PebbleException, IOException {
    PebbleEngine pebble = new PebbleEngine.Builder().loader(new StringLoader()).strictVariables(false).build();

    String source = "{% for user in users %}{{ user }}{% endfor %}";
    PebbleTemplate template = pebble.getTemplate(source);

    Map<String, Object> context = new HashMap<>();

    String[] users = new String[3];
    users[0] = "User 1";
    users[1] = "User 2";
    users[2] = "User 3";
    context.put("users", users);

    Writer writer = new StringWriter();
    template.evaluate(writer, context);
    assertEquals("User 1User 2User 3", writer.toString());
}
 
Example 27
Project: jarn   File: YarnState.java   View source code 5 votes vote down vote up
/**
 * Replaces any {{ }} wrapped variable placeholders in a {@link String} with
 * the current value in this {@link YarnState}
 * 
 * @param text
 *            The {@link String} to replace variable placeholders in
 * @return The {@link String} with variable values inserted
 */
public String applyVariables(String text) {
	if (!mustacheCache.containsKey(text)) {
		mustacheCache.put(text, mustacheFactory.compile(new StringReader(text), text));
	}
	Mustache mustache = mustacheCache.get(text);

	StringWriter result = new StringWriter();
	mustache.execute(result, variablesMustache);
	return result.toString();
}
 
Example 28
Project: openjdk-jdk10   File: Bug6490380.java   View source code 5 votes vote down vote up
@Test
public void test() {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        URL input = Bug6490380.class.getResource("Bug4693341.xml");
        StreamSource source = new StreamSource(input.openStream(), input.toString());
        StringWriter sw = new StringWriter();
        transformer.transform(source, new StreamResult(sw));
        String s = sw.toString();
        Assert.assertEquals(s.indexOf("!DOCTYPE"), s.lastIndexOf("!DOCTYPE"));
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
}
 
Example 29
Project: googles-monorepo-demo   File: FreshValueGeneratorTest.java   View source code 5 votes vote down vote up
@AndroidIncompatible // problem with equality of Type objects?
public void testFreshInstance() {
  assertFreshInstances(
      String.class, CharSequence.class,
      Appendable.class, StringBuffer.class, StringBuilder.class,
      Pattern.class, MatchResult.class,
      Number.class, int.class, Integer.class,
      long.class, Long.class,
      short.class, Short.class,
      byte.class, Byte.class,
      boolean.class, Boolean.class,
      char.class, Character.class,
      int[].class, Object[].class,
      UnsignedInteger.class, UnsignedLong.class,
      BigInteger.class, BigDecimal.class,
      Throwable.class, Error.class, Exception.class, RuntimeException.class,
      Charset.class, Locale.class, Currency.class,
      List.class, Map.Entry.class,
      Object.class,
      Equivalence.class, Predicate.class, Function.class,
      Comparable.class, Comparator.class, Ordering.class,
      Class.class, Type.class, TypeToken.class,
      TimeUnit.class, Ticker.class,
      Joiner.class, Splitter.class, CharMatcher.class,
      InputStream.class, ByteArrayInputStream.class,
      Reader.class, Readable.class, StringReader.class,
      OutputStream.class, ByteArrayOutputStream.class,
      Writer.class, StringWriter.class, File.class,
      Buffer.class, ByteBuffer.class, CharBuffer.class,
      ShortBuffer.class, IntBuffer.class, LongBuffer.class,
      FloatBuffer.class, DoubleBuffer.class,
      String[].class, Object[].class, int[].class);
}
 
Example 30
Project: https-github.com-hyb1996-NoRootScriptDroid   File: CrashHandler.java   View source code 5 votes vote down vote up
public static String throwableToString(Throwable throwable) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    throwable.printStackTrace();
    throwable.printStackTrace(pw);
    return sw.toString();
}
 
Example 31
Project: GitHub   File: OnPreSerializeProcessor.java   View source code 5 votes vote down vote up
@Override
public void findAndParseObjects(RoundEnvironment env, Map<String, JsonObjectHolder> jsonObjectMap, Elements elements, Types types) {
    for (Element element : env.getElementsAnnotatedWith(OnPreJsonSerialize.class)) {
        try {
            processOnPreJsonSerializeMethodAnnotation(element, jsonObjectMap, elements);
        } catch (Exception e) {
            StringWriter stackTrace = new StringWriter();
            e.printStackTrace(new PrintWriter(stackTrace));

            error(element, "Unable to generate injector for %s. Stack trace incoming:\n%s", OnPreJsonSerialize.class, stackTrace.toString());
        }
    }
}
 
Example 32
Project: jetfuel   File: StringAdapter.java   View source code 5 votes vote down vote up
/**
 * Converts an input stream to a string.
 * 
 * @param is
 * @return
 */
public String convertStream(InputStream is) {
	try {
		StringWriter writer = new StringWriter();
		for (int i = is.read(); i >= 0; i = is.read())
			writer.write(i);
		is.close();
		return writer.toString();
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 33
Project: dracoon-dropzone   File: Crypto.java   View source code 5 votes vote down vote up
private static String getStringFromPublicKey(PublicKey pubKey) throws InvalidKeyPairException {
    try {
        StringWriter writer = new StringWriter();
        JcaPEMWriter pemWriter = new JcaPEMWriter(writer);
        pemWriter.writeObject(pubKey);
        pemWriter.close();
        return writer.toString();
    } catch (IOException e) {
        throw new InvalidKeyPairException("Could not encode public key. PEM encoding failed.",
                e);
    }
}
 
Example 34
Project: ARCLib   File: IndexStore.java   View source code 5 votes vote down vote up
/**
 * Converts XML node to String.
 *
 * @param node
 * @return
 * @throws TransformerException
 */
default String nodeToString(Node node)
        throws TransformerException {
    StringWriter buf = new StringWriter();
    Transformer xform = TransformerFactory.newInstance().newTransformer();
    xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    xform.transform(new DOMSource(node), new StreamResult(buf));
    return (buf.toString());
}
 
Example 35
Project: Pet-Supply-Store   File: AbstractUIServlet.java   View source code 5 votes vote down vote up
private void serveNotFoundException(HttpServletRequest request, HttpServletResponse response, Exception e)
		throws ServletException, IOException {
	StringWriter sw = new StringWriter();
	e.printStackTrace(new PrintWriter(sw));
	String exceptionAsString = sw.toString();
	response.setStatus(404);
	request.setAttribute("CategoryList", new ArrayList<Category>());
	request.setAttribute("storeIcon", "");
	request.setAttribute("errorImage", "");
	request.setAttribute("title", "Pet Supply Store Timeout");
	request.setAttribute("messagetitle", "404: Not Found Exception: " + e.getMessage());
	request.setAttribute("messageparagraph", exceptionAsString);
	request.setAttribute("login", false);
	request.getRequestDispatcher("WEB-INF/pages/error.jsp").forward(request, response);
}
 
Example 36
Project: apache-tomcat-7.0.73-with-comment   File: HTMLManagerServlet.java   View source code 5 votes vote down vote up
/**
 * Deploy an application for the specified path from the specified
 * web application archive.
 *
 * @param config URL of the context configuration file to be deployed
 * @param cn Name of the application to be deployed
 * @param war URL of the web application archive to be deployed
 * @return message String
 */
protected String deployInternal(String config, ContextName cn, String war,
        StringManager smClient) {

    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);

    super.deploy(printWriter, config, cn, war, false, smClient);

    return stringWriter.toString();
}
 
Example 37
Project: de.flapdoodle.solid   File: LogicTest.java   View source code 5 votes vote down vote up
@Test
public void testContainsOperatorWithNot() throws PebbleException, IOException {
    
    PebbleEngine pebble = new PebbleEngine.Builder().loader(new StringLoader()).strictVariables(false).build();

    String source = "{% if not (names contains 'Cobra') %}yes{% else %}no{% endif %}";
    PebbleTemplate template = pebble.getTemplate(source);

    Map<String, Object> context = new HashMap<>();
    context.put("names", Arrays.asList("Bob", "Maria", "John"));

    Writer writer = new StringWriter();
    template.evaluate(writer, context);
    assertEquals("yes", writer.toString());
}
 
Example 38
Project: letv   File: CrashHandler.java   View source code 5 votes vote down vote up
private String saveCrashInfo(Throwable ex) {
    Writer info = new StringWriter();
    PrintWriter printWriter = new PrintWriter(info);
    ex.printStackTrace(printWriter);
    for (Throwable cause = ex.getCause(); cause != null; cause = cause.getCause()) {
        cause.printStackTrace(printWriter);
    }
    String result = info.toString() + "\t" + ex.getMessage();
    printWriter.close();
    return result;
}
 
Example 39
Project: EatDubbo   File: StringEscapeUtils.java   View source code 5 votes vote down vote up
/**
 * <p>Worker method for the {@link #escapeJavaScript(String)} method.</p>
 * 
 * @param str String to escape values in, may be null
 * @param escapeSingleQuotes escapes single quotes if <code>true</code>
 * @return the escaped string
 */
private static String escapeJavaStyleString(String str, boolean escapeSingleQuotes) {
    if (str == null) {
        return null;
    }
    try {
        StringWriter writer = new StringWriter(str.length() * 2);
        escapeJavaStyleString(writer, str, escapeSingleQuotes);
        return writer.toString();
    } catch (IOException ioe) {
        // this should never ever happen while writing to a StringWriter
        ioe.printStackTrace();
        return null;
    }
}
 
Example 40
Project: lams   File: NestableDelegate.java   View source code 5 votes vote down vote up
/**
 * Captures the stack trace associated with the specified
 * <code>Throwable</code> object, decomposing it into a list of
 * stack frames.
 *
 * @param t The <code>Throwable</code>.
 * @return  An array of strings describing each stack frame.
 * @since 2.0
 */
protected String[] getStackFrames(Throwable t) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw, true);

    // Avoid infinite loop between decompose() and printStackTrace().
    if (t instanceof Nestable) {
        ((Nestable) t).printPartialStackTrace(pw);
    } else {
        t.printStackTrace(pw);
    }
    return ExceptionUtils.getStackFrames(sw.getBuffer().toString());
}