Example usage for java.io DataInputStream read

List of usage examples for java.io DataInputStream read

Introduction

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

Prototype

public final int read(byte b[]) throws IOException 

Source Link

Document

Reads some number of bytes from the contained input stream and stores them into the buffer array b.

Usage

From source file:de.tum.frm2.nicos_android.nicos.NicosClient.java

public void event_handler() {
    DataInputStream din = new DataInputStream(eventSocketIn);
    while (true) {
        try {//w  w w. ja va 2s . c  o  m
            // receive STX (1 byte) + eventcode (2) + length (4)
            byte[] start = new byte[7];
            try {
                //noinspection ResultOfMethodCallIgnored
                din.read(start);
            } catch (IOException e) {
                if (!disconnecting) {
                    signal("broken", "Server connection broken.");
                    _close();
                }
                return;
            }
            if (start[0] != daemon.STX) {
                // Every event starts with STX. Else, something's wrong.
                if (!disconnecting) {
                    signal("broken", "Server connection broken.");
                    _close();
                }
                return;
            }
            byte[] slice = Arrays.copyOfRange(start, 3, 7);
            ByteBuffer bb = ByteBuffer.wrap(slice);
            bb.order(ByteOrder.BIG_ENDIAN);

            // Get length, allocate byte buffer.
            int length = bb.getInt();
            byte[] buf = new byte[length];

            // Read length bytes and store them in buf.
            din.readFully(buf, 0, length);

            boolean should_signal = true;
            String event = null;
            Object data = null;
            try {
                // Stackoverflow magic to convert 2 bytes to int which can be compared in
                // daemon.command2event().
                int eventcode = ((start[1] & 0xff) << 8) | (start[2] & 0x00ff);
                event = daemon.command2event(eventcode);
                // serialized or raw data?
                if (daemon.eventNeedsUnserialize(event)) {
                    Unpickler unpickler = new Unpickler();
                    data = unpickler.loads(buf);
                } else {
                    data = buf;
                }
            } catch (Exception e) {
                // Garbled event
                should_signal = false;
            }
            if (should_signal) {
                signal(event, data);
            }
        } catch (Exception e) {
            if (!disconnecting) {
                signal("broken", "Server connection broken.");
                _close();
            }
            return;
        }
    }
}

From source file:br.org.indt.ndg.servlets.OpenRosaManagement.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    m_openRosaBD.setPortAndAddress(SystemProperties.getServerAddress());

    String action = request.getParameter(ACTION_PARAM);

    if (SET_AVAILABLE_FOR_USER.equals(action)) {
        String selectedImei = request.getParameter(SELECTED_IMEI_PARAM);
        String[] selectedSurveyIds = request.getParameterValues(SELECTED_SURVEY_ID_PARAM);
        if (selectedImei != null && selectedSurveyIds != null) {
            log.info("IMEI: " + selectedImei);
            for (int i = 0; i < selectedSurveyIds.length; i++) {
                log.info("Survey id:" + selectedSurveyIds[i]);
            }//  w w w  . j  a va 2  s.  c om
        }
        boolean result = m_openRosaBD.makeSurveysAvailableForImei(selectedImei, selectedSurveyIds);
        request.setAttribute(RESULT_ATTR, result);
        dispatchSurveysForUserSelectionPage(request, response);
    } else if (EXPORT_RESULTS_FOR_USER.equals(action)) {
        ServletOutputStream outputStream = null;
        FileInputStream fileInputStream = null;
        DataInputStream dataInputStream = null;
        File file = null;
        try {
            String zipFilename = m_openRosaBD.exportZippedResultsForUser("223344556677");
            file = new File(zipFilename);
            int length = 0;
            outputStream = response.getOutputStream();
            ServletContext context = getServletConfig().getServletContext();
            String mimetype = context.getMimeType("application/octet-stream");

            response.setContentType(mimetype);
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition", "attachment; filename=\"" + zipFilename + "\"");

            byte[] bbuf = new byte[1024];
            fileInputStream = new FileInputStream(file);
            dataInputStream = new DataInputStream(fileInputStream);

            while ((dataInputStream != null) && ((length = dataInputStream.read(bbuf)) != -1)) {
                outputStream.write(bbuf, 0, length);
            }
            outputStream.flush();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (fileInputStream != null)
                    fileInputStream.close();
                if (dataInputStream != null)
                    dataInputStream.close();
                if (fileInputStream != null)
                    fileInputStream.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            file.delete();
        }
    }
}

From source file:net.sf.gazpachoquest.rest.auth.TokenStore.java

/**
 * Load the current set of tokens from the token file. If reading the tokens
 * fails or the token file does not exist, tokens will be generated on
 * demand.//  w  w  w  .ja  va 2s  .  co m
 */
private void loadTokens() {
    if (tokenFile.isFile() && tokenFile.canRead()) {
        FileInputStream fin = null;
        DataInputStream keyInputStream = null;
        try {
            fin = new FileInputStream(tokenFile);
            keyInputStream = new DataInputStream(fin);
            int newCurrentToken = keyInputStream.readInt();
            long newNextUpdate = keyInputStream.readLong();
            SecretKey[] newKeys = new SecretKey[TOKEN_BUFFER_SIZE];
            for (int i = 0; i < newKeys.length; i++) {
                int isNull = keyInputStream.readInt();
                if (isNull == 1) {
                    int l = keyInputStream.readInt();
                    byte[] b = new byte[l];
                    keyInputStream.read(b);
                    newKeys[i] = new SecretKeySpec(b, HMAC_SHA1);
                } else {
                    newKeys[i] = null;
                }
            }

            // assign the tokes and schedule a next update
            nextUpdate = newNextUpdate;
            currentToken = newCurrentToken;
            currentTokens = newKeys;

        } catch (IOException e) {

            log.error("Failed to load cookie keys " + e.getMessage());

        } finally {

            if (keyInputStream != null) {
                try {
                    keyInputStream.close();
                } catch (IOException e) {
                }
            } else if (fin != null) {
                try {
                    fin.close();
                } catch (IOException e) {
                }
            }
        }
    }

    // if there was a failure to read the current tokens, create new ones
    if (currentTokens == null) {
        currentTokens = new SecretKey[TOKEN_BUFFER_SIZE];
        nextUpdate = System.currentTimeMillis();
        currentToken = 0;
    }
}

From source file:com.chaosinmotion.securechat.messages.SCMessageQueue.java

/**
 *  Process a data packet from the back end notification service. A data
 *  packet response form the back end has the format:
 *
 *  first byte//from  w ww  . j av  a2 s  . co  m
 *  0x20        Message
 *  0x21        Token response
 *  0x22        Login failure
 *
 *  Note login success is implicit; if login worked, we start receiving
 *  message notifications, starting with the backlog of stored messages
 *  waiting for us
 */

private void processDataPacket(byte[] data) {
    if (data.length == 0)
        return;

    if (data[0] == 0x20) {
        /*
         *  Process received message.
         */

        ByteArrayInputStream bais = new ByteArrayInputStream(data, 1, data.length - 1);
        DataInputStream dis = new DataInputStream(bais);

        try {
            boolean toflag = dis.readBoolean();
            int messageID = dis.readInt();
            int senderID = dis.readInt();
            String ts = dis.readUTF();
            String senderName = dis.readUTF();
            int messagelen = dis.readInt();
            byte[] message = new byte[messagelen];
            dis.read(message);

            dis.close();

            insertMessage(senderID, senderName, toflag, messageID, DateUtils.parseServerDate(ts), message);

        } catch (IOException e) {
            e.printStackTrace();
        }
    } else if (data[0] == 0x21) {
        /*
         * Received token; rest is string
         */

        try {
            String token = new String(data, 1, data.length - 1, "UTF-8");
            loginPhaseTwo(token);
        } catch (UnsupportedEncodingException e) {
            // SHould never happen
        }
    } else if (data[0] == 0x22) {
        /*
         *  Login failure. Close connection and start polling
         */

        closeConnection();
        startPolling("Login failure");
    }
}

From source file:org.sakaiproject.nakamura.auth.trusted.TokenStore.java

/**
 *
 *//*  w w  w  . j a  va2 s.c o  m*/
private void loadLocalSecretKeys() {
    FileInputStream fin = null;
    DataInputStream keyInputStream = null;
    try {
        fin = new FileInputStream(tokenFile);
        keyInputStream = new DataInputStream(fin);
        int newCurrentToken = keyInputStream.readInt();
        long newNextUpdate = keyInputStream.readLong();
        ExpiringSecretKey[] newKeys = new ExpiringSecretKey[5];
        for (int i = 0; i < newKeys.length; i++) {
            int isNull = keyInputStream.readInt();
            if (isNull == 1) {
                long expires = keyInputStream.readLong();
                String keyServerId = keyInputStream.readUTF();
                int l = keyInputStream.readInt();
                byte[] b = new byte[l];
                if (keyInputStream.read(b) != l) {
                    throw new IOException(
                            "Failed to read Key no " + i + " from Secret Keys, end of file reached ");
                }
                newKeys[i] = new ExpiringSecretKey(b, HMAC_SHA1, expires, keyServerId);
                getServerKeyCache().put(getCacheKey(keyServerId, i), newKeys[i].getSecretKeyData());
                LOG.info("Loaded Key {} from Local Store into {} ", getCacheKey(keyServerId, i),
                        getServerKeyCache());
            } else {
                newKeys[i] = null;
            }
        }
        keyInputStream.close();
        nextUpdate = newNextUpdate;
        secretKeyId = newCurrentToken;
        secretKeyRingBuffer = newKeys;

    } catch (IOException e) {
        LOG.error("Failed to load cookie keys " + e.getMessage());
    } finally {
        try {
            keyInputStream.close();
        } catch (Exception e) {
        }
        try {
            fin.close();
        } catch (Exception e) {
        }
    }
    if (secretKeyRingBuffer == null) {
        secretKeyRingBuffer = new ExpiringSecretKey[5];
        nextUpdate = System.currentTimeMillis();
        secretKeyId = 0;
    }
    if (debugCookies) {
        dumpSecretKeyRingBuffer(secretKeyRingBuffer);
    }
}

From source file:com.lrodriguez.SVNBrowser.java

private void doGetGetFile2(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    logDebug("dispatching serveFile request");
    if (request.getParameter("serveFile") != null) {
        if (request.getParameter("serveFile").indexOf("..") >= 0) {
            response.sendError(404);//  w w w  .j  av a 2 s  .c om
            System.err.println("******** Invalid serveFile attempt from " + request.getRemoteAddr());
            return;
        }
        String workingCopyDir = webappRoot
                + getInitParameter(REPOSITORY_DIR).replaceAll("[/\\\\]+", "\\" + File.separator);
        String fileName = workingCopyDir
                + request.getParameter("serveFile").replaceAll("[/\\\\]+", "\\" + File.separator);

        File f = new File(fileName);

        try {
            if (f.getCanonicalPath().indexOf(workingCopyDir) != 0 || !f.exists() || !f.isFile()
                    || f.isHidden()) {
                response.sendError(404);
                System.err.println(
                        "******** Invalid serveFile attempt " + fileName + " from " + request.getRemoteAddr());
                return;
            }
        } catch (IOException e) {
            e.printStackTrace();
            response.sendError(404);
            System.err.println(
                    "******** Invalid serveFile attempt " + fileName + " from " + request.getRemoteAddr());
            return;
        }
        int length = 0;
        byte[] bbuf = new byte[1024];
        DataInputStream in = new DataInputStream(new FileInputStream(f));
        response.setHeader("Content-disposition", "attachment; filename=\"" + request.getParameter("serveFile")
                .substring(request.getParameter("serveFile").lastIndexOf("/") + 1));
        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            response.getOutputStream().write(bbuf, 0, length);
        }
        in.close();
        response.getOutputStream().flush();
        response.getOutputStream().close();
        return;
    }
}

From source file:hd3gtv.embddb.network.DataBlock.java

/**
 * Import mode//  w  w w  .  j  ava  2  s  . c  o  m
 */
DataBlock(Protocol protocol, byte[] request_raw_datas) throws IOException {
    if (log.isTraceEnabled()) {
        log.trace("Get raw datas" + Hexview.LINESEPARATOR + Hexview.tracelog(request_raw_datas));
    }

    ByteArrayInputStream inputstream_client_request = new ByteArrayInputStream(request_raw_datas);

    DataInputStream dis = new DataInputStream(inputstream_client_request);

    byte[] app_socket_header_tag = new byte[Protocol.APP_SOCKET_HEADER_TAG.length];
    dis.readFully(app_socket_header_tag, 0, Protocol.APP_SOCKET_HEADER_TAG.length);

    if (Arrays.equals(Protocol.APP_SOCKET_HEADER_TAG, app_socket_header_tag) == false) {
        throw new IOException("Protocol error with app_socket_header_tag");
    }

    int version = dis.readInt();
    if (version != Protocol.VERSION) {
        throw new IOException(
                "Protocol error with version, this = " + Protocol.VERSION + " and dest = " + version);
    }

    byte tag = dis.readByte();
    if (tag != 0) {
        throw new IOException("Protocol error, can't found request_name raw datas");
    }

    int size = dis.readInt();
    if (size < 1) {
        throw new IOException(
                "Protocol error, can't found request_name raw datas size is too short (" + size + ")");
    }

    byte[] request_name_raw = new byte[size];
    dis.read(request_name_raw);
    request_name = new String(request_name_raw, Protocol.UTF8);

    tag = dis.readByte();
    if (tag != 1) {
        throw new IOException("Protocol error, can't found zip raw datas");
    }

    entries = new ArrayList<>(1);

    ZipInputStream request_zip = new ZipInputStream(dis);

    ZipEntry entry;
    while ((entry = request_zip.getNextEntry()) != null) {
        entries.add(new RequestEntry(entry, request_zip));
    }
    request_zip.close();
}

From source file:ClassFile.java

public boolean read(DataInputStream di, ConstantPoolInfo pool[]) throws IOException {
    int len;/*  www. j av  a2 s .  com*/

    name = pool[di.readShort()];
    len = di.readInt();
    data = new byte[len];
    len = di.read(data);
    if (len != data.length)
        return (false);
    return (true);
}

From source file:com.duroty.application.mail.actions.AttachmentAction.java

/**
 * DOCUMENT ME!/*from   w ww .j av  a 2s.co  m*/
 *
 * @param request DOCUMENT ME!
 * @param response DOCUMENT ME!
 *
 * @throws ServletException DOCUMENT ME!
 * @throws IOException DOCUMENT ME!
 */
protected void doDownload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    DataInputStream in = null;
    ByteArrayInputStream bais = null;
    ServletOutputStream op = null;

    try {
        String mid = request.getParameter("mid");
        String part = request.getParameter("part");

        Mail filesInstance = getMailInstance(request);

        MailPartObj obj = filesInstance.getAttachment(mid, part);

        int length = 0;
        op = response.getOutputStream();

        String mimetype = obj.getContentType();

        //
        //  Set the response and go!
        //
        //  Yes, I know that the RFC says 'attachment'.  Unfortunately, IE has a typo
        //  in it somewhere, and Netscape seems to accept this typing as well.
        //
        response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
        response.setContentLength((int) obj.getSize());
        response.setHeader("Content-Disposition", "attachement; filename=\"" + obj.getName() + "\"");
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "max-age=0");

        //
        //  Stream to the requester.
        //
        byte[] bbuf = new byte[1024];
        bais = new ByteArrayInputStream(obj.getAttachent());
        in = new DataInputStream(bais);

        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            op.write(bbuf, 0, length);
        }
    } catch (Exception ex) {
    } finally {
        try {
            op.flush();
        } catch (Exception ex) {
        }

        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(op);
    }
}

From source file:com.duroty.application.files.actions.DownloadFileAction.java

/**
 * DOCUMENT ME!/*from   w  w w  .j  a v  a 2 s .  c om*/
 *
 * @param request DOCUMENT ME!
 * @param response DOCUMENT ME!
 *
 * @throws ServletException DOCUMENT ME!
 * @throws IOException DOCUMENT ME!
 */
protected void doDownload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    DataInputStream in = null;
    ByteArrayInputStream bais = null;
    ServletOutputStream op = null;

    try {
        String mid = request.getParameter("mid");
        String part = request.getParameter("part");

        Files filesInstance = getFilesInstance(request);

        MailPartObj obj = filesInstance.getAttachment(mid, part);

        int length = 0;
        op = response.getOutputStream();

        String mimetype = obj.getContentType();

        //
        //  Set the response and go!
        //
        //  Yes, I know that the RFC says 'attachment'.  Unfortunately, IE has a typo
        //  in it somewhere, and Netscape seems to accept this typing as well.
        //
        response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
        response.setContentLength((int) obj.getSize());
        response.setHeader("Content-Disposition", "attachement; filename=\"" + obj.getName() + "\"");
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "max-age=0");

        //
        //  Stream to the requester.
        //
        byte[] bbuf = new byte[1024];
        bais = new ByteArrayInputStream(obj.getAttachent());
        in = new DataInputStream(bais);

        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            op.write(bbuf, 0, length);
        }
    } catch (Exception ex) {
    } finally {
        try {
            op.flush();
        } catch (Exception ex) {
        }

        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(op);
    }
}