Java Code Examples for java.io.ByteArrayOutputStream

The following are top voted examples for showing how to use java.io.ByteArrayOutputStream. 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: java-restclient   File: RestClientSyncTest.java   Source Code and License 7 votes vote down vote up
@Test
public void shouldHandleGzipContentInOutputStream() throws RestException, IOException {
    String url = "http://dummy.com/test";
    byte[] body = getGzipped("ok");
    String output;
    Response response;

    try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
        MockResponse.builder()
                .withURL(url)
                .withMethod(GET)
                .withStatusCode(200)
                .withResponseHeader(ContentType.HEADER_NAME, ContentType.TEXT_PLAIN.toString())
                .withResponseHeader("Content-Encoding", "gzip")
                .withResponseBody(body)
                .build();

        response = RestClient.getDefault().get(url, os);
        output = new String(os.toByteArray(), StandardCharsets.UTF_8);
    }

    assertEquals(200, response.getStatus());
    assertNull(response.getString());
    assertEquals("ok", output);
}
 
Example 2
Project: jdk8u-jdk   File: WrongAAD.java   Source Code and License 6 votes vote down vote up
private void decryptWithWrongAAD() throws Exception {
    System.out.println("decrypt with wrong AAD");

    // initialize it with wrong AAD to get an exception during decryption
    Cipher decryptCipher = createCipher(Cipher.DECRYPT_MODE,
            encryptCipher.getParameters());
    byte[] someAAD = Helper.generateBytes(AAD_SIZE + 1);
    decryptCipher.updateAAD(someAAD);

    // init output stream
    try (ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
            CipherOutputStream ciOutput = new CipherOutputStream(baOutput,
                    decryptCipher);) {
        if (decrypt(ciOutput, baOutput)) {
            throw new RuntimeException(
                    "A decryption has been perfomed successfully in"
                            + " spite of the decrypt Cipher has been"
                            + " initialized with fake AAD");
        }
    }

    System.out.println("Passed");
}
 
Example 3
Project: Robin_Java   File: SafeTest.java   Source Code and License 6 votes vote down vote up
public static void main( String[] args ) throws IOException, ClassNotFoundException
{
    Person obj = new Person();
    obj.setName( "Robin" );
           
    PersonHack objH = new PersonHack();
      
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(objH);
    
    //反序列化漏洞,如果反序列化的對象可以試任意的,則有可能執行任意有風險額代碼
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    ObjectInputStream  ois = new SecurityObjectInputStream(bais);
    
    Person objCopy = (Person)ois.readObject();        
    System.out.println(objCopy.getName());

}
 
Example 4
Project: parabuild-ci   File: DialPlotTests.java   Source Code and License 6 votes vote down vote up
/**
 * Serialize an instance, restore it, and check for equality.
 */
public void testSerialization() {
    DialPlot p1 = new DialPlot();
    DialPlot p2 = null;

    try {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(buffer);
        out.writeObject(p1);
        out.close();

        ObjectInput in = new ObjectInputStream(
                new ByteArrayInputStream(buffer.toByteArray()));
        p2 = (DialPlot) in.readObject();
        in.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    assertEquals(p1, p2);
}
 
Example 5
Project: ats-framework   File: SwingElementLocator.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @param driver Swing driver
 * @return the component hierarchy as {@link String}
 */
public static String getComponentHierarchy(
                                            SwingDriverInternal driver ) {

    ContainerFixture<?> containerFixture = driver.getActiveContainerFixture();
    Robot robot = null;
    if (containerFixture != null) {
        // use the current robot instance
        robot = containerFixture.robot;
    } else {
        robot = BasicRobot.robotWithCurrentAwtHierarchy();
    }

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    robot.printer().printComponents(new PrintStream(outputStream), ( (containerFixture != null)
                                                                                                ? containerFixture.component()
                                                                                                : null));

    return outputStream.toString();
}
 
Example 6
Project: incubator-netbeans   File: MethodEntryExitCallsInjector.java   Source Code and License 6 votes vote down vote up
private void getAloadCode(int index, ByteArrayOutputStream code) {
    switch (index) {
        case 0:
            code.write(opc_aload_0);
            break;
        case 1:
            code.write(opc_aload_1);
            break;
        case 2:
            code.write(opc_aload_2);
            break;
        case 3:
            code.write(opc_aload_3);
            break;
        default:
            code.write(opc_aload);
            code.write(index);
    }
}
 
Example 7
Project: vogar   File: JUnitRunnerTest.java   Source Code and License 6 votes vote down vote up
public void test_init_and_run_for_FailTest_should_perform_test() {
    Class<?> target = FailTest.class;
    String actionName = "actionName";

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    System.setOut(new PrintStream(baos));

    runner.init(monitor, actionName, null, target, skipPastReference, testEnvironment, 0, false);
    runner.run("", null, null);

    verify(monitor).outcomeStarted(runner,
            target.getName() + "#testSuccess", actionName);
    verify(monitor).outcomeStarted(runner, target.getName() + "#testFail",
            actionName);
    verify(monitor).outcomeStarted(runner,
            target.getName() + "#testThrowException", actionName);
    verify(monitor).outcomeFinished(Result.SUCCESS);
    verify(monitor, times(2)).outcomeFinished(Result.EXEC_FAILED);

    String outStr = baos.toString();
    assertTrue(outStr
            .contains("junit.framework.AssertionFailedError: failed."));
    assertTrue(outStr.contains("java.lang.RuntimeException: exceptrion"));
}
 
Example 8
Project: elasticsearch_my   File: CreateIndexRequestBuilderTests.java   Source Code and License 6 votes vote down vote up
/**
 * test setting the source with available setters
 */
public void testSetSource() throws IOException {
    CreateIndexRequestBuilder builder = new CreateIndexRequestBuilder(this.testClient, CreateIndexAction.INSTANCE);
    builder.setSource("{\""+KEY+"\" : \""+VALUE+"\"}", XContentType.JSON);
    assertEquals(VALUE, builder.request().settings().get(KEY));

    XContentBuilder xContent = XContentFactory.jsonBuilder().startObject().field(KEY, VALUE).endObject();
    xContent.close();
    builder.setSource(xContent);
    assertEquals(VALUE, builder.request().settings().get(KEY));

    ByteArrayOutputStream docOut = new ByteArrayOutputStream();
    XContentBuilder doc = XContentFactory.jsonBuilder(docOut).startObject().field(KEY, VALUE).endObject();
    doc.close();
    builder.setSource(docOut.toByteArray(), XContentType.JSON);
    assertEquals(VALUE, builder.request().settings().get(KEY));

    Map<String, String> settingsMap = new HashMap<>();
    settingsMap.put(KEY, VALUE);
    builder.setSettings(settingsMap);
    assertEquals(VALUE, builder.request().settings().get(KEY));
}
 
Example 9
Project: asura   File: StdJDBCDelegate.java   Source Code and License 6 votes vote down vote up
/**
 * Find the key of the first non-serializable value in the given Map.
 * 
 * @return The key of the first non-serializable value in the given Map or 
 * null if all values are serializable.
 */
protected Object getKeyOfNonSerializableValue(Map data) {
    for (Iterator entryIter = data.entrySet().iterator(); entryIter.hasNext();) {
        Map.Entry entry = (Map.Entry)entryIter.next();
        
        ByteArrayOutputStream baos = null;
        try {
            baos = serializeObject(entry.getValue());
        } catch (IOException e) {
            return entry.getKey();
        } finally {
            if (baos != null) {
                try { baos.close(); } catch (IOException ignore) {}
            }
        }
    }
    
    // As long as it is true that the Map was not serializable, we should
    // not hit this case.
    return null;   
}
 
Example 10
Project: litiengine   File: CompressionUtilities.java   Source Code and License 6 votes vote down vote up
public static byte[] compress(final byte[] data) {
  final Deflater deflater = new Deflater();
  deflater.setInput(data);
  final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
  deflater.finish();
  final byte[] buffer = new byte[1024];
  try {
    while (!deflater.finished()) {
      final int count = deflater.deflate(buffer); // returns the generated
                                                  // code...
      // index
      outputStream.write(buffer, 0, count);
    }
    outputStream.close();
  } catch (final IOException e) {
    log.log(Level.SEVERE, e.getMessage(), e);
  }

  return outputStream.toByteArray();
}
 
Example 11
Project: lams   File: PointbaseDelegate.java   Source Code and License 6 votes vote down vote up
/**
 * <p>
 * Update the job data map for the given job.
 * </p>
 * 
 * @param conn
 *          the DB Connection
 * @param job
 *          the job to update
 * @return the number of rows updated
 */
@Override           
public int updateJobData(Connection conn, JobDetail job)
    throws IOException, SQLException {
    //log.debug( "Updating Job Data for Job " + job );
    ByteArrayOutputStream baos = serializeJobData(job.getJobDataMap());
    int len = baos.toByteArray().length;
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    PreparedStatement ps = null;

    try {
        ps = conn.prepareStatement(rtp(UPDATE_JOB_DATA));
        ps.setBinaryStream(1, bais, len);
        ps.setString(2, job.getKey().getName());
        ps.setString(3, job.getKey().getGroup());

        return ps.executeUpdate();
    } finally {
        closeStatement(ps);
    }
}
 
Example 12
Project: MetadataEditor   File: Mp4TagReverseDnsField.java   Source Code and License 6 votes vote down vote up
@Override
public byte[] getRawContentDataOnly() throws UnsupportedEncodingException
{
    logger.fine("Getting Raw data for:" + getId());
    try
    {
        //Create DataBox data
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] dataRawData = content.getBytes(getEncoding());
        baos.write(Utils.getSizeBEInt32(Mp4BoxHeader.HEADER_LENGTH + Mp4DataBox.PRE_DATA_LENGTH + dataRawData.length));
        baos.write(Mp4DataBox.IDENTIFIER.getBytes(StandardCharsets.ISO_8859_1));
        baos.write(new byte[]{0});
        baos.write(new byte[]{0, 0, (byte) getFieldType().getFileClassId()});
        baos.write(new byte[]{0, 0, 0, 0});
        baos.write(dataRawData);
        return baos.toByteArray();
    }
    catch (IOException ioe)
    {
        //This should never happen as were not actually writing to/from a file
        throw new RuntimeException(ioe);
    }
}
 
Example 13
Project: BiglyBT   File: DERBitString.java   Source Code and License 6 votes vote down vote up
@Override
public String getString()
{
    StringBuilder buf = new StringBuilder("#");
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    ASN1OutputStream      aOut = new ASN1OutputStream(bOut);

    try
    {
        aOut.writeObject(this);
    }
    catch (IOException e)
    {
       throw new RuntimeException("internal error encoding BitString");
    }

    byte[]    string = bOut.toByteArray();

    for (int i = 0; i != string.length; i++)
    {
        buf.append(table[(string[i] >>> 4) & 0xf]);
        buf.append(table[string[i] & 0xf]);
    }

    return buf.toString();
}
 
Example 14
Project: NSS   File: CryptBase.java   Source Code and License 6 votes vote down vote up
@Override
public void decrypt(byte[] data, ByteArrayOutputStream stream) {
	byte[] temp;
	synchronized (decLock) {
		stream.reset();
		if (!_decryptIVSet) {
			_decryptIVSet = true;
			setIV(data, false);
			temp = new byte[data.length - _ivLength];
			System.arraycopy(data, _ivLength, temp, 0, data.length
					- _ivLength);
		} else {
			temp = data;
		}

		_decrypt(temp, stream);
	}
}
 
Example 15
Project: boohee_v5.6   File: CommonUtils.java   Source Code and License 6 votes vote down vote up
public static String textCompress(String str) {
    try {
        Object array = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(str.length()).array();
        OutputStream byteArrayOutputStream = new ByteArrayOutputStream(str.length());
        GZIPOutputStream gZIPOutputStream = new GZIPOutputStream(byteArrayOutputStream);
        gZIPOutputStream.write(str.getBytes("UTF-8"));
        gZIPOutputStream.close();
        byteArrayOutputStream.close();
        Object obj = new byte[(byteArrayOutputStream.toByteArray().length + 4)];
        System.arraycopy(array, 0, obj, 0, 4);
        System.arraycopy(byteArrayOutputStream.toByteArray(), 0, obj, 4, byteArrayOutputStream.toByteArray().length);
        return Base64.encodeToString(obj, 8);
    } catch (Exception e) {
        return "";
    }
}
 
Example 16
Project: openjdk-jdk10   File: DestTypeTest.java   Source Code and License 6 votes vote down vote up
public byte[] writeTest(BufferedImage bi,
                        ImageWriteParam p,
                        IIOMetadata m) throws IOException {
    ByteArrayOutputStream baos =
        new ByteArrayOutputStream();

    // write test image as jpeg
    ImageOutputStream ios =
        ImageIO.createImageOutputStream(baos);
    w.setOutput(ios);
    w.write(null,
            new IIOImage(bi, null, m),
            p);
    ios.close();
    return baos.toByteArray();
}
 
Example 17
Project: dubbo2   File: SerializationCompareTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testCompactedJavaOutputPerm() throws Exception
{
	Bean bean = new Bean();
	int len = 0;
	long now = System.currentTimeMillis();
	for(int i=0;i<500;i++)
	{
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		CompactedObjectOutputStream out = new CompactedObjectOutputStream(os);
		out.writeObject(bean);
		os.close();
		if( i == 0 )
			len = os.toByteArray().length;
		ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
		CompactedObjectInputStream in = new CompactedObjectInputStream(is);
		assertEquals(in.readObject().getClass(), Bean.class);
	}
	System.out.println("compacted java write and parse 500 times in " + (System.currentTimeMillis()-now)+"ms, size " + len);
}
 
Example 18
Project: util4j   File: NMap.java   Source Code and License 6 votes vote down vote up
/**
 * 根据文件解码一个新nmap对象
 * @param file
 * @return
 * @throws Exception
 */
public final NMap load(File file) throws Exception
{
	if(file.exists())
	{
		FileInputStream fis=new FileInputStream(file);
		BufferedInputStream bis=new BufferedInputStream(fis);
		ByteArrayOutputStream bos=new ByteArrayOutputStream();//定义一个内存输出流
		int i=-1;
		while(true)
		{
			i=bis.read();
			if(i==-1)
			{
				break;
			}
			bos.write(i);//保存到内存数组
		}
		bos.flush();
		bos.close();
		bis.close();
		return (NMap) decoder(bos.toByteArray());
	}
	return null;
}
 
Example 19
Project: MetadataEditor   File: Mp4FreeBox.java   Source Code and License 6 votes vote down vote up
/**
 * Construct a new FreeBox containing datasize padding (i.e doesnt include header size)
 *
 * @param datasize padding size
 */
public Mp4FreeBox(int datasize)
{
    try
    {
        //Header
        header = new Mp4BoxHeader();
        ByteArrayOutputStream headerBaos = new ByteArrayOutputStream();
        headerBaos.write(Utils.getSizeBEInt32(Mp4BoxHeader.HEADER_LENGTH + datasize));
        headerBaos.write(Mp4AtomIdentifier.FREE.getFieldName().getBytes(StandardCharsets.ISO_8859_1));
        header.update(ByteBuffer.wrap(headerBaos.toByteArray()));

        //Body
        ByteArrayOutputStream freeBaos = new ByteArrayOutputStream();
        for (int i = 0; i < datasize; i++)
        {
            freeBaos.write(0x0);
        }
        dataBuffer = ByteBuffer.wrap(freeBaos.toByteArray());
    }
    catch (IOException ioe)
    {
        //This should never happen as were not actually writing to/from a file
        throw new RuntimeException(ioe);
    }
}
 
Example 20
Project: rdf4j-schema-generator   File: SchemaGeneratorTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test method for {@link com.github.ansell.rdf4j.schemagenerator.RDF4JSchemaGeneratorCore#generate(java.nio.file.Path)}.
 */
@Test
public final void testNoExplicitCaseLocalName() throws Exception {
    Path outputPath = testDir.resolve("output");
    Files.createDirectories(outputPath);

    RDF4JSchemaGeneratorCore testBuilder = new RDF4JSchemaGeneratorCore(inputPath.toAbsolutePath().toString(), format);

    testBuilder.setLocalNameStringConstantCase(null);

    Path javaFilePath = outputPath.resolve("Test.java");
    testBuilder.generate(javaFilePath);
    assertTrue("Java file was not found", Files.exists(javaFilePath));
    assertTrue("Java file was empty", Files.size(javaFilePath) > 0);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Files.copy(javaFilePath, out);
    String result = new String(out.toByteArray(), StandardCharsets.UTF_8);
    assertTrue("Did not find expected key case", result.contains("propertyLocalised4 = "));
    assertTrue("Did not find original URI", result.contains("\"http://example.com/ns/ontology#propertyLocalised4\""));
}
 
Example 21
Project: TinkerDemo   File: Utils.java   Source Code and License 6 votes vote down vote up
public static String getExceptionCauseString(final Throwable ex) {
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final PrintStream ps = new PrintStream(bos);

    try {
        // print directly
        Throwable t = ex;
        while (t.getCause() != null) {
            t = t.getCause();
        }
        t.printStackTrace(ps);
        return toVisualString(bos.toString());
    } finally {
        try {
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
Example 22
Project: fuck_zookeeper   File: Utils.java   Source Code and License 6 votes vote down vote up
/**
 * Converts a CSV-serialized representation of buffer to a new
 * ByteArrayOutputStream.
 * @param s CSV-serialized representation of buffer
 * @throws java.io.IOException 
 * @return Deserialized ByteArrayOutputStream
 */
static byte[] fromCSVBuffer(String s)
throws IOException {
    if (s.charAt(0) != '#') {
        throw new IOException("Error deserializing buffer.");
    }
    ByteArrayOutputStream stream =  new ByteArrayOutputStream();
    if (s.length() == 1) { return stream.toByteArray(); }
    int blen = (s.length()-1)/2;
    byte[] barr = new byte[blen];
    for (int idx = 0; idx < blen; idx++) {
        char c1 = s.charAt(2*idx+1);
        char c2 = s.charAt(2*idx+2);
        barr[idx] = Byte.parseByte(""+c1+c2, 16);
    }
    stream.write(barr);
    return stream.toByteArray();
}
 
Example 23
Project: openjdk-jdk10   File: WDataTransferer.java   Source Code and License 6 votes vote down vote up
@Override
protected ByteArrayOutputStream convertFileListToBytes(ArrayList<String> fileList)
        throws IOException
{
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    if(fileList.isEmpty()) {
        //store empty unicode string (null terminator)
        bos.write(UNICODE_NULL_TERMINATOR);
    } else {
        for (int i = 0; i < fileList.size(); i++) {
            byte[] bytes = fileList.get(i).getBytes(getDefaultUnicodeEncoding());
            //store unicode string with null terminator
            bos.write(bytes, 0, bytes.length);
            bos.write(UNICODE_NULL_TERMINATOR);
        }
    }

    // According to MSDN the byte array have to be double NULL-terminated.
    // The array contains Unicode characters, so each NULL-terminator is
    // a pair of bytes

    bos.write(UNICODE_NULL_TERMINATOR);
    return bos;
}
 
Example 24
Project: parabuild-ci   File: ComparableObjectSeriesTests.java   Source Code and License 6 votes vote down vote up
/**
 * Serialize an instance, restore it, and check for equality.
 */
public void testSerialization() {
    MyComparableObjectSeries s1 = new MyComparableObjectSeries("A");
    s1.add(new Integer(1), "ABC");
    MyComparableObjectSeries s2 = null;
    try {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(buffer);
        out.writeObject(s1);
        out.close();

        ObjectInput in = new ObjectInputStream(
                new ByteArrayInputStream(buffer.toByteArray()));
        s2 = (MyComparableObjectSeries) in.readObject();
        in.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    assertEquals(s1, s2);
}
 
Example 25
Project: CorePatch   File: BsPatchTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testApplyPatch_DiffSegmentLengthNegative() throws Exception {
  createEmptyOldFile(10);
  InputStream patchIn =
      makePatch(
          SIGNATURE,
          10, // newLength
          -10, // diffSegmentLength (negative)
          0, // copySegmentLength
          0, // offsetToNextInput
          new byte[10] // addends
          );
  ByteArrayOutputStream newData = new ByteArrayOutputStream();
  try {
    BsPatch.applyPatch(new RandomAccessFile(oldFile, "r"), newData, patchIn);
    Assert.fail("Read patch with negative diffSegmentLength");
  } catch (PatchFormatException expected) {
    // No way to mock the internal logic, so resort to testing exception string for coverage
    String actual = expected.getMessage();
    Assert.assertEquals("bad diffSegmentLength", actual);
  }
}
 
Example 26
Project: BiglyBT   File: IDATChunk.java   Source Code and License 6 votes vote down vote up
@Override
public byte[] getContentPayload() {
	byte[] payload = new byte[(width+1)*height];
	for(int i = 0; i<height ; i++) {
		int offset = i * (width+1);
		//NO filter on this line
		payload[offset++] = 0;
		for(int j = 0 ; j<width ; j++) {
			payload[offset+j] = (byte)(127);
		}
	}

	Deflater deflater = new Deflater( Deflater.DEFAULT_COMPRESSION );
    ByteArrayOutputStream outBytes = new ByteArrayOutputStream((width+1)*height);

    DeflaterOutputStream compBytes = new DeflaterOutputStream( outBytes, deflater );
    try {
    	compBytes.write(payload);
    	compBytes.close();
    } catch(Exception e) {
    	e.printStackTrace();
    }
    byte[] compPayload = outBytes.toByteArray();

	return compPayload;
}
 
Example 27
Project: parabuild-ci   File: StandardCategoryLabelGeneratorTests.java   Source Code and License 6 votes vote down vote up
/**
 * Serialize an instance, restore it, and check for equality.
 */
public void testSerialization() {

    StandardCategoryLabelGenerator g1 = new StandardCategoryLabelGenerator(
        "{2}", DateFormat.getInstance()
    );
    StandardCategoryLabelGenerator g2 = null;

    try {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(buffer);
        out.writeObject(g1);
        out.close();

        ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()));
        g2 = (StandardCategoryLabelGenerator) in.readObject();
        in.close();
    }
    catch (Exception e) {
        System.out.println(e.toString());
    }
    assertEquals(g1, g2);

}
 
Example 28
Project: bubichain-sdk-java   File: BytesUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 将输入流的所有内容都读入到字节数组返回;
 * <p>
 * 如果输入流的长度超出 MAX_BUFFER_SIZE 定义的值,则抛出 IllegalArgumentException ;
 *
 * @param in
 * @return
 * @throws IOException
 */
public static byte[] copyToBytes(InputStream in) throws IOException{
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] buffer = new byte[BUFFER_SIZE];
    int len = 0;
    long size = 0;
    while ((len = in.read(buffer)) > 0) {
        size += len;
        if (size > MAX_BUFFER_SIZE) {
            throw new IllegalArgumentException(
                    "The size of the InputStream exceed the max buffer size [" + MAX_BUFFER_SIZE + "]!");
        }
        out.write(buffer, 0, len);
    }
    return out.toByteArray();
}
 
Example 29
Project: openjdk-jdk10   File: NulFile.java   Source Code and License 6 votes vote down vote up
private static void testSerialization(File testFile) {
    String path = testFile.getPath();
    try {
        // serialize test file
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(testFile);
        oos.close();
        // deserialize test file
        byte[] bytes = baos.toByteArray();
        ByteArrayInputStream is = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(is);
        File newFile = (File) ois.readObject();
        // test
        String newPath = newFile.getPath();
        if (!path.equals(newPath)) {
            throw new RuntimeException(
                    "Serialization should not change file path");
        }
        test(newFile, false);
    } catch (IOException | ClassNotFoundException ex) {
        System.err.println("Exception happens in testSerialization");
        System.err.println(ex.getMessage());
    }
}
 
Example 30
Project: CacheWebView   File: ResourseInputStream.java   Source Code and License 6 votes vote down vote up
private void getStream(DiskLruCache.Editor content){
    if (content == null){
        return;
    }
    try {
        mOutputStream = content.newOutputStream(CacheIndexType.CONTENT.ordinal());
        mOutputStreamProperty = content.newOutputStream(CacheIndexType.PROPERTY.ordinal());
        mOutputStreamAllProperty = content.newOutputStream(CacheIndexType.ALL_PROPERTY.ordinal());
    } catch (IOException e) {
        e.printStackTrace();
    }
    String extension = MimeTypeMapUtils.getFileExtensionFromUrl(mUrl);
    if (mCacheExtensionConfig.canRamCache(extension)){
        mRamArray = new ByteArrayOutputStream();
    }
}
 
Example 31
Project: hadoop   File: TestClusterId.java   Source Code and License 6 votes vote down vote up
/**
 * Test namenode format with -clusterid -force option. Format command should
 * fail as no cluster id was provided.
 * 
 * @throws IOException
 */
@Test
public void testFormatWithInvalidClusterIdOption() throws IOException {

  String[] argv = { "-format", "-clusterid", "-force" };
  PrintStream origErr = System.err;
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  PrintStream stdErr = new PrintStream(baos);
  System.setErr(stdErr);

  NameNode.createNameNode(argv, config);

  // Check if usage is printed
  assertTrue(baos.toString("UTF-8").contains("Usage: java NameNode"));
  System.setErr(origErr);

  // check if the version file does not exists.
  File version = new File(hdfsDir, "current/VERSION");
  assertFalse("Check version should not exist", version.exists());
}
 
Example 32
Project: AndroidProgramming3e   File: FlickrFetchr.java   Source Code and License 6 votes vote down vote up
public byte[] getUrlBytes(String urlSpec) throws IOException {
    URL url = new URL(urlSpec);
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        InputStream in = connection.getInputStream();
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new IOException(connection.getResponseMessage() +
                    ": with " +
                    urlSpec);
        }
        int bytesRead = 0;
        byte[] buffer = new byte[1024];
        while ((bytesRead = in.read(buffer)) > 0) {
            out.write(buffer, 0, bytesRead);
        }
        out.close();
        return out.toByteArray();
    } finally {
        connection.disconnect();
    }
}
 
Example 33
Project: directory-ldap-api   File: ValueSerializationTest.java   Source Code and License 6 votes vote down vote up
@Ignore
@Test
public void testStringValueWithDataNormalizedSerializationPerf() throws IOException, LdapException,
    ClassNotFoundException
{
    Value value = new Value( ats, sv1n );
    Value svDeser = new Value( ats );

    long t0 = System.currentTimeMillis();

    for ( int i = 0; i < 10000000; i++ )
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream( baos );
        value.writeExternal( out );
        out.close();
        byte[] data = baos.toByteArray();
        ObjectInputStream in = new ObjectInputStream( new ByteArrayInputStream( data ) );
        svDeser.readExternal( in );
        in.close();
    }

    long t1 = System.currentTimeMillis();

    System.out.println( "Delta ser slow = " + ( t1 - t0 ) );
}
 
Example 34
Project: NotifyTools   File: QuotedPrintableCodec.java   Source Code and License 6 votes vote down vote up
/***
 * Decodes an array quoted-printable characters into an array of original bytes. Escaped characters are converted
 * back to their original representation.
 *
 * <p>
 * This function implements a subset of quoted-printable encoding specification (rule #1 and rule #2) as defined in
 * RFC 1521.
 * </p>
 *
 * @param bytes
 *                  array of quoted-printable characters
 * @return array of original bytes
 * @throws DecoderException
 *                  Thrown if quoted-printable decoding is unsuccessful
 */
public static final byte[] decodeQuotedPrintable(byte[] bytes) throws DecoderException {
    if (bytes == null) {
        return null;
    }
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    for (int i = 0; i < bytes.length; i++) {
        int b = bytes[i];
        if (b == ESCAPE_CHAR) {
            try {
                int u = Character.digit((char) bytes[++i], 16);
                int l = Character.digit((char) bytes[++i], 16);
                if (u == -1 || l == -1) {
                    throw new DecoderException("Invalid quoted-printable encoding");
                }
                buffer.write((char) ((u << 4) + l));
            } catch (ArrayIndexOutOfBoundsException e) {
                throw new DecoderException("Invalid quoted-printable encoding");
            }
        } else {
            buffer.write(b);
        }
    }
    return buffer.toByteArray();
}
 
Example 35
Project: ats-framework   File: GssClient.java   Source Code and License 6 votes vote down vote up
private int traceBeforeNegotiate() {

            int beforeNumSubjectCreds = 0;
            // Traces all credentials too.
            if (subject != null) {
                log.debug("[" + getName() + "] AUTH_NEGOTIATE as subject " + subject.toString());
                beforeNumSubjectCreds = subject.getPrivateCredentials().size();
            }

            if (negotiationToken != null && negotiationToken.length > 0) {
                try {
                    OutputStream os = new ByteArrayOutputStream();
                    HexDump.dump(negotiationToken, 0, os, 0);
                    log.debug("[" + getName() + "] AUTH_NEGOTIATE Process token from acceptor==>\n"
                              + os.toString());
                } catch (IOException e) {}
            }

            return beforeNumSubjectCreds;
        }
 
Example 36
Project: playTorrent   File: BitDecoder.java   Source Code and License 6 votes vote down vote up
private ByteBuffer decodeBytes(@NonNull InputStream in, int prevLoad) throws IOException {
    ByteArrayOutputStream lengthBuffer = new ByteArrayOutputStream();
    if (prevLoad > 0) {
        // we should handle prev loaded string length byte.
        lengthBuffer.write(prevLoad);
    }

    int temp;
    while ((temp = in.read()) != ':') {
        if (temp == -1) { // reach end of file
            throw new IOException("We've met end of file");
        }
        lengthBuffer.write(temp);
    }

    int length = Integer.parseInt(lengthBuffer.toString());
    byte[] byteArray = new byte[length];
    if (in.read(byteArray) != length) {
        if (DEBUG) {
            Log.d(TAG, "Failed to read string");
        }
        return null;
    }

    return ByteBuffer.wrap(byteArray);
}
 
Example 37
Project: java-restclient   File: RequestBuilderSyncTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldPutWithBuilderAndOutputStream() throws RestException, IOException {
    String url = "http://dummy.com/test";
    String body = "ok";
    String output;
    Response response;

    try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
        MockResponse.builder()
                .withURL(url)
                .withMethod(PUT)
                .withStatusCode(200)
                .withResponseHeader(ContentType.HEADER_NAME, ContentType.TEXT_PLAIN.toString())
                .withRequestBody(body)
                .echoBody()
                .build();

        response = restClient.withPool("test").put(url, body.getBytes(StandardCharsets.UTF_8), os);
        output = new String(os.toByteArray(), StandardCharsets.UTF_8);
    }

    assertEquals(200, response.getStatus());
    assertNull(response.getString());
    assertEquals(body, output);
}
 
Example 38
Project: directory-ldap-api   File: AvaSerializationTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test serialization of a simple ATAV
 */
@Test
public void testNullAtavSerialization() throws LdapException, IOException, ClassNotFoundException
{
    Ava atav = new Ava();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream( baos );

    try
    {
        atav.writeExternal( out );
        fail();
    }
    catch ( IOException ioe )
    {
        assertTrue( true );
    }
}
 
Example 39
Project: GitHub   File: FileUtils.java   Source Code and License 5 votes vote down vote up
public static byte[] readStream(InputStream is, int initSize) throws IOException {
    if (initSize <= 0) {
        initSize = 32 * 1024;
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream(initSize);
    byte[] buffer = new byte[8192];
    int bytesRead;
    while ((bytesRead = is.read(buffer)) > 0) {
        baos.write(buffer, 0, bytesRead);
    }
    return baos.toByteArray();
}
 
Example 40
Project: ditb   File: TestHFileBlock.java   Source Code and License 5 votes vote down vote up
public byte[] createTestV1Block(Compression.Algorithm algo)
    throws IOException {
  Compressor compressor = algo.getCompressor();
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  OutputStream os = algo.createCompressionStream(baos, compressor, 0);
  DataOutputStream dos = new DataOutputStream(os);
  BlockType.META.write(dos); // Let's make this a meta block.
  writeTestBlockContents(dos);
  dos.flush();
  algo.returnCompressor(compressor);
  return baos.toByteArray();
}
 
Example 41
Project: jdk8u-jdk   File: ImmutableDescriptorSerialTest.java   Source Code and License 5 votes vote down vote up
private static <T> T serialize(T x) throws Exception {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ObjectOutputStream oout = new ObjectOutputStream(bout);
    oout.writeObject(x);
    oout.close();
    byte[] bytes = bout.toByteArray();
    ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
    ObjectInputStream oin = new ObjectInputStream(bin);
    return (T) oin.readObject();
}
 
Example 42
Project: XERUNG   File: Comman.java   Source Code and License 5 votes vote down vote up
public String encodeTobase64(Bitmap image) {
	Bitmap immage = image;
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	immage.compress(Bitmap.CompressFormat.PNG, 100, baos);
	byte[] b = baos.toByteArray();
	String imageEncoded = android.util.Base64.encodeToString(b, android.util.Base64.DEFAULT);
	return imageEncoded;
}
 
Example 43
Project: letv   File: BaseImageDownloader.java   Source Code and License 5 votes vote down vote up
protected InputStream getStreamFromContent(String imageUri, Object extra) throws FileNotFoundException {
    ContentResolver res = this.context.getContentResolver();
    Uri uri = Uri.parse(imageUri);
    if (isVideoUri(uri)) {
        Bitmap bitmap = Thumbnails.getThumbnail(res, Long.valueOf(uri.getLastPathSegment()).longValue(), 1, null);
        if (bitmap != null) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.PNG, 0, bos);
            return new ByteArrayInputStream(bos.toByteArray());
        }
    } else if (imageUri.startsWith(CONTENT_CONTACTS_URI_PREFIX)) {
        return Contacts.openContactPhotoInputStream(res, uri);
    }
    return res.openInputStream(uri);
}
 
Example 44
Project: openjdk-jdk10   File: StreamResultTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testStreamWriterWithStAXResultNEventWriter() throws Exception {
    try {
        XMLOutputFactory ofac = XMLOutputFactory.newInstance();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        XMLEventWriter writer = ofac.createXMLEventWriter(buffer);
        StAXResult res = new StAXResult(writer);
        XMLStreamWriter swriter = ofac.createXMLStreamWriter(res);
        Assert.fail("Expected an Exception as XMLStreamWriter can't be created " + "with a StAXResult which has EventWriter.");
    } catch (Exception e) {
        System.out.println(e.toString());
    }
}
 
Example 45
Project: xDoc   File: XDocController.java   Source Code and License 5 votes vote down vote up
@PostConstruct
public void init() {
    if (!xDocProperties.isEnable()) {
        return;
    }
    log.info("开始启动XDoc");

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    String path = xDocProperties.getSourcePath();

    if (StringUtils.isBlank(path)) {
        path = ".";//默认为当前目录
    }

    List<String> paths = Arrays.asList(path.split(","));

    log.debug("源码路径:{}", paths);

    try {
        SpringXDocOutputImpl output = new SpringXDocOutputImpl(out, null);
        XDoc xDoc = new XDoc(paths, output);
        xDoc.build();
        log.info("启动XDoc完成");

        this.apiModules = ApiModulesHolder.getCurrentApiModules();
    } catch (Exception e) {
        log.error("启动XDoc失败,生成接口文档失败", e);
    }
}
 
Example 46
Project: RankVouchers   File: MetricUtil.java   Source Code and License 5 votes vote down vote up
/**
 * Gzips the given String.
 *
 * @param str The string to gzip.
 * @return The gzipped String.
 * @throws IOException If the compression failed.
 */
private static byte[] compress(final String str) throws IOException {
    if (str == null) {
        return null;
    }
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(outputStream);
    gzip.write(str.getBytes("UTF-8"));
    gzip.close();
    return outputStream.toByteArray();
}
 
Example 47
Project: stynico   File: PersistentCookieStore.java   Source Code and License 5 votes vote down vote up
protected String encodeCookie(SerializableHttpCookie cookie) {
    if (cookie == null)
        return null;
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        ObjectOutputStream outputStream = new ObjectOutputStream(os);
        outputStream.writeObject(cookie);
    } catch (IOException e) {
      //  Log.d(LOG_TAG, "IOException in encodeCookie", e);
        return null;
    }

    return byteArrayToHexString(os.toByteArray());
}
 
Example 48
Project: multiple-dimension-spread   File: TestUnionSchema.java   Source Code and License 5 votes vote down vote up
@Test
public void T_18() throws IOException{
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  Configuration config = new Configuration();
  MDSWriter writer = new MDSWriter( out , config );

  Spread s = new Spread();
  Map<String,Object> d = new HashMap<String,Object>();
  d.put( "d" , new BytesObj( new byte[0] ) );
  s.addRow( d );
  d.put( "d" , new StringObj( "1" ) );
  s.addRow( d );
  writer.append( s );
  writer.close();

  assertEquals( s.getColumn("d").getColumnType() , ColumnType.UNION );

  MDSReader reader = new MDSReader();
  Configuration readerConfig = new Configuration();
  byte[] data = out.toByteArray();
  InputStream fileIn = new ByteArrayInputStream( data );
  reader.setNewStream( fileIn , data.length , readerConfig );
  while( reader.hasNext() ){
    Spread spread = reader.next();
    IColumn column = spread.getColumn( "d" );
    assertEquals( column.getColumnType() , ColumnType.UNION );
  }
}
 
Example 49
Project: opentsdb-rpc-kafka   File: TestJSONDeserializer.java   Source Code and License 5 votes vote down vote up
private byte[] serialize(final List<TypedIncomingData> data) throws Exception {
  final ByteArrayOutputStream output = new ByteArrayOutputStream();
  final JsonGenerator json = JSON.getFactory().createGenerator(output);
  json.writeStartArray();
  for (final TypedIncomingData d : data) {
    json.writeObject(d);
  }
  json.writeEndArray();
  json.close();
  return output.toByteArray();
}
 
Example 50
Project: hadoop   File: TestMRJobClient.java   Source Code and License 5 votes vote down vote up
/**
 * print counters 
 */
public void testGetCounter(String jobId, Configuration conf) throws Exception {
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  // bad command 
  int exitCode = runTool(conf, createJobClient(),
      new String[] { "-counter", }, out);
  assertEquals("Exit code", -1, exitCode);
  
  exitCode = runTool(conf, createJobClient(),
      new String[] { "-counter", jobId,
          "org.apache.hadoop.mapreduce.TaskCounter", "MAP_INPUT_RECORDS" },
      out);
  assertEquals("Exit code", 0, exitCode);
  assertEquals("Counter", "3", out.toString().trim());
}
 
Example 51
Project: Notebook   File: HttpGets.java   Source Code and License 5 votes vote down vote up
private byte[] readInputStream(InputStream inStream) throws Exception {
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len = 0;
    while ((len = inStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, len);
    }
    byte[] datas = outStream.toByteArray();
    outStream.close();
    inStream.close();
    return datas;
}
 
Example 52
Project: cyberduck   File: CopyWorkerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCopyFile() throws Exception {
    final Host host = new Host(new AzureProtocol(), "kahy9boj3eib.blob.core.windows.net", new Credentials(
            System.getProperties().getProperty("azure.account"), System.getProperties().getProperty("azure.key")
    ));
    final AzureSession session = new AzureSession(host);
    session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path home = new Path("cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
    final Path vault = new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory));
    final Path source = new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final Path target = new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final CryptoVault cryptomator = new CryptoVault(vault, new DisabledPasswordStore());
    cryptomator.create(session, null, new VaultCredentials("test"));
    final DefaultVaultRegistry registry = new DefaultVaultRegistry(new DisabledPasswordStore(), new DisabledPasswordCallback(), cryptomator);
    session.withRegistry(registry);
    final byte[] content = RandomUtils.nextBytes(40500);
    final TransferStatus status = new TransferStatus();
    new CryptoBulkFeature<>(session, new DisabledBulkFeature(), new AzureDeleteFeature(session, null), cryptomator).pre(Transfer.Type.upload, Collections.singletonMap(source, status), new DisabledConnectionCallback());
    new StreamCopier(new TransferStatus(), new TransferStatus()).transfer(new ByteArrayInputStream(content), new CryptoWriteFeature<>(session, new AzureWriteFeature(session, null), cryptomator).write(source, status.length(content.length), new DisabledConnectionCallback()));
    assertTrue(new CryptoFindFeature(session, new DefaultFindFeature(session), cryptomator).find(source));
    final CopyWorker worker = new CopyWorker(Collections.singletonMap(source, target), new TestSessionPool(session, registry), PathCache.empty(), new DisabledProgressListener(), new DisabledConnectionCallback());
    worker.run(session);
    assertTrue(new CryptoFindFeature(session, new AzureFindFeature(session, null), cryptomator).find(source));
    assertTrue(new CryptoFindFeature(session, new AzureFindFeature(session, null), cryptomator).find(target));
    final ByteArrayOutputStream out = new ByteArrayOutputStream(content.length);
    assertEquals(content.length, IOUtils.copy(new CryptoReadFeature(session, new AzureReadFeature(session, null), cryptomator).read(target, new TransferStatus().length(content.length), new DisabledConnectionCallback()), out));
    assertArrayEquals(content, out.toByteArray());
    new DeleteWorker(new DisabledLoginCallback(), Collections.singletonList(vault), PathCache.empty(), new DisabledProgressListener()).run(session);
    session.close();
}
 
Example 53
Project: fuck_zookeeper   File: ReferenceCountedACLCacheTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSerializeDeserialize() throws IOException {
    ReferenceCountedACLCache cache = new ReferenceCountedACLCache();

    List<ACL> acl1 = createACL("one");
    List<ACL> acl2 = createACL("two");
    List<ACL> acl3 = createACL("three");
    List<ACL> acl4 = createACL("four");
    List<ACL> acl5 = createACL("five");

    Long aclId1 = convertACLsNTimes(cache, acl1, 1);
    Long aclId2 = convertACLsNTimes(cache, acl2, 2);
    Long aclId3 = convertACLsNTimes(cache, acl3, 3);
    Long aclId4 = convertACLsNTimes(cache, acl4, 4);
    Long aclId5 = convertACLsNTimes(cache, acl5, 5);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BinaryOutputArchive archive = BinaryOutputArchive.getArchive(baos);
    cache.serialize(archive);

    BinaryInputArchive inArchive = BinaryInputArchive.getArchive(new ByteArrayInputStream(baos.toByteArray()));
    ReferenceCountedACLCache deserializedCache = new ReferenceCountedACLCache();
    deserializedCache.deserialize(inArchive);
    callAddUsageNTimes(deserializedCache, aclId1, 1);
    callAddUsageNTimes(deserializedCache, aclId2, 2);
    callAddUsageNTimes(deserializedCache, aclId3, 3);
    callAddUsageNTimes(deserializedCache, aclId4, 4);
    callAddUsageNTimes(deserializedCache, aclId5, 5);

    assertCachesEqual(cache, deserializedCache);
}
 
Example 54
Project: xitk   File: P11DSAContentSigner.java   Source Code and License 5 votes vote down vote up
@Override
public OutputStream getOutputStream() {
    if (outputStream instanceof ByteArrayOutputStream) {
        ((ByteArrayOutputStream) outputStream).reset();
    } else {
        ((DigestOutputStream) outputStream).reset();
    }
    return outputStream;
}
 
Example 55
Project: mi-firma-android   File: AOUtil.java   Source Code and License 5 votes vote down vote up
/** Convierte un objeto de propiedades en una cadena Base64 URL SAFE.
 * @param p Objeto de propiedades a convertir.
 * @return Base64 URL SAFE que descodificado es un fichero de propiedades en texto plano.
 * @throws IOException Si hay problemas en la conversi&oacute;n a Base64. */
public static String properties2Base64(final Properties p) throws IOException {
	if (p == null) {
		return ""; //$NON-NLS-1$
	}
	final ByteArrayOutputStream baos = new ByteArrayOutputStream();
	final OutputStreamWriter osw = new OutputStreamWriter(baos, DEFAULT_ENCODING);
	p.store(osw, ""); //$NON-NLS-1$
	return Base64.encode(baos.toByteArray(), true);
}
 
Example 56
Project: mczone   File: Gamer.java   Source Code and License 5 votes vote down vote up
public void sendToServer(String ip, int port, String msg) {
	if (msg != null)
		sendMessage(msg);

	ByteArrayOutputStream b = new ByteArrayOutputStream();
	DataOutputStream out = new DataOutputStream(b);
	try {
	    out.writeUTF("Transfer");
	    out.writeUTF(ip + ":" + port); // Target Server
	} catch (IOException e) {
	    // Can never happen
	}
	getPlayer().sendPluginMessage(MCZone.getInstance(), "BungeeCord", b.toByteArray());
}
 
Example 57
Project: boohee_v5.6   File: FastJsonJsonView.java   Source Code and License 5 votes vote down vote up
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
    byte[] bytes = JSON.toJSONString(filterModel(model), this.serializerFeatures).getBytes(this.charset);
    OutputStream stream = this.updateContentLength ? createTemporaryOutputStream() : response.getOutputStream();
    stream.write(bytes);
    if (this.updateContentLength) {
        writeToResponse(response, (ByteArrayOutputStream) stream);
    }
}
 
Example 58
Project: ditb   File: ChecksumUtil.java   Source Code and License 5 votes vote down vote up
/**
 * Write dummy checksums to the end of the specified bytes array
 * to reserve space for writing checksums later
 * @param baos OutputStream to write dummy checkum values
 * @param numBytes Number of bytes of data for which dummy checksums
 *                 need to be generated
 * @param bytesPerChecksum Number of bytes per checksum value
 */
static void reserveSpaceForChecksums(ByteArrayOutputStream baos,
  int numBytes, int bytesPerChecksum) throws IOException {
  long numChunks = numChunks(numBytes, bytesPerChecksum);
  long bytesLeft = numChunks * HFileBlock.CHECKSUM_SIZE;
  while (bytesLeft > 0) {
    long count = Math.min(bytesLeft, DUMMY_VALUE.length);
    baos.write(DUMMY_VALUE, 0, (int)count);
    bytesLeft -= count;
  }
}
 
Example 59
Project: react-native-image-intent   File: ImageIntentModule.java   Source Code and License 5 votes vote down vote up
private String encodeImage(Bitmap bm)
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG,70,baos);
    byte[] b = baos.toByteArray();
    String encImage = Base64.encodeToString(b, Base64.DEFAULT);

    return encImage;
}
 
Example 60
Project: react-native-image-intent   File: ImageIntentModule.java   Source Code and License 5 votes vote down vote up
private String encodeImage(Bitmap bm)
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG,70,baos);
    byte[] b = baos.toByteArray();
    String encImage = Base64.encodeToString(b, Base64.DEFAULT);

    return encImage;
}