当前位置: 首页>>代码示例>>Java>>正文


Java ByteArrayOutputStream类代码示例

本文整理汇总了Java中java.io.ByteArrayOutputStream的典型用法代码示例。如果您正苦于以下问题:Java ByteArrayOutputStream类的具体用法?Java ByteArrayOutputStream怎么用?Java ByteArrayOutputStream使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


ByteArrayOutputStream类属于java.io包,在下文中一共展示了ByteArrayOutputStream类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: shouldHandleGzipContentInOutputStream

import java.io.ByteArrayOutputStream; //导入依赖的package包/类
@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);
}
 
开发者ID:mercadolibre,项目名称:java-restclient,代码行数:26,代码来源:RestClientSyncTest.java

示例2: decryptWithWrongAAD

import java.io.ByteArrayOutputStream; //导入依赖的package包/类
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");
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:24,代码来源:WrongAAD.java

示例3: main

import java.io.ByteArrayOutputStream; //导入依赖的package包/类
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());

}
 
开发者ID:ruobingding,项目名称:Robin_Java,代码行数:20,代码来源:SafeTest.java

示例4: testSerialization

import java.io.ByteArrayOutputStream; //导入依赖的package包/类
/**
 * 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);
}
 
开发者ID:parabuild-ci,项目名称:parabuild-ci,代码行数:24,代码来源:DialPlotTests.java

示例5: getComponentHierarchy

import java.io.ByteArrayOutputStream; //导入依赖的package包/类
/**
 *
 * @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();
}
 
开发者ID:Axway,项目名称:ats-framework,代码行数:25,代码来源:SwingElementLocator.java

示例6: getAloadCode

import java.io.ByteArrayOutputStream; //导入依赖的package包/类
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);
    }
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:20,代码来源:MethodEntryExitCallsInjector.java

示例7: test_init_and_run_for_FailTest_should_perform_test

import java.io.ByteArrayOutputStream; //导入依赖的package包/类
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"));
}
 
开发者ID:dryganets,项目名称:vogar,代码行数:25,代码来源:JUnitRunnerTest.java

示例8: testSetSource

import java.io.ByteArrayOutputStream; //导入依赖的package包/类
/**
 * 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));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:25,代码来源:CreateIndexRequestBuilderTests.java

示例9: getKeyOfNonSerializableValue

import java.io.ByteArrayOutputStream; //导入依赖的package包/类
/**
 * 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;   
}
 
开发者ID:AsuraTeam,项目名称:asura,代码行数:27,代码来源:StdJDBCDelegate.java

示例10: compress

import java.io.ByteArrayOutputStream; //导入依赖的package包/类
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();
}
 
开发者ID:gurkenlabs,项目名称:litiengine,代码行数:21,代码来源:CompressionUtilities.java

示例11: updateJobData

import java.io.ByteArrayOutputStream; //导入依赖的package包/类
/**
 * <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);
    }
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:32,代码来源:PointbaseDelegate.java

示例12: getRawContentDataOnly

import java.io.ByteArrayOutputStream; //导入依赖的package包/类
@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);
    }
}
 
开发者ID:GlennioTech,项目名称:MetadataEditor,代码行数:24,代码来源:Mp4TagReverseDnsField.java

示例13: getString

import java.io.ByteArrayOutputStream; //导入依赖的package包/类
@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();
}
 
开发者ID:BiglySoftware,项目名称:BiglyBT,代码行数:27,代码来源:DERBitString.java

示例14: decrypt

import java.io.ByteArrayOutputStream; //导入依赖的package包/类
@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);
	}
}
 
开发者ID:breakEval13,项目名称:NSS,代码行数:19,代码来源:CryptBase.java

示例15: textCompress

import java.io.ByteArrayOutputStream; //导入依赖的package包/类
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 "";
    }
}
 
开发者ID:JackChan1999,项目名称:boohee_v5.6,代码行数:17,代码来源:CommonUtils.java


注:本文中的java.io.ByteArrayOutputStream类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。