Java Code Examples for java.io.ByteArrayOutputStream.toByteArray()

The following are Jave code examples for showing how to use toByteArray() of the java.io.ByteArrayOutputStream class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: alfresco-repository   File: RemotableInputStream.java   View Source Code Vote up 6 votes
public static void main(String[] args) throws Exception
{
    RemotableInputStream remotableInputStream = new RemotableInputStream(InetAddress.getLocalHost().getHostName(), 7777, new ByteArrayInputStream("test".getBytes()));

    for (int b = -1; (b = remotableInputStream.read()) != -1;)
    {
        System.out.println((char) b);
    }

    remotableInputStream = new RemotableInputStream(InetAddress.getLocalHost().getHostName(), 7777, new ByteArrayInputStream("test".getBytes()));

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(remotableInputStream);

    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
    remotableInputStream = (RemotableInputStream) ois.readObject();

    for (int b = -1; (b = remotableInputStream.read()) != -1;)
    {
        System.out.println((char) b);
    }
    remotableInputStream.close();
}
 
Example 2
Project: alfresco-core   File: AbstractEncryptor.java   View Source Code Vote up 6 votes
/**
 * {@inheritDoc}
 * <p/>
 * Serializes and {@link #encrypt(String, AlgorithmParameters, byte[]) encrypts} the input data.
 */
@Override
public Pair<byte[], AlgorithmParameters> encryptObject(String keyAlias, AlgorithmParameters params, Object input)
{
    try
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(input);
        byte[] unencrypted = bos.toByteArray();
        return encrypt(keyAlias, params, unencrypted);
    }
    catch (Exception e)
    {
        throw new AlfrescoRuntimeException("Failed to serialize or encrypt object", e);
    }
}
 
Example 3
Project: ditb   File: TestCellCodec.java   View Source Code Vote up 6 votes
@Test
public void testEmptyWorks() throws IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  CountingOutputStream cos = new CountingOutputStream(baos);
  DataOutputStream dos = new DataOutputStream(cos);
  Codec codec = new CellCodec();
  Codec.Encoder encoder = codec.getEncoder(dos);
  encoder.flush();
  dos.close();
  long offset = cos.getCount();
  assertEquals(0, offset);
  CountingInputStream cis =
    new CountingInputStream(new ByteArrayInputStream(baos.toByteArray()));
  DataInputStream dis = new DataInputStream(cis);
  Codec.Decoder decoder = codec.getDecoder(dis);
  assertFalse(decoder.advance());
  dis.close();
  assertEquals(0, cis.getCount());
}
 
Example 4
Project: beanmother   File: FixtureMap.java   View Source Code Vote up 6 votes
/**
 * Reproduce this.
 *
 * Generally, data is changed by pre-processors before mapping to bean object.
 * Use this to prevent unexpected change of origin fixtureMap.
 *
 * @return reproduced data
 */
public FixtureMap reproduce() {
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream(1024 * 2);
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(this);
        oos.flush();
        oos.close();

        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
        Object obj = ois.readObject();
        FixtureMap dup = (FixtureMap) obj;

        dup.setParent(getParent());
        dup.setRoot(isRoot());
        dup.setFixtureName(getFixtureName());

        return dup;
    } catch (Exception e) {
        throw new FixtureFormatException(getFixtureName(), e);
    }
}
 
Example 5
Project: CXJPadProject   File: ConvertUtils.java   View Source Code Vote up 6 votes
public static byte[] toByteArray(String hexData, boolean isHex) {
    if (hexData == null || hexData.equals("")) {
        return null;
    }
    if (!isHex) {
        return hexData.getBytes();
    }
    hexData = hexData.replaceAll("\\s+", "");
    String hexDigits = "0123456789ABCDEF";
    ByteArrayOutputStream baos = new ByteArrayOutputStream(
            hexData.length() / 2);
    // 将每2位16进制整数组装成一个字节
    for (int i = 0; i < hexData.length(); i += 2) {
        baos.write((hexDigits.indexOf(hexData.charAt(i)) << 4 | hexDigits
                .indexOf(hexData.charAt(i + 1))));
    }
    byte[] bytes = baos.toByteArray();
    try {
        baos.close();
    } catch (IOException e) {
        LogUtils.warn(e);
    }
    return bytes;
}
 
Example 6
Project: jfrog-idea-plugin   File: SummaryImpl.java   View Source Code Vote up 6 votes
@Override
public SummaryResponse component(Components components) throws IOException {
    if (components == null) {
        return new SummaryResponseImpl();
    }

    ObjectMapper mapper = ObjectMapperHelper.get();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    mapper.writeValue(out, components);
    ByteArrayInputStream content = new ByteArrayInputStream(out.toByteArray());

    Map<String, String> headers = new HashMap<>();
    XrayImpl.addContentTypeJsonHeader(headers);

    HttpResponse response = xray.post("summary/component", headers, content);
    return mapper.readValue(response.getEntity().getContent(), SummaryResponseImpl.class);
}
 
Example 7
Project: openrouteservice   File: PostgresSQLStatisticsProvider.java   View Source Code Vote up 5 votes
private byte[] geometryToWKB(Geometry geom) throws IOException
{
	WKBWriter wkbWriter = new WKBWriter();
	ByteArrayOutputStream bytesStream = new ByteArrayOutputStream();
	wkbWriter.write(geom, new OutputStreamOutStream(bytesStream));
	byte[] geomBytes = bytesStream.toByteArray();
	bytesStream.close();

	return geomBytes;
}
 
Example 8
Project: Exoplayer2Radio   File: Util.java   View Source Code Vote up 5 votes
/**
 * Converts the entirety of an {@link InputStream} to a byte array.
 *
 * @param inputStream the {@link InputStream} to be read. The input stream is not closed by this
 *    method.
 * @return a byte array containing all of the inputStream's bytes.
 * @throws IOException if an error occurs reading from the stream.
 */
public static byte[] toByteArray(InputStream inputStream) throws IOException {
  byte[] buffer = new byte[1024 * 4];
  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  int bytesRead;
  while ((bytesRead = inputStream.read(buffer)) != -1) {
    outputStream.write(buffer, 0, bytesRead);
  }
  return outputStream.toByteArray();
}
 
Example 9
Project: monarch   File: BeanUtilFuncs.java   View Source Code Vote up 5 votes
/**
 * Compresses a given String. It is encoded using ISO-8859-1, So any decompression of the
 * compressed string should also use ISO-8859-1
 * 
 * @param str String to be compressed.
 * @return compressed bytes
 * @throws IOException
 */
public static byte[] compress(String str) throws IOException {
  if (str == null || str.length() == 0) {
    return null;
  }
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  GZIPOutputStream gzip = new GZIPOutputStream(out);
  gzip.write(str.getBytes("UTF-8"));
  gzip.close();
  byte[] outBytes = out.toByteArray();
  return outBytes;
}
 
Example 10
Project: magic_imageloader_network   File: BaseDownloadStream.java   View Source Code Vote up 5 votes
protected InputStream getStreamFromDrawable(String imageUri) {
    try {
        int drawableId = Integer.parseInt(imageUri);
        BitmapDrawable drawable = (BitmapDrawable) this.context.getResources().getDrawable(drawableId);
        Bitmap bitmap = drawable.getBitmap();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 0, os);
        return new ByteArrayInputStream(os.toByteArray());
    } catch (Exception e) {
        Log.e("e", e.toString());
    }
    return null;
}
 
Example 11
Project: Nird2   File: BriarIntegrationTest.java   View Source Code Vote up 5 votes
private void syncMessage(SyncSessionFactory fromSync, ContactId fromId,
		SyncSessionFactory toSync, ContactId toId, int num, boolean valid)
		throws IOException, TimeoutException {

	// Debug output
	String from = "0";
	if (fromSync == sync1) from = "1";
	else if (fromSync == sync2) from = "2";
	String to = "0";
	if (toSync == sync1) to = "1";
	else if (toSync == sync2) to = "2";
	LOG.info("TEST: Sending message from " + from + " to " + to);

	ByteArrayOutputStream out = new ByteArrayOutputStream();
	// Create an outgoing sync session
	SyncSession sessionFrom =
			fromSync.createSimplexOutgoingSession(toId, TestPluginConfigModule.MAX_LATENCY, out);
	// Write whatever needs to be written
	sessionFrom.run();
	out.close();

	ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
	// Create an incoming sync session
	SyncSession sessionTo = toSync.createIncomingSession(fromId, in);
	// Read whatever needs to be read
	sessionTo.run();
	in.close();

	if (valid) {
		deliveryWaiter.await(TIMEOUT, num);
	} else {
		validationWaiter.await(TIMEOUT, num);
	}
}
 
Example 12
Project: aws-sdk-java-v2   File: NamespaceRemovingInputStreamTest.java   View Source Code Vote up 5 votes
private String removeNamespace(String xml) throws Exception {
    NamespaceRemovingInputStream inputStream = new NamespaceRemovingInputStream(new ByteArrayInputStream(xml.getBytes()));
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    IOUtils.copy(inputStream, outputStream);

    return new String(outputStream.toByteArray());
}
 
Example 13
Project: netty_op   File: HessianSerializer.java   View Source Code Vote up 5 votes
public static <T> byte[] serialize(T obj){
	ByteArrayOutputStream os = new ByteArrayOutputStream();
	HessianOutput ho = new HessianOutput(os);
	try {
		ho.writeObject(obj);
	} catch (IOException e) {
		throw new IllegalStateException(e.getMessage(), e);
	}
	return os.toByteArray();
}
 
Example 14
Project: rmq4note   File: DefaultMQPushConsumerTest.java   View Source Code Vote up 5 votes
private PullResultExt createPullResult(PullMessageRequestHeader requestHeader, PullStatus pullStatus, List<MessageExt> messageExtList) throws Exception {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    for (MessageExt messageExt : messageExtList) {
        outputStream.write(MessageDecoder.encode(messageExt, false));
    }
    return new PullResultExt(pullStatus, requestHeader.getQueueOffset() + messageExtList.size(), 123, 2048, messageExtList, 0, outputStream.toByteArray());
}
 
Example 15
Project: jdk8u-jdk   File: PNGImageWriter.java   View Source Code Vote up 5 votes
private byte[] deflate(byte[] b) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DeflaterOutputStream dos = new DeflaterOutputStream(baos);
    dos.write(b);
    dos.close();
    return baos.toByteArray();
}
 
Example 16
Project: CSipSimple   File: SipSharedPreferencesHelper.java   View Source Code Vote up 5 votes
private void writeData(BackupDataOutput data, String value) throws IOException {
    // Create buffer stream and data output stream for our data
    ByteArrayOutputStream bufStream = new ByteArrayOutputStream();
    DataOutputStream outWriter = new DataOutputStream(bufStream);
    // Write structured data
    outWriter.writeUTF(value);
    // Send the data to the Backup Manager via the BackupDataOutput
    byte[] buffer = bufStream.toByteArray();
    int len = buffer.length;
    data.writeEntityHeader(SETTINGS_BACKUP_KEY, len);
    data.writeEntityData(buffer, len);
}
 
Example 17
Project: lams   File: PointbaseDelegate.java   View Source Code Vote up 4 votes
@Override           
public int updateTrigger(Connection conn, OperableTrigger trigger, String state,
        JobDetail jobDetail) throws SQLException, IOException {

    ByteArrayOutputStream baos = serializeJobData(trigger.getJobDataMap());
    int len = baos.toByteArray().length;
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            
    PreparedStatement ps = null;

    int insertResult = 0;


    try {
        ps = conn.prepareStatement(rtp(UPDATE_TRIGGER));
            
        ps.setString(1, trigger.getJobKey().getName());
        ps.setString(2, trigger.getJobKey().getGroup());
        ps.setString(3, trigger.getDescription());
        long nextFireTime = -1;
        if (trigger.getNextFireTime() != null) {
            nextFireTime = trigger.getNextFireTime().getTime();
        }
        ps.setBigDecimal(4, new BigDecimal(String.valueOf(nextFireTime)));
        long prevFireTime = -1;
        if (trigger.getPreviousFireTime() != null) {
            prevFireTime = trigger.getPreviousFireTime().getTime();
        }
        ps.setBigDecimal(5, new BigDecimal(String.valueOf(prevFireTime)));
        ps.setString(6, state);
        
        TriggerPersistenceDelegate tDel = findTriggerPersistenceDelegate(trigger);
        
        String type = TTYPE_BLOB;
        if(tDel != null)
            type = tDel.getHandledTriggerTypeDiscriminator();

        ps.setString(7, type);
        
        ps.setBigDecimal(8, new BigDecimal(String.valueOf(trigger
                .getStartTime().getTime())));
        long endTime = 0;
        if (trigger.getEndTime() != null) {
            endTime = trigger.getEndTime().getTime();
        }
        ps.setBigDecimal(9, new BigDecimal(String.valueOf(endTime)));
        ps.setString(10, trigger.getCalendarName());
        ps.setInt(11, trigger.getMisfireInstruction());
        
        ps.setInt(12, trigger.getPriority());
        ps.setBinaryStream(13, bais, len);
        ps.setString(14, trigger.getKey().getName());
        ps.setString(15, trigger.getKey().getGroup());

        insertResult = ps.executeUpdate();
        
        if(tDel == null)
            updateBlobTrigger(conn, trigger);
        else
            tDel.updateExtendedTriggerProperties(conn, trigger, state, jobDetail);
        
    } finally {
        closeStatement(ps);
    }

    return insertResult;
}
 
Example 18
Project: hadoop   File: TestFetcher.java   View Source Code Vote up 4 votes
@Test
public void testCopyFromHostExtraBytes() throws Exception {
  Fetcher<Text,Text> underTest = new FakeFetcher<Text,Text>(job, id, ss, mm,
      r, metrics, except, key, connection);

  String replyHash = SecureShuffleUtils.generateHash(encHash.getBytes(), key);

  when(connection.getResponseCode()).thenReturn(200);
  when(connection.getHeaderField(ShuffleHeader.HTTP_HEADER_NAME))
      .thenReturn(ShuffleHeader.DEFAULT_HTTP_HEADER_NAME);
  when(connection.getHeaderField(ShuffleHeader.HTTP_HEADER_VERSION))
      .thenReturn(ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION);
  when(connection.getHeaderField(
      SecureShuffleUtils.HTTP_HEADER_REPLY_URL_HASH)).thenReturn(replyHash);
  ShuffleHeader header = new ShuffleHeader(map1ID.toString(), 14, 10, 1);

  ByteArrayOutputStream bout = new ByteArrayOutputStream();
  DataOutputStream dos = new DataOutputStream(bout);
  IFileOutputStream ios = new IFileOutputStream(dos);
  header.write(dos);
  ios.write("MAPDATA123".getBytes());
  ios.finish();

  ShuffleHeader header2 = new ShuffleHeader(map2ID.toString(), 14, 10, 1);
  IFileOutputStream ios2 = new IFileOutputStream(dos);
  header2.write(dos);
  ios2.write("MAPDATA456".getBytes());
  ios2.finish();

  ByteArrayInputStream in = new ByteArrayInputStream(bout.toByteArray());
  when(connection.getInputStream()).thenReturn(in);
  // 8 < 10 therefore there appear to be extra bytes in the IFileInputStream
  InMemoryMapOutput<Text,Text> mapOut = new InMemoryMapOutput<Text, Text>(
      job, map1ID, mm, 8, null, true );
  InMemoryMapOutput<Text,Text> mapOut2 = new InMemoryMapOutput<Text, Text>(
      job, map2ID, mm, 10, null, true );

  when(mm.reserve(eq(map1ID), anyLong(), anyInt())).thenReturn(mapOut);
  when(mm.reserve(eq(map2ID), anyLong(), anyInt())).thenReturn(mapOut2);

  underTest.copyFromHost(host);

  verify(allErrs).increment(1);
  verify(ss).copyFailed(map1ID, host, true, false);
  verify(ss, never()).copyFailed(map2ID, host, true, false);

  verify(ss).putBackKnownMapOutput(any(MapHost.class), eq(map1ID));
  verify(ss).putBackKnownMapOutput(any(MapHost.class), eq(map2ID));
}
 
Example 19
Project: GitHub   File: CacheUtils.java   View Source Code Vote up 4 votes
private static byte[] bitmap2Bytes(final Bitmap bitmap) {
    if (bitmap == null) return null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
    return baos.toByteArray();
}
 
Example 20
Project: saveOrganizer   File: DataXMLParser.java   View Source Code Vote up 4 votes
public static void writeData(File file, List<Calendar> data, List<PGPPublicKey> keys) throws DOMException, Exception
{
	DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
	Document doc = docBuilder.newDocument();
	Element rootElement = doc.createElement("company");
	doc.appendChild(rootElement);

	for (Calendar c : data)
		rootElement.appendChild(c.getObjectAsElement(doc, rootElement));

	TransformerFactory transformerFactory = TransformerFactory.newInstance();
	Transformer transformer = transformerFactory.newTransformer();
	DOMSource source = new DOMSource(doc);

	ByteArrayOutputStream bos = new ByteArrayOutputStream();

	StreamResult sr = new StreamResult(bos);

	transformer.transform(source, sr);
	bos.close();
	byte[] secData = bos.toByteArray();

	FileOutputStream fos = new FileOutputStream(file);
	Encryption.encryptBytesAndArmor(secData, file.getName(), keys, fos);
	fos.flush();
	fos.close();

}