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   View source code 6 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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: ramus   File: ReportEditorView.java   View source code 6 votes vote down vote up
protected String getHTMLText() {
    String page;
    try {
        HashMap<String, Object> map = new HashMap<String, Object>();
        Query query = queryView.getQuery();
        if (query != null)
            map.put("query", query);
        page = ((ReportQuery) framework.getEngine()).getHTMLReport(element,
                map);
    } catch (Exception e1) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        PrintStream s = new PrintStream(stream);
        e1.printStackTrace();
        if (e1 instanceof DataException)
            s.println(((DataException) e1)
                    .getMessage(new MessageFormatter() {

                        @Override
                        public String getString(String key,
                                                Object[] arguments) {
                            return MessageFormat.format(
                                    ReportResourceManager.getString(key),
                                    arguments);
                        }
                    }));
        else {
            e1.printStackTrace(s);
        }

        s.flush();

        page = new String(stream.toByteArray());
    }
    return page;
}
 
Example 33
Project: AndroidProgramming3e   File: FlickrFetchr.java   View source code 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 34
Project: directory-ldap-api   File: ValueSerializationTest.java   View source code 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 35
Project: NotifyTools   File: QuotedPrintableCodec.java   View source code 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 36
Project: ats-framework   File: GssClient.java   View source code 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 37
Project: playTorrent   File: BitDecoder.java   View source code 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 38
Project: java-restclient   File: RequestBuilderSyncTest.java   View source code 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 39
Project: directory-ldap-api   File: AvaSerializationTest.java   View source code 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 40
Project: Equella   File: HttpServiceImpl.java   View source code 6 votes vote down vote up
@Override
public String getBody()
{
	if( body == null )
	{
		final ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
		try (InputStream in = getInputStream())
		{
			ByteStreams.copy(in, out);
			// TODO: check headers to see if indeed UTF8...
			body = new String(out.toByteArray(), Constants.UTF8);
			if( LOGGER.isTraceEnabled() )
			{
				LOGGER.trace("Received\n" + body);
			}
		}
		catch( IOException u )
		{
			throw Throwables.propagate(u);
		}
	}
	return body;
}