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

The following examples show how to use java.io.ByteArrayOutputStream#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: HttpExecuteFieldLevelEncryptionInterceptorTest.java    From client-encryption-java with MIT License 6 votes vote down vote up
@Test
public void testIntercept_ShouldEncryptRequestPayloadAndUpdateContentLengthHeader() throws Exception {

    // GIVEN
    FieldLevelEncryptionConfig config = getTestFieldLevelEncryptionConfigBuilder()
            .withEncryptionPath("$.foo", "$.encryptedFoo")
            .build();
    HttpRequest request = mock(HttpRequest.class);
    HttpHeaders httpHeaders = new HttpHeaders();
    when(request.getContent()).thenReturn(new ByteArrayContent(JSON_TYPE, "{\"foo\":\"bar\"}".getBytes()));
    when(request.getHeaders()).thenReturn(httpHeaders);

    // WHEN
    HttpExecuteFieldLevelEncryptionInterceptor instanceUnderTest = new HttpExecuteFieldLevelEncryptionInterceptor(config);
    instanceUnderTest.intercept(request);

    // THEN
    ArgumentCaptor<HttpContent> contentCaptor = ArgumentCaptor.forClass(HttpContent.class);
    verify(request).setContent(contentCaptor.capture());
    ByteArrayOutputStream encryptedPayloadStream = new ByteArrayOutputStream();
    contentCaptor.getValue().writeTo(encryptedPayloadStream);
    String encryptedPayload = encryptedPayloadStream.toString(StandardCharsets.UTF_8.name());
    Assert.assertFalse(encryptedPayload.contains("foo"));
    Assert.assertTrue(encryptedPayload.contains("encryptedFoo"));
    assertEquals(encryptedPayload.length(), httpHeaders.getContentLength().intValue());
}
 
Example 2
Source File: HarFileHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private String getEnvelope(SOAPMessage message) throws SOAPException, IOException {
   ByteArrayOutputStream stream = new ByteArrayOutputStream();

   String var3;
   try {
      message.writeTo(stream);
      if (stream.size() >= 1232896) {
         var3 = "message to large to log";
         return var3;
      }

      var3 = stream.toString(Charset.UTF_8.getName());
   } finally {
      ConnectorIOUtils.closeQuietly((Object)stream);
   }

   return var3;
}
 
Example 3
Source File: BuildCommandTest.java    From smithy with Apache License 2.0 6 votes vote down vote up
@Test
public void validationFailuresCausedByProjectionsAreDetected() throws Exception {
    PrintStream out = System.out;
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PrintStream printStream = new PrintStream(outputStream);
    System.setOut(printStream);

    CliError e = Assertions.assertThrows(CliError.class, () -> {
        String model = getClass().getResource("valid-model.smithy").getPath();
        String config = getClass().getResource("projection-build-failure.json").getPath();
        SmithyCli.create().run("build", "--debug", "--config", config, model);
    });

    System.setOut(out);
    String output = outputStream.toString("UTF-8");

    assertThat(output, containsString("ResourceLifecycle"));
    assertThat(e.getMessage(),
               containsString("The following 1 Smithy build projection(s) failed: [exampleProjection]"));
}
 
Example 4
Source File: CrashHandlerHelper.java    From base-module with Apache License 2.0 5 votes vote down vote up
private String inputStream2String(InputStream is) throws IOException {
    byte[] buf = new byte[1024];
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    for (int i; (i = is.read(buf)) != -1; ) {
        baos.write(buf, 0, i);
    }
    String data = baos.toString("UTF-8");
    baos.close();
    return data;
}
 
Example 5
Source File: PropertiesToStringConverter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public String convert(Properties source) {
	try {
		ByteArrayOutputStream os = new ByteArrayOutputStream(256);
		source.store(os, null);
		return os.toString("ISO-8859-1");
	}
	catch (IOException ex) {
		// Should never happen.
		throw new IllegalArgumentException("Failed to store [" + source + "] into String", ex);
	}
}
 
Example 6
Source File: RunTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
void testRun() throws BadArgs, IOException {
    System.err.println("test run(String[])");
    DocLint dl = new DocLint();
    String[] args = { "-help" };
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(baos);
    PrintStream prev = System.out;
    try {
        System.setOut(ps);
        dl.run(args);
    } finally {
        System.setOut(prev);
    }
    ps.close();
    String stdout = baos.toString();

    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    dl.run(pw, args);
    pw.close();
    String direct = sw.toString();

    if (!stdout.equals(direct)) {
        error("unexpected output");
        System.err.println("EXPECT>>" + direct + "<<");
        System.err.println("FOUND>>" + stdout + "<<");
    }
}
 
Example 7
Source File: GridController.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
String getDatasetXML() {
  if (gridDataset == null)
    return "";
  try {
    ByteArrayOutputStream bos = new ByteArrayOutputStream(10000);
    GridDatasetInfo info = new GridDatasetInfo(gridDataset, "path");
    info.writeXML(info.makeDatasetDescription(), bos);
    return bos.toString(StandardCharsets.UTF_8.name());
  } catch (IOException ioe) {
    ioe.printStackTrace();
  }
  return "";
}
 
Example 8
Source File: Utils.java    From jellyfin-androidtv with GNU General Public License v2.0 5 votes vote down vote up
public static String readStringFromStream(InputStream inputStream) throws IOException {
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int length;
    while ((length = inputStream.read(buffer)) != -1) {
        result.write(buffer, 0, length);
    }

    return result.toString(StandardCharsets.UTF_8.name());
}
 
Example 9
Source File: AbstractYarnClusterDescriptor.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@Override
public String getClusterDescription() {

	try {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		PrintStream ps = new PrintStream(baos);

		YarnClusterMetrics metrics = yarnClient.getYarnClusterMetrics();

		ps.append("NodeManagers in the ClusterClient " + metrics.getNumNodeManagers());
		List<NodeReport> nodes = yarnClient.getNodeReports(NodeState.RUNNING);
		final String format = "|%-16s |%-16s %n";
		ps.printf("|Property         |Value          %n");
		ps.println("+---------------------------------------+");
		int totalMemory = 0;
		int totalCores = 0;
		for (NodeReport rep : nodes) {
			final Resource res = rep.getCapability();
			totalMemory += res.getMemory();
			totalCores += res.getVirtualCores();
			ps.format(format, "NodeID", rep.getNodeId());
			ps.format(format, "Memory", res.getMemory() + " MB");
			ps.format(format, "vCores", res.getVirtualCores());
			ps.format(format, "HealthReport", rep.getHealthReport());
			ps.format(format, "Containers", rep.getNumContainers());
			ps.println("+---------------------------------------+");
		}
		ps.println("Summary: totalMemory " + totalMemory + " totalCores " + totalCores);
		List<QueueInfo> qInfo = yarnClient.getAllQueues();
		for (QueueInfo q : qInfo) {
			ps.println("Queue: " + q.getQueueName() + ", Current Capacity: " + q.getCurrentCapacity() + " Max Capacity: " +
				q.getMaximumCapacity() + " Applications: " + q.getApplications().size());
		}
		return baos.toString();
	} catch (Exception e) {
		throw new RuntimeException("Couldn't get cluster description", e);
	}
}
 
Example 10
Source File: SuseDataXmlWriter.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 *
 * @param pkgDto pkg info to add to xml
 */
public void addPackage(PackageDto pkgDto) {
    long pkgId = pkgDto.getId().longValue();
    List<String> eulas = new EulaManager().getEulasForPackage(pkgId);

    Collection<String> keywords = TaskManager
            .getChannelPackageKeywords(channelId, pkgId);

    if (keywords.isEmpty() && eulas.isEmpty()) {
        // this package has no keywords and no EULA
        return;
    }
    try {
        ByteArrayOutputStream st = new ByteArrayOutputStream();
        SimpleContentHandler tmpHandler = getTemporaryHandler(st);

        tmpHandler.startDocument();
        addPackageBoilerplate(tmpHandler, pkgDto);
        addEulas(pkgId, eulas, tmpHandler);
        addKeywords(pkgId, keywords, tmpHandler);
        tmpHandler.endElement("package");
        tmpHandler.endDocument();

        String pkg =  st.toString();
        handler.addCharacters(pkg);
    }
    catch (SAXException e) {
        throw new RepomdRuntimeException(e);
    }
}
 
Example 11
Source File: CompressUtil.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
public static String Decompress(byte[] bytes) throws Exception {
	Inflater decompressor = new Inflater();
	decompressor.setInput(bytes);

	// Create an expandable byte array to hold the decompressed data
	ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length);

	byte[] buffer = new byte[1024];
	try {
		while (true) {
			int count = decompressor.inflate(buffer);
			if (count > 0) {
				bos.write(buffer, 0, count);
			}
			else if (count == 0 && decompressor.finished()) {
				break;
			}
			else {
				throw new RuntimeException("Bad zip data, size: " + bytes.length);
			}
		}
	}
	finally {
		decompressor.end();
	}

	bos.close();
	return bos.toString("UTF-16LE");
}
 
Example 12
Source File: EmailSendTaskTest.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected String getMessage(MimeMessage mimeMessage) throws MessagingException, IOException {
  DataHandler dataHandler = mimeMessage.getDataHandler();
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  dataHandler.writeTo(baos);
  baos.flush();
  return baos.toString();
}
 
Example 13
Source File: S3Resource.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@GET
@Path("blocking")
@Produces(TEXT_PLAIN)
public String testBlockingS3() {
    LOG.info("Testing S3 Blocking client with bucket: " + SYNC_BUCKET);

    String keyValue = UUID.randomUUID().toString();
    String result = null;

    try {
        if (S3Utils.createBucket(s3Client, SYNC_BUCKET)) {
            if (s3Client.putObject(S3Utils.createPutRequest(SYNC_BUCKET, keyValue),
                    RequestBody.fromString(SAMPLE_S3_OBJECT)) != null) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();

                GetObjectResponse object = s3Client.getObject(S3Utils.createGetRequest(SYNC_BUCKET, keyValue),
                        ResponseTransformer.toOutputStream(baos));

                if (object != null) {
                    result = metadata(object) + "+" + baos.toString();
                }
            }
        }
    } catch (Exception ex) {
        LOG.error("Error during S3 operations.", ex);
        return "ERROR";
    }
    return result;
}
 
Example 14
Source File: ResourcesLoader.java    From Box with Apache License 2.0 4 votes vote down vote up
public static CodeWriter loadToCodeWriter(InputStream is) throws IOException {
	ByteArrayOutputStream baos = new ByteArrayOutputStream(READ_BUFFER_SIZE);
	copyStream(is, baos);
	return new CodeWriter(baos.toString("UTF-8"));
}
 
Example 15
Source File: TypeCodeImpl.java    From JDKSourceCode1.8 with MIT License 4 votes vote down vote up
public String toString() {
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream(1024);
    PrintStream printOut = new PrintStream(byteOut, true);
    printStream(printOut);
    return super.toString() + " =\n" + byteOut.toString();
}
 
Example 16
Source File: Node.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public String toString() {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    print(new PrintStream(bos));
    return bos.toString();
}
 
Example 17
Source File: StrictLineReader.java    From MediaSDK with Apache License 2.0 4 votes vote down vote up
/**
 * Reads the next line. A line ends with {@code "\n"} or {@code "\r\n"},
 * this end of line marker is not included in the result.
 *
 * @return the next line from the input.
 * @throws IOException for underlying {@code InputStream} errors.
 * @throws EOFException for the end of source stream.
 */
public String readLine() throws IOException {
    synchronized (in) {
        if (buf == null) {
            throw new IOException("LineReader is closed");
        }

        // Read more data if we are at the end of the buffered data.
        // Though it's an error to read after an exception, we will let {@code fillBuf()}
        // throw again if that happens; thus we need to handle end == -1 as well as end == pos.
        if (pos >= end) {
            fillBuf();
        }
        // Try to find LF in the buffered data and return the line if successful.
        for (int i = pos; i != end; ++i) {
            if (buf[i] == LF) {
                int lineEnd = (i != pos && buf[i - 1] == CR) ? i - 1 : i;
                String res = new String(buf, pos, lineEnd - pos);
                pos = i + 1;
                return res;
            }
        }

        // Let's anticipate up to 80 characters on top of those already read.
        ByteArrayOutputStream out = new ByteArrayOutputStream(end - pos + 80) {
            @Override
            public String toString() {
                int length = (count > 0 && buf[count - 1] == CR) ? count - 1 : count;
                return new String(buf, 0, length);
            }
        };

        while (true) {
            out.write(buf, pos, end - pos);
            // Mark unterminated line in case fillBuf throws EOFException or IOException.
            end = -1;
            fillBuf();
            // Try to find LF in the buffered data and return the line if successful.
            for (int i = pos; i != end; ++i) {
                if (buf[i] == LF) {
                    if (i != pos) {
                        out.write(buf, pos, i - pos);
                    }
                    pos = i + 1;
                    return out.toString();
                }
            }
        }
    }
}
 
Example 18
Source File: FunctionNamespaceTest.java    From systemds with Apache License 2.0 4 votes vote down vote up
private void runFunctionNoInliningNamespaceTest(String TEST_NAME, boolean IPA)
{
	boolean origIPA = OptimizerUtils.ALLOW_INTER_PROCEDURAL_ANALYSIS;
	
	getAndLoadTestConfiguration(TEST_NAME);
	
	fullDMLScriptName = SCRIPT_DIR + TEST_DIR + TEST_NAME + ".dml";
	programArgs = new String[]{"-args", String.valueOf(rows), String.valueOf(cols), String.valueOf(val), output("Rout")};
	
	PrintStream originalStdErr = System.err;

	try
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		PrintStream newStdErr = new PrintStream(baos);
		System.setErr(newStdErr);
		
		OptimizerUtils.ALLOW_INTER_PROCEDURAL_ANALYSIS = IPA;
		runTest(true, false, null, -1); 
		
		//compare output
		double ret = HDFSTool.readDoubleFromHDFSFile(output("Rout"));
		Assert.assertEquals(Double.valueOf(rows*cols*val*6), Double.valueOf(ret));
		
		//compiled MR jobs
		int expectNumCompiled = IPA ? 0 : 4; 
		Assert.assertEquals("Unexpected number of compiled MR jobs.", expectNumCompiled, Statistics.getNoOfCompiledSPInst());
	
		//check executed MR jobs (should always be 0 due to dynamic recompilation)
		int expectNumExecuted = 0;
		Assert.assertEquals("Unexpected number of executed MR jobs.", expectNumExecuted, Statistics.getNoOfExecutedSPInst());
		
		String stdErrString = baos.toString();
		if (stdErrString != null && stdErrString.length() > 0)
			Assert.fail("Unexpected parse error or DML script error: " + stdErrString);
	}
	catch (Exception e) {
		e.printStackTrace(originalStdErr);
		Assert.fail("Unexpected exception: " + e);
	}
	finally {
		System.setErr(originalStdErr);
		OptimizerUtils.ALLOW_INTER_PROCEDURAL_ANALYSIS = origIPA;
	}
}
 
Example 19
Source File: LoadAndStoreXMLWithDefaults.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public String writeToXML(Properties p) throws IOException {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    p.storeToXML(baos, "Test 8016344");
    return baos.toString();
}
 
Example 20
Source File: AbstractSerializer.java    From TencentKona-8 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Returns a <code>String</code> representation of the specified
 * <code>NodeList</code>.
 * <p/>
 * This is a special case because the NodeList may represent a
 * <code>DocumentFragment</code>. A document fragment may be a
 * non-valid XML document (refer to appropriate description of
 * W3C) because it my start with a non-element node, e.g. a text
 * node.
 * <p/>
 * The methods first converts the node list into a document fragment.
 * Special care is taken to not destroy the current document, thus
 * the method clones the nodes (deep cloning) before it appends
 * them to the document fragment.
 * <p/>
 * Refer also to comments about setup of format.
 *
 * @param content the <code>NodeList</code> to serialize.
 * @return the <code>String</code> representation of the serialized
 *   <code>NodeList</code>.
 * @throws Exception
 */
public String serialize(NodeList content) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    canon.setWriter(baos);
    canon.notReset();
    for (int i = 0; i < content.getLength(); i++) {
        canon.canonicalizeSubtree(content.item(i));
    }
    String ret = baos.toString("UTF-8");
    baos.reset();
    return ret;
}