Java 类java.io.ByteArrayOutputStream 实例源码
项目:java-restclient
文件:RestClientSyncTest.java
@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);
}
项目:jdk8u-jdk
文件:WrongAAD.java
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");
}
项目:Robin_Java
文件:SafeTest.java
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());
}
项目:parabuild-ci
文件:DialPlotTests.java
/**
* 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);
}
项目:ats-framework
文件:SwingElementLocator.java
/**
*
* @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();
}
项目:incubator-netbeans
文件:MethodEntryExitCallsInjector.java
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);
}
}
项目:vogar
文件:JUnitRunnerTest.java
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"));
}
项目:elasticsearch_my
文件:CreateIndexRequestBuilderTests.java
/**
* 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));
}
项目:asura
文件:StdJDBCDelegate.java
/**
* 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;
}
项目:litiengine
文件:CompressionUtilities.java
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();
}
项目:lams
文件:PointbaseDelegate.java
/**
* <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);
}
}
项目:MetadataEditor
文件:Mp4TagReverseDnsField.java
@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);
}
}
项目:BiglyBT
文件:DERBitString.java
@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();
}
项目:NSS
文件:CryptBase.java
@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);
}
}
项目:boohee_v5.6
文件:CommonUtils.java
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 "";
}
}
项目:openjdk-jdk10
文件:DestTypeTest.java
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();
}
项目:dubbo2
文件:SerializationCompareTest.java
@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);
}
项目:util4j
文件:NMap.java
/**
* 根据文件解码一个新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;
}
项目:MetadataEditor
文件:Mp4FreeBox.java
/**
* 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);
}
}
项目:rdf4j-schema-generator
文件:SchemaGeneratorTest.java
/**
* 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\""));
}
项目:TinkerDemo
文件:Utils.java
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();
}
}
}
项目:fuck_zookeeper
文件:Utils.java
/**
* 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();
}
项目:openjdk-jdk10
文件:WDataTransferer.java
@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;
}
项目:parabuild-ci
文件:ComparableObjectSeriesTests.java
/**
* 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);
}
项目:CorePatch
文件:BsPatchTest.java
@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);
}
}
项目:BiglyBT
文件:IDATChunk.java
@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;
}
项目:parabuild-ci
文件:StandardCategoryLabelGeneratorTests.java
/**
* 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);
}
项目:bubichain-sdk-java
文件:BytesUtils.java
/**
* 将输入流的所有内容都读入到字节数组返回;
* <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();
}
项目:openjdk-jdk10
文件:NulFile.java
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());
}
}
项目:CacheWebView
文件:ResourseInputStream.java
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();
}
}
项目:hadoop
文件:TestClusterId.java
/**
* 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());
}
项目:ramus
文件:ReportEditorView.java
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;
}
项目:AndroidProgramming3e
文件:FlickrFetchr.java
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();
}
}
项目:directory-ldap-api
文件:ValueSerializationTest.java
@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 ) );
}
项目:NotifyTools
文件:QuotedPrintableCodec.java
/***
* 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();
}
项目:ats-framework
文件:GssClient.java
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;
}
项目:playTorrent
文件:BitDecoder.java
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);
}
项目:java-restclient
文件:RequestBuilderSyncTest.java
@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);
}
项目:directory-ldap-api
文件:AvaSerializationTest.java
/**
* 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 );
}
}
项目:Equella
文件:HttpServiceImpl.java
@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;
}