Java Code Examples for java.io.OutputStream#toString()

The following examples show how to use java.io.OutputStream#toString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ExceptionTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Test GlassFishException with no parameters specified throwing
 * and logging.
 */
@Test
public void testGlassFishExceptionWithNothing() {
    // this message must match GlassFishIdeException() constructor
    // log message.
    String gfieMsg = "Caught GlassFishIdeException.";
    java.util.logging.Logger logger = Logger.getLogger();
    Level logLevel = logger.getLevel();
    OutputStream logOut = new ByteArrayOutputStream(256);
    Handler handler = new StreamHandler(logOut, new SimpleFormatter());
    handler.setLevel(Level.WARNING);
    logger.addHandler(handler);       
    logger.setLevel(Level.WARNING);
    try {
        throw new GlassFishIdeException();
    } catch (GlassFishIdeException gfie) {
        handler.flush();
    } finally {
        logger.removeHandler(handler);
        handler.close();
        logger.setLevel(logLevel);
    }
    String logMsg = logOut.toString();
    int contains = logMsg.indexOf(gfieMsg);
    assertTrue(contains > -1);
}
 
Example 2
Source File: DevModeResponse.java    From ha-bridge with Apache License 2.0 6 votes vote down vote up
private String dataReader(String filePath) {

		String content = null;
		try {
			InputStream input = getClass().getResourceAsStream(filePath);
			OutputStream out = new ByteArrayOutputStream();
			int read;
			byte[] bytes = new byte[1024];

			while ((read = input.read(bytes)) != -1) {
				out.write(bytes, 0, read);
			}
			content = out.toString();
		} catch (IOException e) {
			log.error("Error reading the file: " + filePath + " message: " + e.getMessage(), e);
		}
		return content;
	}
 
Example 3
Source File: TransUtil.java    From oneops with Apache License 2.0 6 votes vote down vote up
public Map<String,String> keyGen(String passPhrase, String pubDesc) {
	JSch jsch=new JSch();
       String passphrase= (passPhrase == null) ? "" : passPhrase;
       Map<String,String> result = new HashMap<String,String>();
       try{
        KeyPair kpair=KeyPair.genKeyPair(jsch, KeyPair.RSA, 2048);
        kpair.setPassphrase(passphrase);
        OutputStream prkos = new ByteArrayOutputStream();
        kpair.writePrivateKey(prkos);
        String privateKey = prkos.toString();
        //removing "\n" at the end of the string
        result.put("private", privateKey.substring(0, privateKey.length() - 1));
        OutputStream pubkos = new ByteArrayOutputStream();
        kpair.writePublicKey(pubkos, pubDesc);
        String pubKey = pubkos.toString();
        //removing "\n" at the end of the string
        result.put("public", pubKey.substring(0, pubKey.length() - 1));
        kpair.dispose();
        return result;
       } catch(Exception e){
       	System.out.println(e);
       	logger.error(e.getMessage());
       	throw new TransistorException(CmsError.TRANSISTOR_EXCEPTION, e.getMessage());
       }
}
 
Example 4
Source File: DataIDGenerator.java    From gerbil with GNU Affero General Public License v3.0 6 votes vote down vote up
public String createDataIDModel(List<ExperimentTaskStatus> results, String eID) {
    // If the experiment is not existing (== there are no results), return
    // an empty String
    if (results.size() == 0) {
        return "";
    }

    Model model = generateDataIDModel();

    addToModel(model, results, eID);

    // writing dataid result to output
    OutputStream o = new ByteArrayOutputStream();

    // creating json-ld output format
    RDFDataMgr.write(o, model, Lang.JSONLD);

    return o.toString();
}
 
Example 5
Source File: JaxbParser.java    From sword-lang with Apache License 2.0 6 votes vote down vote up
/**
 * 转为xml串
 * @param obj
 * @return
 */
public String toXML(Object obj){
	String result = null;
	try {
		JAXBContext context = JAXBContext.newInstance(obj.getClass());
		Marshaller m = context.createMarshaller();
		m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		m.setProperty(Marshaller.JAXB_FRAGMENT, true);// 去掉报文头
	    OutputStream os = new ByteOutputStream();
		StringWriter writer = new StringWriter();
		XMLSerializer serializer = getXMLSerializer(os);
		m.marshal(obj, serializer.asContentHandler());
		result = os.toString();
	} catch (Exception e) {
		e.printStackTrace();
	}
	logger.info("response text:" + result);
	return result;
}
 
Example 6
Source File: CodeGenerator_new.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
/**
 * Compile simple class to check whether value valid.
 * If compilation failed appropriate message will be stored in ErrorStore.
 * @throws AMLException
 */
   protected final String compileTest(File javaFile, File classFile) throws AMLException
{
       try {
		List<String> args = new LinkedList<>();
		args.add("-classpath");
		args.add(compilerClassPath);
		args.add(javaFile.getAbsolutePath());

           logger.debug("compilerClassPath = " + compilerClassPath);

		String[] sargs = args.toArray(new String[0]);

		InputStream inStream = new ByteArrayInputStream(new byte[0]);
		OutputStream outStream = new ByteArrayOutputStream();
		OutputStream errStream = new ByteArrayOutputStream();
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		long time = System.currentTimeMillis();
		int err = compiler.run(inStream, outStream, errStream, sargs);
           logger.debug("compile time: " + (System.currentTimeMillis() - time));
		if (err != 0)
		{
			logger.error("Test file saved to: {}", javaFile.getCanonicalPath());
			// leave test file
			return errStream.toString();
		}

		javaFile.delete();
		if (classFile.exists())
		{
			classFile.delete();
		}

           return null;
       } catch(IOException e) {
		throw new AMLException("Failed write to file '"+javaFile+"':"+e.getLocalizedMessage(), e);
	}
   }
 
Example 7
Source File: HtmlWriterTest.java    From tablesaw with Apache License 2.0 5 votes vote down vote up
@Test
public void noEscape() throws IOException {
  String[] data = {"<p>foo</p>"};
  Table table = Table.create("t", StringColumn.create("data", data));

  OutputStream baos = new ByteArrayOutputStream();

  table.write().usingOptions(HtmlWriteOptions.builder(baos).escapeText(false).build());
  String output = baos.toString();
  assertEquals(
      "<table>"
          + LINE_END
          + " <thead>"
          + LINE_END
          + "  <tr>"
          + LINE_END
          + "   <th>data</th>"
          + LINE_END
          + "  </tr>"
          + LINE_END
          + " </thead>"
          + LINE_END
          + " <tbody>"
          + LINE_END
          + "  <tr>"
          + LINE_END
          + "   <td><p>foo</p></td>"
          + LINE_END
          + "  </tr>"
          + LINE_END
          + " </tbody>"
          + LINE_END
          + "</table>",
      output);
}
 
Example 8
Source File: SshMachineLocationIntegrationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups = "Integration")
public void testOverridingPropertyOnExec() throws Exception {
    SshMachineLocation host = new SshMachineLocation(MutableMap.of("address", Networking.getReachableLocalHost(), "sshPrivateKeyData", "wrongdata"));
    
    OutputStream outStream = new ByteArrayOutputStream();
    String expectedName = Os.user();
    host.execCommands(MutableMap.of("sshPrivateKeyData", null, "out", outStream), "my summary", ImmutableList.of("whoami"));
    String outString = outStream.toString();
    
    assertTrue(outString.contains(expectedName), "outString="+outString);
}
 
Example 9
Source File: HtmlWriterTest.java    From tablesaw with Apache License 2.0 5 votes vote down vote up
@Test
public void escape() throws IOException {
  String[] data = {"<p>foo</p>"};
  Table table = Table.create("t", StringColumn.create("data", data));

  OutputStream baos = new ByteArrayOutputStream();

  table.write().usingOptions(HtmlWriteOptions.builder(baos).build());
  String output = baos.toString();
  assertEquals(
      "<table>"
          + LINE_END
          + " <thead>"
          + LINE_END
          + "  <tr>"
          + LINE_END
          + "   <th>data</th>"
          + LINE_END
          + "  </tr>"
          + LINE_END
          + " </thead>"
          + LINE_END
          + " <tbody>"
          + LINE_END
          + "  <tr>"
          + LINE_END
          + "   <td>&lt;p&gt;foo&lt;/p&gt;</td>"
          + LINE_END
          + "  </tr>"
          + LINE_END
          + " </tbody>"
          + LINE_END
          + "</table>",
      output);
}
 
Example 10
Source File: ExceptionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Test PayaraException with message and cause <code>Throwable</code>
 * throwing and logging.
 */
@Test
public void testPayaraExceptionWithMsgAndCause() {
    String gfieMsg = "Test exception";
    String causeMsg = "Cause exception";
    java.util.logging.Logger logger = Logger.getLogger();
    Level logLevel = logger.getLevel();
    OutputStream logOut = new ByteArrayOutputStream(256);
    Handler handler = new StreamHandler(logOut, new SimpleFormatter());
    handler.setLevel(Level.WARNING);
    logger.addHandler(handler);       
    logger.setLevel(Level.WARNING);
    try {
        try {
            throw new Exception(causeMsg);
        } catch (Exception e) {
            throw new PayaraIdeException(gfieMsg, e);
        }
    } catch (PayaraIdeException gfie) {
        handler.flush();
    } finally {
        logger.removeHandler(handler);
        handler.close();
        logger.setLevel(logLevel);
    }
    String logMsg = logOut.toString();
    int containsGfieMsg = logMsg.indexOf(gfieMsg);
    int containsCauseMsg = logMsg.indexOf(causeMsg);
    assertTrue(containsGfieMsg > -1 && containsCauseMsg > -1);
}
 
Example 11
Source File: EntityBrokerImplTest.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Test
public void testFormatAndOutputEntity() {

    String fo = null;
    String reference = null;
    OutputStream output = null;
    String format = Formats.XML;

    // XML test valid resolveable entity
    reference = TestData.REF4;
    output = new ByteArrayOutputStream();
    entityBroker.formatAndOutputEntity(reference, format, null, output, null);
    fo = output.toString();
    assertNotNull(fo);
    assertTrue(fo.length() > 20);
    assertTrue(fo.contains(TestData.PREFIX4));
    assertTrue(fo.contains("<id>4-one</id>"));
    assertTrue(fo.contains(EntityEncodingManager.ENTITY_REFERENCE));

    // test list of entities
    ArrayList<EntityData> testEntities = new ArrayList<EntityData>();
    testEntities.add( new EntityData(TestData.REF4, null, TestData.entity4) );
    testEntities.add( new EntityData(TestData.REF4_two, null, TestData.entity4_two) );
    reference = TestData.SPACE4;
    output = new ByteArrayOutputStream();
    entityBroker.formatAndOutputEntity(reference, format, testEntities, output, null);
    fo = output.toString();
    assertNotNull(fo);
    assertTrue(fo.length() > 20);
    assertTrue(fo.contains(TestData.PREFIX4));
    assertTrue(fo.contains("<id>4-one</id>"));
    assertTrue(fo.contains("<id>4-two</id>"));
    assertFalse(fo.contains("<id>4-three</id>"));
    assertTrue(fo.contains(EntityEncodingManager.ENTITY_REFERENCE));

}
 
Example 12
Source File: XtextGrammarSerializationTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private void doTestSerialization(final String model, final String expectedModel) throws Exception {
  final XtextResource resource = this.getResourceFromString(model);
  Assert.assertTrue(resource.getErrors().isEmpty());
  EObject _rootASTElement = resource.getParseResult().getRootASTElement();
  final Grammar g = ((Grammar) _rootASTElement);
  Assert.assertNotNull(g);
  final OutputStream outputStream = new ByteArrayOutputStream();
  resource.save(outputStream, SaveOptions.newBuilder().format().getOptions().toOptionsMap());
  final String serializedModel = outputStream.toString();
  Assert.assertEquals(LineDelimiters.toPlatform(expectedModel), serializedModel);
}
 
Example 13
Source File: RecordingSshToolTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private ExecResult execScript(SshMachineLocation machine, String cmd) {
    OutputStream outStream = new ByteArrayOutputStream();
    OutputStream errStream = new ByteArrayOutputStream();
    int exitCode = machine.execScript(ImmutableMap.of("out", outStream, "err", errStream), "mysummary", ImmutableList.of(cmd));
    String outString = outStream.toString();
    String errString = errStream.toString();
    return new ExecResult(exitCode, outString, errString);
}
 
Example 14
Source File: PurgeUtilityLoggerTest.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings( "null" )
@Test
public void htmlLoggerTest() {
  OutputStream out = new ByteArrayOutputStream();
  PurgeUtilityLog.layoutClass = PurgeUtilityHTMLLayout.class;
  PurgeUtilityLogger.createNewInstance( out, PURGE_PATH, Level.DEBUG );
  PurgeUtilityLogger logger = PurgeUtilityLogger.getPurgeUtilityLogger();
  logger.setCurrentFilePath( "file1" );
  logger.info( "info on 1st file" );
  logger.setCurrentFilePath( "file2" );
  logger.debug( "debug on file2" );
  String nullString = null;
  try {
    nullString.getBytes(); // Generate an error to log
  } catch ( Exception e ) {
    logger.error( e );
  }

  logger.endJob();

  String logOutput = out.toString();

  Assert.assertTrue( logOutput.contains( PURGE_PATH ) );
  Assert.assertTrue( logOutput.contains( "info on 1st file" ) );
  Assert.assertTrue( logOutput.contains( "debug on file2" ) );
  Assert.assertTrue( logOutput.contains( "java.lang.NullPointerException" ) );
}
 
Example 15
Source File: XMLUtil.java    From developer-studio with Apache License 2.0 5 votes vote down vote up
public static String prettify(OMElement wsdlElement) throws Exception {
	OutputStream out = new ByteArrayOutputStream();
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	wsdlElement.serialize(baos);

	Source stylesheetSource = new StreamSource(new ByteArrayInputStream(prettyPrintStylesheet.getBytes()));
	Source xmlSource = new StreamSource(new ByteArrayInputStream(baos.toByteArray()));

	TransformerFactory tf = TransformerFactory.newInstance();
	Templates templates = tf.newTemplates(stylesheetSource);
	Transformer transformer = templates.newTransformer();
	transformer.transform(xmlSource, new StreamResult(out));
	return out.toString();
}
 
Example 16
Source File: OntologyRest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Gets the requested serialization of the provided Ontology.
 *
 * @param ontology  the Ontology you want to serialize in a different format.
 * @param rdfFormat the format you want.
 * @param skolemize whether or not the Ontology should be skoelmized before serialized (NOTE: only applies to
 *                  serializing as JSON-LD)
 * @return A String containing the newly serialized Ontology.
 */
private String getOntologyAsRdf(Ontology ontology, String rdfFormat, boolean skolemize) {
    switch (rdfFormat.toLowerCase()) {
        case "rdf/xml":
            return ontology.asRdfXml().toString();
        case "owl/xml":
            return ontology.asOwlXml().toString();
        case "turtle":
            return ontology.asTurtle().toString();
        default:
            OutputStream outputStream = ontology.asJsonLD(skolemize);
            return outputStream.toString();
    }
}
 
Example 17
Source File: MainTest.java    From wildfly-swarm with Apache License 2.0 5 votes vote down vote up
static Result runTool(String... args) throws Exception {
    final OutputStream err = new ByteArrayOutputStream();
    final OutputStream out = new ByteArrayOutputStream();
    final PrintStream origErr = System.err;
    final PrintStream origOut = System.out;
    final Result result = new Result();

    try {
        System.setErr(new PrintStream(err));
        System.setOut(new PrintStream(out));
        final String[] fullArgs = Arrays.copyOf(args, args.length + 1);
        fullArgs[fullArgs.length - 1] = "--output-dir=target/test-output";

        final long t = System.currentTimeMillis();
        result.jarFile(Main.generateSwarmJar(fullArgs));
        //origErr.println("generateSwarmJar took " + (System.currentTimeMillis() - t) + "ms");

    } catch (Main.ExitException e) {
        result.exitStatus = e.status;
        result.exitMessage = e.getMessage();
    } finally {
        System.setErr(origErr);
        System.setOut(origOut);
    }

    result.err = err.toString();
    result.out = out.toString();

    //System.out.println(result.err);

    return result;
}
 
Example 18
Source File: OutputStreamAppenderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testOutputStreamAppenderToByteArrayOutputStream() {
    final OutputStream out = new ByteArrayOutputStream();
    final String name = getName(out);
    final Logger logger = LogManager.getLogger(name);
    addAppender(out, name);
    logger.error(TEST_MSG);
    final String actual = out.toString();
    Assert.assertTrue(actual, actual.contains(TEST_MSG));
}
 
Example 19
Source File: EntityBrokerImplTest.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Test
public void testFormatAndOutputEntity() {

    String fo = null;
    String reference = null;
    OutputStream output = null;
    String format = Formats.XML;

    // XML test valid resolveable entity
    reference = TestData.REF4;
    output = new ByteArrayOutputStream();
    entityBroker.formatAndOutputEntity(reference, format, null, output, null);
    fo = output.toString();
    assertNotNull(fo);
    assertTrue(fo.length() > 20);
    assertTrue(fo.contains(TestData.PREFIX4));
    assertTrue(fo.contains("<id>4-one</id>"));
    assertTrue(fo.contains(EntityEncodingManager.ENTITY_REFERENCE));

    // test list of entities
    ArrayList<EntityData> testEntities = new ArrayList<EntityData>();
    testEntities.add( new EntityData(TestData.REF4, null, TestData.entity4) );
    testEntities.add( new EntityData(TestData.REF4_two, null, TestData.entity4_two) );
    reference = TestData.SPACE4;
    output = new ByteArrayOutputStream();
    entityBroker.formatAndOutputEntity(reference, format, testEntities, output, null);
    fo = output.toString();
    assertNotNull(fo);
    assertTrue(fo.length() > 20);
    assertTrue(fo.contains(TestData.PREFIX4));
    assertTrue(fo.contains("<id>4-one</id>"));
    assertTrue(fo.contains("<id>4-two</id>"));
    assertFalse(fo.contains("<id>4-three</id>"));
    assertTrue(fo.contains(EntityEncodingManager.ENTITY_REFERENCE));

}
 
Example 20
Source File: WorkflowModelServerAccess.java    From graphical-lsp with Eclipse Public License 2.0 4 votes vote down vote up
public static String toXMI(Resource resource) throws IOException {
	OutputStream out = new ByteArrayOutputStream();
	resource.save(out, Collections.EMPTY_MAP);
	return out.toString();
}