Here are the examples of the java api class java.io.ByteArrayOutputStream taken from open source projects.
1. EmulatorControl#setPMState()
Project: JPC
File: EmulatorControl.java
File: EmulatorControl.java
private void setPMState(int[] state, int currentCSEIP) throws IOException { // get to cs:eip = 0:2000 // Assumes we are currently in real mode int codeAddress16 = 0x2000; int dataAddress16 = 0x3000; int nextDataAddress = dataAddress16; setPhysicalMemory(currentCSEIP, new byte[] { (byte) 0xea, (byte) codeAddress16, (byte) (codeAddress16 >> 8), (byte) 0, (byte) 0 }); executeInstruction(); // zero what we just wrote setPhysicalMemory(currentCSEIP, new byte[5]); ByteArrayOutputStream bout = new ByteArrayOutputStream(); // assume we are starting in real mode int intCount = 0; // create GDTR setPhysicalMemory(nextDataAddress, new byte[] { (byte) state[GDT_LIMIT_INDEX], (byte) (state[GDT_LIMIT_INDEX] >> 8), (byte) state[GDT_BASE_INDEX], (byte) (state[GDT_BASE_INDEX] >> 8), (byte) (state[GDT_BASE_INDEX] >> 16), (byte) (state[GDT_BASE_INDEX] >> 24) }); // LGDT ds:IW bout.write(0x0f); bout.write(0x01); bout.write(0x16); bout.write(nextDataAddress); bout.write(nextDataAddress >> 8); nextDataAddress += 6; intCount++; byte[] gdt = toBytes(new long[] { 0L, getDataDescriptor(state[ES_BASE_INDEX], state[ES_LIMIT_INDEX]), getCodeDescriptor(state[CS_BASE_INDEX], state[CS_LIMIT_INDEX]), getDataDescriptor(state[SS_BASE_INDEX], state[SS_LIMIT_INDEX]), getDataDescriptor(state[DS_BASE_INDEX], state[DS_LIMIT_INDEX]), getDataDescriptor(state[FS_BASE_INDEX], state[FS_LIMIT_INDEX]), getDataDescriptor(state[GS_BASE_INDEX], state[GS_LIMIT_INDEX]), getCodeDescriptor(0, 0xffffffff) }); setPhysicalMemory(state[GDT_BASE_INDEX], gdt); // create IDTR setPhysicalMemory(nextDataAddress, new byte[] { (byte) state[IDT_LIMIT_INDEX], (byte) (state[IDT_LIMIT_INDEX] >> 8), (byte) state[IDT_BASE_INDEX], (byte) (state[IDT_BASE_INDEX] >> 8), (byte) (state[IDT_BASE_INDEX] >> 16), (byte) (state[IDT_BASE_INDEX] >> 24) }); // LIDT ds:IW bout.write(0x0f); bout.write(0x01); bout.write(0x1e); bout.write(nextDataAddress); bout.write(nextDataAddress >> 8); nextDataAddress += 6; intCount++; for (int i = 1; i < 8; i++) { // mov reg, ID bout.write(0x66); bout.write(0xc7); bout.write(0xc0 + i); bout.write(state[i]); bout.write(state[i] >> 8); bout.write(state[i] >> 16); bout.write(state[i] >> 24); intCount++; } // reset FPU bout.write(0xdb); bout.write(0xe3); intCount++; // set FPU stack (relies on ds base being 0) for (int i = 7; i >= 0; i--) { byte[] value = new byte[8]; for (int j = 0; j < 4; j++) value[7 - j] = (byte) (state[37 + 2 * i] >> (8 * (3 - j))); for (int j = 4; j < 8; j++) value[7 - j] = (byte) (state[37 + 2 * i + 1] >> (8 * (7 - j))); // put value in mem at dataAddress setPhysicalMemory(nextDataAddress, value); // fld that mem section bout.write(0xdd); bout.write(0x06); bout.write(nextDataAddress); bout.write(nextDataAddress >> 8); nextDataAddress += 8; intCount++; } // set ds (FPU set needed it zero) bout.write(0xc7); bout.write(0xc0); bout.write(state[3 + 10]); bout.write(state[3 + 10] >> 8); bout.write(0x8e); bout.write(0xc0 + (3 << 3)); intCount += 2; // set eflags // push ID bout.write(0x66); bout.write(0x68); bout.write(state[9]); bout.write(state[9] >> 8); bout.write(state[9] >> 16); bout.write(state[9] >> 24); // popfd bout.write(0x66); bout.write(0x9d); intCount += 2; // set CR0 and switch to protected mode // mov eax, cr0 bout.write(0x0f); bout.write(0x20); bout.write(0xc0); // or al, 1 bout.write(0x0c); bout.write(0x01); // mov cr0, eax bout.write(0x0f); bout.write(0x22); bout.write(0xc0); intCount += 3; // far jump to where we are (to load cs) int currentEIP = codeAddress16 + bout.size() + 8; bout.write(0x66); bout.write(0xea); bout.write(currentEIP); bout.write(currentEIP >> 8); bout.write(currentEIP >> 16); bout.write(currentEIP >> 24); // the last GDT entry pointing to base 0, limit 0xffffffff bout.write(7 << 3); bout.write(0); intCount++; // 8e e8 = mov gs, ax for (int seg = 0; seg < 6; seg++) { if (// can't load CS like this seg == 1) continue; bout.write(0xc7); bout.write(0xc0); // gdt index is seg +1 bout.write((seg + 1) << 3); bout.write(0); // mov S, ax bout.write(0x8e); bout.write(0xc0 + (seg << 3)); intCount += 2; } // set eax: mov reg, ID bout.write(0x66); bout.write(0xc7); bout.write(0xc0); bout.write(state[0]); bout.write(state[0] >> 8); bout.write(state[0] >> 16); bout.write(state[0] >> 24); intCount++; // set cs:eip with far jmp bout.write(0x66); bout.write(0xea); bout.write(state[8]); bout.write(state[8] >> 8); bout.write(state[8] >> 16); bout.write(state[8] >> 24); bout.write(2 << 3); bout.write(0); intCount++; setPhysicalMemory(codeAddress16, bout.toByteArray()); for (int i = 0; i < intCount - 1; i++) executeInstruction(); // account for mov ss, X executing 2 instructions in JPC int[] stateNow = getState(); if (stateNow[8] != state[8]) executeInstruction(); // zero what we just wrote setPhysicalMemory(codeAddress16, new byte[bout.size()]); // and the data too setPhysicalMemory(dataAddress16, new byte[8 * 8]); }
2. EmulatorControl#setState()
Project: JPC
File: EmulatorControl.java
File: EmulatorControl.java
public void setState(int[] state, int currentCSEIP) throws IOException { boolean targetPM = (state[EmulatorControl.CRO_INDEX] & 1) != 0; if (targetPM) { if ((state[EFLAGS_INDEX] & VM86_FLAG) != 0) setVM86State(state, currentCSEIP); else setPMState(state, currentCSEIP); return; } // get to cs:eip = 0:2000 // Assumes we are currently in real mode int codeAddress16 = 0x2000; int dataAddress16 = 0x3000; setPhysicalMemory(currentCSEIP, new byte[] { (byte) 0xea, (byte) codeAddress16, (byte) (codeAddress16 >> 8), (byte) 0, (byte) 0 }); executeInstruction(); // zero what we just wrote setPhysicalMemory(currentCSEIP, new byte[5]); ByteArrayOutputStream bout = new ByteArrayOutputStream(); // assume we are starting in real mode int intCount = 0; for (int i = 1; i < 8; i++) { // mov reg, ID bout.write(0x66); bout.write(0xc7); bout.write(0xc0 + i); if (i == 4) { int esp = 0x1000; bout.write(esp); bout.write(esp >> 8); bout.write(esp >> 16); bout.write(esp >> 24); } else { bout.write(state[i]); bout.write(state[i] >> 8); bout.write(state[i] >> 16); bout.write(state[i] >> 24); } intCount++; } // 8e e8 = mov gs, ax for (int seg = 0; seg < 6; seg++) { if (// can't load CS like this seg == 1) continue; bout.write(0xc7); bout.write(0xc0); if (// ds seg == 3) { bout.write(0); bout.write(0); } else if (// ss seg == 2) { bout.write(0); bout.write(0); } else { bout.write(state[seg + 10]); bout.write(state[seg + 10] >> 8); } bout.write(0x8e); bout.write(0xc0 + (seg << 3)); intCount += 2; } // reset FPU bout.write(0xdb); bout.write(0xe3); intCount++; // set FPU stack (relies on ds base being 0) int nextDataAddress = dataAddress16; for (int i = 7; i >= 0; i--) { byte[] value = new byte[8]; for (int j = 0; j < 4; j++) value[7 - j] = (byte) (state[37 + 2 * i] >> (8 * (3 - j))); for (int j = 4; j < 8; j++) value[7 - j] = (byte) (state[37 + 2 * i + 1] >> (8 * (7 - j))); // put value in mem at dataAddress setPhysicalMemory(nextDataAddress, value); // fld that mem section bout.write(0xdd); bout.write(0x06); bout.write(nextDataAddress); bout.write(nextDataAddress >> 8); nextDataAddress += 8; intCount++; } // set eflags // push ID bout.write(0x66); bout.write(0x68); bout.write(state[9]); bout.write(state[9] >> 8); bout.write(state[9] >> 16); bout.write(state[9] >> 24); // popfd bout.write(0x66); bout.write(0x9d); intCount += 2; // set CR0 bout.write(0x66); bout.write(0xc7); bout.write(0xc0); bout.write(state[36]); bout.write(state[36] >> 8); bout.write(state[36] >> 16); bout.write(state[36] >> 24); bout.write(0x0f); bout.write(0x22); bout.write(0xc0); intCount += 2; // set ds (FPU set needed it zero) bout.write(0xc7); bout.write(0xc0); bout.write(state[3 + 10]); bout.write(state[3 + 10] >> 8); bout.write(0x8e); bout.write(0xc0 + (3 << 3)); intCount += 2; // set ss (mov cr0,eax needed it zero) bout.write(0xc7); bout.write(0xc0); bout.write(state[3 + 10]); bout.write(state[3 + 10] >> 8); bout.write(0x8e); bout.write(0xc0 + (2 << 3)); intCount += 2; // set eax: mov reg, ID bout.write(0x66); bout.write(0xc7); bout.write(0xc0); bout.write(state[0]); bout.write(state[0] >> 8); bout.write(state[0] >> 16); bout.write(state[0] >> 24); intCount++; // set esp (push and popf needed it different): mov reg, ID bout.write(0x66); bout.write(0xc7); bout.write(0xc4); bout.write(state[4]); bout.write(state[4] >> 8); bout.write(state[4] >> 16); bout.write(state[4] >> 24); intCount++; // set cs:eip with far jmp bout.write(0xea); bout.write(state[8]); bout.write(state[8] >> 8); bout.write(state[11]); bout.write(state[11] >> 8); intCount++; setPhysicalMemory(codeAddress16, bout.toByteArray()); for (int i = 0; i < intCount - 2; i++) executeInstruction(); // account for mov ss, X executing 2 instructions in JPC for (int i : new int[] { 0, 1 }) { int[] stateNow = getState(); if (stateNow[8] != state[8]) executeInstruction(); } // zero what we just wrote setPhysicalMemory(codeAddress16, new byte[bout.size()]); // and the data too setPhysicalMemory(dataAddress16, new byte[8 * 8]); }
3. EmulatorControl#setVM86State()
Project: JPC
File: EmulatorControl.java
File: EmulatorControl.java
private void setVM86State(int[] state, int currentCSEIP) throws IOException { // need to have [EIP, CS, EFLAGS, ESP, SS, ES, DS, FS, GS] on stack, then do iret_o32_a32 int[] stack = new int[9]; stack[0] = state[EIP_INDEX]; stack[1] = state[CS_BASE_INDEX] >> 4; stack[2] = state[EFLAGS_INDEX]; stack[3] = state[ESP_INDEX]; stack[4] = state[SS_BASE_INDEX] >> 4; stack[5] = state[ES_BASE_INDEX] >> 4; stack[6] = state[DS_BASE_INDEX] >> 4; stack[7] = state[FS_BASE_INDEX] >> 4; stack[8] = state[GS_BASE_INDEX] >> 4; // get to cs:eip = 0:2000 // Assumes we are currently in real mode int codeAddress16 = 0x2000; int dataAddress16 = 0x3000; int ssespAddress16 = 0x4000; int nextDataAddress = dataAddress16; setPhysicalMemory(currentCSEIP, new byte[] { (byte) 0xea, (byte) codeAddress16, (byte) (codeAddress16 >> 8), (byte) 0, (byte) 0 }); executeInstruction(); // zero what we just wrote setPhysicalMemory(currentCSEIP, new byte[5]); ByteArrayOutputStream bout = new ByteArrayOutputStream(); // assume we are starting in real mode int intCount = 0; // create GDTR setPhysicalMemory(nextDataAddress, new byte[] { (byte) state[GDT_LIMIT_INDEX], (byte) (state[GDT_LIMIT_INDEX] >> 8), (byte) state[GDT_BASE_INDEX], (byte) (state[GDT_BASE_INDEX] >> 8), (byte) (state[GDT_BASE_INDEX] >> 16), (byte) (state[GDT_BASE_INDEX] >> 24) }); // LGDT ds:IW bout.write(0x0f); bout.write(0x01); bout.write(0x16); bout.write(nextDataAddress); bout.write(nextDataAddress >> 8); nextDataAddress += 6; intCount++; byte[] gdt = toBytes(new long[] { 0L, getDataDescriptor(state[ES_BASE_INDEX], state[ES_LIMIT_INDEX]), getCodeDescriptor(state[CS_BASE_INDEX], state[CS_LIMIT_INDEX]), getDataDescriptor(state[SS_BASE_INDEX], state[SS_LIMIT_INDEX]), getDataDescriptor(state[DS_BASE_INDEX], state[DS_LIMIT_INDEX]), getDataDescriptor(state[FS_BASE_INDEX], state[FS_LIMIT_INDEX]), getDataDescriptor(state[GS_BASE_INDEX], state[GS_LIMIT_INDEX]), getCodeDescriptor(0, 0xffffffff), getDataDescriptor(0, 0xffffffff) }); setPhysicalMemory(state[GDT_BASE_INDEX], gdt); // create IDTR setPhysicalMemory(nextDataAddress, new byte[] { (byte) state[IDT_LIMIT_INDEX], (byte) (state[IDT_LIMIT_INDEX] >> 8), (byte) state[IDT_BASE_INDEX], (byte) (state[IDT_BASE_INDEX] >> 8), (byte) (state[IDT_BASE_INDEX] >> 16), (byte) (state[IDT_BASE_INDEX] >> 24) }); // LIDT ds:IW bout.write(0x0f); bout.write(0x01); bout.write(0x1e); bout.write(nextDataAddress); bout.write(nextDataAddress >> 8); nextDataAddress += 6; intCount++; for (int i = 1; i < 8; i++) { // mov reg, ID bout.write(0x66); bout.write(0xc7); bout.write(0xc0 + i); bout.write(state[i]); bout.write(state[i] >> 8); bout.write(state[i] >> 16); bout.write(state[i] >> 24); intCount++; } // reset FPU bout.write(0xdb); bout.write(0xe3); intCount++; // set FPU stack (relies on ds base being 0) for (int i = 7; i >= 0; i--) { byte[] value = new byte[8]; for (int j = 0; j < 4; j++) value[7 - j] = (byte) (state[37 + 2 * i] >> (8 * (3 - j))); for (int j = 4; j < 8; j++) value[7 - j] = (byte) (state[37 + 2 * i + 1] >> (8 * (7 - j))); // put value in mem at dataAddress setPhysicalMemory(nextDataAddress, value); // fld that mem section bout.write(0xdd); bout.write(0x06); bout.write(nextDataAddress); bout.write(nextDataAddress >> 8); nextDataAddress += 8; intCount++; } // set esp for iret: mov esp, ID bout.write(0x66); bout.write(0xc7); bout.write(0xc4); bout.write(ssespAddress16); bout.write(ssespAddress16 >> 8); bout.write(ssespAddress16 >> 16); bout.write(ssespAddress16 >> 24); intCount++; // set CR0 and switch to 16 bit protected mode // mov eax, cr0 bout.write(0x0f); bout.write(0x20); bout.write(0xc0); // or al, 1 bout.write(0x0c); bout.write(0x01); // mov cr0, eax bout.write(0x0f); bout.write(0x22); bout.write(0xc0); intCount += 3; // set ss base to 0 bout.write(0xc7); bout.write(0xc0); // gdt index is 8 = base 0 bout.write(8 << 3); bout.write(0); // mov S, ax bout.write(0x8e); bout.write(0xd0); intCount += 2; // set eax: mov eax, ID bout.write(0x66); bout.write(0xc7); bout.write(0xc0); bout.write(state[0]); bout.write(state[0] >> 8); bout.write(state[0] >> 16); bout.write(state[0] >> 24); intCount++; // iretd to VM86 (loads eip, esp, segments and eflags) bout.write(0x66); bout.write(0xcf); intCount++; setPhysicalMemory(ssespAddress16, toBytes(stack)); setPhysicalMemory(codeAddress16, bout.toByteArray()); for (int i = 0; i < intCount - 1; i++) executeInstruction(); // account for mov ss, X executing 2 instructions in JPC int[] stateNow = getState(); if (stateNow[8] != state[8]) executeInstruction(); // zero what we just wrote setPhysicalMemory(codeAddress16, new byte[bout.size()]); // and the data too setPhysicalMemory(dataAddress16, new byte[8 * 8]); setPhysicalMemory(ssespAddress16, new byte[4 * stack.length]); }
4. PCLSoftFontManager#writeFontHeader()
Project: fop
File: PCLSoftFontManager.java
File: PCLSoftFontManager.java
private void writeFontHeader(Map<Character, Integer> mappedGlyphs) throws IOException { ByteArrayOutputStream header = new ByteArrayOutputStream(); header.write(pclByteWriter.unsignedInt(fontReader.getDescriptorSize())); header.write(pclByteWriter.unsignedByte(fontReader.getHeaderFormat())); header.write(pclByteWriter.unsignedByte(fontReader.getFontType())); header.write(pclByteWriter.unsignedByte(fontReader.getStyleMSB())); // Reserved header.write(0); header.write(pclByteWriter.unsignedInt(fontReader.getBaselinePosition())); header.write(pclByteWriter.unsignedInt(fontReader.getCellWidth())); header.write(pclByteWriter.unsignedInt(fontReader.getCellHeight())); header.write(pclByteWriter.unsignedByte(fontReader.getOrientation())); header.write(fontReader.getSpacing()); header.write(pclByteWriter.unsignedInt(fontReader.getSymbolSet())); header.write(pclByteWriter.unsignedInt(fontReader.getPitch())); header.write(pclByteWriter.unsignedInt(fontReader.getHeight())); header.write(pclByteWriter.unsignedInt(fontReader.getXHeight())); header.write(pclByteWriter.signedByte(fontReader.getWidthType())); header.write(pclByteWriter.unsignedByte(fontReader.getStyleLSB())); header.write(pclByteWriter.signedByte(fontReader.getStrokeWeight())); header.write(pclByteWriter.unsignedByte(fontReader.getTypefaceLSB())); header.write(pclByteWriter.unsignedByte(fontReader.getTypefaceMSB())); header.write(pclByteWriter.unsignedByte(fontReader.getSerifStyle())); header.write(pclByteWriter.unsignedByte(fontReader.getQuality())); header.write(pclByteWriter.signedByte(fontReader.getPlacement())); header.write(pclByteWriter.signedByte(fontReader.getUnderlinePosition())); header.write(pclByteWriter.unsignedByte(fontReader.getUnderlineThickness())); header.write(pclByteWriter.unsignedInt(fontReader.getTextHeight())); header.write(pclByteWriter.unsignedInt(fontReader.getTextWidth())); header.write(pclByteWriter.unsignedInt(fontReader.getFirstCode())); header.write(pclByteWriter.unsignedInt(fontReader.getLastCode())); header.write(pclByteWriter.unsignedByte(fontReader.getPitchExtended())); header.write(pclByteWriter.unsignedByte(fontReader.getHeightExtended())); header.write(pclByteWriter.unsignedInt(fontReader.getCapHeight())); header.write(pclByteWriter.unsignedLongInt(fontReader.getFontNumber())); header.write(pclByteWriter.padBytes(fontReader.getFontName().getBytes("US-ASCII"), 16, 32)); header.write(pclByteWriter.unsignedInt(fontReader.getScaleFactor())); header.write(pclByteWriter.signedInt(fontReader.getMasterUnderlinePosition())); header.write(pclByteWriter.unsignedInt(fontReader.getMasterUnderlineThickness())); header.write(pclByteWriter.unsignedByte(fontReader.getFontScalingTechnology())); header.write(pclByteWriter.unsignedByte(fontReader.getVariety())); writeSegmentedFontData(header, mappedGlyphs); baos.write(getFontHeaderCommand(header.size())); baos.write(header.toByteArray()); }
5. ZWaveTimeParametersCommandClass#getSetMessage()
Project: openhab2-addons
File: ZWaveTimeParametersCommandClass.java
File: ZWaveTimeParametersCommandClass.java
/** * Gets a SerialMessage with the TIME_SET command * * @return the serial message. */ public SerialMessage getSetMessage(Calendar cal) { logger.debug("NODE {}: Creating new message for command TIME_SET", getNode().getNodeId()); SerialMessage result = new SerialMessage(getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.SendData, SerialMessagePriority.RealTime); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write(getNode().getNodeId()); outputData.write(9); outputData.write(getCommandClass().getKey()); outputData.write(TIME_SET); outputData.write((cal.get(Calendar.YEAR) & 0xff00) >> 8); outputData.write((cal.get(Calendar.YEAR) & 0xff)); outputData.write(cal.get(Calendar.MONTH) + 1); outputData.write(cal.get(Calendar.DAY_OF_MONTH)); outputData.write(cal.get(Calendar.HOUR_OF_DAY)); outputData.write(cal.get(Calendar.MINUTE)); outputData.write(cal.get(Calendar.SECOND)); result.setMessagePayload(outputData.toByteArray()); return result; }
6. Account#toBytes()
Project: scouter
File: Account.java
File: Account.java
public byte[] toBytes() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] idBytes = id.getBytes(); out.write(idBytes.length); out.write(idBytes); byte[] passBytes = password.getBytes(); out.write(passBytes.length); out.write(passBytes); byte[] emailBytes = email.getBytes(); out.write(emailBytes.length); out.write(emailBytes); byte[] groupBytes = group.getBytes(); out.write(groupBytes.length); out.write(groupBytes); return out.toByteArray(); }
7. RFC6637Utils#createUserKeyingMaterial()
Project: bc-java
File: RFC6637Utils.java
File: RFC6637Utils.java
// RFC 6637 - Section 8 // curve_OID_len = (byte)len(curve_OID); // Param = curve_OID_len || curve_OID || public_key_alg_ID || 03 // || 01 || KDF_hash_ID || KEK_alg_ID for AESKeyWrap || "Anonymous // Sender " || recipient_fingerprint; // Z_len = the key size for the KEK_alg_ID used with AESKeyWrap // Compute Z = KDF( S, Z_len, Param ); public static byte[] createUserKeyingMaterial(PublicKeyPacket pubKeyData, KeyFingerPrintCalculator fingerPrintCalculator) throws IOException, PGPException { ByteArrayOutputStream pOut = new ByteArrayOutputStream(); ECDHPublicBCPGKey ecKey = (ECDHPublicBCPGKey) pubKeyData.getKey(); byte[] encOid = ecKey.getCurveOID().getEncoded(); pOut.write(encOid, 1, encOid.length - 1); pOut.write(pubKeyData.getAlgorithm()); pOut.write(0x03); pOut.write(0x01); pOut.write(ecKey.getHashAlgorithm()); pOut.write(ecKey.getSymmetricKeyAlgorithm()); pOut.write(ANONYMOUS_SENDER); pOut.write(fingerPrintCalculator.calculateFingerprint(pubKeyData)); return pOut.toByteArray(); }
8. PngWriter#writeChunkXmpiTXt()
Project: sanselan
File: PngWriter.java
File: PngWriter.java
private void writeChunkXmpiTXt(OutputStream os, String xmpXml) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); // keyword baos.write(XMP_KEYWORD.getBytes("ISO-8859-1")); baos.write(0); // compressed flag, true baos.write(1); // compression method baos.write(COMPRESSION_DEFLATE_INFLATE); // language tag (ignore). TODO baos.write(0); // translated keyword baos.write(XMP_KEYWORD.getBytes("utf-8")); baos.write(0); baos.write(new ZLibUtils().deflate(xmpXml.getBytes("utf-8"))); writeChunk(os, iTXt_CHUNK_TYPE.toByteArray(), baos.toByteArray()); }
9. PngWriter#writeChunkXmpiTXt()
Project: commons-imaging
File: PngWriter.java
File: PngWriter.java
private void writeChunkXmpiTXt(final OutputStream os, final String xmpXml) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // keyword baos.write(PngConstants.XMP_KEYWORD.getBytes("ISO-8859-1")); baos.write(0); // compressed flag, true baos.write(1); // compression method baos.write(PngConstants.COMPRESSION_DEFLATE_INFLATE); // language tag (ignore). TODO baos.write(0); // translated keyword baos.write(PngConstants.XMP_KEYWORD.getBytes("utf-8")); baos.write(0); baos.write(deflate(xmpXml.getBytes("utf-8"))); writeChunk(os, ChunkType.iTXt, baos.toByteArray()); }
10. ZWaveMeterTblMonitorCommandClass#getCurrentData()
Project: openhab2-addons
File: ZWaveMeterTblMonitorCommandClass.java
File: ZWaveMeterTblMonitorCommandClass.java
/** * Gets a SerialMessage with the METER_TBL_CURRENT_DATA_GET command * * @return the serial message */ public SerialMessage getCurrentData(int dataset) { logger.debug("NODE {}: Creating new message for application command METER_TBL_CURRENT_DATA_GET", getNode().getNodeId()); SerialMessage message = new SerialMessage(getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write(this.getNode().getNodeId()); outputData.write(5); outputData.write(getCommandClass().getKey()); outputData.write(METER_TBL_CURRENT_DATA_GET); outputData.write(dataset >> 16); outputData.write(dataset >> 8); outputData.write(dataset); message.setMessagePayload(outputData.toByteArray()); return message; }
11. RegAssertionBuilder#getAttestationBasicFull()
Project: UAF
File: RegAssertionBuilder.java
File: RegAssertionBuilder.java
private byte[] getAttestationBasicFull(byte[] signedDataValue) throws Exception { ByteArrayOutputStream byteout = new ByteArrayOutputStream(); byte[] value = null; int length = 0; byteout.write(encodeInt(TagsEnum.TAG_SIGNATURE.id)); value = getSignature(signedDataValue); length = value.length; byteout.write(encodeInt(length)); byteout.write(value); byteout.write(encodeInt(TagsEnum.TAG_ATTESTATION_CERT.id)); value = Base64.decode(AttestCert.base64DERCert, Base64.URL_SAFE); length = value.length; byteout.write(encodeInt(length)); byteout.write(value); return byteout.toByteArray(); }
12. RegAssertionBuilder#getRegAssertion()
Project: UAF
File: RegAssertionBuilder.java
File: RegAssertionBuilder.java
private byte[] getRegAssertion(RegistrationResponse response) throws Exception { ByteArrayOutputStream byteout = new ByteArrayOutputStream(); byte[] value = null; int length = 0; byteout.write(encodeInt(TagsEnum.TAG_UAFV1_KRD.id)); value = getSignedData(response); length = value.length; byteout.write(encodeInt(length)); byteout.write(value); byte[] signedDataValue = byteout.toByteArray(); byteout.write(encodeInt(TagsEnum.TAG_ATTESTATION_BASIC_FULL.id)); value = getAttestationBasicFull(signedDataValue); length = value.length; byteout.write(encodeInt(length)); byteout.write(value); return byteout.toByteArray(); }
13. AuthAssertionBuilder#getAuthAssertion()
Project: UAF
File: AuthAssertionBuilder.java
File: AuthAssertionBuilder.java
private byte[] getAuthAssertion(AuthenticationResponse response) throws Exception { ByteArrayOutputStream byteout = new ByteArrayOutputStream(); byte[] value = null; int length = 0; byteout.write(encodeInt(TagsEnum.TAG_UAFV1_SIGNED_DATA.id)); value = getSignedData(response); length = value.length; byteout.write(encodeInt(length)); byteout.write(value); byte[] signedDataValue = byteout.toByteArray(); byteout.write(encodeInt(TagsEnum.TAG_SIGNATURE.id)); value = getSignature(signedDataValue); length = value.length; byteout.write(encodeInt(length)); byteout.write(value); return byteout.toByteArray(); }
14. RegAssertionBuilder#getRegAssertion()
Project: UAF
File: RegAssertionBuilder.java
File: RegAssertionBuilder.java
private byte[] getRegAssertion() throws Exception { ByteArrayOutputStream byteout = new ByteArrayOutputStream(); byte[] value = null; int length = 0; byteout.write(encodeInt(TagsEnum.TAG_UAFV1_KRD.id)); value = getSignedData(); length = value.length; byteout.write(encodeInt(length)); byteout.write(value); byte[] signedDataValue = byteout.toByteArray(); byteout.write(encodeInt(TagsEnum.TAG_SIGNATURE.id)); value = getSignature(signedDataValue); length = value.length; byteout.write(encodeInt(length)); byteout.write(value); return byteout.toByteArray(); }
15. AuthAssertionBuilder#getAuthAssertion()
Project: UAF
File: AuthAssertionBuilder.java
File: AuthAssertionBuilder.java
private byte[] getAuthAssertion() throws Exception { ByteArrayOutputStream byteout = new ByteArrayOutputStream(); byte[] value = null; int length = 0; byteout.write(encodeInt(TagsEnum.TAG_UAFV1_SIGNED_DATA.id)); value = getSignedData(); length = value.length; byteout.write(encodeInt(length)); byteout.write(value); byte[] signedDataValue = byteout.toByteArray(); byteout.write(encodeInt(TagsEnum.TAG_SIGNATURE.id)); value = getSignature(signedDataValue); length = value.length; byteout.write(encodeInt(length)); byteout.write(value); return byteout.toByteArray(); }
16. ZWaveClockCommandClass#getSetMessage()
Project: openhab2-addons
File: ZWaveClockCommandClass.java
File: ZWaveClockCommandClass.java
/** * Gets a SerialMessage with the CLOCK_SET command * * @return the serial message. */ public SerialMessage getSetMessage(Calendar cal) { logger.debug("NODE {}: Creating new message for command CLOCK_SET", getNode().getNodeId()); int day = cal.get(Calendar.DAY_OF_WEEK) == 1 ? 7 : cal.get(Calendar.DAY_OF_WEEK) - 1; int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); SerialMessage result = new SerialMessage(getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.SendData, SerialMessagePriority.RealTime); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write(getNode().getNodeId()); outputData.write(4); outputData.write(getCommandClass().getKey()); outputData.write(CLOCK_SET); outputData.write((day << 5) | hour); outputData.write(minute); result.setMessagePayload(outputData.toByteArray()); return result; }
17. ZwaveAssociationGroupInfoCommandClass#getCommandListMessage()
Project: openhab2-addons
File: ZwaveAssociationGroupInfoCommandClass.java
File: ZwaveAssociationGroupInfoCommandClass.java
/** * Gets a SerialMessage with the COMMAND_LIST_GET command * * @return the serial message */ public SerialMessage getCommandListMessage(int groupidx) { logger.debug("NODE {}: Creating new message for application command COMMAND_LIST_GET for group {}", getNode().getNodeId(), groupidx); SerialMessage result = new SerialMessage(getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); byte allowCache = 0; ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write(getNode().getNodeId()); outputData.write(4); outputData.write(getCommandClass().getKey()); outputData.write(COMMAND_LIST_GET); outputData.write(allowCache); outputData.write(groupidx); result.setMessagePayload(outputData.toByteArray()); return result; }
18. ZwaveAssociationGroupInfoCommandClass#getInfoMessage()
Project: openhab2-addons
File: ZwaveAssociationGroupInfoCommandClass.java
File: ZwaveAssociationGroupInfoCommandClass.java
/** * Gets a SerialMessage with the INFO_GET command * * @return the serial message */ public SerialMessage getInfoMessage(int groupidx) { logger.debug("NODE {}: Creating new message for application command INFO_GET for group {}", getNode().getNodeId(), groupidx); SerialMessage result = new SerialMessage(getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); byte listMode = 0; if (groupidx == 0) { // request all groups listMode = GET_LISTMODE_MASK; } ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write(getNode().getNodeId()); outputData.write(4); outputData.write(getCommandClass().getKey()); outputData.write(INFO_GET); outputData.write(listMode); outputData.write(groupidx); result.setMessagePayload(outputData.toByteArray()); return result; }
19. ZWaveClockCommandClass#getSetMessage()
Project: openhab
File: ZWaveClockCommandClass.java
File: ZWaveClockCommandClass.java
/** * Gets a SerialMessage with the CLOCK_SET command * * @return the serial message. */ public SerialMessage getSetMessage(Calendar cal) { logger.debug("NODE {}: Creating new message for command CLOCK_SET", getNode().getNodeId()); int day = cal.get(Calendar.DAY_OF_WEEK) == 1 ? 7 : cal.get(Calendar.DAY_OF_WEEK) - 1; int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); SerialMessage result = new SerialMessage(getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.SendData, SerialMessagePriority.Immediate); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write(getNode().getNodeId()); outputData.write(4); outputData.write(getCommandClass().getKey()); outputData.write(CLOCK_SET); outputData.write((day << 5) | hour); outputData.write(minute); result.setMessagePayload(outputData.toByteArray()); return result; }
20. XmpReader#serializeDoc()
Project: clj-pdf
File: XmpReader.java
File: XmpReader.java
/** * Writes the document to a byte array. */ public byte[] serializeDoc() throws IOException { XmlDomWriter xw = new XmlDomWriter(); ByteArrayOutputStream fout = new ByteArrayOutputStream(); xw.setOutput(fout, null); fout.write(XmpWriter.XPACKET_PI_BEGIN.getBytes("UTF-8")); fout.flush(); NodeList xmpmeta = domDocument.getElementsByTagName("x:xmpmeta"); xw.write(xmpmeta.item(0)); fout.flush(); for (int i = 0; i < 20; i++) { fout.write(XmpWriter.EXTRASPACE.getBytes()); } fout.write(XmpWriter.XPACKET_PI_END_W.getBytes()); fout.close(); return fout.toByteArray(); }
21. DesfireProtocol#wrapMessage()
Project: farebot
File: DesfireProtocol.java
File: DesfireProtocol.java
private byte[] wrapMessage(byte command, byte[] parameters) throws Exception { ByteArrayOutputStream stream = new ByteArrayOutputStream(); stream.write((byte) 0x90); stream.write(command); stream.write((byte) 0x00); stream.write((byte) 0x00); if (parameters != null) { stream.write((byte) parameters.length); stream.write(parameters); } stream.write((byte) 0x00); return stream.toByteArray(); }
22. CEPASProtocol#wrapMessage()
Project: farebot
File: CEPASProtocol.java
File: CEPASProtocol.java
private byte[] wrapMessage(byte command, byte p1, byte p2, byte lc, byte[] parameters) throws IOException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); // CLA stream.write((byte) 0x90); // INS stream.write(command); // P1 stream.write(p1); // P2 stream.write(p2); // Lc stream.write(lc); // Write Lc and data fields if (parameters != null) { // Data field stream.write(parameters); } return stream.toByteArray(); }
23. MergeType1Fonts#writeFont()
Project: fop-pdf-images
File: MergeType1Fonts.java
File: MergeType1Fonts.java
public byte[] writeFont() throws IOException { ByteArrayOutputStream boasHeader = writeHeader(pfbData, encoding); ByteArrayOutputStream boasMain = writeMainSection(decoded, mainSection, charStrings); byte[] mainSectionBytes = BinaryCoder.encodeBytes(boasMain.toByteArray(), 55665, 4); boasMain.reset(); boasMain.write(mainSectionBytes); ByteArrayOutputStream baosTrailer = new ByteArrayOutputStream(); baosTrailer.write(pfbData.getTrailerSegment(), 0, pfbData.getTrailerSegment().length); return stitchFont(boasHeader, boasMain, baosTrailer); }
24. PngWriter#writeChunkIHDR()
Project: commons-imaging
File: PngWriter.java
File: PngWriter.java
private void writeChunkIHDR(final OutputStream os, final ImageHeader value) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); writeInt(baos, value.width); writeInt(baos, value.height); baos.write(0xff & value.bitDepth); baos.write(0xff & value.pngColorType.getValue()); baos.write(0xff & value.compressionMethod); baos.write(0xff & value.filterMethod); baos.write(0xff & value.interlaceMethod.ordinal()); writeChunk(os, ChunkType.IHDR, baos.toByteArray()); }
25. CFFToType1Font#convertOTFToType1()
Project: fop
File: CFFToType1Font.java
File: CFFToType1Font.java
private InputStream convertOTFToType1(Map<Integer, Integer> glyphs, CFFFont f, String i) throws IOException { byte[] t1 = new Type1FontFormatter(glyphs).format((CFFType1Font) f, i); PFBData pfb = new PFBParser().parsePFB(new ByteArrayInputStream(t1)); ByteArrayOutputStream s1 = new ByteArrayOutputStream(); s1.write(pfb.getHeaderSegment()); ByteArrayOutputStream s2 = new ByteArrayOutputStream(); s2.write(pfb.getEncryptedSegment()); ByteArrayOutputStream s3 = new ByteArrayOutputStream(); s3.write(pfb.getTrailerSegment()); byte[] out = new Type1SubsetFile().stitchFont(s1, s2, s3); return new ByteArrayInputStream(out); }
26. ZWaveUserCodeCommandClass#getUserCode()
Project: openhab2-addons
File: ZWaveUserCodeCommandClass.java
File: ZWaveUserCodeCommandClass.java
public SerialMessage getUserCode(int id) { logger.debug("NODE {}: Creating new message for application command USER_CODE_GET({})", this.getNode().getNodeId(), id); SerialMessage message = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write((byte) this.getNode().getNodeId()); outputData.write(3); outputData.write((byte) getCommandClass().getKey()); outputData.write((byte) USER_CODE_GET); outputData.write((byte) (id)); message.setMessagePayload(outputData.toByteArray()); return message; }
27. ZWaveDoorLockLoggingCommandClass#getEntry()
Project: openhab2-addons
File: ZWaveDoorLockLoggingCommandClass.java
File: ZWaveDoorLockLoggingCommandClass.java
public SerialMessage getEntry(int id) { logger.debug("NODE {}: Creating new message for application command LOGGING_RECORD_GET", this.getNode().getNodeId()); SerialMessage message = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write((byte) this.getNode().getNodeId()); outputData.write(3); outputData.write((byte) getCommandClass().getKey()); outputData.write((byte) LOGGING_RECORD_GET); outputData.write((byte) id); message.setMessagePayload(outputData.toByteArray()); return message; }
28. ZWaveBinarySensorCommandClass#getValueMessage()
Project: openhab2-addons
File: ZWaveBinarySensorCommandClass.java
File: ZWaveBinarySensorCommandClass.java
public SerialMessage getValueMessage(SensorType type) { if (getVersion() == 1) { logger.debug("NODE {}: Node doesn't support SENSOR_BINARY_GET with SensorType", getNode().getNodeId()); return null; } logger.debug("NODE {}: Creating new message for application command SENSOR_BINARY_GET for {}", getNode().getNodeId(), type); SerialMessage result = new SerialMessage(getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write(getNode().getNodeId()); outputData.write(3); outputData.write(getCommandClass().getKey()); outputData.write(SENSOR_BINARY_GET); outputData.write(type.getKey()); result.setMessagePayload(outputData.toByteArray()); return result; }
29. ZWaveBarrierOperatorCommandClass#setValueMessage()
Project: openhab2-addons
File: ZWaveBarrierOperatorCommandClass.java
File: ZWaveBarrierOperatorCommandClass.java
@Override public SerialMessage setValueMessage(int value) { logger.debug("NODE {}: Creating new message for application command BARRIER_OPERATOR_SET", getNode().getNodeId()); SerialMessage message = new SerialMessage(getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.SendData, SerialMessagePriority.Set); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write((byte) getNode().getNodeId()); outputData.write(3); outputData.write((byte) getCommandClass().getKey()); outputData.write(BARRIER_OPERATOR_SET); outputData.write(value > 0 ? 0xFF : 0x00); message.setMessagePayload(outputData.toByteArray()); return message; }
30. ZwaveAssociationGroupInfoCommandClass#getGroupNameMessage()
Project: openhab2-addons
File: ZwaveAssociationGroupInfoCommandClass.java
File: ZwaveAssociationGroupInfoCommandClass.java
/** * Gets a SerialMessage with the GROUP_NAME_GET command * * @return the serial message */ public SerialMessage getGroupNameMessage(int groupidx) { logger.debug("NODE {}: Creating new message for application command GROUP_NAME_GET for group {}", getNode().getNodeId(), groupidx); SerialMessage result = new SerialMessage(getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write(getNode().getNodeId()); outputData.write(3); outputData.write(getCommandClass().getKey()); outputData.write(GROUP_NAME_GET); outputData.write(groupidx); result.setMessagePayload(outputData.toByteArray()); return result; }
31. PngWriter#writeChunkIHDR()
Project: sanselan
File: PngWriter.java
File: PngWriter.java
private void writeChunkIHDR(OutputStream os, ImageHeader value) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); writeInt(baos, value.width); writeInt(baos, value.height); baos.write(0xff & value.bit_depth); baos.write(0xff & value.colorType); baos.write(0xff & value.compressionMethod); baos.write(0xff & value.filterMethod); baos.write(0xff & value.interlaceMethod); // Debug.debug("baos", baos.toByteArray()); writeChunk(os, IHDR_CHUNK_TYPE.toByteArray(), baos.toByteArray()); }
32. FTPClientTest#testUnparseableFiles()
Project: commons-net
File: FTPClientTest.java
File: FTPClientTest.java
public void testUnparseableFiles() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write("-rwxr-xr-x 2 root root 4096 Mar 2 15:13 zxbox".getBytes()); baos.write(new byte[] { '\r', '\n' }); baos.write("zrwxr-xr-x 2 root root 4096 Mar 2 15:13 zxbox".getBytes()); baos.write(new byte[] { '\r', '\n' }); FTPFileEntryParser parser = new UnixFTPEntryParser(); FTPClientConfig config = new FTPClientConfig(); FTPListParseEngine engine = new FTPListParseEngine(parser, config); config.setUnparseableEntries(false); // use default encoding engine.readServerList(new ByteArrayInputStream(baos.toByteArray()), null); FTPFile[] files = engine.getFiles(); assertEquals(1, files.length); config.setUnparseableEntries(true); engine = new FTPListParseEngine(parser, config); // use default encoding engine.readServerList(new ByteArrayInputStream(baos.toByteArray()), null); files = engine.getFiles(); assertEquals(2, files.length); }
33. PngWriter#writeChunkzTXt()
Project: commons-imaging
File: PngWriter.java
File: PngWriter.java
private void writeChunkzTXt(final OutputStream os, final PngText.Ztxt text) throws IOException, ImageWriteException { if (!isValidISO_8859_1(text.keyword)) { throw new ImageWriteException("Png zTXt chunk keyword is not ISO-8859-1: " + text.keyword); } if (!isValidISO_8859_1(text.text)) { throw new ImageWriteException("Png zTXt chunk text is not ISO-8859-1: " + text.text); } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // keyword baos.write(text.keyword.getBytes("ISO-8859-1")); baos.write(0); // compression method baos.write(PngConstants.COMPRESSION_DEFLATE_INFLATE); // text baos.write(deflate(text.text.getBytes("ISO-8859-1"))); writeChunk(os, ChunkType.zTXt, baos.toByteArray()); }
34. AbstractPDFStreamTestCase#testOutput()
Project: fop
File: AbstractPDFStreamTestCase.java
File: AbstractPDFStreamTestCase.java
/** * Tests output() - ensure that this object is correctly formatted to the output stream. * @throws IOException if an I/O error occurs */ @Test public void testOutput() throws IOException { // This differs from most other objects, if the object number = 0 an exception is thrown ByteArrayOutputStream outStream = new ByteArrayOutputStream(); abstractStream.setObjectNumber(1); ByteArrayOutputStream expectedStream = new ByteArrayOutputStream(); expectedStream.write(startStream.getBytes()); expectedStream.write(encodedBytes); expectedStream.write(endStream.getBytes()); assertEquals(expectedStream.size(), abstractStream.output(outStream)); assertEquals(expectedStream.toString(), outStream.toString()); }
35. BasicSerializationTest#testWriteString()
Project: gerrit
File: BasicSerializationTest.java
File: BasicSerializationTest.java
@Test public void testWriteString() throws IOException { ByteArrayOutputStream out; out = new ByteArrayOutputStream(); writeString(out, null); assertOutput(b(0), out); out = new ByteArrayOutputStream(); writeString(out, ""); assertOutput(b(0), out); out = new ByteArrayOutputStream(); writeString(out, "a"); assertOutput(b(1, 'a'), out); out = new ByteArrayOutputStream(); writeString(out, "coffee4"); assertOutput(b(7, 'c', 'o', 'f', 'f', 'e', 'e', '4'), out); }
36. BloomFilter#encode()
Project: ccnx
File: BloomFilter.java
File: BloomFilter.java
@Override public void encode(XMLEncoder encoder) throws ContentEncodingException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write((byte) _lgBits); baos.write((byte) _nHash); // "method" - must be 'A' for now baos.write('A'); // "reserved" - must be 0 for now baos.write(0); for (int i = 0; i < _seed.length; i++) baos.write((byte) _seed[i]); int size = usedBits(); for (int i = 0; i < size; i++) baos.write(_bloom[i]); encoder.writeElement(getElementLabel(), baos.toByteArray()); }
37. BinlogDumpCommandPacket#toBytes()
Project: canal
File: BinlogDumpCommandPacket.java
File: BinlogDumpCommandPacket.java
/** * <pre> * Bytes Name * ----- ---- * 1 command * n arg * -------------------------------------------------------- * Bytes Name * ----- ---- * 4 binlog position to start at (little endian) * 2 binlog flags (currently not used; always 0) * 4 server_id of the slave (little endian) * n binlog file name (optional) * * </pre> */ public byte[] toBytes() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); // 0. write command number out.write(getCommand()); // 1. write 4 bytes bin-log position to start at ByteHelper.writeUnsignedIntLittleEndian(binlogPosition, out); // 2. write 2 bytes bin-log flags int binlog_flags = 0; binlog_flags |= BINLOG_SEND_ANNOTATE_ROWS_EVENT; out.write(binlog_flags); out.write(0x00); // 3. write 4 bytes server id of the slave ByteHelper.writeUnsignedIntLittleEndian(this.slaveServerId, out); // 4. write bin-log file name if necessary if (StringUtils.isNotEmpty(this.binlogFileName)) { out.write(this.binlogFileName.getBytes()); } return out.toByteArray(); }
38. OldAndroidByteArrayOutputStreamTest#testByteArrayOutputStream()
Project: j2objc
File: OldAndroidByteArrayOutputStreamTest.java
File: OldAndroidByteArrayOutputStreamTest.java
public void testByteArrayOutputStream() throws Exception { String str = "AbCdEfGhIjKlMnOpQrStUvWxYz"; ByteArrayOutputStream a = new ByteArrayOutputStream(); ByteArrayOutputStream b = new ByteArrayOutputStream(10); a.write(str.getBytes(), 0, 26); a.write('X'); a.writeTo(b); assertEquals(27, a.size()); assertEquals("AbCdEfGhIjKlMnOpQrStUvWxYzX", a.toString()); assertEquals("AbCdEfGhIjKlMnOpQrStUvWxYzX", b.toString()); }
39. Tag#toByteArray()
Project: jdk7u-jdk
File: Tag.java
File: Tag.java
public byte[] toByteArray() { ByteArrayOutputStream os = new ByteArrayOutputStream(); os.write(length); os.write(tag); os.write(tagLen); if (time_offset != null) { os.write(time_offset.intValue()); } if (usec_offset != null) { os.write(usec_offset.intValue()); } return os.toByteArray(); }
40. MinimalPerfectHash#generate()
Project: ThriftyPaxos
File: MinimalPerfectHash.java
File: MinimalPerfectHash.java
/** * Generate the minimal perfect hash function data from the given set of * integers. * * @param set the data * @param hash the universal hash function * @return the hash function description */ public static <K> byte[] generate(Set<K> set, UniversalHash<K> hash) { ArrayList<K> list = new ArrayList<K>(); list.addAll(set); ByteArrayOutputStream out = new ByteArrayOutputStream(); int seed = RANDOM.nextInt(); out.write(seed >>> 24); out.write(seed >>> 16); out.write(seed >>> 8); out.write(seed); generate(list, hash, 0, seed, out); return compress(out.toByteArray()); }
41. SimpleAuthenticatorTest#shouldUseTinkerGraphForCredentialsStoreAndFail()
Project: tinkerpop
File: SimpleAuthenticatorTest.java
File: SimpleAuthenticatorTest.java
@Test(expected = AuthenticationException.class) public void shouldUseTinkerGraphForCredentialsStoreAndFail() throws Exception { final Map<String, Object> config = new HashMap<>(); config.put(SimpleAuthenticator.CONFIG_CREDENTIALS_DB, "conf/tinkergraph-empty.properties"); config.put(SimpleAuthenticator.CONFIG_CREDENTIALS_LOCATION, "data/credentials.kryo"); authenticator.setup(config); final Authenticator.SaslNegotiator negotiator = authenticator.newSaslNegotiator(); final ByteArrayOutputStream stream = new ByteArrayOutputStream(); final byte[] nul = new byte[] { 0 }; stream.write(nul); stream.write("stephen".getBytes()); stream.write(nul); stream.write("bad-password".getBytes()); negotiator.evaluateResponse(stream.toByteArray()); assertTrue(negotiator.isComplete()); negotiator.getAuthenticatedUser(); }
42. SimpleAuthenticatorTest#shouldUseTinkerGraphForCredentialsStoreAndSucceed()
Project: tinkerpop
File: SimpleAuthenticatorTest.java
File: SimpleAuthenticatorTest.java
@Test public void shouldUseTinkerGraphForCredentialsStoreAndSucceed() throws Exception { final Map<String, Object> config = new HashMap<>(); config.put(SimpleAuthenticator.CONFIG_CREDENTIALS_DB, "conf/tinkergraph-empty.properties"); config.put(SimpleAuthenticator.CONFIG_CREDENTIALS_LOCATION, "data/credentials.kryo"); authenticator.setup(config); final Authenticator.SaslNegotiator negotiator = authenticator.newSaslNegotiator(); final ByteArrayOutputStream stream = new ByteArrayOutputStream(); final byte[] nul = new byte[] { 0 }; stream.write(nul); stream.write("stephen".getBytes()); stream.write(nul); stream.write("password".getBytes()); negotiator.evaluateResponse(stream.toByteArray()); assertTrue(negotiator.isComplete()); assertEquals("stephen", negotiator.getAuthenticatedUser().getName()); }
43. Tag#toByteArray()
Project: openjdk
File: Tag.java
File: Tag.java
public byte[] toByteArray() { ByteArrayOutputStream os = new ByteArrayOutputStream(); os.write(length); os.write(tag); os.write(tagLen); if (time_offset != null) { os.write(time_offset.intValue()); } if (usec_offset != null) { os.write(usec_offset.intValue()); } return os.toByteArray(); }
44. write#test()
Project: pluotsorbet
File: write.java
File: write.java
public void test(TestHarness harness) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); byte[] ba = { (byte) 'B', (byte) 'C', (byte) 'D' }; String tststr = "ABCD"; baos.write('A'); harness.check(true, "write(int)"); baos.write(ba, 0, 3); harness.check(true, "write(buf, off, len)"); harness.check(baos.size(), 4, "size()"); String finalstr1 = baos.toString(); harness.check(finalstr1.equals(tststr), "toString()"); byte[] finalba = baos.toByteArray(); String finalstr2 = new String(finalba); harness.check(finalstr2.equals(tststr), "toByteArray()"); baos.reset(); harness.check(baos.size(), 0, "reset()"); }
45. ZWaveUserCodeCommandClass#getSupported()
Project: openhab2-addons
File: ZWaveUserCodeCommandClass.java
File: ZWaveUserCodeCommandClass.java
public SerialMessage getSupported() { logger.debug("NODE {}: Creating new message for application command USER_NUMBER_GET", this.getNode().getNodeId()); SerialMessage message = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write((byte) this.getNode().getNodeId()); outputData.write(2); outputData.write((byte) getCommandClass().getKey()); outputData.write((byte) USER_NUMBER_GET); message.setMessagePayload(outputData.toByteArray()); return message; }
46. ZWaveTimeParametersCommandClass#getValueMessage()
Project: openhab2-addons
File: ZWaveTimeParametersCommandClass.java
File: ZWaveTimeParametersCommandClass.java
/** * Gets a SerialMessage with the TIME_GET command * * @return the serial message. */ @Override public SerialMessage getValueMessage() { logger.debug("NODE {}: Creating new message for command TIME_GET", getNode().getNodeId()); SerialMessage result = new SerialMessage(getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write(getNode().getNodeId()); outputData.write(2); outputData.write(getCommandClass().getKey()); outputData.write(TIME_GET); result.setMessagePayload(outputData.toByteArray()); return result; }
47. ZWaveProtectionCommandClass#getValueMessage()
Project: openhab2-addons
File: ZWaveProtectionCommandClass.java
File: ZWaveProtectionCommandClass.java
/** * Gets a SerialMessage with the PROTECTION_GET command * * @return the serial message, or null if the supported command is not supported. */ @Override public SerialMessage getValueMessage() { logger.debug("NODE {}: Creating new message for command PROTECTION_GET", getNode().getNodeId()); SerialMessage result = new SerialMessage(getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write(getNode().getNodeId()); outputData.write(2); outputData.write(getCommandClass().getKey()); outputData.write(PROTECTION_GET); result.setMessagePayload(outputData.toByteArray()); return result; }
48. ZWaveProtectionCommandClass#getSupportedMessage()
Project: openhab2-addons
File: ZWaveProtectionCommandClass.java
File: ZWaveProtectionCommandClass.java
/** * Gets a SerialMessage with the PROTECTION_SUPPORTED_GET command * * @return the serial message, or null if the supported command is not supported. */ public SerialMessage getSupportedMessage() { if (getVersion() == 1) { logger.debug("NODE {}: PROTECTION_SUPPORTED_GET not supported for V1", getNode().getNodeId()); return null; } logger.debug("NODE {}: Creating new message for command PROTECTION_SUPPORTED_GET", getNode().getNodeId()); SerialMessage result = new SerialMessage(getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write(getNode().getNodeId()); outputData.write(2); outputData.write(getCommandClass().getKey()); outputData.write(PROTECTION_SUPPORTED_GET); result.setMessagePayload(outputData.toByteArray()); return result; }
49. ZWavePowerLevelCommandClass#getValueMessage()
Project: openhab2-addons
File: ZWavePowerLevelCommandClass.java
File: ZWavePowerLevelCommandClass.java
@Override public SerialMessage getValueMessage() { logger.debug("NODE {}: Creating new message for application command POWERLEVEL_GET", getNode().getNodeId()); SerialMessage message = new SerialMessage(getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write((byte) getNode().getNodeId()); outputData.write(2); outputData.write((byte) getCommandClass().getKey()); outputData.write((byte) POWERLEVEL_GET); message.setMessagePayload(outputData.toByteArray()); return message; }
50. ZWaveMeterTblMonitorCommandClass#getTableIDGet()
Project: openhab2-addons
File: ZWaveMeterTblMonitorCommandClass.java
File: ZWaveMeterTblMonitorCommandClass.java
/** * Gets a SerialMessage with the METER_TBL_TABLE_ID_GET command * * @return the serial message */ public SerialMessage getTableIDGet() { logger.debug("NODE {}: Creating new message for application command METER_TBL_TABLE_ID_GET", getNode().getNodeId()); SerialMessage message = new SerialMessage(getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write(this.getNode().getNodeId()); outputData.write(2); outputData.write(getCommandClass().getKey()); outputData.write(METER_TBL_TABLE_ID_GET); message.setMessagePayload(outputData.toByteArray()); return message; }
51. ZWaveMeterTblMonitorCommandClass#getCapabilityGet()
Project: openhab2-addons
File: ZWaveMeterTblMonitorCommandClass.java
File: ZWaveMeterTblMonitorCommandClass.java
/** * Gets a SerialMessage with the METER_TBL_TABLE_CAPABILITY_GET command * * @return the serial message */ public SerialMessage getCapabilityGet() { logger.debug("NODE {}: Creating new message for application command METER_TBL_TABLE_CAPABILITY_GET", getNode().getNodeId()); SerialMessage message = new SerialMessage(getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write(this.getNode().getNodeId()); outputData.write(2); outputData.write(getCommandClass().getKey()); outputData.write(METER_TBL_TABLE_CAPABILITY_GET); message.setMessagePayload(outputData.toByteArray()); return message; }
52. ZWaveMeterPulseCommandClass#getValueMessage()
Project: openhab2-addons
File: ZWaveMeterPulseCommandClass.java
File: ZWaveMeterPulseCommandClass.java
@Override public SerialMessage getValueMessage() { logger.debug("NODE {}: Creating new message for application command METER_PULSE_GET", getNode().getNodeId()); SerialMessage message = new SerialMessage(getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write((byte) getNode().getNodeId()); outputData.write(2); outputData.write((byte) getCommandClass().getKey()); outputData.write((byte) METER_PULSE_GET); message.setMessagePayload(outputData.toByteArray()); return message; }
53. ZWaveDoorLockLoggingCommandClass#getSupported()
Project: openhab2-addons
File: ZWaveDoorLockLoggingCommandClass.java
File: ZWaveDoorLockLoggingCommandClass.java
public SerialMessage getSupported() { logger.debug("NODE {}: Creating new message for application command LOGGING_SUPPORTED_GET", this.getNode().getNodeId()); SerialMessage message = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write((byte) this.getNode().getNodeId()); outputData.write(2); outputData.write((byte) getCommandClass().getKey()); outputData.write((byte) LOGGING_SUPPORTED_GET); message.setMessagePayload(outputData.toByteArray()); return message; }
54. ZWaveDoorLockCommandClass#getConfigMessage()
Project: openhab2-addons
File: ZWaveDoorLockCommandClass.java
File: ZWaveDoorLockCommandClass.java
public SerialMessage getConfigMessage() { logger.debug("NODE {}: Creating new message for application command DOORLOCK_CONFIG_GET", getNode().getNodeId()); SerialMessage message = new SerialMessage(getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write((byte) getNode().getNodeId()); outputData.write(2); outputData.write((byte) getCommandClass().getKey()); outputData.write((byte) DOOR_LOCK_CONFIG_GET); message.setMessagePayload(outputData.toByteArray()); return message; }
55. ZWaveClockCommandClass#getValueMessage()
Project: openhab2-addons
File: ZWaveClockCommandClass.java
File: ZWaveClockCommandClass.java
/** * Gets a SerialMessage with the CLOCK_GET command * * @return the serial message. */ @Override public SerialMessage getValueMessage() { logger.debug("NODE {}: Creating new message for command CLOCK_GET", getNode().getNodeId()); SerialMessage result = new SerialMessage(getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write(getNode().getNodeId()); outputData.write(2); outputData.write(getCommandClass().getKey()); outputData.write(CLOCK_GET); result.setMessagePayload(outputData.toByteArray()); return result; }
56. ZWaveBinarySensorCommandClass#getSupportedMessage()
Project: openhab2-addons
File: ZWaveBinarySensorCommandClass.java
File: ZWaveBinarySensorCommandClass.java
/** * Gets a SerialMessage with the SENSOR_BINARY_SUPPORTEDSENSOR_GET command * * @return the serial message, or null if the supported command is not supported. */ public SerialMessage getSupportedMessage() { if (getVersion() == 1) { logger.debug("NODE {}: SENSOR_BINARY_SUPPORTEDSENSOR_GET not supported for V1", getNode().getNodeId()); return null; } logger.debug("NODE {}: Creating new message for command SENSOR_BINARY_SUPPORTEDSENSOR_GET", getNode().getNodeId()); SerialMessage result = new SerialMessage(getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write(getNode().getNodeId()); outputData.write(2); outputData.write(getCommandClass().getKey()); outputData.write(SENSOR_BINARY_SUPPORTEDSENSOR_GET); result.setMessagePayload(outputData.toByteArray()); return result; }
57. ZWaveBinarySensorCommandClass#getValueMessage()
Project: openhab2-addons
File: ZWaveBinarySensorCommandClass.java
File: ZWaveBinarySensorCommandClass.java
/** * Gets a SerialMessage with the SENSOR_BINARY_GET command * * @return the serial message */ @Override public SerialMessage getValueMessage() { if (isGetSupported == false) { logger.debug("NODE {}: Node doesn't support get requests", getNode().getNodeId()); return null; } logger.debug("NODE {}: Creating new message for application command SENSOR_BINARY_GET", getNode().getNodeId()); SerialMessage result = new SerialMessage(getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write(getNode().getNodeId()); outputData.write(2); outputData.write(getCommandClass().getKey()); outputData.write(SENSOR_BINARY_GET); result.setMessagePayload(outputData.toByteArray()); return result; }
58. ZWaveBarrierOperatorCommandClass#getValueMessage()
Project: openhab2-addons
File: ZWaveBarrierOperatorCommandClass.java
File: ZWaveBarrierOperatorCommandClass.java
@Override public SerialMessage getValueMessage() { logger.debug("NODE {}: Creating new message for command BARRIER_OPERATOR_GET", getNode().getNodeId()); SerialMessage message = new SerialMessage(getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write((byte) getNode().getNodeId()); outputData.write(2); outputData.write((byte) getCommandClass().getKey()); outputData.write(BARRIER_OPERATOR_GET); message.setMessagePayload(outputData.toByteArray()); return message; }
59. ZWaveClockCommandClass#getValueMessage()
Project: openhab
File: ZWaveClockCommandClass.java
File: ZWaveClockCommandClass.java
/** * Gets a SerialMessage with the CLOCK_GET command * * @return the serial message. */ @Override public SerialMessage getValueMessage() { logger.debug("NODE {}: Creating new message for command CLOCK_GET", getNode().getNodeId()); SerialMessage result = new SerialMessage(getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write(getNode().getNodeId()); outputData.write(2); outputData.write(getCommandClass().getKey()); outputData.write(CLOCK_GET); result.setMessagePayload(outputData.toByteArray()); return result; }
60. WindowsPreferences#windowsAbsolutePath()
Project: jdk7u-jdk
File: WindowsPreferences.java
File: WindowsPreferences.java
/** * Returns Windows absolute path of the current node as a byte array. * Java "/" separator is transformed into Windows "\". * @see Preferences#absolutePath() */ private byte[] windowsAbsolutePath() { ByteArrayOutputStream bstream = new ByteArrayOutputStream(); bstream.write(WINDOWS_ROOT_PATH, 0, WINDOWS_ROOT_PATH.length - 1); StringTokenizer tokenizer = new StringTokenizer(absolutePath(), "/"); while (tokenizer.hasMoreTokens()) { bstream.write((byte) '\\'); String nextName = tokenizer.nextToken(); byte[] windowsNextName = toWindowsName(nextName); bstream.write(windowsNextName, 0, windowsNextName.length - 1); } bstream.write(0); return bstream.toByteArray(); }
61. XStream2EncodingTest#toXMLUnspecifiedEncoding()
Project: Jenkins2
File: XStream2EncodingTest.java
File: XStream2EncodingTest.java
@SuppressWarnings("deprecation") @Test public void toXMLUnspecifiedEncoding() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); XStream2 xs = new XStream2(); String msg = "k chyb?"; xs.toXML(new Thing(msg), baos); byte[] ambiguousXml = baos.toByteArray(); Thing t = (Thing) xs.fromXML(new ByteArrayInputStream(ambiguousXml)); assertThat(t.field, not(msg)); ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); baos2.write("<?xml version='1.0' encoding='UTF-8'?>\n".getBytes("UTF-8")); baos2.write(ambiguousXml); t = (Thing) xs.fromXML(new ByteArrayInputStream(ambiguousXml)); assertThat(t.field, not(msg)); }
62. XStream2EncodingTest#toXMLUnspecifiedEncoding()
Project: hudson
File: XStream2EncodingTest.java
File: XStream2EncodingTest.java
@SuppressWarnings("deprecation") @Test public void toXMLUnspecifiedEncoding() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); XStream2 xs = new XStream2(); String msg = "k chyb?"; xs.toXML(new Thing(msg), baos); byte[] ambiguousXml = baos.toByteArray(); Thing t = (Thing) xs.fromXML(new ByteArrayInputStream(ambiguousXml)); assertThat(t.field, not(msg)); ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); baos2.write("<?xml version='1.0' encoding='UTF-8'?>\n".getBytes("UTF-8")); baos2.write(ambiguousXml); t = (Thing) xs.fromXML(new ByteArrayInputStream(ambiguousXml)); assertThat(t.field, not(msg)); }
63. WinkTransferEncodingTest#testSendSmallGzipContentEncoded()
Project: wink
File: WinkTransferEncodingTest.java
File: WinkTransferEncodingTest.java
/** * Tests sending in small bits of chunked content. * * @throws HttpException * @throws IOException */ public void testSendSmallGzipContentEncoded() throws HttpException, IOException { ByteArrayOutputStream originalContent = new ByteArrayOutputStream(); originalContent.write("Hello world".getBytes("UTF-8")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); originalContent.writeTo(baos); byte[] content = baos.toByteArray(); ClientResponse response = client.resource(BASE_URI + "/chunkedbook").accept(MediaType.TEXT_PLAIN_TYPE).contentType("text/plain; charset=utf-8").post(content); assertEquals(200, response.getStatusCode()); String responseBody = response.getEntity(String.class); assertEquals("Hello world", responseBody); }
64. TransferEncodingTest#testSendSmallGzipContentEncoded()
Project: wink
File: TransferEncodingTest.java
File: TransferEncodingTest.java
/** * Tests sending in small bits of chunked content. * * @throws HttpException * @throws IOException */ public void testSendSmallGzipContentEncoded() throws HttpException, IOException { PostMethod postMethod = new PostMethod(BASE_URI + "/chunkedbook"); postMethod.setContentChunked(true); postMethod.addRequestHeader("Accept", "text/plain"); ByteArrayOutputStream originalContent = new ByteArrayOutputStream(); originalContent.write("Hello world".getBytes("UTF-8")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); originalContent.writeTo(baos); byte[] content = baos.toByteArray(); postMethod.setRequestEntity(new ByteArrayRequestEntity(content, "text/plain; charset=utf-8")); try { int result = client.executeMethod(postMethod); assertEquals(200, result); String response = postMethod.getResponseBodyAsString(); assertEquals("Hello world", response); } finally { postMethod.releaseConnection(); } }
65. WinkContentEncodingTest#testSendSmallGzipContentEncoded()
Project: wink
File: WinkContentEncodingTest.java
File: WinkContentEncodingTest.java
/** * Tests sending in small bits of gzip encoded content. * * @throws HttpException * @throws IOException */ public void testSendSmallGzipContentEncoded() throws HttpException, IOException { ByteArrayOutputStream originalContent = new ByteArrayOutputStream(); originalContent.write("Hello world".getBytes("UTF-8")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ChunkedOutputStream chunkedOut = new ChunkedOutputStream(baos); GZIPOutputStream gzipOut = new GZIPOutputStream(chunkedOut); originalContent.writeTo(gzipOut); gzipOut.finish(); chunkedOut.finish(); byte[] content = baos.toByteArray(); ClientResponse response = client.resource(BASE_URI + "/bigbook").accept(MediaType.TEXT_PLAIN).header("Transfer-Encoding", "chunked").header("Content-Encoding", "gzip").contentType("text/plain; charset=utf-8").post(content); assertEquals(200, response.getStatusCode()); String responseBody = response.getEntity(String.class); assertEquals("Hello world" + "helloworld", responseBody); }
66. WinkApacheContentEncodingTest#testSendSmallGzipContentEncoded()
Project: wink
File: WinkApacheContentEncodingTest.java
File: WinkApacheContentEncodingTest.java
/** * Tests sending in small bits of gzip encoded content. * * @throws HttpException * @throws IOException */ @Override public void testSendSmallGzipContentEncoded() throws HttpException, IOException { ByteArrayOutputStream originalContent = new ByteArrayOutputStream(); originalContent.write("Hello world".getBytes("UTF-8")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gzipOut = new GZIPOutputStream(baos); originalContent.writeTo(gzipOut); gzipOut.finish(); byte[] content = baos.toByteArray(); ClientResponse response = client.resource(BASE_URI + "/bigbook").accept(MediaType.TEXT_PLAIN).header("Content-Encoding", "gzip").contentType("text/plain; charset=utf-8").post(content); assertEquals(200, response.getStatusCode()); String responseBody = response.getEntity(String.class); assertEquals("Hello world" + "helloworld", responseBody); }
67. UriRetriever#pullData()
Project: UniversalMediaServer
File: UriRetriever.java
File: UriRetriever.java
private static byte[] pullData(String uri, HttpMethod method, UriRetrieverCallback callback, int totalBytes) throws IOException { int bytesWritten = 0; InputStream input = method.getResponseBodyAsStream(); ByteArrayOutputStream output = new ByteArrayOutputStream(totalBytes); byte[] buffer = new byte[BUFFER_SIZE]; int count = -1; while ((count = input.read(buffer)) != -1) { output.write(buffer, 0, count); bytesWritten += count; invokeCallback(uri, callback, totalBytes, bytesWritten); } output.flush(); output.close(); return output.toByteArray(); }
68. ALPNHackClientHelloExplorer#generateAlpnExtension()
Project: undertow
File: ALPNHackClientHelloExplorer.java
File: ALPNHackClientHelloExplorer.java
private static byte[] generateAlpnExtension(List<String> alpnProtocols) { ByteArrayOutputStream alpnBits = new ByteArrayOutputStream(); alpnBits.write(0); //ALPN type alpnBits.write(16); int length = 2; for (String p : alpnProtocols) { length++; length += p.length(); } writeInt16(alpnBits, length); length -= 2; writeInt16(alpnBits, length); for (String p : alpnProtocols) { alpnBits.write(p.length() & 0xFF); for (int i = 0; i < p.length(); ++i) { alpnBits.write(p.charAt(i) & 0xFF); } } return alpnBits.toByteArray(); }
69. PngWriter#writeChunktEXt()
Project: sanselan
File: PngWriter.java
File: PngWriter.java
private void writeChunktEXt(OutputStream os, PngText.tEXt text) throws IOException, ImageWriteException { if (!UnicodeUtils.isValidISO_8859_1(text.keyword)) throw new ImageWriteException("Png tEXt chunk keyword is not ISO-8859-1: " + text.keyword); if (!UnicodeUtils.isValidISO_8859_1(text.text)) throw new ImageWriteException("Png tEXt chunk text is not ISO-8859-1: " + text.text); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // keyword baos.write(text.keyword.getBytes("ISO-8859-1")); baos.write(0); // text baos.write(text.text.getBytes("ISO-8859-1")); writeChunk(os, tEXt_CHUNK_TYPE.toByteArray(), baos.toByteArray()); }
70. RegAssertionBuilder#getAssertions()
Project: UAF
File: RegAssertionBuilder.java
File: RegAssertionBuilder.java
public String getAssertions(RegistrationResponse response) throws Exception { ByteArrayOutputStream byteout = new ByteArrayOutputStream(); byte[] value = null; int length = 0; byteout.write(encodeInt(TagsEnum.TAG_UAFV1_REG_ASSERTION.id)); value = getRegAssertion(response); length = value.length; byteout.write(encodeInt(length)); byteout.write(value); String ret = Base64.encodeToString(byteout.toByteArray(), Base64.URL_SAFE); logger.info(" : assertion : " + ret); Tags tags = parser.parse(ret); String AAID = new String(tags.getTags().get(TagsEnum.TAG_AAID.id).value); String KeyID = new String(tags.getTags().get(TagsEnum.TAG_KEYID.id).value); return ret; }
71. AuthAssertionBuilder#getAssertions()
Project: UAF
File: AuthAssertionBuilder.java
File: AuthAssertionBuilder.java
public String getAssertions(AuthenticationResponse response) throws Exception { ByteArrayOutputStream byteout = new ByteArrayOutputStream(); byte[] value = null; int length = 0; byteout.write(encodeInt(TagsEnum.TAG_UAFV1_AUTH_ASSERTION.id)); value = getAuthAssertion(response); length = value.length; byteout.write(encodeInt(length)); byteout.write(value); String ret = Base64.encodeToString(byteout.toByteArray(), Base64.NO_PADDING); logger.info(" : assertion : " + ret); return ret; }
72. RegAssertionBuilder#getAssertions()
Project: UAF
File: RegAssertionBuilder.java
File: RegAssertionBuilder.java
public String getAssertions() throws Exception { ByteArrayOutputStream byteout = new ByteArrayOutputStream(); byte[] value = null; int length = 0; byteout.write(encodeInt(TagsEnum.TAG_UAFV1_REG_ASSERTION.id)); value = getRegAssertion(); length = value.length; byteout.write(encodeInt(length)); byteout.write(value); String ret = Base64.encodeBase64String(byteout.toByteArray()); logger.info(" : assertion : " + ret); return ret; }
73. AuthAssertionBuilder#getAssertions()
Project: UAF
File: AuthAssertionBuilder.java
File: AuthAssertionBuilder.java
public String getAssertions() throws Exception { ByteArrayOutputStream byteout = new ByteArrayOutputStream(); byte[] value = null; int length = 0; byteout.write(encodeInt(TagsEnum.TAG_UAFV1_AUTH_ASSERTION.id)); value = getAuthAssertion(); length = value.length; byteout.write(encodeInt(length)); byteout.write(value); String ret = Base64.encodeBase64URLSafeString(byteout.toByteArray()); logger.info(" : assertion : " + ret); return ret; }
74. KeyCodec#getKeyAsRawBytes()
Project: UAF
File: KeyCodec.java
File: KeyCodec.java
@SuppressWarnings("deprecation") public static byte[] getKeyAsRawBytes(org.bouncycastle.jce.interfaces.ECPublicKey pub) throws IOException { byte[] raw; ByteArrayOutputStream bos = new ByteArrayOutputStream(65); bos.write(0x04); bos.write(asUnsignedByteArray(pub.getQ().getX().toBigInteger())); bos.write(asUnsignedByteArray(pub.getQ().getY().toBigInteger())); raw = bos.toByteArray(); logger.info("Raw key length:" + raw.length); return raw; }
75. AssignReturnRouteMessageClass#doRequest()
Project: openhab2-addons
File: AssignReturnRouteMessageClass.java
File: AssignReturnRouteMessageClass.java
public SerialMessage doRequest(int nodeId, int destinationId, int callbackId) { logger.debug("NODE {}: Assigning return route to node {}", nodeId, destinationId); // Queue the request SerialMessage newMessage = new SerialMessage(SerialMessageClass.AssignReturnRoute, SerialMessageType.Request, SerialMessageClass.AssignReturnRoute, SerialMessagePriority.High); ByteArrayOutputStream outputData = new ByteArrayOutputStream(); outputData.write(nodeId); outputData.write(destinationId); outputData.write(callbackId); newMessage.setMessagePayload(outputData.toByteArray()); return newMessage; }
76. UriRetriever#pullData()
Project: ps3mediaserver
File: UriRetriever.java
File: UriRetriever.java
private static byte[] pullData(String uri, HttpMethod method, UriRetrieverCallback callback, int totalBytes) throws IOException { int bytesWritten = 0; InputStream input = method.getResponseBodyAsStream(); ByteArrayOutputStream output = new ByteArrayOutputStream(totalBytes); byte[] buffer = new byte[BUFFER_SIZE]; int count = -1; while ((count = input.read(buffer)) != -1) { output.write(buffer, 0, count); bytesWritten += count; invokeCallback(uri, callback, totalBytes, bytesWritten); } output.flush(); output.close(); return output.toByteArray(); }
77. BaseFileUtils#readInputStream()
Project: orz
File: BaseFileUtils.java
File: BaseFileUtils.java
public static byte[] readInputStream(InputStream is) throws IOException { byte[] buffer = new byte[1024]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len; while ((len = is.read(buffer)) != -1) { baos.write(buffer, 0, len); } baos.flush(); baos.close(); is.close(); return baos.toByteArray(); }
78. JsonSerializerTest#testMessage()
Project: orbit
File: JsonSerializerTest.java
File: JsonSerializerTest.java
@Test public void testMessage() throws Exception { Message message = new Message(); JsonMessageSerializer jsonMessageSerializer = new JsonMessageSerializer(); ByteArrayOutputStream out = new ByteArrayOutputStream(); out.reset(); message.setPayload(Arrays.asList(1, 2, 3)); jsonMessageSerializer.serializeMessage(null, out, message); System.out.println(new String(out.toByteArray())); out.reset(); message.setPayload(new Object[] { 1, 2, 3 }); jsonMessageSerializer.serializeMessage(null, out, message); System.out.println(new String(out.toByteArray())); out.reset(); message.setPayload(new ArrayList(Arrays.asList(new Object[] { 1, 2, 3 }))); jsonMessageSerializer.serializeMessage(null, out, message); System.out.println(new String(out.toByteArray())); }
79. TokenizerModelTest#testSentenceModel()
Project: opennlp
File: TokenizerModelTest.java
File: TokenizerModelTest.java
@Test public void testSentenceModel() throws IOException, InvalidFormatException { TokenizerModel model = TokenizerTestUtil.createSimpleMaxentTokenModel(); ByteArrayOutputStream arrayOut = new ByteArrayOutputStream(); model.serialize(arrayOut); arrayOut.close(); model = new TokenizerModel(new ByteArrayInputStream(arrayOut.toByteArray())); // TODO: check that both maxent models are equal // Also test serialization after building model from an inputstream arrayOut = new ByteArrayOutputStream(); model.serialize(arrayOut); arrayOut.close(); new TokenizerModel(new ByteArrayInputStream(arrayOut.toByteArray())); // TODO: check that both maxent models are equal }
80. AppearanceGeneratorHelper#createAppearanceContent()
Project: PdfBox-Android
File: AppearanceGeneratorHelper.java
File: AppearanceGeneratorHelper.java
/** * Create new content. */ private void createAppearanceContent(List<Object> tokens, PDAnnotationWidget widget, PDFont pdFont, PDAppearanceStream appearanceStream) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); // BJL 9/25/2004 Must prepend existing stream // because it might have operators to draw things like // rectangles and such ContentStreamWriter writer = new ContentStreamWriter(output); writer.writeTokens(tokens); output.write("/Tx BMC\n".getBytes("ISO-8859-1")); PDRectangle boundingBox = resolveBoundingBox(widget, appearanceStream); insertGeneratedAppearance(boundingBox, output, pdFont, tokens); output.write("EMC".getBytes("ISO-8859-1")); output.close(); writeToStream(output.toByteArray(), appearanceStream); }
81. WindowsPreferences#windowsAbsolutePath()
Project: openjdk
File: WindowsPreferences.java
File: WindowsPreferences.java
/** * Returns Windows absolute path of the current node as a byte array. * Java "/" separator is transformed into Windows "\". * @see Preferences#absolutePath() */ private byte[] windowsAbsolutePath() { ByteArrayOutputStream bstream = new ByteArrayOutputStream(); bstream.write(WINDOWS_ROOT_PATH, 0, WINDOWS_ROOT_PATH.length - 1); StringTokenizer tokenizer = new StringTokenizer(absolutePath(), "/"); while (tokenizer.hasMoreTokens()) { bstream.write((byte) '\\'); String nextName = tokenizer.nextToken(); byte[] windowsNextName = toWindowsName(nextName); bstream.write(windowsNextName, 0, windowsNextName.length - 1); } bstream.write(0); return bstream.toByteArray(); }
82. SMIMETestUtil#verifyMessageBytes()
Project: bc-java
File: SMIMETestUtil.java
File: SMIMETestUtil.java
public static void verifyMessageBytes(MimeMessage a, MimeBodyPart b) throws IOException, MessagingException { ByteArrayOutputStream _baos = new ByteArrayOutputStream(); a.writeTo(_baos); _baos.close(); byte[] _msgBytes = _baos.toByteArray(); _baos = new ByteArrayOutputStream(); b.writeTo(_baos); _baos.close(); byte[] _resBytes = _baos.toByteArray(); TestCase.assertEquals(true, Arrays.areEqual(_msgBytes, _resBytes)); }
83. SMIMETestUtil#verifyMessageBytes()
Project: bc-java
File: SMIMETestUtil.java
File: SMIMETestUtil.java
public static void verifyMessageBytes(MimeBodyPart a, MimeBodyPart b) throws IOException, MessagingException { ByteArrayOutputStream _baos = new ByteArrayOutputStream(); a.writeTo(_baos); _baos.close(); byte[] _msgBytes = _baos.toByteArray(); _baos = new ByteArrayOutputStream(); b.writeTo(_baos); _baos.close(); byte[] _resBytes = _baos.toByteArray(); TestCase.assertEquals(true, Arrays.areEqual(_msgBytes, _resBytes)); }
84. SMIMEMiscTest#verifyMessageBytes()
Project: bc-java
File: SMIMEMiscTest.java
File: SMIMEMiscTest.java
private void verifyMessageBytes(MimeBodyPart a, MimeBodyPart b) throws Exception { ByteArrayOutputStream bOut1 = new ByteArrayOutputStream(); a.writeTo(bOut1); bOut1.close(); ByteArrayOutputStream bOut2 = new ByteArrayOutputStream(); b.writeTo(bOut2); bOut2.close(); assertEquals(true, Arrays.equals(bOut1.toByteArray(), bOut2.toByteArray())); }
85. NewSMIMESignedTest#verifyMessageBytes()
Project: bc-java
File: NewSMIMESignedTest.java
File: NewSMIMESignedTest.java
private void verifyMessageBytes(MimeBodyPart a, MimeBodyPart b) throws Exception { ByteArrayOutputStream bOut1 = new ByteArrayOutputStream(); a.writeTo(bOut1); bOut1.close(); ByteArrayOutputStream bOut2 = new ByteArrayOutputStream(); b.writeTo(bOut2); bOut2.close(); assertEquals(true, Arrays.equals(bOut1.toByteArray(), bOut2.toByteArray())); }
86. CompressorStreamFactoryRoundtripTest#testCompressorStreamFactoryRoundtrip()
Project: commons-compress
File: CompressorStreamFactoryRoundtripTest.java
File: CompressorStreamFactoryRoundtripTest.java
@Test public void testCompressorStreamFactoryRoundtrip() throws Exception { final CompressorStreamFactory factory = new CompressorStreamFactory(); final ByteArrayOutputStream compressedOs = new ByteArrayOutputStream(); final CompressorOutputStream compressorOutputStream = factory.createCompressorOutputStream(compressorName, compressedOs); final String fixture = "The quick brown fox jumps over the lazy dog"; compressorOutputStream.write(fixture.getBytes("UTF-8")); compressorOutputStream.flush(); compressorOutputStream.close(); final ByteArrayInputStream is = new ByteArrayInputStream(compressedOs.toByteArray()); final CompressorInputStream compressorInputStream = factory.createCompressorInputStream(compressorName, is); final ByteArrayOutputStream decompressedOs = new ByteArrayOutputStream(); IOUtils.copy(compressorInputStream, decompressedOs); compressorInputStream.close(); decompressedOs.flush(); decompressedOs.close(); Assert.assertEquals(fixture, decompressedOs.toString("UTF-8")); }
87. ImageProcessorTest#testRotateImage360()
Project: clerezza
File: ImageProcessorTest.java
File: ImageProcessorTest.java
/** * Tests if a copy of an image which was rotated 360 degrees is the same * as the original image */ @Test public void testRotateImage360() throws IOException { BufferedImage tempImg = processor.rotate(bimg, 360); Assert.assertTrue(bimg.getWidth() == tempImg.getWidth()); Assert.assertTrue(bimg.getHeight() == tempImg.getHeight()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream tempBaos = new ByteArrayOutputStream(); ImageIO.write(bimg, "png", baos); ImageIO.write(tempImg, "png", tempBaos); byte[] bytesOut = baos.toByteArray(); baos.flush(); byte[] tempBytesOut = tempBaos.toByteArray(); tempBaos.flush(); Assert.assertArrayEquals(bytesOut, tempBytesOut); }
88. BaseHandler#StreamToBytes()
Project: BepHttpUtils
File: BaseHandler.java
File: BaseHandler.java
protected byte[] StreamToBytes(InputStream is) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] bytesBuffer = new byte[2048]; int lenRead; while ((lenRead = is.read(bytesBuffer, 0, bytesBuffer.length)) != -1) { bos.write(bytesBuffer, 0, lenRead); } bos.flush(); bos.close(); return bos.toByteArray(); }
89. DownloadController#zipFiles()
Project: cello
File: DownloadController.java
File: DownloadController.java
/** * Compress the given directory with all its files. */ private byte[] zipFiles(File directory, String[] files) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); //byte bytes[] = new byte[2048]; addFolderToZip("", directory.getPath(), zos); zos.flush(); baos.flush(); zos.close(); baos.close(); return baos.toByteArray(); }
90. TestLogStreamer#testStreamerFullLen()
Project: datacollector
File: TestLogStreamer.java
File: TestLogStreamer.java
@Test public void testStreamerFullLen() throws Exception { LogStreamer streamer = new LogStreamer(LOG.getAbsolutePath(), LOG.length(), 6); ByteArrayOutputStream baos = new ByteArrayOutputStream(); streamer.stream(baos); baos.close(); Assert.assertEquals(LOG.length() - 6, streamer.getNewEndingOffset()); Assert.assertEquals("9:ABC\n", baos.toString()); streamer = new LogStreamer(LOG.getAbsolutePath(), streamer.getNewEndingOffset(), 6); baos = new ByteArrayOutputStream(); streamer.stream(baos); baos.close(); Assert.assertEquals(LOG.length() - 6 - 6, streamer.getNewEndingOffset()); Assert.assertEquals("8:ABC\n", baos.toString()); }
91. BasicSerializationTest#testWriteVarInt32()
Project: gerrit
File: BasicSerializationTest.java
File: BasicSerializationTest.java
@Test public void testWriteVarInt32() throws IOException { ByteArrayOutputStream out; out = new ByteArrayOutputStream(); writeVarInt32(out, 0); assertOutput(b(0), out); out = new ByteArrayOutputStream(); writeVarInt32(out, 3); assertOutput(b(3), out); out = new ByteArrayOutputStream(); writeVarInt32(out, 0xff); assertOutput(b(0x80 | 0x7f, 0x01), out); }
92. PubkeyListActivity#readRaw()
Project: connectbot
File: PubkeyListActivity.java
File: PubkeyListActivity.java
/** * Read given file into memory as <code>byte[]</code>. */ protected static byte[] readRaw(File file) throws Exception { InputStream is = new FileInputStream(file); ByteArrayOutputStream os = new ByteArrayOutputStream(); int bytesRead; byte[] buffer = new byte[1024]; while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } os.flush(); os.close(); is.close(); return os.toByteArray(); }
93. ExceptionUtilsTest#testPrintRootCauseStackTrace_ThrowableStream()
Project: commons-lang
File: ExceptionUtilsTest.java
File: ExceptionUtilsTest.java
@Test public void testPrintRootCauseStackTrace_ThrowableStream() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(1024); ExceptionUtils.printRootCauseStackTrace(null, (PrintStream) null); ExceptionUtils.printRootCauseStackTrace(null, new PrintStream(out)); assertEquals(0, out.toString().length()); out = new ByteArrayOutputStream(1024); try { ExceptionUtils.printRootCauseStackTrace(withCause, (PrintStream) null); fail(); } catch (final IllegalArgumentException ex) { } out = new ByteArrayOutputStream(1024); final Throwable cause = createExceptionWithCause(); ExceptionUtils.printRootCauseStackTrace(cause, new PrintStream(out)); String stackTrace = out.toString(); assertTrue(stackTrace.indexOf(ExceptionUtils.WRAPPED_MARKER) != -1); out = new ByteArrayOutputStream(1024); ExceptionUtils.printRootCauseStackTrace(withoutCause, new PrintStream(out)); stackTrace = out.toString(); assertTrue(stackTrace.indexOf(ExceptionUtils.WRAPPED_MARKER) == -1); }
94. PngWriter#writeChunktEXt()
Project: commons-imaging
File: PngWriter.java
File: PngWriter.java
private void writeChunktEXt(final OutputStream os, final PngText.Text text) throws IOException, ImageWriteException { if (!isValidISO_8859_1(text.keyword)) { throw new ImageWriteException("Png tEXt chunk keyword is not ISO-8859-1: " + text.keyword); } if (!isValidISO_8859_1(text.text)) { throw new ImageWriteException("Png tEXt chunk text is not ISO-8859-1: " + text.text); } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // keyword baos.write(text.keyword.getBytes("ISO-8859-1")); baos.write(0); // text baos.write(text.text.getBytes("ISO-8859-1")); writeChunk(os, ChunkType.tEXt, baos.toByteArray()); }
95. TestCsv#testPseudoBom()
Project: ThriftyPaxos
File: TestCsv.java
File: TestCsv.java
private void testPseudoBom() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); out.write(StringUtils.convertHexToBytes("ef" + "bb" + "bf")); out.write("\"ID\", \"NAME\"\n1, Hello".getBytes("UTF-8")); byte[] buff = out.toByteArray(); Reader r = new InputStreamReader(new ByteArrayInputStream(buff), "UTF-8"); ResultSet rs = new Csv().read(r, null); assertEquals("ID", rs.getMetaData().getColumnLabel(1)); assertEquals("NAME", rs.getMetaData().getColumnLabel(2)); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals("Hello", rs.getString(2)); assertFalse(rs.next()); }
96. TestHistoryEventsProtoConversion#testSummaryProtoConversion()
Project: tez
File: TestHistoryEventsProtoConversion.java
File: TestHistoryEventsProtoConversion.java
private HistoryEvent testSummaryProtoConversion(HistoryEvent historyEvent) throws IOException, TezException { SummaryEvent event = (SummaryEvent) historyEvent; ByteArrayOutputStream os = new ByteArrayOutputStream(); HistoryEvent deserializedEvent = null; event.toSummaryProtoStream(os); os.flush(); os.close(); LOG.info("Serialized event to byte array" + ", eventType=" + historyEvent.getEventType() + ", bufLen=" + os.toByteArray().length); SummaryEventProto summaryEventProto = SummaryEventProto.parseDelimitedFrom(new ByteArrayInputStream(os.toByteArray())); deserializedEvent = ReflectionUtils.createClazzInstance(event.getClass().getName()); ((SummaryEvent) deserializedEvent).fromSummaryProtoStream(summaryEventProto); return deserializedEvent; }
97. TestHistoryEventsProtoConversion#testProtoConversion()
Project: tez
File: TestHistoryEventsProtoConversion.java
File: TestHistoryEventsProtoConversion.java
private HistoryEvent testProtoConversion(HistoryEvent event) throws IOException, TezException { ByteArrayOutputStream os = new ByteArrayOutputStream(); HistoryEvent deserializedEvent = null; event.toProtoStream(os); os.flush(); os.close(); deserializedEvent = ReflectionUtils.createClazzInstance(event.getClass().getName()); LOG.info("Serialized event to byte array" + ", eventType=" + event.getEventType() + ", bufLen=" + os.toByteArray().length); deserializedEvent.fromProtoStream(new ByteArrayInputStream(os.toByteArray())); return deserializedEvent; }
98. IntegrationTests#readContent()
Project: tapestry5
File: IntegrationTests.java
File: IntegrationTests.java
private byte[] readContent(URL url) throws Exception { InputStream is = new BufferedInputStream(url.openStream()); ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] buffer = new byte[10000]; while (true) { int length = is.read(buffer); if (length < 0) break; os.write(buffer, 0, length); } os.close(); is.close(); return os.toByteArray(); }
99. AssetTests#readContent()
Project: tapestry-5
File: AssetTests.java
File: AssetTests.java
private byte[] readContent(URL url) throws Exception { InputStream is = new BufferedInputStream(url.openStream()); ByteArrayOutputStream os = new ByteArrayOutputStream(); TapestryInternalUtils.copy(is, os); os.close(); is.close(); return os.toByteArray(); }
100. SAISTest#setUp()
Project: succinct
File: SAISTest.java
File: SAISTest.java
/** * Set up test. * * @throws Exception */ public void setUp() throws Exception { super.setUp(); File inputFile = new File(testFileRaw); byte[] fileData = new byte[(int) inputFile.length()]; DataInputStream dis = new DataInputStream(new FileInputStream(inputFile)); dis.readFully(fileData); ByteArrayOutputStream out = new ByteArrayOutputStream(fileData.length + 1); out.write(fileData); out.write(0); data = out.toByteArray(); }