Example usage for java.io DataInputStream readByte

List of usage examples for java.io DataInputStream readByte

Introduction

In this page you can find the example usage for java.io DataInputStream readByte.

Prototype

public final byte readByte() throws IOException 

Source Link

Document

See the general contract of the readByte method of DataInput.

Usage

From source file:com.jivesoftware.os.amza.service.replication.http.endpoints.AmzaReplicationRestEndpoints.java

@POST
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Path("/ackBatch")
public Response ackBatch(InputStream is) {
    try {//from   w ww  .j  av  a  2s  .  co  m

        DataInputStream in = new DataInputStream(is);
        try {

            while (in.readByte() == 1) {

                int length = in.readShort();
                byte[] bytes = new byte[length];
                in.readFully(bytes);
                VersionedPartitionName versionedPartitionName = amzaInterner.internVersionedPartitionName(bytes,
                        0, length);

                length = in.readShort();
                bytes = new byte[length];
                in.readFully(bytes);
                RingMember ringMember = amzaInterner.internRingMember(bytes, 0, length);

                long takeSessionId = in.readLong();
                long takeSharedKey = in.readLong();
                long txId = in.readLong();
                long leadershipToken = in.readLong();

                amzaInstance.rowsTaken(ringMember, takeSessionId, takeSharedKey, versionedPartitionName, txId,
                        leadershipToken);

            }

            if (in.readByte() == 1) {
                int length = in.readShort();
                byte[] bytes = new byte[length];
                in.readFully(bytes);
                RingMember ringMember = amzaInterner.internRingMember(bytes, 0, length);

                long takeSessionId = in.readLong();
                long takeSharedKey = in.readLong();

                amzaInstance.pong(ringMember, takeSessionId, takeSharedKey);
            }

            return Response.ok(conf.asByteArray(Boolean.TRUE)).build();

        } finally {
            try {
                in.close();
            } catch (Exception x) {
                LOG.error("Failed to close input stream", x);
            }
        }

    } catch (Exception x) {
        LOG.warn("Failed ackBatch", x);
        return ResponseHelper.INSTANCE.errorResponse("Failed ackBatch.", x);
    } finally {
        amzaStats.pongsReceived.increment();
    }
}

From source file:edu.cornell.med.icb.goby.compression.MessageChunksReader.java

private boolean confirmDelimiter(DataInputStream in) throws IOException {

    for (int i = 0; i < MessageChunksWriter.DELIMITER_LENGTH; i++) {
        if (in.available() == 0) {
            return false;
        }/*from   w  w  w.  ja va  2s . com*/
        final byte b = in.readByte();
        bytesRead += 1;
        if (b != MessageChunksWriter.DELIMITER_CONTENT) {
            return false;
        }
    }

    return true;
}

From source file:bankingclient.DNFrame.java

public DNFrame(MainFrame vmain) {

    initComponents();/*from   w ww.  j  a  va2 s  . c  o  m*/

    this.jTextField1.setText("");
    this.jTextField2.setText("");
    this.jTextField_cmt.setText("");
    this.jTextField_sdt.setText("");

    this.main = vmain;
    noAcc = new NewOrOldAccFrame(this);
    this.setVisible(false);
    jL_sdt.setVisible(false);
    jL_cmtnd.setVisible(false);
    jTextField_cmt.setVisible(false);
    jTextField_sdt.setVisible(false);

    jBt_dn.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            if (!jCheck_qmk.isSelected()) {
                try {
                    Socket client = new Socket("113.22.46.207", 6013);
                    DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                    dout.writeByte(2);
                    dout.writeUTF(jTextField1.getText() + "\n" + jTextField2.getText());
                    dout.flush();
                    while (true) {
                        break;
                    }
                    DataInputStream din = new DataInputStream(client.getInputStream());
                    byte check = din.readByte();
                    if (check == 1) {
                        noAcc.setVisible(true);
                        DNFrame.this.setVisible(false);
                        noAcc.setMainCustomer(jTextField1.getText());

                    } else {
                        JOptionPane.showMessageDialog(new JFrame(),
                                "Tn ?ang Nhp Khng Tn Ti, hoac mat khau sai");
                    }

                } catch (Exception ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(rootPane, "C Li Kt Ni Mng....");
                }
            } else if ((!jTextField_cmt.getText().equals("")) && (!jTextField_sdt.getText().equals(""))
                    && (NumberUtils.isNumber(jTextField_cmt.getText()))
                    && (NumberUtils.isNumber(jTextField_sdt.getText()))) {
                try {
                    Socket client = new Socket("113.22.46.207", 6013);
                    DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                    dout.writeByte(9);
                    dout.writeUTF(jTextField1.getText() + "\n" + jTextField_sdt.getText() + "\n"
                            + jTextField_cmt.getText());
                    dout.flush();
                    DataInputStream din = new DataInputStream(client.getInputStream());
                    byte check = din.readByte();
                    if (check == 1) {
                        noAcc.setVisible(true);
                        DNFrame.this.setVisible(false);
                        noAcc.setMainCustomer(jTextField1.getText());
                    } else {
                        JOptionPane.showMessageDialog(new JFrame(), "Khong dang nhap duoc, thong tin sai");
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else {
                JOptionPane.showMessageDialog(new JFrame(), "Can dien day du thong tin va dung mau");
            }
        }
    });
    jBt_ql.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            main.setVisible(true);
            DNFrame.this.setVisible(false);
        }
    });
    jCheck_qmk.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (jCheck_qmk.isSelected()) {
                jL_sdt.setVisible(true);
                jL_cmtnd.setVisible(true);
                jTextField_cmt.setVisible(true);
                jTextField_sdt.setVisible(true);
            } else {
                jL_sdt.setVisible(false);
                jL_cmtnd.setVisible(false);
                jTextField_cmt.setVisible(false);
                jTextField_sdt.setVisible(false);
            }
        }
    });
}

From source file:org.rifidi.emulator.io.comm.serial.SerialCommunicationIncomingMessageHandler.java

public void run() {
    // byte[] message = null;
    DataBuffer<byte[]> newBuffer = host.getReceiveBuffer();
    ArrayList<Byte> receivedData = new ArrayList<Byte>();

    boolean keepRunning = true;

    DataInputStream dataStream = new DataInputStream(serialIn);

    while (keepRunning) {

        boolean eof = false;

        /* Read as fully as we can */
        while (!eof) {

            try {
                /* Attempt to read in a byte */
                receivedData.add(new Byte(dataStream.readByte()));
                if (dataStream.available() <= 0) {
                    eof = true;//  ww w  .j  a  v  a  2  s. c o m
                }
            } catch (EOFException eofe) {
                /* Indicate end of file */
                eof = true;
            } catch (IOException e) {
                logger.error(e.getMessage());
                eof = true;
            }
        }

        /* Check that we have something to "receive" */
        if (!receivedData.isEmpty()) {
            logger.debug("Back in the if statement");
            /* Construct an array of bytes */
            byte[] receivedBytes = new byte[receivedData.size()];
            for (int i = 0; i < receivedData.size(); i++) {
                receivedBytes[i] = receivedData.get(i).byteValue();
            }
            receivedData.clear();
            if (keepRunning) {
                /* Actually add to the receive buffer */
                try {
                    logger.debug("Adding to buffer: " + receivedBytes);
                    List<byte[]> listOfBytes = this.host.getProtocol().removeProtocol(receivedBytes);
                    for (byte[] b : listOfBytes) {
                        newBuffer.addToBuffer(b);
                    }
                    String x = "";
                    for (byte i : receivedBytes) {
                        x += String.format("%1$02x", i) + " ";
                    }
                    this.host.getConsoleLogger().info("<INPUT> " + x + "</INPUT>");
                } catch (DataBufferInterruptedException e) {
                    logger.error(e.getMessage());
                    keepRunning = false;
                } catch (ProtocolValidationException e) {
                    logger.error(e.getMessage());
                    keepRunning = false;
                }
            }
        }
    }
}

From source file:ubic.gemma.core.analysis.preprocess.batcheffects.AffyScanDateExtractor.java

private int readIntBigEndian(DataInputStream dis) throws IOException {
    byte[] buf = new byte[4];

    for (int i = 0; i < buf.length; i++) {
        buf[i] = dis.readByte();
    }//from   w  ww  . j  a v  a 2s  .c  om

    return ByteBuffer.wrap(buf).order(ByteOrder.BIG_ENDIAN).getInt();
}

From source file:org.apache.hadoop.hdfs.server.namenode.TestStorageRestore.java

/**
 * This function returns a md5 hash of a file.
 *
 * @param file input file//from   ww w . ja  va 2  s .  c  o m
 * @return The md5 string
 */
public String getFileMD5(File file) throws Exception {
    String res = new String();
    MessageDigest mD = MessageDigest.getInstance("MD5");
    DataInputStream dis = new DataInputStream(new FileInputStream(file));

    try {
        while (true) {
            mD.update(dis.readByte());
        }
    } catch (EOFException eof) {
    }

    BigInteger bigInt = new BigInteger(1, mD.digest());
    res = bigInt.toString(16);
    dis.close();

    return res;
}

From source file:org.apache.hadoop.security.Credentials.java

/**
 * Convenience method for reading a token storage file directly from a 
 * datainputstream//from w w  w  .  j av a 2s.  com
 */
public void readTokenStorageStream(DataInputStream in) throws IOException {
    byte[] magic = new byte[TOKEN_STORAGE_MAGIC.length];
    in.readFully(magic);
    if (!Arrays.equals(magic, TOKEN_STORAGE_MAGIC)) {
        throw new IOException("Bad header found in token storage.");
    }
    byte version = in.readByte();
    if (version != TOKEN_STORAGE_VERSION) {
        throw new IOException("Unknown version " + version + " in token storage.");
    }
    readFields(in);
}

From source file:org.kaaproject.kaa.server.transports.http.transport.HttpTestClient.java

@Override
public void run() {
    logger.trace("Test: " + testId + " started...");
    IOException error = null;//  w  w  w . j a v a  2s. c  om
    try {
        //connection.setChunkedStreamingMode(2048);
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", objects.getContentType());

        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        objects.dumbObjects(out);
        out.flush();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
        error = e;
    }
    List<Byte> bodyArray = new Vector<>();

    try {
        DataInputStream r = new DataInputStream(connection.getInputStream());
        while (true) {
            bodyArray.add(new Byte(r.readByte()));
        }
    } catch (EOFException eof) {

    } catch (IOException e) {
        e.printStackTrace();
        error = e;
    }
    byte[] body = new byte[bodyArray.size()];
    for (int i = 0; i < body.length; i++) {
        body[i] = bodyArray.get(i);
    }
    processComplete(error, connection.getHeaderFields(), body);
}

From source file:org.openxdata.server.FormsServer.java

/**
 * Called when a new connection has been received. Failures are not handled
 * in this class as different servers (BT,SMS, etc) may want to handle them
 * differently.// w ww.j a v a  2s  .c o m
 * 
 * @param dis - the stream to read from.
 * @param dos - the stream to write to.
 */
public void processConnection(InputStream disParam, OutputStream dosParam) {

    ZOutputStream gzip = new ZOutputStream(dosParam, JZlib.Z_BEST_COMPRESSION);
    DataOutputStream zdos = new DataOutputStream(gzip);

    byte responseStatus = ResponseStatus.STATUS_ERROR;

    try {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataInputStream dis = new DataInputStream(disParam);

            String name = dis.readUTF();
            String password = dis.readUTF();
            String serializer = dis.readUTF();
            String locale = dis.readUTF();

            byte action = dis.readByte();

            User user = authenticationService.authenticate(name, password);
            if (user == null)
                responseStatus = ResponseStatus.STATUS_ACCESS_DENIED;
            else {
                DataOutputStream dosTemp = new DataOutputStream(baos);

                if (action == ACTION_DOWNLOAD_FORMS)
                    formDownloadService.downloadForms(dosTemp, serializer, locale);
                else if (action == ACTION_UPLOAD_DATA)
                    submitXforms(dis, dosTemp, serializer);
                else if (action == ACTION_DOWNLOAD_USERS)
                    formDownloadService.downloadUsers(dosTemp, serializer);
                else if (action == ACTION_DOWNLOAD_USERS_AND_FORMS)
                    downloadUsersAndForms(dis.readInt(), dosTemp, serializer, locale);
                else if (action == ACTION_DOWNLOAD_STUDY_LIST)
                    formDownloadService.downloadStudies(dosTemp, serializer, locale);
                else if (action == ACTION_DOWNLOAD_LANGUAGES)
                    formDownloadService.downloadLocales(dis, dosTemp, serializer);
                else if (action == ACTION_DOWNLOAD_MENU_TEXT)
                    formDownloadService.downloadMenuText(dis, dosTemp, serializer, locale);
                else if (action == ACTION_DOWNLOAD_STUDY_FORMS)
                    formDownloadService.downloadForms(dis.readInt(), zdos, serializer, locale);
                else if (action == ACTION_DOWNLOAD_USERS_AND_ALL_FORMS)
                    downloadUsersAndAllForms(dosTemp, serializer, locale);

                responseStatus = ResponseStatus.STATUS_SUCCESS;
            }

            zdos.writeByte(responseStatus);

            if (responseStatus == ResponseStatus.STATUS_SUCCESS) {
                zdos.write(baos.toByteArray());
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            zdos.writeByte(responseStatus);
        } finally {
            zdos.flush();
            gzip.finish();
        }
    } catch (IOException e) {
        // this is for exceptions occurring in the catch or finally clauses.
        log.error(e.getMessage(), e);
    }
}

From source file:ubic.gemma.analysis.preprocess.batcheffects.AffyScanDateExtractor.java

private String readGCOSString(DataInputStream str) throws IOException {
    int fieldLength = readIntLittleEndian(str);
    StringBuilder buf = new StringBuilder();
    for (int i = 0; i < fieldLength; i++) {
        if (str.available() == 0)
            throw new IOException("Reached end of file without string end");
        buf.append(new String(new byte[] { str.readByte() }, "US-ASCII"));
    }/*from  ww w  . j a va  2s .  c  o m*/
    String field = buf.toString();
    return field;
}