Java Code Examples for java.io.ByteArrayInputStream.read()

The following are Jave code examples for showing how to use read() of the java.io.ByteArrayInputStream class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: grift   File: ThriftInputStream.java   View Source Code Vote up 6 votes
@Override
public int read() throws IOException {
  if (message != null) {
    try {
      partial = new ByteArrayInputStream(serializer.serialize(message));
      message = null;
    } catch (TException e) {
      throw Status.INTERNAL.withDescription("failed to serialize thrift message")
          .withCause(e).asRuntimeException();
    }
  }
  if (partial != null) {
    return partial.read();
  }
  return -1;
}
 
Example 2
Project: rskj   File: ECIESCoder.java   View Source Code Vote up 6 votes
public static byte[] decrypt(BigInteger privKey, byte[] cipher, byte[] macData) throws IOException, InvalidCipherTextException {

        byte[] plaintext;

        ByteArrayInputStream is = new ByteArrayInputStream(cipher);
        byte[] ephemBytes = new byte[2*((CURVE.getCurve().getFieldSize()+7)/8) + 1];

        is.read(ephemBytes);
        ECPoint ephem = CURVE.getCurve().decodePoint(ephemBytes);
        byte[] iv = new byte[KEY_SIZE /8];
        is.read(iv);
        byte[] cipherBody = new byte[is.available()];
        is.read(cipherBody);

        plaintext = decrypt(ephem, privKey, iv, cipherBody, macData);

        return plaintext;
    }
 
Example 3
Project: jdk8u-jdk   File: AttributeClass.java   View Source Code Vote up 6 votes
/**
 * Returns String value.
 */
public String getStringValue() {
    //assumes only 1 attribute value.  Will get the first value
    // if > 1.
    String strVal = null;
    byte[] bufArray = (byte[])myValue;
    if (bufArray != null) {
        ByteArrayInputStream bufStream =
            new ByteArrayInputStream(bufArray);

        int valLength = bufStream.read();

        byte[] strBytes = new byte[valLength];
        bufStream.read(strBytes, 0, valLength);
        try {
            strVal = new String(strBytes, "UTF-8");
        } catch (java.io.UnsupportedEncodingException uee) {
        }
    }
    return strVal;
}
 
Example 4
Project: boohee_v5.6   File: MultipartRequest.java   View Source Code Vote up 6 votes
private void buildDataPart(DataOutputStream dataOutputStream, DataPart dataFile, String
        inputName) throws IOException {
    dataOutputStream.writeBytes("--" + this.boundary + "\r\n");
    dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + inputName + "\"; " +
            "filename=\"" + dataFile.getFileName() + a.e + "\r\n");
    if (!(dataFile.getType() == null || dataFile.getType().trim().isEmpty())) {
        dataOutputStream.writeBytes("Content-Type: " + dataFile.getType() + "\r\n");
    }
    dataOutputStream.writeBytes("\r\n");
    ByteArrayInputStream fileInputStream = new ByteArrayInputStream(dataFile.getContent());
    int bufferSize = Math.min(fileInputStream.available(), 1048576);
    byte[] buffer = new byte[bufferSize];
    int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    while (bytesRead > 0) {
        dataOutputStream.write(buffer, 0, bufferSize);
        bufferSize = Math.min(fileInputStream.available(), 1048576);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }
    dataOutputStream.writeBytes("\r\n");
}
 
Example 5
Project: maxcube-java   File: Room.java   View Source Code Vote up 5 votes
public static Room read(ByteArrayInputStream bis) {
    int roomId = bis.read();
    int nameLength = bis.read();
    byte[] roomName = new byte[nameLength];
    bis.read(roomName, 0, nameLength);

    // next three bytes are the rf address
    int rfaddress = readRfAddress(bis);

    return new Room(roomId, new String(roomName, UTF_8), rfaddress);
}
 
Example 6
Project: Spitfire   File: UploadFileRequest.java   View Source Code Vote up 5 votes
/**
 * Returns the raw POST or PUT body to be sent.
 *
 * <p>By default, the body consists of the request parameters in
 * application/x-www-form-urlencoded format. When overriding this method, consider overriding
 * {@link #getBodyContentType()} as well to match the new body format.
 *
 * @throws AuthFailureError in the event of auth failure
 */
@Override
public byte[] getBody() throws AuthFailureError {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);

    try {
        ByteArrayInputStream fileInputStream = new ByteArrayInputStream(getPartData().getContent());
        int bytesAvailable = fileInputStream.available();

        int maxBufferSize = 1024 * 1024;
        int bufferSize = Math.min(bytesAvailable, maxBufferSize);
        byte[] buffer = new byte[bufferSize];

        int bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        return bos.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 7
Project: AppCoins-ethereumj   File: ECIESTest.java   View Source Code Vote up 5 votes
public static byte[] decrypt(BigInteger prv, byte[] cipher) throws InvalidCipherTextException, IOException {
    ByteArrayInputStream is = new ByteArrayInputStream(cipher);
    byte[] ephemBytes = new byte[2*((curve.getCurve().getFieldSize()+7)/8) + 1];
    is.read(ephemBytes);
    ECPoint ephem = curve.getCurve().decodePoint(ephemBytes);
    byte[] IV = new byte[KEY_SIZE /8];
    is.read(IV);
    byte[] cipherBody = new byte[is.available()];
    is.read(cipherBody);

    EthereumIESEngine iesEngine = makeIESEngine(false, ephem, prv, IV);

    byte[] message = iesEngine.processBlock(cipherBody, 0, cipherBody.length);
    return message;
}
 
Example 8
Project: talchain   File: ECIESTest.java   View Source Code Vote up 5 votes
public static byte[] decrypt(BigInteger prv, byte[] cipher) throws InvalidCipherTextException, IOException {
    ByteArrayInputStream is = new ByteArrayInputStream(cipher);
    byte[] ephemBytes = new byte[2*((curve.getCurve().getFieldSize()+7)/8) + 1];
    is.read(ephemBytes);
    ECPoint ephem = curve.getCurve().decodePoint(ephemBytes);
    byte[] IV = new byte[KEY_SIZE /8];
    is.read(IV);
    byte[] cipherBody = new byte[is.available()];
    is.read(cipherBody);

    EthereumIESEngine iesEngine = makeIESEngine(false, ephem, prv, IV);

    byte[] message = iesEngine.processBlock(cipherBody, 0, cipherBody.length);
    return message;
}
 
Example 9
Project: my-spring-boot-project   File: XssHttpServletRequestWrapper.java   View Source Code Vote up 5 votes
@Override
public ServletInputStream getInputStream() throws IOException {
    //非json类型,直接返回
    if (!super.getHeader(HttpHeaders.CONTENT_TYPE).equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)) {
        return super.getInputStream();
    }

    //为空,直接返回
    String json = IOUtils.toString(super.getInputStream(), "utf-8");
    if (StringUtils.isBlank(json)) {
        return super.getInputStream();
    }

    //xss过滤
    json = xssEncode(json);
    final ByteArrayInputStream bis = new ByteArrayInputStream(json.getBytes("utf-8"));
    return new ServletInputStream() {
        @Override
        public boolean isFinished() {
            return false;
        }

        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setReadListener(ReadListener readListener) {

        }

        @Override
        public int read() throws IOException {
            return bis.read();
        }
    };
}
 
Example 10
Project: PeSanKita-android   File: PduParser.java   View Source Code Vote up 5 votes
protected static byte[] getWapString(ByteArrayInputStream pduDataStream,
        int stringType) {
    assert(null != pduDataStream);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int temp = pduDataStream.read();
    assert(-1 != temp);
    while((-1 != temp) && ('\0' != temp)) {
        // check each of the character
        if (stringType == TYPE_TOKEN_STRING) {
            if (isTokenCharacter(temp)) {
                out.write(temp);
            }
        } else {
            if (isText(temp)) {
                out.write(temp);
            }
        }

        temp = pduDataStream.read();
        assert(-1 != temp);
    }

    if (out.size() > 0) {
        return out.toByteArray();
    }

    return null;
}
 
Example 11
Project: ProtocolSupportPocketStuff   File: SkinUtils.java   View Source Code Vote up 5 votes
public static BufferedImage fromData(byte[] data) {
	System.out.println(data.length);
	Validate.isTrue((data.length == 8192) || (data.length == 16384), "Skin data must be either 8192 or 16384 bytes long!");
	int width = 64, height = (data.length == 16384) ? 64 : 32;
	ByteArrayInputStream stream = new ByteArrayInputStream(data);
	BufferedImage skin = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
	for (int y = 0; y < height; y++) {
		for (int x = 0; x < width; x++) {
			Color color = new Color(stream.read(), stream.read(), stream.read(), stream.read());
			skin.setRGB(x, y, color.getRGB());
		}
	}
	return skin;
}
 
Example 12
Project: jdk8u-jdk   File: AttributeClass.java   View Source Code Vote up 5 votes
/**
 * Returns array of String values.
 */
public String[] getArrayOfStringValues() {

    byte[] bufArray = (byte[])myValue;
    if (bufArray != null) {
        ByteArrayInputStream bufStream =
            new ByteArrayInputStream(bufArray);
        int available = bufStream.available();

        // total number of values is at the end of the stream
        bufStream.mark(available);
        bufStream.skip(available-1);
        int length = bufStream.read();
        bufStream.reset();

        String[] valueArray = new String[length];
        for (int i = 0; i < length; i++) {
            // read length
            int valLength = bufStream.read();
            byte[] bufBytes = new byte[valLength];
            bufStream.read(bufBytes, 0, valLength);
            try {
                valueArray[i] = new String(bufBytes, "UTF-8");
            } catch (java.io.UnsupportedEncodingException uee) {
            }
        }
        return valueArray;
    }
    return null;
}
 
Example 13
Project: wxcard   File: JsonRequestWrapper.java   View Source Code Vote up 5 votes
@Override
  public ServletInputStream getInputStream() throws IOException {
    final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
    ServletInputStream servletInputStream = new ServletInputStream() {
      public int read() throws IOException {
        return byteArrayInputStream.read();
      }

@Override
public boolean isFinished() {
	// TODO Auto-generated method stub
	return false;
}

@Override
public boolean isReady() {
	// TODO Auto-generated method stub
	return false;
}

@Override
public void setReadListener(ReadListener readListener) {
	// TODO Auto-generated method stub
	
}
    };
    return servletInputStream;
  }
 
Example 14
Project: phone-simulator   File: SmsStatusReportTpduImpl.java   View Source Code Vote up 4 votes
public SmsStatusReportTpduImpl(byte[] data, Charset gsm8Charset) throws MAPException {
    this();

    if (data == null)
        throw new MAPException("Error creating a new SmsStatusReport instance: data is empty");
    if (data.length < 1)
        throw new MAPException("Error creating a new SmsStatusReport instance: data length is equal zero");

    ByteArrayInputStream stm = new ByteArrayInputStream(data);

    int bt = stm.read();
    if ((bt & _MASK_TP_UDHI) != 0)
        this.userDataHeaderIndicator = true;
    if ((bt & _MASK_TP_MMS) == 0)
        this.moreMessagesToSend = true;
    if ((bt & _MASK_TP_LP) != 0)
        this.forwardedOrSpawned = true;
    int code = (bt & _MASK_TP_SRQ) >> 5;
    this.statusReportQualifier = StatusReportQualifier.getInstance(code);

    this.messageReference = stm.read();
    if (this.messageReference == -1)
        throw new MAPException("Error creating a new SmsStatusReport instance: messageReference field has not been found");

    this.recipientAddress = AddressFieldImpl.createMessage(stm);
    this.serviceCentreTimeStamp = AbsoluteTimeStampImpl.createMessage(stm);
    this.dischargeTime = AbsoluteTimeStampImpl.createMessage(stm);

    bt = stm.read();
    if (bt == -1)
        throw new MAPException("Error creating a new SmsStatusReport instance: Status field has not been found");
    this.status = new StatusImpl(bt);

    bt = stm.read();
    if (bt == -1)
        this.parameterIndicator = new ParameterIndicatorImpl(0);
    else
        this.parameterIndicator = new ParameterIndicatorImpl(bt);

    if (this.parameterIndicator.getTP_PIDPresence()) {
        bt = stm.read();
        if (bt == -1)
            throw new MAPException(
                    "Error creating a new SmsStatusReport instance: protocolIdentifier field has not been found");
        this.protocolIdentifier = new ProtocolIdentifierImpl(bt);
    }

    if (this.parameterIndicator.getTP_DCSPresence()) {
        bt = stm.read();
        if (bt == -1)
            throw new MAPException(
                    "Error creating a new SmsStatusReport instance: dataCodingScheme field has not been found");
        this.dataCodingScheme = new DataCodingSchemeImpl(bt);
    }

    if (this.parameterIndicator.getTP_UDLPresence()) {
        this.userDataLength = stm.read();
        if (this.userDataLength == -1)
            throw new MAPException("Error creating a new SmsStatusReport instance: userDataLength field has not been found");

        int avail = stm.available();
        byte[] buf = new byte[avail];
        try {
            stm.read(buf);
        } catch (IOException e) {
            throw new MAPException("IOException while creating a new SmsStatusReport instance: " + e.getMessage(), e);
        }
        userData = new UserDataImpl(buf, dataCodingScheme, userDataLength, userDataHeaderIndicator, gsm8Charset);
    }
}
 
Example 15
Project: phone-simulator   File: SmsCommandTpduImpl.java   View Source Code Vote up 4 votes
public SmsCommandTpduImpl(byte[] data) throws MAPException {
    this();

    if (data == null)
        throw new MAPException("Error creating a new SmsCommandTpdu instance: data is empty");
    if (data.length < 1)
        throw new MAPException("Error creating a new SmsCommandTpdu instance: data length is equal zero");

    ByteArrayInputStream stm = new ByteArrayInputStream(data);

    int bt = stm.read();
    if ((bt & _MASK_TP_UDHI) != 0)
        this.userDataHeaderIndicator = true;
    if ((bt & _MASK_TP_SRR) != 0)
        this.statusReportRequest = true;

    this.messageReference = stm.read();
    if (this.messageReference == -1)
        throw new MAPException("Error creating a new SmsCommandTpdu instance: messageReference field has not been found");

    bt = stm.read();
    if (bt == -1)
        throw new MAPException("Error creating a new SmsCommandTpdu instance: protocolIdentifier field has not been found");
    this.protocolIdentifier = new ProtocolIdentifierImpl(bt);

    bt = stm.read();
    if (bt == -1)
        throw new MAPException("Error creating a new SmsCommandTpdu instance: commandType field has not been found");
    this.commandType = new CommandTypeImpl(bt);

    this.messageNumber = stm.read();
    if (this.messageNumber == -1)
        throw new MAPException("Error creating a new SmsCommandTpdu instance: messageNumber field has not been found");

    this.destinationAddress = AddressFieldImpl.createMessage(stm);

    this.commandDataLength = stm.read();
    if (this.commandDataLength == -1)
        throw new MAPException("Error creating a new SmsCommandTpdu instance: commandDataLength field has not been found");

    int avail = this.commandDataLength;
    byte[] buf = new byte[avail];
    try {
        stm.read(buf);
    } catch (IOException e) {
        throw new MAPException("IOException while creating a new SmsCommandTpdu instance: " + e.getMessage(), e);
    }
    commandData = new CommandDataImpl(buf);
}
 
Example 16
Project: Arduino-android-serial-communication   File: Udp4JArduino.java   View Source Code Vote up 4 votes
@Override
public void run() {
    byte[] buffer = new byte[1024];
    DatagramPacket p = new DatagramPacket(buffer, buffer.length);
    while (true) {
        try {
            datagramSocket.receive(p);
            ByteArrayInputStream in = new ByteArrayInputStream(p.getData());
            int data;
            while ((data = in.read()) > -1) {
                // we got a byte from the serial port
                if (state == RCV_WAIT) { // it should be a start byte or we just ignore it
                    if (data == START_BYTE) {
                        state = RCV_MSG;
                        buffer_idx = 0;
                    }
                } else if (state == RCV_MSG) {
                    if (data == ESCAPE_BYTE) {
                        state = RCV_ESC;
                    } else if (data == STOP_BYTE) {
                        // We got a complete frame
                        byte[] packet = new byte[buffer_idx];
                        for (int i = 0; i < buffer_idx; i++) {
                            packet[i] = buffer[i];
                        }
                        for (JArduinoObserver o : observers) {
                            o.receiveMsg(packet);
                        }
                        state = RCV_WAIT;
                    } else if (data == START_BYTE) {
                        // Should not happen but we reset just in case
                        state = RCV_MSG;
                        buffer_idx = 0;
                    } else { // it is just a byte to store
                        buffer[buffer_idx] = (byte) data;
                        buffer_idx++;
                    }
                } else if (state == RCV_ESC) {
                    // Store the byte without looking at it
                    buffer[buffer_idx] = (byte) data;
                    buffer_idx++;
                    state = RCV_MSG;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
 
Example 17
Project: alerta-fraude   File: LocalFilesystem.java   View Source Code Vote up 4 votes
@Override
public long writeToFileAtURL(LocalFilesystemURL inputURL, String data,
		int offset, boolean isBinary) throws IOException, NoModificationAllowedException {

       boolean append = false;
       if (offset > 0) {
           this.truncateFileAtURL(inputURL, offset);
           append = true;
       }

       byte[] rawData;
       if (isBinary) {
           rawData = Base64.decode(data, Base64.DEFAULT);
       } else {
           rawData = data.getBytes(Charset.defaultCharset());
       }
       ByteArrayInputStream in = new ByteArrayInputStream(rawData);
       try
       {
       	byte buff[] = new byte[rawData.length];
           String absolutePath = filesystemPathForURL(inputURL);
           FileOutputStream out = new FileOutputStream(absolutePath, append);
           try {
           	in.read(buff, 0, buff.length);
           	out.write(buff, 0, rawData.length);
           	out.flush();
           } finally {
           	// Always close the output
           	out.close();
           }
           if (isPublicDirectory(absolutePath)) {
               broadcastNewFile(Uri.fromFile(new File(absolutePath)));
           }
       }
       catch (NullPointerException e)
       {
           // This is a bug in the Android implementation of the Java Stack
           NoModificationAllowedException realException = new NoModificationAllowedException(inputURL.toString());
           realException.initCause(e);
           throw realException;
       }

       return rawData.length;
}
 
Example 18
Project: siiMobilityAppKit   File: LocalFilesystem.java   View Source Code Vote up 4 votes
@Override
public long writeToFileAtURL(LocalFilesystemURL inputURL, String data,
		int offset, boolean isBinary) throws IOException, NoModificationAllowedException {

       boolean append = false;
       if (offset > 0) {
           this.truncateFileAtURL(inputURL, offset);
           append = true;
       }

       byte[] rawData;
       if (isBinary) {
           rawData = Base64.decode(data, Base64.DEFAULT);
       } else {
           rawData = data.getBytes(Charset.defaultCharset());
       }
       ByteArrayInputStream in = new ByteArrayInputStream(rawData);
       try
       {
       	byte buff[] = new byte[rawData.length];
           String absolutePath = filesystemPathForURL(inputURL);
           FileOutputStream out = new FileOutputStream(absolutePath, append);
           try {
           	in.read(buff, 0, buff.length);
           	out.write(buff, 0, rawData.length);
           	out.flush();
           } finally {
           	// Always close the output
           	out.close();
           }
           if (isPublicDirectory(absolutePath)) {
               broadcastNewFile(Uri.fromFile(new File(absolutePath)));
           }
       }
       catch (NullPointerException e)
       {
           // This is a bug in the Android implementation of the Java Stack
           NoModificationAllowedException realException = new NoModificationAllowedException(inputURL.toString());
           realException.initCause(e);
           throw realException;
       }

       return rawData.length;
}
 
Example 19
Project: maxcube-java   File: Configuration.java   View Source Code Vote up 4 votes
public static Configuration readFrom(ByteArrayInputStream bis) {
    int len = bis.read();

    int rfAddress = Parser.readRfAddress(bis);
    DeviceType type = DeviceType.fromId(bis.read());

    byte[] unknown = new byte[3];
    bis.read(unknown, 0, unknown.length);

    byte[] serialBytes = new byte[10];
    bis.read(serialBytes, 0, serialBytes.length);
    String serial = new String(serialBytes, UTF_8);

    if (type == DeviceType.THERMOSTAST_PLUS || type == DeviceType.THERMOSTAST) {
        double temperatureComfort = bis.read() / 2.0;
        double temperatureEco = bis.read() / 2.0;
        double temperatureSetpointMax = bis.read() / 2.0;
        double temperatureSetpointMin = bis.read() / 2.0;
        double temperatureOffset = bis.read() / 2.0 - 3.5;
        double temperatureWindowOpen = bis.read() / 2.0;
        int durationWindowOpen = bis.read();
        int durationBoost = bis.read();
        int decalcification = bis.read();
        double valveMaximum = bis.read() * 100/255.0;
        double valveOffset = bis.read() * 100/255.0;

        // TODO decipher the weekly program, always has a length of 182
        bis.skip(bis.available());

        return new ValveConfiguration(type, rfAddress, serial,
                temperatureComfort, temperatureEco, temperatureSetpointMax, temperatureSetpointMin, temperatureOffset,
                temperatureWindowOpen, durationWindowOpen, durationBoost, decalcification, valveMaximum, valveOffset);
    } else if (type == DeviceType.CUBE) {
        // TODO decipher the cube configuration
        bis.skip(bis.available());
    }

    if (bis.available() > 0) {
        String message = String.format(Locale.ROOT, "Device of type [%s] claims a length of [%s] and has [%s] unread bytes", type,
                len, bis.available());
        throw new IllegalStateException(message);
    }

    return new Configuration(type, rfAddress, serial);
}
 
Example 20
Project: creacoinj   File: Script.java   View Source Code Vote up 4 votes
/**
 * <p>To run a script, first we parse it which breaks it up into chunks representing pushes of data or logical
 * opcodes. Then we can run the parsed chunks.</p>
 *
 * <p>The reason for this split, instead of just interpreting directly, is to make it easier
 * to reach into a programs structure and pull out bits of data without having to run it.
 * This is necessary to render the to/from addresses of transactions in a user interface.
 * Bitcoin Core does something similar.</p>
 */
private void parse(byte[] program) throws ScriptException {
    chunks = new ArrayList<>(5);   // Common size.
    ByteArrayInputStream bis = new ByteArrayInputStream(program);
    int initialSize = bis.available();
    while (bis.available() > 0) {
        int startLocationInProgram = initialSize - bis.available();
        int opcode = bis.read();

        long dataToRead = -1;
        if (opcode >= 0 && opcode < OP_PUSHDATA1) {
            // Read some bytes of data, where how many is the opcode value itself.
            dataToRead = opcode;
        } else if (opcode == OP_PUSHDATA1) {
            if (bis.available() < 1) throw new ScriptException("Unexpected end of script");
            dataToRead = bis.read();
        } else if (opcode == OP_PUSHDATA2) {
            // Read a short, then read that many bytes of data.
            if (bis.available() < 2) throw new ScriptException("Unexpected end of script");
            dataToRead = bis.read() | (bis.read() << 8);
        } else if (opcode == OP_PUSHDATA4) {
            // Read a uint32, then read that many bytes of data.
            // Though this is allowed, because its value cannot be > 520, it should never actually be used
            if (bis.available() < 4) throw new ScriptException("Unexpected end of script");
            dataToRead = ((long)bis.read()) | (((long)bis.read()) << 8) | (((long)bis.read()) << 16) | (((long)bis.read()) << 24);
        }

        ScriptChunk chunk;
        if (dataToRead == -1) {
            chunk = new ScriptChunk(opcode, null, startLocationInProgram);
        } else {
            if (dataToRead > bis.available())
                throw new ScriptException("Push of data element that is larger than remaining data");
            byte[] data = new byte[(int)dataToRead];
            checkState(dataToRead == 0 || bis.read(data, 0, (int)dataToRead) == dataToRead);
            chunk = new ScriptChunk(opcode, data, startLocationInProgram);
        }
        // Save some memory by eliminating redundant copies of the same chunk objects.
        for (ScriptChunk c : STANDARD_TRANSACTION_SCRIPT_CHUNKS) {
            if (c.equals(chunk)) chunk = c;
        }
        chunks.add(chunk);
    }
}