Java Code Examples for org.apache.commons.io.output.ByteArrayOutputStream#toByteArray()

The following examples show how to use org.apache.commons.io.output.ByteArrayOutputStream#toByteArray() . 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: CloverDataParserTest.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected byte[] getBytes(int compressLevel) {
	try {
		CloverDataFormatter formatter = new CloverDataFormatter();
		formatter.setCompressLevel(compressLevel);
		DataRecordMetadata metadata = getMetadata();
		formatter.init(metadata);
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		formatter.setDataTarget(os);
		formatter.writeHeader();
		DataRecord record = DataRecordFactory.newRecord(metadata);
		CloverBuffer buffer = null;
		if (formatter.isDirect()) {
			buffer = CloverBuffer.allocate(Defaults.Record.RECORD_INITIAL_SIZE, Defaults.Record.RECORD_LIMIT_SIZE);
		}
		record.getField(0).setValue("test1");
		writeRecord(formatter, record, buffer);
		record.getField(0).setValue("test2");
		writeRecord(formatter, record, buffer);
		formatter.writeFooter();
		formatter.flush();
		formatter.close();
		return os.toByteArray();
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 2
Source File: LogDataListPersistanceVer2Test.java    From otroslogviewer with Apache License 2.0 6 votes vote down vote up
@Test
public void testLogDataWithoutProperties() throws IOException {
  LogData logData = new LogDataBuilder().withId(1).withDate(new Date()).withLevel(Level.INFO).withMessage("My Message1").build();

  List<LogData> list = new ArrayList<>();
  list.add(logData);

  ByteArrayOutputStream out = new ByteArrayOutputStream();
  ver2.saveLogsList(out, list);

  ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
  List<LogData> loadLogsList = ver2.loadLogsList(in);

  AssertJUnit.assertEquals(1, loadLogsList.size());
  Map<String, String> propertiesRead = loadLogsList.get(0).getProperties();
  AssertJUnit.assertEquals(0, propertiesRead.size());
}
 
Example 3
Source File: LogDataListPersistanceVer2Test.java    From otroslogviewer with Apache License 2.0 6 votes vote down vote up
@Test
public void testLogMessagesWithCarriageReturn() throws IOException {
  List<LogData> list = new ArrayList<>();
  LogData ld1 = new LogDataBuilder().withId(1).withDate(new Date()).withLevel(Level.INFO).withMessage("My Message1\r\nLine2").withThread("T1").build();
  LogData ld2 = new LogDataBuilder().withId(2).withDate(new Date()).withLevel(Level.INFO).withMessage("My Message2\r\nLine2").withThread("T1").build();
  list.add(ld1);
  list.add(ld2);
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  ver2.saveLogsList(out, list);

  ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
  List<LogData> loadLogsList = ver2.loadLogsList(in);

  AssertJUnit.assertEquals(2, loadLogsList.size());
  AssertJUnit.assertEquals(ld1.getMessage(), loadLogsList.get(0).getMessage());
  AssertJUnit.assertEquals(ld2.getMessage(), loadLogsList.get(1).getMessage());
  AssertJUnit.assertEquals(ld1, loadLogsList.get(0));
  AssertJUnit.assertEquals(ld2, loadLogsList.get(1));
}
 
Example 4
Source File: AvroLWM2MDataPublish.java    From SDA with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 데이타 전송
 * @param event
 * @throws Exception
 * @return void
 */
public void send(COL_LWM2M event) throws Exception {
	EncoderFactory avroEncoderFactory = EncoderFactory.get();
	SpecificDatumWriter<COL_LWM2M> avroEventWriter = new SpecificDatumWriter<COL_LWM2M>(COL_LWM2M.SCHEMA$);
	
	ByteArrayOutputStream stream = new ByteArrayOutputStream();
	BinaryEncoder binaryEncoder = avroEncoderFactory.binaryEncoder(stream,null);

	try {
		avroEventWriter.write(event, binaryEncoder);
		binaryEncoder.flush();
	} catch (IOException e) {
		e.printStackTrace();
		throw e;
	}
	IOUtils.closeQuietly(stream);

	KeyedMessage<String, byte[]> data = new KeyedMessage<String, byte[]>(
			TOPIC, stream.toByteArray());

	producer.send(data);
}
 
Example 5
Source File: LogDataListPersistanceVer2Test.java    From otroslogviewer with Apache License 2.0 6 votes vote down vote up
@Test
public void testLogMessagesWithEmptyLastParams() throws IOException {
  List<LogData> list = new ArrayList<>();
  LogData ld1 = new LogDataBuilder().withId(1).withDate(new Date()).withLevel(Level.INFO).withMessage("My Message1").build();
  LogData ld2 = new LogDataBuilder().withId(2).withDate(new Date()).withLevel(Level.INFO).withMessage("My Message2").build();
  list.add(ld1);
  list.add(ld2);
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  ver2.saveLogsList(out, list);

  ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
  List<LogData> loadLogsList = ver2.loadLogsList(in);

  AssertJUnit.assertEquals(2, loadLogsList.size());
  AssertJUnit.assertEquals(ld1.getMessage(), loadLogsList.get(0).getMessage());
  AssertJUnit.assertEquals(ld2.getMessage(), loadLogsList.get(1).getMessage());
  AssertJUnit.assertEquals(ld1, loadLogsList.get(0));
  AssertJUnit.assertEquals(ld2, loadLogsList.get(1));
}
 
Example 6
Source File: TestObjectSerializer.java    From java-license-manager with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadObject3() throws Exception
{
    MockTestObject1 object = new MockTestObject1();
    object.coolTest = true;
    Arrays.fill(object.myArray, (byte) 12);

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    ObjectOutputStream stream = new ObjectOutputStream(bytes);

    stream.writeObject(object);
    stream.close();

    byte[] data = bytes.toByteArray();

    MockTestObject1 returned = this.serializer.readObject(MockTestObject1.class, data);

    assertNotNull("The returned object should not be null.", returned);
    assertNotSame("The returned object should not be the same.", returned, object);
    assertEquals("The returned object should be equal.", object, returned);
}
 
Example 7
Source File: SerializationTest.java    From pravega with Apache License 2.0 6 votes vote down vote up
@Test
public void testRevision() throws IOException, ClassNotFoundException {
    RevisionImpl revision = new RevisionImpl(Segment.fromScopedName("Foo/Bar/1"), 2, 3);
    String string = revision.toString();
    Revision revision2 = Revision.fromString(string);
    assertEquals(revision, revision2);
    assertEquals(Segment.fromScopedName("Foo/Bar/1"), revision2.asImpl().getSegment());
    assertEquals(2, revision2.asImpl().getOffsetInSegment());
    assertEquals(3, revision2.asImpl().getEventAtOffset());

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    @Cleanup
    ObjectOutputStream oout = new ObjectOutputStream(bout);
    oout.writeObject(revision);
    byte[] byteArray = bout.toByteArray();
    ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(byteArray));
    Object revision3 = oin.readObject();
    assertEquals(revision, revision3);
    assertEquals(revision2, revision3);
}
 
Example 8
Source File: PropertyManagementTest.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Test
public void testStore() throws Exception {
  final PropertyManagement pm = new PropertyManagement();
  pm.store(
      ExtractParameters.Extract.QUERY,
      QueryBuilder.newBuilder().addTypeName("adapterId").indexName("indexId").build());
  assertEquals(
      QueryBuilder.newBuilder().addTypeName("adapterId").indexName("indexId").build(),
      pm.getPropertyAsQuery(ExtractParameters.Extract.QUERY));

  final Path path1 = new Path("http://java.sun.com/j2se/1.3/foo");
  pm.store(Input.HDFS_INPUT_PATH, path1);

  final ByteArrayOutputStream bos = new ByteArrayOutputStream();
  try (ObjectOutputStream os = new ObjectOutputStream(bos)) {
    os.writeObject(pm);
  }
  final ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
  try (ObjectInputStream is = new ObjectInputStream(bis)) {
    final PropertyManagement pm2 = (PropertyManagement) is.readObject();
    assertEquals(
        QueryBuilder.newBuilder().addTypeName("adapterId").indexName("indexId").build(),
        pm2.getPropertyAsQuery(ExtractParameters.Extract.QUERY));
    assertEquals(path1, pm2.getPropertyAsPath(Input.HDFS_INPUT_PATH));
  }
}
 
Example 9
Source File: TestWorkflowBundleIO.java    From incubator-taverna-language with Apache License 2.0 5 votes vote down vote up
@Test
public void writeBundleStream() throws Exception {
	ByteArrayOutputStream output = new ByteArrayOutputStream();
	bundleIO.writeBundle(wfBundle, output, TEXT_VND_TAVERNA_SCUFL2_STRUCTURE);
	String bundleTxt = new String(output.toByteArray(), UTF_8);
               String getStructureFormatWorkflowBundle = getStructureFormatWorkflowBundle();
               bundleTxt = bundleTxt.replaceAll("\r", "").replaceAll("\n", "");
               getStructureFormatWorkflowBundle = getStructureFormatWorkflowBundle.replaceAll("\r", "").replaceAll("\n", "");
	assertEquals(getStructureFormatWorkflowBundle, bundleTxt);
}
 
Example 10
Source File: GzipUtils.java    From nem-apps-lib with MIT License 5 votes vote down vote up
/**
 * Compress.
 *
 * @param str the str
 * @return the byte[]
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static byte[] compress(final String str) throws IOException {
	if ((str == null) || (str.length() == 0)) {
		return null;
	}
	ByteArrayOutputStream obj = new ByteArrayOutputStream();
	GZIPOutputStream gzip = new GZIPOutputStream(obj);
	gzip.write(str.getBytes("UTF-8"));
	gzip.flush();
	gzip.close();
	return obj.toByteArray();
}
 
Example 11
Source File: BlogIterator.java    From newblog with Apache License 2.0 5 votes vote down vote up
/**
 * 将Blog对象序列化存入payload
 * 可以只将所需要的字段存入payload,这里对整个实体类进行序列化,方便以后需求,不建议采用这种方法
 */
@Override
public BytesRef payload() {
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bos);
        out.writeObject(currentBlog);
        out.close();
        BytesRef bytesRef = new BytesRef(bos.toByteArray());
        return bytesRef;
    } catch (IOException e) {
        logger.error("", e);
        return null;
    }
}
 
Example 12
Source File: TestRDFXMLReader.java    From incubator-taverna-language with Apache License 2.0 5 votes vote down vote up
@Test
	public void xmlOutput() throws Exception {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		new RDFXMLSerializer(workflowBundle).workflowDoc(output,
				workflowBundle.getMainWorkflow(),
				URI.create("workflows/HelloWorld.rdf"));
		@SuppressWarnings("unused")
		String bundleTxt = new String(output.toByteArray(), "UTF-8");
//		System.out.println(bundleTxt);

	}
 
Example 13
Source File: LazySvnVersionedFile.java    From Getaviz with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] getContent() throws FilesNotAvailableException {
	try {
		ByteArrayOutputStream output = new ByteArrayOutputStream(ONE_MB);
		repo.getFile(currentFilePath, revision, null, output);
		return output.toByteArray();
	} catch (SVNException e) {
		throw new FilesNotAvailableException(e);
	}
}
 
Example 14
Source File: PostgreSqlIntegrationTest.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Test(groups = "Integration")
public void test_localhost_withRoles() throws Exception {
    PostgreSqlNode pgsql = app.createAndManageChild(EntitySpec.create(PostgreSqlNode.class)
            .configure(PostgreSqlNode.MAX_CONNECTIONS, 10)
            .configure(PostgreSqlNode.SHARED_MEMORY, "512kB") // Very low so kernel configuration not needed
            .configure(PostgreSqlNode.INITIALIZE_DB, true)
            .configure(PostgreSqlNode.ROLES, ImmutableMap.<String, Map<String, ?>>of(
                    "Developer", ImmutableMap.<String, Object>of(
                            "properties", "CREATEDB LOGIN",
                            "privileges", ImmutableList.of(
                                    "SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public", 
                                    "EXECUTE ON ALL FUNCTIONS IN SCHEMA public")),
                    "Analyst", ImmutableMap.<String, Object>of(
                            "properties", "LOGIN",
                            "privileges", "SELECT ON ALL TABLES IN SCHEMA public")))
            ); 

    app.start(ImmutableList.of(loc));
    String url = pgsql.getAttribute(DatastoreCommon.DATASTORE_URL);
    log.info("PostgreSql started on "+url);
    
    // Use psql to get the roles and properties
    // TODO Does not list privileges, so that is not tested.
    SshMachineLocation machine = Machines.findUniqueMachineLocation(pgsql.getLocations(), SshMachineLocation.class).get();
    String installDir = pgsql.sensors().get(PostgreSqlNode.INSTALL_DIR);
    int port = pgsql.sensors().get(PostgreSqlNode.POSTGRESQL_PORT);
    ByteArrayOutputStream stdoutStream = new ByteArrayOutputStream();
    ByteArrayOutputStream stderrStream = new ByteArrayOutputStream();
    int result = machine.execCommands(
            ImmutableMap.of(
                    SshMachineLocation.STDOUT.getName(), stdoutStream,
                    SshMachineLocation.STDERR.getName(), stderrStream),
            "checkState", 
            ImmutableList.of(BashCommands.sudoAsUser("postgres", installDir + "/bin/psql -p " + port + " --command \"\\du\"")));
    String stdout = new String(stdoutStream.toByteArray());
    String stderr = new String(stderrStream.toByteArray());
    assertEquals(result, 0, "stdout="+stdout+"; stderr="+stderr);
    checkRole(stdout, "analyst", "");
    checkRole(stdout, "developer", "Create DB");
}
 
Example 15
Source File: AbstractLocProfileTest.java    From coderadar with MIT License 5 votes vote down vote up
Loc countLines(String path, LocProfile profile) throws IOException {
  InputStream in = getClass().getResourceAsStream(path);
  assertThat(in).isNotNull();
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  IOUtils.copy(in, out);
  byte[] file = out.toByteArray();
  LocCounter counter = new LocCounter();

  path = path.replaceAll("\\.loctest", "");
  assertThatProfileIsRegistered(path, file, profile);

  return counter.count(file, profile);
}
 
Example 16
Source File: NoEntityBodyPropertyCheck.java    From product-ei with Apache License 2.0 5 votes vote down vote up
@Test(groups = "wso2.esb", description = " Checking NO_ENTITY_BODY_PROPERTY", enabled = true)
public void testNoEntityBodyPropertyTestCase() throws Exception {
    String payload =
               "      <Person>" +
               "         <ID>12999E105</ID>" +
               "      </Person>";

    HttpResponse response = httpClient.doPost("http://localhost:8480/services/NoEntityBodyPropertyTestProxy",
                                              null, payload, "application/xml");
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    response.getEntity().writeTo(bos);
    String exPayload = new String(bos.toByteArray());
    Assert.assertEquals("", exPayload);
}
 
Example 17
Source File: TestObjectSerializer.java    From java-license-manager with Apache License 2.0 5 votes vote down vote up
@Test(expected = ObjectTypeNotExpectedException.class)
public void testReadObject1() throws Exception
{
    MockTestObject1 object = new MockTestObject1();

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    ObjectOutputStream stream = new ObjectOutputStream(bytes);

    stream.writeObject(object);
    stream.close();

    byte[] data = bytes.toByteArray();

    this.serializer.readObject(MockTestObject2.class, data);
}
 
Example 18
Source File: SVGImageMinimizer.java    From qualinsight-plugins-sonarqube-badges with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Processes font transformation on an SVG input stream.
 *
 * @param inputStream InputStream that contains the SVG image to be transformed.
 * @param parameters parameters to set before minimization.
 * @return an InputStream with transformed content.
 * @throws SVGImageMinimizerException if a problem occurs during stream transformation.
 */
public InputStream process(final InputStream inputStream, final Map<String, Object> parameters) throws SVGImageMinimizerException {
    try {
        final DocumentBuilder builder = this.builderFactory.newDocumentBuilder();
        final Document document = builder.parse(inputStream);
        final Source source = new DOMSource(document);
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        final Result result = new StreamResult(outputStream);
        transform(source, result, parameters);
        return new ByteArrayInputStream(outputStream.toByteArray());
    } catch (final IOException | TransformerException | SAXException | ParserConfigurationException e) {
        throw new SVGImageMinimizerException(e);
    }
}
 
Example 19
Source File: XSLTonEmptySoapBodyWithSourceXPath.java    From product-ei with Apache License 2.0 4 votes vote down vote up
@Test(groups = "wso2.esb",
      description = "xslt mediator should be able to transform empty soap body messages when the source xpath is specified")
public void testXSLTMediatorForEmptySOAPBody() throws Exception {

    Map<String, String> requestHeaders = new HashMap<String, String>();
    requestHeaders.put("accept", "text/xml");

    HttpResponse response = httpClient.doGet(getApiInvocationURL("xsltEmptySoapBodyWithSourceXPath"),
                                             requestHeaders);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    response.getEntity().writeTo(outputStream);

    String payload = new String(outputStream.toByteArray());

    assertTrue(payload.contains("Hello"), "Response should contain 'Hello'");

}
 
Example 20
Source File: MS1ScanForWellAndMassCharge.java    From act with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Serialize an object to an array of Serialized, gzip'd bytes.
 *
 * Note that this returns a byte stream (a) to be symmetrical with deserialize, and (b) because we anticipate
 * manifesting the entire byte array at some point so there's no advantage to streaming the results.  If that changes
 * and performance suffers from allocating the entire byte array, we can use byte streams instead (and we'll probably
 * have bigger performance problems to deal with anyway).
 *
 * @param object The object to serialize
 * @param <T> The type of the object (unbound to allow serialization of Maps, which sadly don't explicitly implement
 *            Serializable).
 * @return A byte array representing a compressed object stream for the specified object.
 * @throws IOException
 */
private static <T> byte[] serialize(T object) throws IOException {
  ByteArrayOutputStream postGzipOutputStream = new ByteArrayOutputStream();

  try (ObjectOutputStream out = new ObjectOutputStream(new GZIPOutputStream(postGzipOutputStream))) {
    out.writeObject(object);
  }

  return postGzipOutputStream.toByteArray();
}