java.io.ByteArrayOutputStream

Here are the examples of the java api class java.io.ByteArrayOutputStream taken from open source projects.

1. EmulatorControl#setPMState()

Project: JPC
Source File: EmulatorControl.java
View license
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
Source File: EmulatorControl.java
View license
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
Source File: EmulatorControl.java
View license
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
Source File: PCLSoftFontManager.java
View license
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()

View license
/**
     * 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. RFC6637Utils#createUserKeyingMaterial()

Project: bc-java
Source File: RFC6637Utils.java
View license
// 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();
}

7. Account#toBytes()

Project: scouter
Source File: Account.java
View license
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();
}

8. PngWriter#writeChunkXmpiTXt()

Project: sanselan
Source File: PngWriter.java
View license
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
Source File: PngWriter.java
View license
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()

View license
/**
     * 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. AuthAssertionBuilder#getAuthAssertion()

Project: UAF
Source File: AuthAssertionBuilder.java
View license
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();
}

12. RegAssertionBuilder#getRegAssertion()

Project: UAF
Source File: RegAssertionBuilder.java
View license
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();
}

13. AuthAssertionBuilder#getAuthAssertion()

Project: UAF
Source File: AuthAssertionBuilder.java
View license
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
Source File: RegAssertionBuilder.java
View license
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();
}

15. RegAssertionBuilder#getAttestationBasicFull()

Project: UAF
Source File: RegAssertionBuilder.java
View license
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();
}

16. XmpReader#serializeDoc()

Project: clj-pdf
Source File: XmpReader.java
View license
/**
     * 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();
}

17. CEPASProtocol#wrapMessage()

Project: farebot
Source File: CEPASProtocol.java
View license
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();
}

18. DesfireProtocol#wrapMessage()

Project: farebot
Source File: DesfireProtocol.java
View license
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();
}

19. ZWaveClockCommandClass#getSetMessage()

Project: openhab
Source File: ZWaveClockCommandClass.java
View license
/**
     * 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. ZwaveAssociationGroupInfoCommandClass#getInfoMessage()

View license
/**
     * 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;
}

21. ZwaveAssociationGroupInfoCommandClass#getCommandListMessage()

View license
/**
     * 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;
}

22. ZWaveClockCommandClass#getSetMessage()

View license
/**
     * 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;
}

23. PngWriter#writeChunkIHDR()

Project: commons-imaging
Source File: PngWriter.java
View license
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());
}

24. CFFToType1Font#convertOTFToType1()

Project: fop
Source File: CFFToType1Font.java
View license
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);
}

25. MergeType1Fonts#writeFont()

Project: fop-pdf-images
Source File: MergeType1Fonts.java
View license
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);
}

26. ZwaveAssociationGroupInfoCommandClass#getGroupNameMessage()

View license
/**
     * 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;
}

27. ZWaveBarrierOperatorCommandClass#setValueMessage()

View license
@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;
}

28. ZWaveBinarySensorCommandClass#getValueMessage()

View license
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. ZWaveDoorLockLoggingCommandClass#getEntry()

View license
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;
}

30. ZWaveUserCodeCommandClass#getUserCode()

View license
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;
}

31. PngWriter#writeChunkIHDR()

Project: sanselan
Source File: PngWriter.java
View license
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. write#test()

Project: pluotsorbet
Source File: write.java
View license
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()");
}

33. MinimalPerfectHash#generate()

View license
/**
     * 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());
}

34. SimpleAuthenticatorTest#shouldUseTinkerGraphForCredentialsStoreAndSucceed()

View license
@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());
}

35. SimpleAuthenticatorTest#shouldUseTinkerGraphForCredentialsStoreAndFail()

View license
@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();
}

36. BinlogDumpCommandPacket#toBytes()

Project: canal
Source File: BinlogDumpCommandPacket.java
View license
/**
     * <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();
}

37. BloomFilter#encode()

Project: ccnx
Source File: BloomFilter.java
View license
@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());
}

38. PngWriter#writeChunkzTXt()

Project: commons-imaging
Source File: PngWriter.java
View license
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());
}

39. FTPClientTest#testUnparseableFiles()

Project: commons-net
Source File: FTPClientTest.java
View license
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);
}

40. AbstractPDFStreamTestCase#testOutput()

Project: fop
Source File: AbstractPDFStreamTestCase.java
View license
/**
     * 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());
}

41. BasicSerializationTest#testWriteString()

Project: gerrit
Source File: BasicSerializationTest.java
View license
@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);
}

42. OldAndroidByteArrayOutputStreamTest#testByteArrayOutputStream()

View license
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());
}

43. Tag#toByteArray()

Project: jdk7u-jdk
Source File: Tag.java
View license
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. ZWaveClockCommandClass#getValueMessage()

Project: openhab
Source File: ZWaveClockCommandClass.java
View license
/**
     * 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;
}

45. ZWaveBarrierOperatorCommandClass#getValueMessage()

View license
@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;
}

46. ZWaveBinarySensorCommandClass#getValueMessage()

View license
/**
     * 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;
}

47. ZWaveBinarySensorCommandClass#getSupportedMessage()

View license
/**
     * 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;
}

48. ZWaveClockCommandClass#getValueMessage()

View license
/**
     * 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;
}

49. ZWaveDoorLockCommandClass#getConfigMessage()

View license
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;
}

50. ZWaveDoorLockLoggingCommandClass#getSupported()

View license
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;
}

51. ZWaveMeterPulseCommandClass#getValueMessage()

View license
@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;
}

52. ZWaveMeterTblMonitorCommandClass#getCapabilityGet()

View license
/**
     * 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;
}

53. ZWaveMeterTblMonitorCommandClass#getTableIDGet()

View license
/**
     * 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;
}

54. ZWavePowerLevelCommandClass#getValueMessage()

View license
@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;
}

55. ZWaveProtectionCommandClass#getSupportedMessage()

View license
/**
     * 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;
}

56. ZWaveProtectionCommandClass#getValueMessage()

View license
/**
     * 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;
}

57. ZWaveTimeParametersCommandClass#getValueMessage()

View license
/**
     * 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;
}

58. ZWaveUserCodeCommandClass#getSupported()

View license
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;
}

59. Tag#toByteArray()

Project: openjdk
Source File: Tag.java
View license
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();
}

60. NewSMIMESignedTest#verifyMessageBytes()

Project: bc-java
Source File: NewSMIMESignedTest.java
View license
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()));
}

61. SMIMEMiscTest#verifyMessageBytes()

Project: bc-java
Source File: SMIMEMiscTest.java
View license
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()));
}

62. SMIMETestUtil#verifyMessageBytes()

Project: bc-java
Source File: SMIMETestUtil.java
View license
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));
}

63. SMIMETestUtil#verifyMessageBytes()

Project: bc-java
Source File: SMIMETestUtil.java
View license
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));
}

64. BaseHandler#StreamToBytes()

Project: BepHttpUtils
Source File: BaseHandler.java
View license
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();
}

65. DownloadController#zipFiles()

Project: cello
Source File: DownloadController.java
View license
/**
     * 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();
}

66. ImageProcessorTest#testRotateImage360()

Project: clerezza
Source File: ImageProcessorTest.java
View license
/**
     * 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);
}

67. CompressorStreamFactoryRoundtripTest#testCompressorStreamFactoryRoundtrip()

View license
@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"));
}

68. PngWriter#writeChunktEXt()

Project: commons-imaging
Source File: PngWriter.java
View license
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());
}

69. ExceptionUtilsTest#testPrintRootCauseStackTrace_ThrowableStream()

View license
@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);
}

70. PubkeyListActivity#readRaw()

Project: connectbot
Source File: PubkeyListActivity.java
View license
/**
	 * 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();
}

71. TestLogStreamer#testStreamerFullLen()

Project: datacollector
Source File: TestLogStreamer.java
View license
@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());
}

72. BasicSerializationTest#testWriteVarInt32()

Project: gerrit
Source File: BasicSerializationTest.java
View license
@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);
}

73. XStream2EncodingTest#toXMLUnspecifiedEncoding()

Project: hudson
Source File: XStream2EncodingTest.java
View license
@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));
}

74. WindowsPreferences#windowsAbsolutePath()

Project: jdk7u-jdk
Source File: WindowsPreferences.java
View license
/**
     * 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();
}

75. XStream2EncodingTest#toXMLUnspecifiedEncoding()

Project: Jenkins2
Source File: XStream2EncodingTest.java
View license
@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));
}

76. AssignReturnRouteMessageClass#doRequest()

View license
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;
}

77. WindowsPreferences#windowsAbsolutePath()

Project: openjdk
Source File: WindowsPreferences.java
View license
/**
     * 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();
}

78. TokenizerModelTest#testSentenceModel()

Project: opennlp
Source File: TokenizerModelTest.java
View license
@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
}

79. JsonSerializerTest#testMessage()

Project: orbit
Source File: JsonSerializerTest.java
View license
@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()));
}

80. BaseFileUtils#readInputStream()

Project: orz
Source File: BaseFileUtils.java
View license
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();
}

81. AppearanceGeneratorHelper#createAppearanceContent()

View license
/**
     * 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);
}

82. UriRetriever#pullData()

Project: ps3mediaserver
Source File: UriRetriever.java
View license
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();
}

83. PngWriter#writeChunktEXt()

Project: sanselan
Source File: PngWriter.java
View license
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());
}

84. KeyCodec#getKeyAsRawBytes()

Project: UAF
Source File: KeyCodec.java
View license
@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;
}

85. AuthAssertionBuilder#getAssertions()

Project: UAF
Source File: AuthAssertionBuilder.java
View license
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;
}

86. RegAssertionBuilder#getAssertions()

Project: UAF
Source File: RegAssertionBuilder.java
View license
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;
}

87. AuthAssertionBuilder#getAssertions()

Project: UAF
Source File: AuthAssertionBuilder.java
View license
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;
}

88. RegAssertionBuilder#getAssertions()

Project: UAF
Source File: RegAssertionBuilder.java
View license
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;
}

89. ALPNHackClientHelloExplorer#generateAlpnExtension()

View license
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();
}

90. UriRetriever#pullData()

View license
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();
}

91. WinkApacheContentEncodingTest#testSendSmallGzipContentEncoded()

View license
/**
     * 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);
}

92. WinkContentEncodingTest#testSendSmallGzipContentEncoded()

Project: wink
Source File: WinkContentEncodingTest.java
View license
/**
     * 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);
}

93. TransferEncodingTest#testSendSmallGzipContentEncoded()

Project: wink
Source File: TransferEncodingTest.java
View license
/**
     * 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();
    }
}

94. WinkTransferEncodingTest#testSendSmallGzipContentEncoded()

Project: wink
Source File: WinkTransferEncodingTest.java
View license
/**
     * 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);
}

95. ModelUtil#read()

Project: opennlp
Source File: ModelUtil.java
View license
/**
   * Writes the provided [email protected] InputStream} into a byte array
   * which is returned
   *
   * @param in stream to read data for the byte array from
   * @return byte array with the contents of the stream
   *
   * @throws IOException if an exception is thrown while reading
   *     from the provided [email protected] InputStream}
   */
public static byte[] read(InputStream in) throws IOException {
    ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
    int length;
    byte buffer[] = new byte[1024];
    while ((length = in.read(buffer)) > 0) {
        byteArrayOut.write(buffer, 0, length);
    }
    byteArrayOut.close();
    return byteArrayOut.toByteArray();
}

96. TestARCReader#buildRecordContent()

Project: openwayback
Source File: TestARCReader.java
View license
/**
     * build minimally-conforming ARC record byte stream. 
     * @param recinfo WARCRecordInfo with record metadata and content.
     *      type parameter does not matter, be sure to set contentType to that of
     *      payload.
     * @return InputStream reading from created record bits
     * @throws IOException
     */
public InputStream buildRecordContent(WARCRecordInfo recinfo) throws IOException {
    final char FS = ARCWriter.HEADER_FIELD_SEPARATOR;
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    String timeStamp = isozToDateTime14(recinfo.getCreate14DigitDate());
    String mimetype = recinfo.getMimetype();
    long contentLen = recinfo.getContentLength();
    // URL Record v1.
    String urlRecordLine = recinfo.getUrl() + FS + "4.4.4.4" + FS + timeStamp + FS + mimetype + FS + contentLen + ARCWriter.LINE_SEPARATOR;
    buf.write(urlRecordLine.getBytes("UTF-8"));
    IOUtils.copy(recinfo.getContentStream(), buf);
    buf.write(ARCWriter.LINE_SEPARATOR);
    return new ByteArrayInputStream(buf.toByteArray());
}

97. TestWARCReader#buildRecordContent()

Project: openwayback
Source File: TestWARCReader.java
View license
/**
     * build minimal WARC record byte stream.
     * @param recinfo WARCRecordInfo with record metadata and content
     * @return InputStream reading from created record bits
     * @throws IOException
     */
public static InputStream buildRecordContent(WARCRecordInfo recinfo) throws IOException {
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    Writer w = new OutputStreamWriter(buf);
    w.write("WARC/1.0" + CRLF);
    w.write("WARC-Type: " + recinfo.getType() + CRLF);
    if (StringUtils.isNotEmpty(recinfo.getUrl())) {
        w.write("WARC-Target-URI: " + recinfo.getUrl() + CRLF);
    }
    w.write("WARC-Date: " + recinfo.getCreate14DigitDate() + CRLF);
    if (recinfo.getExtraHeaders() != null) {
        ANVLRecord headers = recinfo.getExtraHeaders();
        for (Element el : headers) {
            w.write(el.getLabel() + ": " + el.getValue() + CRLF);
        }
    }
    w.write("Content-Type: " + recinfo.getMimetype() + CRLF);
    w.write("Content-Length: " + recinfo.getContentLength() + CRLF);
    w.write(CRLF);
    w.flush();
    IOUtils.copy(recinfo.getContentStream(), buf);
    buf.write((CRLF + CRLF).getBytes());
    buf.close();
    return new ByteArrayInputStream(buf.toByteArray());
}

98. TransparentReplayRendererTest#buildPartialContentResponseBlock()

View license
protected static byte[] buildPartialContentResponseBlock(String ctype, byte[] payloadBytes, long startPos, long instanceSize) throws IOException {
    assertTrue(startPos + payloadBytes.length <= instanceSize);
    final String CRLF = "\r\n";
    final String contentRange = String.format("bytes %d-%d/%d", startPos, startPos + payloadBytes.length - 1, instanceSize);
    ByteArrayOutputStream blockbuf = new ByteArrayOutputStream();
    Writer bw = new OutputStreamWriter(blockbuf);
    bw.write("HTTP/1.0 206 Partial Content" + CRLF);
    bw.write("Content-Type: " + ctype + CRLF);
    bw.write("Content-Range: " + contentRange + CRLF);
    bw.write("Content-Length: " + payloadBytes.length + CRLF);
    bw.write(CRLF);
    bw.close();
    blockbuf.write(payloadBytes);
    return blockbuf.toByteArray();
}

99. AppearanceGeneratorHelper#updateAppearanceContent()

View license
/**
     * Update existing content.
     */
private void updateAppearanceContent(List<Object> tokens, PDAnnotationWidget widget, PDFont pdFont, PDAppearanceStream appearanceStream) throws IOException {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    ContentStreamWriter writer = new ContentStreamWriter(output);
    PDRectangle boundingBox = resolveBoundingBox(widget, appearanceStream);
    int bmcIndex = tokens.indexOf(Operator.getOperator("BMC"));
    int emcIndex = tokens.indexOf(Operator.getOperator("EMC"));
    writer.writeTokens(tokens, 0, bmcIndex + 1);
    output.write("\n".getBytes("ISO-8859-1"));
    insertGeneratedAppearance(boundingBox, output, pdFont, tokens);
    if (emcIndex != -1) {
        writer.writeTokens(tokens, emcIndex, tokens.size());
    }
    output.close();
    writeToStream(output.toByteArray(), appearanceStream);
}

100. AggregationPhaseMapOutputKey#toBytes()

View license
public byte[] toBytes() throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    byte[] bytes;
    // time
    dos.writeLong(time);
    // dimensions size
    dos.writeInt(dimensions.size());
    // dimension values
    for (String dimension : dimensions) {
        bytes = dimension.getBytes();
        dos.writeInt(bytes.length);
        dos.write(bytes);
    }
    baos.close();
    dos.close();
    return baos.toByteArray();
}