Example usage for java.io ByteArrayInputStream available

List of usage examples for java.io ByteArrayInputStream available

Introduction

In this page you can find the example usage for java.io ByteArrayInputStream available.

Prototype

public synchronized int available() 

Source Link

Document

Returns the number of remaining bytes that can be read (or skipped over) from this input stream.

Usage

From source file:org.jopenray.server.thinclient.DisplayReaderThread.java

private void handlePacket(byte[] udpData, int l) {
    boolean dump = false;
    ByteArrayInputStream bIn = new ByteArrayInputStream(udpData, 0, l);
    int r = readInt16(bIn);
    int flag = readInt16(bIn);
    int type = readInt16(bIn);
    int dir = readInt16(bIn);
    if (DEBUG)/*from ww  w .j  a  v a2 s  .c  o m*/
        System.out.print("Seq number:" + r + " Flag:" + flag + " Type:" + type + " Dir:" + dir);

    // Sunray ->Server
    int a = readInt16(bIn);
    int b = readInt16(bIn);
    int c = readInt16(bIn);
    int d = readInt16(bIn);
    if (DEBUG)
        System.out.println("Sunray -> Server:" + a + "," + b + "," + c + "," + d);
    if (bIn.available() == 0) {
        DisplayMessage m = new DisplayMessage(client.getWriter());
        m.addOperation(new PadOperation());
        this.client.getWriter().addMessage(m);
    } else
        while (bIn.available() > 0) {
            int opcode = bIn.read();
            int hdat = readInt16(bIn);
            int idat = bIn.read();
            String opCodeHeader = "";

            opCodeHeader += "[ Opcode: " + opcode + " , " + hdat + " ," + idat + " ]";

            switch (opcode) {
            case 0xc1:
                dump = true;
                int jdat = readInt16(bIn);
                int modifier = readInt16(bIn);
                // 6 octet
                int key1 = bIn.read();
                int key2 = bIn.read();
                int key3 = bIn.read();
                int key4 = bIn.read();
                int key5 = bIn.read();
                int key6 = bIn.read();

                //
                int mdat = readInt16(bIn);
                System.out.println("Keyboard " + opCodeHeader + " " + jdat + " modifier:" + modifier + " keys:("
                        + key1 + "," + key2 + "," + key3 + "," + key4 + "," + key5 + "," + key6 + ") " + mdat);

                /*
                 * if(lastPressed>0){
                 * System.out.println("Send Key Released:"+lastPressed);
                 * sendKeyReleased(lastPressed); lastPressed=-1; }
                 */

                if (key1 > 0) {
                    if (!keysPressed.contains(key1)) {

                        int hidToKeyCode = HID.hidToKeyCode(key1);
                        System.out.println(modifier + " : " + (modifier & 0x2));
                        sendKeyPressed(hidToKeyCode, (modifier & 2) != 0 || (modifier & 32) != 0,
                                (modifier & 1) != 0, (modifier & 4) != 0, (modifier & 8) != 0,
                                (modifier & 64) != 0);
                        keysPressed.add(key1);
                    }

                } else {
                    for (int i = 0; i < this.keysPressed.size(); i++) {
                        int k = keysPressed.get(i);
                        int hidToKeyCode = HID.hidToKeyCode(k);
                        sendKeyReleased(hidToKeyCode);

                    }
                    keysPressed.clear();
                }

                break;
            case 0xc2:
                int buttons = readInt16(bIn);
                int mouseX = readInt16(bIn);
                int mouseY = readInt16(bIn);
                int c2 = readInt16(bIn);
                if (DEBUG)
                    System.out.println("Mouse" + opCodeHeader + " buttons:" + buttons + " (" + mouseX + ","
                            + mouseY + ")" + c2);
                processMouseEvent(buttons, mouseX, mouseY);
                break;
            case 0xc4: {
                int c41 = readInt32(bIn);
                int c42 = readInt32(bIn);
                int c43 = readInt32(bIn);

                System.out.println("NACK  seq= " + c41 + "  type: " + c42 + " , " + c43);
                client.resend(c42, c43);
                break;
            }
            case 0xc5:
                int c51 = bIn.read();
                int c52 = bIn.read();
                int c53 = bIn.read();
                int c54 = bIn.read();

                System.out.println("0xC5 " + opCodeHeader + " " + c51 + "," + c52 + "," + c53 + "," + c54);
                break;
            case 0xc6:
                int dataLength = readInt16(bIn);
                int stringLength = bIn.read();
                byte[] string = new byte[stringLength];

                try {
                    int rL = bIn.read(string);
                    System.out.println(dataLength + " , " + stringLength + " readLength" + rL);
                    System.out.println("Firmware: " + new String(string));
                    // dump = true;
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                break;

            case 0xc7: {
                int x1 = readInt16(bIn);
                int y1 = readInt16(bIn);
                int w1 = readInt16(bIn);
                int h1 = readInt16(bIn);
                int x2 = readInt16(bIn);
                int y2 = readInt16(bIn);
                int w2 = readInt16(bIn);
                int h2 = readInt16(bIn);
                int x3 = readInt16(bIn);
                int y3 = readInt16(bIn);
                int w3 = readInt16(bIn);
                int h3 = readInt16(bIn);
                if (DEBUG)
                    System.out.println("Rect: " + opCodeHeader + " [" + x1 + "," + y1 + "," + w1 + "," + h1
                            + "][" + x2 + "," + y2 + "," + w2 + "," + h2 + "][" + x3 + "," + y3 + "," + w3 + ","
                            + h3 + "]");

                break;
            }
            case 0xcb:
                int bc1 = bIn.read();
                int bc2 = readInt16(bIn);
                int bc3 = readInt16(bIn);
                int bc4 = readInt16(bIn);
                int bc5 = readInt16(bIn);
                int bc6 = readInt16(bIn);
                int bc7 = readInt16(bIn);
                int bc8 = readInt16(bIn);
                int bc9 = readInt16(bIn);
                int bc10 = readInt16(bIn);
                int bc11 = readInt16(bIn);
                if (DEBUG)
                    System.out.println(
                            "0xCB " + opCodeHeader + " " + bc1 + "," + bc2 + "," + bc3 + "," + bc4 + "," + bc5
                                    + "," + bc6 + "," + bc7 + "," + bc8 + "," + bc9 + "," + bc10 + "," + bc11);
                break;
            default:
                System.out.println("Unknown opcode: " + opCodeHeader);
                dump = true;
                break;
            }
        }
    if (dump) {
        try {
            HexDump.dump(udpData, 0, System.err, 0);
        } catch (Exception ignr) {
        }
    }

}

From source file:org.jzkit.a2j.codec.runtime.BERInputStream.java

public int[] oid_codec(Object instance, boolean is_constructed) throws java.io.IOException {
    // System.err.println("Decoding OID, length = "+next_length);

    int[] retval = new int[next_length + 1];
    byte[] decode_buffer = new byte[next_length];
    int pos = 2;/* w w w  .j av a  2  s  .com*/

    int bytes_left_to_read = next_length;
    int offset = 0;

    // We may need to call read repeatedly until we have all the data.
    while (bytes_left_to_read > 0) {
        int bytes_read = read(decode_buffer, offset, bytes_left_to_read);
        bytes_left_to_read -= bytes_read;
        offset += bytes_read;
    }

    ByteArrayInputStream bais = new ByteArrayInputStream(decode_buffer);

    byte octet = (byte) bais.read();

    if (octet >= 80) {
        retval[0] = 2;
        retval[1] = octet - 80;
    } else if (octet >= 40) {
        retval[0] = 1;
        retval[1] = octet - 40;
    } else {
        retval[0] = 0;
        retval[1] = octet;
    }

    // Split first octet into first 2 elements of OID

    while (bais.available() > 0) {
        retval[pos++] = decodeBase128Int(bais);
    }

    int[] result = new int[pos];
    System.arraycopy(retval, 0, result, 0, pos);

    // debug("oid_codec returns "+result+" length="+next_length);

    return result;
}

From source file:org.accada.epcis.repository.query.QueryOperationsBackendSQL.java

/**
 * {@inheritDoc}/*from  w  w w.  ja va2  s.c  o m*/
 */
public void storeSupscriptions(final QueryOperationsSession session, QueryParams queryParams, String dest,
        String subscrId, SubscriptionControls controls, String trigger,
        QuerySubscriptionScheduled newSubscription, String queryName, Schedule schedule)
        throws SQLException, ImplementationExceptionResponse {
    String insert = "INSERT INTO subscription (subscriptionid, "
            + "params, dest, sched, trigg, initialrecordingtime, "
            + "exportifempty, queryname, lastexecuted) VALUES "
            + "((?), (?), (?), (?), (?), (?), (?), (?), (?))";
    PreparedStatement stmt = session.getConnection().prepareStatement(insert);
    LOG.debug("QUERY: " + insert);
    try {
        stmt.setString(1, subscrId);
        LOG.debug("       query param 1: " + subscrId);

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(outStream);
        out.writeObject(queryParams);
        ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
        stmt.setBinaryStream(2, inStream, inStream.available());
        LOG.debug("       query param 2: [" + inStream.available() + " bytes]");

        stmt.setString(3, dest.toString());
        LOG.debug("       query param 3: " + dest);

        outStream = new ByteArrayOutputStream();
        out = new ObjectOutputStream(outStream);
        out.writeObject(schedule);
        inStream = new ByteArrayInputStream(outStream.toByteArray());
        stmt.setBinaryStream(4, inStream, inStream.available());
        LOG.debug("       query param 4: [" + inStream.available() + " bytes]");

        stmt.setString(5, trigger);
        LOG.debug("       query param 5: " + trigger);

        Calendar cal = newSubscription.getInitialRecordTime();
        Timestamp ts = new Timestamp(cal.getTimeInMillis());
        String time = ts.toString();
        stmt.setString(6, time);
        LOG.debug("       query param 6: " + time);

        stmt.setBoolean(7, controls.isReportIfEmpty());
        LOG.debug("       query param 7: " + controls.isReportIfEmpty());

        stmt.setString(8, queryName);
        LOG.debug("       query param 8: " + queryName);

        stmt.setString(9, time);
        LOG.debug("       query param 9: " + time);

        stmt.executeUpdate();
    } catch (IOException e) {
        String msg = "Unable to store the subscription to the database: " + e.getMessage();
        LOG.error(msg);
        ImplementationException iex = new ImplementationException();
        iex.setReason(msg);
        iex.setSeverity(ImplementationExceptionSeverity.ERROR);
        throw new ImplementationExceptionResponse(msg, iex, e);
    }
}

From source file:csic.ceab.movelab.beepath.Util.java

public static boolean uploadFile(byte[] bytes, String filename, String uploadurl) {

    HttpURLConnection conn = null;
    DataOutputStream dos = null;//  w w w  .ja v  a  2s  .  c  o  m
    // DataInputStream inStream = null;

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 64 * 1024; // old value 1024*1024
    ByteArrayInputStream byteArrayInputStream = null;
    boolean isSuccess = true;
    try {
        // ------------------ CLIENT REQUEST

        byteArrayInputStream = new ByteArrayInputStream(bytes);

        // open a URL connection to the Servlet
        URL url = new URL(uploadurl);
        // Open a HTTP connection to the URL
        conn = (HttpURLConnection) url.openConnection();
        // Allow Inputs
        conn.setDoInput(true);
        // Allow Outputs
        conn.setDoOutput(true);
        // Don't use a cached copy.
        conn.setUseCaches(false);
        // set timeout
        conn.setConnectTimeout(60000);
        conn.setReadTimeout(60000);
        // Use a post method.
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

        dos = new DataOutputStream(conn.getOutputStream());
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + filename + "\""
                + lineEnd);
        dos.writeBytes(lineEnd);

        // create a buffer of maximum size
        bytesAvailable = byteArrayInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = byteArrayInputStream.read(buffer, 0, bufferSize);
        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = byteArrayInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = byteArrayInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // close streams
        // Log.e(TAG,"UploadService Runnable:File is written");
        // fileInputStream.close();
        // dos.flush();
        // dos.close();
    } catch (Exception e) {
        // Log.e(TAG, "UploadService Runnable:Client Request error", e);
        isSuccess = false;
    } finally {
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException e) {
                // Log.e(TAG, "exception" + e);

            }
        }
        if (byteArrayInputStream != null) {
            try {
                byteArrayInputStream.close();
            } catch (IOException e) {
                // Log.e(TAG, "exception" + e);

            }
        }

    }

    // ------------------ read the SERVER RESPONSE
    try {

        if (conn.getResponseCode() != 200) {
            isSuccess = false;
        }
    } catch (IOException e) {
        // Log.e(TAG, "Connection error", e);
        isSuccess = false;
    }

    return isSuccess;
}

From source file:org.fosstrak.epcis.repository.query.QueryOperationsBackendSQL.java

/**
 * {@inheritDoc}/* w w w .  j a  va 2  s .c  o  m*/
 */
public void storeSupscriptions(final QueryOperationsSession session, QueryParams queryParams, String dest,
        String subscrId, SubscriptionControls controls, String trigger,
        QuerySubscriptionScheduled newSubscription, String queryName, Schedule schedule)
        throws SQLException, ImplementationExceptionResponse {
    String insert = "INSERT INTO subscription (subscriptionid, "
            + "params, dest, sched, trigg, initialrecordingtime, "
            + "exportifempty, queryname, lastexecuted) VALUES "
            + "((?), (?), (?), (?), (?), (?), (?), (?), (?))";
    PreparedStatement stmt = session.getConnection().prepareStatement(insert);
    LOG.debug("QUERY: " + insert);
    try {
        stmt.setString(1, subscrId);
        LOG.debug("       query param 1: " + subscrId);

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(outStream);
        out.writeObject(queryParams);
        ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
        stmt.setBinaryStream(2, inStream, inStream.available());
        LOG.debug("       query param 2: [" + inStream.available() + " bytes]");

        stmt.setString(3, dest.toString());
        LOG.debug("       query param 3: " + dest);

        outStream = new ByteArrayOutputStream();
        out = new ObjectOutputStream(outStream);
        out.writeObject(schedule);
        inStream = new ByteArrayInputStream(outStream.toByteArray());
        stmt.setBinaryStream(4, inStream, inStream.available());
        LOG.debug("       query param 4: [" + inStream.available() + " bytes]");

        stmt.setString(5, trigger);
        LOG.debug("       query param 5: " + trigger);

        Calendar cal = newSubscription.getInitialRecordTime();
        Timestamp ts = new Timestamp(cal.getTimeInMillis());
        String time = ts.toString();
        stmt.setString(6, time);
        LOG.debug("       query param 6: " + time);

        stmt.setBoolean(7, controls.isReportIfEmpty());
        LOG.debug("       query param 7: " + controls.isReportIfEmpty());

        stmt.setString(8, queryName);
        LOG.debug("       query param 8: " + queryName);

        stmt.setString(9, time);
        LOG.debug("       query param 9: " + time);

        stmt.executeUpdate();
        session.commit();
    } catch (IOException e) {
        String msg = "Unable to store the subscription to the database: " + e.getMessage();
        LOG.error(msg);
        ImplementationException iex = new ImplementationException();
        iex.setReason(msg);
        iex.setSeverity(ImplementationExceptionSeverity.ERROR);
        throw new ImplementationExceptionResponse(msg, iex, e);
    }
}

From source file:com.linkedin.cubert.io.rubix.RubixFile.java

@SuppressWarnings("unchecked")
public List<KeyData<K>> getKeyData() throws IOException, ClassNotFoundException {
    if (keyData != null)
        return keyData;

    final FileSystem fs = FileSystem.get(conf);
    keyData = new ArrayList<KeyData<K>>();

    final long filesize = fs.getFileStatus(path).getLen();
    FSDataInputStream in = fs.open(path);

    /* The last long in the file is the start position of the trailer section */
    in.seek(filesize - 8);//from w w w  .j a v a2 s. c o m
    long metaDataStartPos = in.readLong();

    in.seek(metaDataStartPos);

    ObjectMapper mapper = new ObjectMapper();
    metadataJson = mapper.readValue(in.readUTF(), JsonNode.class);

    int keySectionSize = in.readInt();

    // load the key section
    byte[] keySection = new byte[keySectionSize];

    in.seek(filesize - keySectionSize - 8);
    in.read(keySection, 0, keySectionSize);
    in.close();

    ByteArrayInputStream bis = new ByteArrayInputStream(keySection);
    DataInput dataInput = new DataInputStream(bis);

    int numberOfBlocks = metadataJson.get("numberOfBlocks").getIntValue();

    // load the key section
    keyClass = (Class<K>) ClassCache.forName(JsonUtils.getText(metadataJson, "keyClass"));
    valueClass = (Class<V>) ClassCache.forName(JsonUtils.getText(metadataJson, "valueClass"));

    SerializationFactory serializationFactory = new SerializationFactory(conf);
    Deserializer<K> deserializer = serializationFactory.getDeserializer(keyClass);

    deserializer.open(bis);

    while (bis.available() > 0 && numberOfBlocks > 0) {
        K key = deserializer.deserialize(null);

        long offset = dataInput.readLong();
        long blockId = dataInput.readLong();
        long numRecords = dataInput.readLong();

        keyData.add(new KeyData<K>(key, offset, 0, numRecords, blockId));
        numberOfBlocks--;
    }

    // Assign length to each keydata entry
    int numEntries = keyData.size();
    for (int i = 1; i < numEntries; i++) {
        KeyData<K> prev = keyData.get(i - 1);
        KeyData<K> current = keyData.get(i);

        prev.setLength(current.getOffset() - prev.getOffset());
    }

    if (numEntries > 0) {
        KeyData<K> last = keyData.get(numEntries - 1);
        last.setLength(metaDataStartPos - last.offset);
    }

    return keyData;
}

From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java

/**
 * To validate the current certificate and alias.
 *
 * @param alias       Alias of the certificate.
 * @param certificate Bas64 endcoded certificated.
 * @return response code based on the validation
 *///from   w ww .jav a2  s  .c  o  m
public ResponseCode validateCertificate(String alias, int tenantId, String certificate) {
    File trustStoreFile = new File(TRUST_STORE);
    ResponseCode responseCode = ResponseCode.SUCCESS;
    ByteArrayInputStream serverCert = null;

    try {
        localTrustStoreStream = new FileInputStream(trustStoreFile);
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD);
        if (StringUtils.isNotEmpty(alias) && trustStore.containsAlias(alias + "_" + tenantId)) {
            responseCode = ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE;
        }
        if (responseCode != ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE) {
            byte[] cert = (Base64.decodeBase64(certificate.getBytes(StandardCharsets.UTF_8)));
            serverCert = new ByteArrayInputStream(cert);

            if (serverCert.available() == 0) {
                responseCode = ResponseCode.CERTIFICATE_NOT_FOUND;
            } else {
                CertificateFactory cf = CertificateFactory.getInstance(CERTIFICATE_TYPE);
                while (serverCert.available() > 0) {
                    Certificate generatedCertificate = cf.generateCertificate(serverCert);
                    X509Certificate x509Certificate = (X509Certificate) generatedCertificate;
                    if (x509Certificate.getNotAfter().getTime() <= System.currentTimeMillis()) {
                        responseCode = ResponseCode.CERTIFICATE_EXPIRED;
                    }
                }
            }
        }
    } catch (IOException e) {
        log.error("I/O Exception while trying to load trust store while trying to check whether alias " + alias
                + " exists", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (CertificateException e) {
        log.error("Certificate Exception while trying to load trust store while trying to check whether alias "
                + alias + " exists", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (NoSuchAlgorithmException e) {
        log.error("No Such Algorithm Exception while trying to load trust store while trying to check whether "
                + "alias " + alias + " exists", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (KeyStoreException e) {
        log.error("KeyStore Exception while trying to load trust store while trying to check whether alias "
                + alias + " exists", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } finally {
        closeStreams(serverCert);
    }
    return responseCode;
}

From source file:hudson.console.ConsoleAnnotationOutputStream.java

/**
 * Called after we read the whole line of plain text, which is stored in {@link #buf}.
 * This method performs annotations and send the result to {@link #out}.
 *///from  w  ww.  j av a 2 s  . c  o m
protected void eol(byte[] in, int sz) throws IOException {
    line.reset();
    final StringBuffer strBuf = line.getStringBuffer();

    int next = ConsoleNote.findPreamble(in, 0, sz);

    List<ConsoleAnnotator<T>> annotators = null;

    {// perform byte[]->char[] while figuring out the char positions of the BLOBs
        int written = 0;
        while (next >= 0) {
            if (next > written) {
                lineOut.write(in, written, next - written);
                lineOut.flush();
                written = next;
            } else {
                assert next == written;
            }

            // character position of this annotation in this line
            final int charPos = strBuf.length();

            int rest = sz - next;
            ByteArrayInputStream b = new ByteArrayInputStream(in, next, rest);

            try {
                final ConsoleNote a = ConsoleNote.readFrom(new DataInputStream(b));
                if (a != null) {
                    if (annotators == null)
                        annotators = new ArrayList<ConsoleAnnotator<T>>();
                    annotators.add(new ConsoleAnnotator<T>() {
                        public ConsoleAnnotator annotate(T context, MarkupText text) {
                            return a.annotate(context, text, charPos);
                        }
                    });
                }
            } catch (IOException e) {
                // if we failed to resurrect an annotation, ignore it.
                LOGGER.log(Level.FINE, "Failed to resurrect annotation", e);
            } catch (ClassNotFoundException e) {
                LOGGER.log(Level.FINE, "Failed to resurrect annotation", e);
            }

            int bytesUsed = rest - b.available(); // bytes consumed by annotations
            written += bytesUsed;

            next = ConsoleNote.findPreamble(in, written, sz - written);
        }
        // finish the remaining bytes->chars conversion
        lineOut.write(in, written, sz - written);

        if (annotators != null) {
            // aggregate newly retrieved ConsoleAnnotators into the current one.
            if (ann != null)
                annotators.add(ann);
            ann = ConsoleAnnotator.combine(annotators);
        }
    }

    lineOut.flush();
    MarkupText mt = new MarkupText(strBuf.toString());
    if (ann != null)
        ann = ann.annotate(context, mt);
    out.write(mt.toString(true)); // this perform escapes
}

From source file:com.amazonaws.serverless.proxy.internal.servlet.AwsProxyHttpServletRequest.java

@Override
public ServletInputStream getInputStream() throws IOException {
    byte[] bodyBytes = request.getBody().getBytes();
    if (request.isBase64Encoded()) {
        bodyBytes = Base64.getDecoder().decode(request.getBody());
    }/*from ww w .j ava2  s. c om*/
    ByteArrayInputStream requestBodyStream = new ByteArrayInputStream(bodyBytes);
    return new ServletInputStream() {

        private ReadListener listener;

        @Override
        public boolean isFinished() {
            return true;
        }

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

        @Override
        public void setReadListener(ReadListener readListener) {
            listener = readListener;
            try {
                listener.onDataAvailable();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public int read() throws IOException {
            int readByte = requestBodyStream.read();
            if (requestBodyStream.available() == 0 && listener != null) {
                listener.onAllDataRead();
            }
            return readByte;
        }
    };
}

From source file:org.jopenray.client.RendererListener.java

private void handlePacket() throws IOException {
    byteCount += dataLength;//w  w  w. j  a v  a2s.  c  o m
    packetCount++;

    PrintStream out = System.out;
    boolean dump = false;
    ByteArrayInputStream bIn = new ByteArrayInputStream(udpData, 0, this.dataLength);
    int r = readInt16(bIn);
    if (r == 1) {
        out.println("===================================================================================");
    }
    out.print("Seq number:" + r);
    int flag = readInt16(bIn);
    out.print(" Flag:" + flag);
    int type = readInt16(bIn);
    out.print(" Type:" + type);
    int dir = readInt16(bIn);
    out.println(" Dir:" + dir + " dataSize:" + udpData.length);
    if (dir != 2000) {

        // Server -> Sunray
        int a = readInt16(bIn);
        int b = readInt16(bIn);
        int c = readInt16(bIn);
        int d = readInt16(bIn);
        out.println("Server -> Sunray:" + a + "," + b + "," + c + "," + d);
        boolean endOfFrame = false;
        while (bIn.available() > 0 && !endOfFrame) {
            String opCodeHeader = "";
            int opcode = bIn.read();
            opCodeHeader += "[ Opcode: " + opcode;
            int f = bIn.read();
            opCodeHeader += " Flag" + f;
            int oseq = readInt16(bIn);
            opCodeHeader += " OpcodeSeq:" + oseq;
            int x = readInt16(bIn);
            int y = readInt16(bIn);

            int w = readInt16(bIn);
            int h = readInt16(bIn);

            opCodeHeader += " x,y: " + x + "," + y + " w:" + w + " h:" + h + " ]";

            switch (opcode) {
            case 0x0: {
                endOfFrame = true;
                break;
            }
            case 0x03:
                out.println("0x03 Strange opcode " + opCodeHeader);
                break;
            case 0xA1:
                int ap1 = bIn.read();
                int ap2 = bIn.read();
                int ap3 = bIn.read();
                int ap4 = bIn.read();
                out.println("0xA1:" + ap1 + "," + ap2 + "," + ap3 + "," + ap4 + opCodeHeader);
                break;
            case 0xA2:
                // out.println("FillRect");
                int a2p1 = bIn.read();
                int a2p2 = bIn.read();
                int a2p3 = bIn.read();
                int a2p4 = bIn.read();
                out.println("FillRect: Color:" + a2p1 + "," + a2p2 + "," + a2p3 + "," + a2p4 + opCodeHeader);
                break;
            case 0xA3: {

                int a3p1 = bIn.read();
                int a3p2 = bIn.read();
                int a3p3 = bIn.read();
                int a3p4 = bIn.read();
                int nbBytesPerRow = round(w, 8) / 8;
                int nbBytes = round(nbBytesPerRow * h, 4);
                byte[] unkuonw = new byte[nbBytes];
                try {
                    int lRead = bIn.read(unkuonw);
                    out.println("FillRectBitmap: Color:" + a3p1 + "," + a3p2 + "," + a3p3 + "," + a3p4
                            + " | bytes/row:" + nbBytesPerRow + "l:" + nbBytes + " lRead:" + lRead
                            + opCodeHeader);

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                break;
            }
            case 0xA4:
                int xsrc = readInt16(bIn);
                int ysrc = readInt16(bIn);
                out.println("CopyRect from : " + xsrc + "," + ysrc + opCodeHeader);

                break;
            case 0xA5: {
                // out.println("SetRectBitmap");
                // err.println("SetRectBitmap not yet implemented");
                try {
                    Color c1 = readColor(bIn);
                    Color c2 = readColor(bIn);
                    int nbBytesPerRow = round(w, 8) / 8;
                    int nbBytes = round(nbBytesPerRow * h, 4);
                    byte[] unkuonw = new byte[nbBytes];

                    int lRead = bIn.read(unkuonw);

                    out.println("SetRectBitmap: " + w + "x" + h + " at " + x + "," + y + " Color:" + c1 + " / "
                            + c2 + " | bytes/row:" + nbBytesPerRow + " l:" + nbBytes + " lRead:" + lRead
                            + opCodeHeader);
                    if (nbBytes > 1024) {
                        out.println("! data too long:" + nbBytes);
                    } else {
                        HexDump.dump(unkuonw, 0, System.err, 0);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    dump = true;
                }

                break;
            }
            case 0xA6: {

                out.println("SetRect:" + opCodeHeader);
                int nbBytesPerRow = round(w * 3, 4);
                int nbBytes = round(nbBytesPerRow * h, 4);
                // int nbBytes=w*h;
                if (nbBytes > 1000000) {
                    System.out.println("Bad length:" + nbBytes);
                } else {
                    byte[] colors = new byte[nbBytes];

                    int lRead = bIn.read(colors);
                    if (lRead != nbBytes) {
                        System.out.println("Bad length:" + nbBytes + " != " + lRead);
                    }
                    // colors contains colors (r,g,b)
                }
                break;
            }
            case 0xA8: {
                int xbound = readInt16(bIn);
                int ybound = readInt16(bIn);
                int wbound = readInt16(bIn);
                int hbound = readInt16(bIn);
                out.println("SetMouseBound to: " + xbound + "," + ybound + " w:" + wbound + " h:" + hbound + " "
                        + opCodeHeader + opCodeHeader);

                break;
            }
            case 0xA9: {

                Color c1 = readColor(bIn);
                Color c2 = readColor(bIn);
                out.println("SetMousePointer pos:" + x + "," + y + " size:" + w + "x" + h + " Color:" + c1
                        + " , " + c2 + opCodeHeader);
                int l = (w * h) / 8;
                byte[] b1 = new byte[l];
                bIn.read(b1);
                out.println("Bitmap");
                // printBits(w, h, b1);

                byte[] b2 = new byte[l];
                bIn.read(b2);
                out.println("Mask");
                // printBits(w, h, b2);
                break;
            }
            case 0xAA:
                int aap1 = bIn.read();
                int aap2 = bIn.read();
                int aap3 = bIn.read();
                int aap4 = bIn.read();
                out.println("SetMousePosition: " + aap1 + "," + aap2 + "," + aap3 + "," + aap4 + opCodeHeader);
                break;
            case 0xAB:
                int ab1 = readInt16(bIn);
                int ab2 = readInt16(bIn);
                out.println("SetKeyLock: " + ab1 + " " + ab2 + opCodeHeader);

                break;
            case 0xAC:

                int ac1 = readInt16(bIn);
                int ac2 = readInt16(bIn);
                int ac3 = readInt16(bIn);
                int ac4 = readInt16(bIn);
                out.println(
                        "0xAC : " + ac1 + " , " + ac2 + "," + ac3 + " , " + ac4 + opCodeHeader + opCodeHeader);
                break;
            case 0xAD:
                out.println("0xAD" + opCodeHeader);

                int l = readInt16(bIn);
                // l = (l & 0xfffc) + 2;

                out.println("l: " + l);
                out.println("(l & 0xfffc) + 2 :" + (l & 0xfffc) + 2);
                byte[] unkuonwn = new byte[l];
                dump = true;
                try {
                    int lRead = bIn.read(unkuonwn);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                break;
            case 0xAF: {

                int p1 = bIn.read();
                int p2 = bIn.read();
                int p3 = bIn.read();
                int p4 = bIn.read();
                for (int i = 0; i < 8; i++) {
                    bIn.read();
                }
                if (p1 != 255 && p2 != 255 && p3 != 255 && p4 != 255) {
                    out.println("PAD:" + p1 + "," + p2 + "," + p3 + "," + p4 + opCodeHeader);
                } else {
                    out.println("PAD " + opCodeHeader);
                }
                break;
            }
            case 0xB1:

                out.println("AUDIO:" + r + "|" + flag + "|" + type + "|" + dir + " l:" + udpData.length + " "
                        + opCodeHeader);
                // outTest.print("AUDIO:"+r+"|"+flag+"|"+type+"|"+dir+" " +
                // opCodeHeader);
                /*
                 * int xbound = readInt16(bIn); int ybound = readInt16(bIn);
                 * int wbound = readInt16(bIn); int hbound = readInt16(bIn);
                 * out.println(" to: " + xbound + "," + ybound + " w:" +
                 * wbound + " h:" + hbound + " " + opCodeHeader +
                 * opCodeHeader); dump=true;
                 */

                int v1 = 0;
                int v2 = 0;
                int totalv1et2 = 0;
                int bigTotal = 0;
                while (bIn.available() >= 0) {
                    int b1 = bIn.read();
                    int b2 = bIn.read();
                    if (b1 == -1 && b2 == -1) {
                        // outTest.print(totalv1et2+" : big total: "+bigTotal);
                        break;
                    }
                    // soundOut.write(b2);
                    // soundOut.write(b1);

                    if (b1 == 0x7F && b2 == 0xFF) {
                        v1++;
                        bigTotal++;
                        totalv1et2++;
                        if (v2 > 0)
                            out.println("v2=" + v2);
                        v2 = 0;
                    } else if (b1 == 0x80 && b2 == 0x01) {
                        v2++;
                        totalv1et2++;
                        bigTotal++;
                        if (v1 > 0)
                            out.println("v1=" + v1);
                        v1 = 0;
                    } else {
                        if (v2 > 0)
                            out.println("v2=" + v2);
                        if (v1 > 0)
                            out.println("v1=" + v1);
                        out.println("Unknwon:" + b1 + " et " + b2 + "[" + (b1 * 256 + b2) + "] total v1+v2:"
                                + totalv1et2);
                        // if(totalv1et2>0)
                        // outTest.print(totalv1et2+",");
                        v1 = 0;
                        v2 = 0;
                        totalv1et2 = 0;
                    }
                    /*
                     * bIn.read(); bIn.read(); for (int j = 0; j < 8; j++) {
                     * for (int i = 0; i < 12; i++) {
                     * 
                     * int aaa1 = bIn.read(); int aaa2 = bIn.read(); if (i %
                     * 2 == 0) { soundOut.write(aaa2); soundOut.write(aaa1);
                     * } } }
                     */

                }
                // outTest.println();

                break;
            case 0xD1:
                out.println("0xD1 " + opCodeHeader + opCodeHeader);
                break;
            case 0xD8:
                out.println("0xD8 " + opCodeHeader + opCodeHeader);
                break;
            case 0xB0: {
                out.println("0xB0 " + opCodeHeader + opCodeHeader);
                int p1 = readInt16(bIn);

                int p2 = readInt16(bIn);
                int p3 = readInt16(bIn);
                int nb = readInt16(bIn);
                out.println(p1 + " ; " + p2 + " ; " + p3);
                for (int i = 0; i < nb; i++) {
                    int xx = readInt16(bIn);
                    int yy = readInt16(bIn);
                    int ww = readInt16(bIn);
                    int hh = readInt16(bIn);
                    out.println("[" + xx + "," + yy + " " + ww + "x" + hh + "]");
                }
                break;
            }
            case 0xB4: {
                // ??
                out.println("0xB4 " + opCodeHeader + opCodeHeader);

                for (int i = 0; i < 19; i++) {
                    int p1 = readInt16(bIn);
                    out.print(p1 + ",");
                }
                int end = readInt16(bIn);
                out.println(end);
                break;
            }
            case 0xB9: {
                // ??
                out.println("0xB9 " + opCodeHeader + opCodeHeader);
                break;
            }
            case 0xBF: {
                int le = readInt16(bIn);
                out.println("0xBF " + le + " bytes " + opCodeHeader);

                byte[] unknown = new byte[le];

                try {
                    int lRead = bIn.read(unknown);
                    if (lRead != le) {
                        out.println("Bad length:" + lRead + " / " + le);
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                break;
            }
            default:
                out.println("Unknown opcode:" + opcode + opCodeHeader);
                dump = true;
                endOfFrame = true;
                break;
            }
        }

    } else {
        out.println("Unknown packet direction:" + dir);
        if (dir != 0)
            dump = true;
    }
    if (dump) {
        HexDump.dump(udpData, 0, System.err, 0);
    }
}