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: openjdk-jdk10   File: XSLTFunctionsTest.java   Source Code and License 10 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 2
Project: JavaRushTasks   File: Solution.java   Source Code and License 7 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 3
Project: cas-server-4.2.1   File: CouchbaseServiceRegistryDao.java   Source Code and License 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 4
Project: elastic-db-tools-for-java   File: StoreOperationRequestBuilder.java   Source Code and License 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 5
Project: Aurora   File: CharacterHandler.java   Source Code and License 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 6
Project: GitHub   File: SerializeWriterTest_17.java   Source Code and License 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 7
Project: hadoop   File: RLESparseResourceAllocation.java   Source Code and License 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 8
Project: uavstack   File: ClobSeriliazer.java   Source Code and License 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 9
Project: hippo-groovy-updater   File: TestUpdaterTransforming.java   Source Code and License 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 10
Project: incubator-netbeans   File: ErrorPanel.java   Source Code and License 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 11
Project: raven   File: JaxbUtils.java   Source Code and License 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 12
Project: OpenJSharp   File: UnixPrintJob.java   Source Code and License 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 13
Project: openjdk-jdk10   File: XMLSignatureInputDebugger.java   Source Code and License 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 14
Project: retroxlibs   File: RetroBoxDialog.java   Source Code and License 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 15
Project: java-debug   File: CompileUtils.java   Source Code and License 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 16
Project: ralasafe   File: UserCategory.java   Source Code and License 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 17
Project: Android-DFU-App   File: UARTActivity.java   Source Code and License 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 18
Project: fluentxml4j   File: FluentXmlSerializerIntegrationTest.java   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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());
}
 
Example 41
Project: Elasticsearch   File: Errors.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the formatted message for an exception with the specified messages.
 */
public static String format(String heading, Collection<Message> errorMessages) {
    try (Formatter fmt = new Formatter(Locale.ROOT)) {
        fmt.format(heading).format(":%n%n");
        int index = 1;
        boolean displayCauses = getOnlyCause(errorMessages) == null;

        for (Message errorMessage : errorMessages) {
            fmt.format("%s) %s%n", index++, errorMessage.getMessage());

            List<Object> dependencies = errorMessage.getSources();
            for (int i = dependencies.size() - 1; i >= 0; i--) {
                Object source = dependencies.get(i);
                formatSource(fmt, source);
            }

            Throwable cause = errorMessage.getCause();
            if (displayCauses && cause != null) {
                StringWriter writer = new StringWriter();
                cause.printStackTrace(new PrintWriter(writer));
                fmt.format("Caused by: %s", writer.getBuffer());
            }

            fmt.format("%n");
        }

        if (errorMessages.size() == 1) {
            fmt.format("1 error");
        } else {
            fmt.format("%s errors", errorMessages.size());
        }

        return fmt.toString();
    }
}
 
Example 42
Project: openjdk-jdk10   File: XMLKit.java   Source Code and License 5 votes vote down vote up
public String prettyString() {
    StringWriter sw = new StringWriter();
    try {
        writePrettyTo(sw);
    } catch (IOException ee) {
        throw new Error(ee);  // should not happen
    }
    return sw.toString();
}
 
Example 43
Project: RLibrary   File: L.java   Source Code and License 5 votes vote down vote up
private static void printXml(String tag, String xml, String headString) {
    if (TextUtils.isEmpty(tag)) {
        tag = TAG;
    }
    if (xml != null) {
        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);
            xml = xmlOutput.getWriter().toString().replaceFirst(">", ">\n");
        } catch (Exception e) {
            e.printStackTrace();
        }
        xml = headString + "\n" + xml;
    } else {
        xml = headString + "Log with null object";
    }

    printLine(tag, true);
    String[] lines = xml.split(LINE_SEPARATOR);
    for (String line : lines) {
        if (!TextUtils.isEmpty(line)) {
            Log.d(tag, "|" + line);
        }
    }
    printLine(tag, false);
}
 
Example 44
Project: oryx2   File: ErrorResource.java   Source Code and License 5 votes vote down vote up
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response errorText(@Context HttpServletRequest request) {
  StringBuilder text = new StringBuilder(1000);

  text.append("Error");
  Number statusCode = (Number) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
  if (statusCode != null) {
    text.append(' ').append(statusCode);
  }
  Object requestURI = request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI);
  if (requestURI != null) {
    text.append(" : ");
    text.append(requestURI);
  }
  text.append('\n');

  Object message = request.getAttribute(RequestDispatcher.ERROR_MESSAGE);
  if (message != null) {
    text.append(message).append('\n');
  }

  Throwable throwable = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
  if (throwable != null) {
    StringWriter sw = new StringWriter();
    throwable.printStackTrace(new PrintWriter(sw));
    text.append(sw);
  }

  Response.Status finalStatus = statusCode == null ?
      Response.Status.OK : Response.Status.fromStatusCode(statusCode.intValue());
  return Response.status(finalStatus).entity(text.toString()).build();
}
 
Example 45
Project: sonar-issueresolver-plugin   File: IssueDataTest.java   Source Code and License 5 votes vote down vote up
@Test
public void test() throws IOException {
	final Issue issue = ReflectionTestUtils.build(Issue.class, "status_", "RESOLVED", "resolution_", "FALSE-POSITIVE",
			"assignee_", "admin", "comments_",
			ReflectionTestUtils.build(Comments.class, "comments_",
					Arrays.asList(ReflectionTestUtils.build(Comment.class, "markdown_", "Comment one"),
							ReflectionTestUtils.build(Comment.class, "markdown_", "Comment two"))));

	final IssueData data = IssueData.fromIssue(issue);
	Assert.assertEquals("RESOLVED", data.getStatus());
	Assert.assertEquals("FALSE-POSITIVE", data.getResolution());
	Assert.assertEquals("admin", data.getAssignee());
	Assert.assertEquals(Arrays.asList("Comment one", "Comment two"), data.getComments());

	final String json;
	try (final StringWriter writer = new StringWriter()) {
		final JsonWriter jsonWriter = JsonWriter.of(writer);
		jsonWriter.beginObject();
		data.write(jsonWriter);
		jsonWriter.endObject();
		jsonWriter.close();

		json = writer.toString();
	}
	Assert.assertEquals("{\"status\":\"RESOLVED\",\"resolution\":\"FALSE-POSITIVE\",\"assignee\":\"admin\",\"comments\":[\"Comment one\",\"Comment two\"]}", json);

	final IssueData readData;
	try (final ByteArrayInputStream bais = new ByteArrayInputStream(json.getBytes("UTF-8"));
			final JsonReader reader = new JsonReader(bais)) {
		reader.beginObject();
		readData = IssueData.read(reader);
		reader.endObject();
	}
	
	Assert.assertEquals("RESOLVED", readData.getStatus());
	Assert.assertEquals("FALSE-POSITIVE", readData.getResolution());
	Assert.assertEquals("admin", readData.getAssignee());
	Assert.assertEquals(Arrays.asList("Comment one", "Comment two"), readData.getComments());
}
 
Example 46
Project: verify-hub   File: TestResponse.java   Source Code and License 5 votes vote down vote up
@Override
public <T> T readEntity(Class<T> entityType) {
    StringWriter writer = new StringWriter();
    try {
        IOUtils.copy(inputStream, writer, "UTF-8");
    } catch (IOException e) {
        throw new RuntimeException();
    }
    return (T) writer.toString();
}
 
Example 47
Project: incubator-netbeans   File: CountingSecurityManager.java   Source Code and License 5 votes vote down vote up
private void assertMembers(int cnt) {
    String res = System.getProperty("counting.reflection.whitelist");
    if (res == null) {
        Assert.fail("Please provide whitelist: " + res);
    }
    Properties okAccess = new Properties();
    try {
        okAccess.load(CountingSecurityManager.class.getResourceAsStream(res));
    } catch (IOException ex) {
        throw new IllegalStateException(ex);
    }

    int myCnt = 0;
    StringWriter w = new StringWriter();
    PrintWriter p = new PrintWriter(w);
    Set<Who> m;
    synchronized (members) {
        m = new TreeSet<Who>(members.values());
    }
    for (Who wh : m) {
        if (wh.isIgnore()) {
            continue;
        }
        String howMuchIsOK = okAccess.getProperty(wh.clazz.getName());
        if (howMuchIsOK != null && Integer.parseInt(howMuchIsOK) >= wh.count) {
            continue;
        }

            myCnt += wh.count;
        wh.printStackTrace(p);
        wh.count = 0;
    }
    if (myCnt > cnt) {
        Assert.fail("Expected at much " + cnt + " reflection efforts, but was: " + myCnt + "\n" + w);
    }
}
 
Example 48
Project: dev-alert-android   File: DevAlertFullView.java   Source Code and License 5 votes vote down vote up
private static String traceToString(DevAlertData data) {
    String exported = data.getMessage() + "\n";
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    data.getThrowable().printStackTrace(pw);
    exported = exported + sw.toString();
    return exported;
}
 
Example 49
Project: beaker-notebook-archive   File: SVGContainer.java   Source Code and License 5 votes vote down vote up
public static MIMEContainer SVG(Object data) throws Exception {
  String code = "";
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = factory.newDocumentBuilder();
  Document doc = validateData(data, builder);
  TransformerFactory tf = TransformerFactory.newInstance();
  Transformer transformer = tf.newTransformer();
  transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
  StringWriter writer = new StringWriter();
  transformer.transform(new DOMSource(doc), new StreamResult(writer));
  code = writer.getBuffer().toString().replaceAll("\n|\r", "");
  return addMimeType(MIME.IMAGE_SVG, code);
}
 
Example 50
Project: PSE   File: JSONArray.java   Source Code and License 5 votes vote down vote up
public static String toJSONString(double[] array){
	final StringWriter writer = new StringWriter();
	
	try {
		writeJSONString(array, writer);
		return writer.toString();
	} catch(IOException e){
		// This should never happen for a StringWriter
		throw new RuntimeException(e);
	}
}
 
Example 51
Project: GitHub   File: JsonMapper.java   Source Code and License 5 votes vote down vote up
/**
 * Serialize a list of objects to a JSON String.
 *
 * @param map The map of objects to serialize.
 */
public String serialize(Map<String, T> map) throws IOException {
    StringWriter sw = new StringWriter();
    JsonGenerator jsonGenerator = LoganSquare.JSON_FACTORY.createGenerator(sw);
    serialize(map, jsonGenerator);
    jsonGenerator.close();
    return sw.toString();
}
 
Example 52
Project: 5zig-TIMV-Plugin   File: JSONArray.java   Source Code and License 5 votes vote down vote up
public static String toJSONString(boolean[] array){
	final StringWriter writer = new StringWriter();
	
	try {
		writeJSONString(array, writer);
		return writer.toString();
	} catch(IOException e){
		// This should never happen for a StringWriter
		throw new RuntimeException(e);
	}
}
 
Example 53
Project: de.flapdoodle.solid   File: GetAttributeTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testNonExistingAttributeWithoutStrictVariables() throws PebbleException, IOException {
    PebbleEngine pebble = new PebbleEngine.Builder().loader(new StringLoader()).strictVariables(false).build();

    PebbleTemplate template = pebble.getTemplate("hello {{ object.name }}");
    Map<String, Object> context = new HashMap<>();
    context.put("object", new Object());

    Writer writer = new StringWriter();
    template.evaluate(writer, context);
    assertEquals("hello ", writer.toString());
}
 
Example 54
Project: vrap   File: IncludeResolver.java   Source Code and License 5 votes vote down vote up
private StringWriter preprocess(final Path filePath, final String currentIndent) throws IOException {
    final StringWriter stringWriter = new StringWriter();

    for (final String line : Files.readAllLines(filePath)) {
        final Matcher matcher = INCLUDE_TAG_PATTERN.matcher(line);

        if (line.startsWith("extends:")) {
            stringWriter.append(line).append("?include").append("\n");
            continue;
        }
        if (!line.startsWith("#%RAML 1.0 DataType")) {
            if (matcher.matches()) {
                final String indent = matcher.group(1) + "  ";
                final Path includePath = filePath.getParent().resolve(matcher.group(3));
                stringWriter.append(currentIndent).append(matcher.group(1)).append(matcher.group(2));
                if (!includePath.getFileName().toString().endsWith(".raml")) {
                    stringWriter.append(" |");
                }
                stringWriter.append("\n");
                final StringWriter includeWriter = preprocess(includePath, currentIndent + indent);
                stringWriter.append(includeWriter.toString()).append("\n");
            } else {
                stringWriter.append(currentIndent).append(line).append("\n");
            }
        }
    }
    return stringWriter;
}
 
Example 55
Project: de.flapdoodle.solid   File: CoreFiltersTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testMergeOk() throws PebbleException, IOException {
    PebbleEngine pebble = new PebbleEngine.Builder().loader(new StringLoader()).extension(new TestingExtension()).strictVariables(false).build();

    PebbleTemplate template = pebble
            .getTemplate("{{{'one':1}|merge({'two':2})|mapToString}} {%set m1 = {'one':1}|merge(['two'])%}{{m1['two']}} {{[1]|merge([2])|listToString}} {%set l1 = [1]|merge({'two':2})%}{{l1[1].value}} {{arr1|merge(arr2)|arrayToString}}");

    Map<String, Object> context = new HashMap<>();
    context.put("arr1", new int[] {1});
    context.put("arr2", new int[] {2});

    Writer writer = new StringWriter();
    template.evaluate(writer, context);
    assertEquals("{one=1, two=2} two [1,2] 2 [1,2]", writer.toString());
}
 
Example 56
Project: okmail   File: OkMailClientTest.java   Source Code and License 5 votes vote down vote up
@Test
@Ignore
public void testThymeleafTemplate() throws IOException, MessagingException {

    ClassLoaderTemplateResolver templateResolver =
            new ClassLoaderTemplateResolver();

    templateResolver.setTemplateMode(TemplateMode.HTML);
    templateResolver.setPrefix("/templates/");
    templateResolver.setSuffix(".html");
    templateResolver.setCacheTTLMs(Long.valueOf(3600000L));

    templateResolver.setCharacterEncoding("UTF-8");
    templateResolver.setCacheable(true);

    TemplateEngine templateEngine = new TemplateEngine();
    templateEngine.setTemplateResolver(templateResolver);

    Context ctx = new Context();
    ctx.setLocale(Locale.ENGLISH);
    ctx.setVariable("username", "ricky");
    ctx.setVariable("url", "http://www.thymeleaf.org");
    ctx.setVariable("email", "[email protected]");

    StringWriter sw = new StringWriter(1024);
    templateEngine.process("registry", ctx, sw);

    String output = sw.toString();
    System.out.println(output);

    Mail mail = Mail.newBuilder().from(from,"ricky fung")
            .to(to)
            .subject("测试邮件[模板邮件-Thymeleaf]")
            .html(output)
            .build();

    client.send(mail);
}
 
Example 57
Project: OpenDA   File: NetcdfUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Converts the data in the given netcdf file to text format and returns this as a String.
 * This can be used e.g. in unit tests to compare the data in human readable text format instead of in binary format.
 *
 * @param netcdfFile netcdf file
 * @param variableNames semicolon delimited list of variables of which the data should be printed.
 *                      If this is null or empty, then all variables are printed.
 * @return String with cdl representation of the data.
 * @throws IOException
 */
public static String netcdfFileToString(File netcdfFile, String variableNames) throws IOException {
	boolean printAllVariables = false;
	if (variableNames == null || variableNames.isEmpty()) {
		printAllVariables = true;
		variableNames = null;
	}

	Writer writer = new StringWriter();
	NCdumpW.print(netcdfFile.getAbsolutePath(), writer, printAllVariables, false, false, true, variableNames, null);
	return writer.toString();
}
 
Example 58
Project: util   File: XmlMapper.java   Source Code and License 5 votes vote down vote up
/**
 * Java Object->Xml with encoding.
 */
@SuppressWarnings("rawtypes")
public static String toXml(Object root, Class clazz, String encoding) {
	try {
		StringWriter writer = new StringWriter();
		createMarshaller(clazz, encoding).marshal(root, writer);
		return writer.toString();
	} catch (JAXBException e) {
		throw ExceptionUtil.unchecked(e);
	}
}
 
Example 59
Project: AlertFX   File: ErrorBox.java   Source Code and License 5 votes vote down vote up
/**
 * Shows the alert
 */
public void show(){
    alert.initStyle(style);
    alert.setTitle("Exception Caught!");
    alert.setHeaderText("Exception encountered");
    alert.setContentText(error.getMessage());

    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    error.printStackTrace(pw);
    String exceptionText = sw.toString();

    Label label = new Label("The exception stacktrace was:");
    TextArea textArea = new TextArea(exceptionText);
    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 60
Project: openjdk-jdk10   File: Issue41Test.java   Source Code and License 5 votes vote down vote up
/**
 * The return of XMLEvent writeAsEncodedUnicode method is not defined This
 * method merely tests that the output exists
 */
public void writeAsEncodedUnicode(XMLEvent evt) throws XMLStreamException {
    if (evt.getEventType() == XMLStreamConstants.END_DOCUMENT) {
        return;
    }
    StringWriter sw = new StringWriter();
    evt.writeAsEncodedUnicode(sw);

    Assert.assertTrue(sw.toString().length() > 0);
    System.out.println(sw.toString());
}