Example usage for java.io DataInputStream DataInputStream

List of usage examples for java.io DataInputStream DataInputStream

Introduction

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

Prototype

public DataInputStream(InputStream in) 

Source Link

Document

Creates a DataInputStream that uses the specified underlying InputStream.

Usage

From source file:com.aliyun.openservices.tablestore.hadoop.Credential.java

public static Credential deserialize(String in) {
    if (in == null) {
        return null;
    }/* w w  w .  ja  v a  2 s  .  c o  m*/
    byte[] buf = Base64.decodeBase64(in);
    ByteArrayInputStream is = new ByteArrayInputStream(buf);
    DataInputStream din = new DataInputStream(is);
    try {
        return read(din);
    } catch (IOException ex) {
        return null;
    }
}

From source file:lirmm.inria.fr.data.DataMatrix.java

protected void loadMatrix(String file, int rowDimension, int columnDimension) {
    FileInputStream fstream;//from   ww  w. j  av  a  2s . co  m
    try {
        fstream = new FileInputStream(file);
        // Get the object of DataInputStream
        DataInputStream in = new DataInputStream(fstream);

        Set<Integer> cI = new HashSet();
        for (int i = 0; i < rowDimension; i++) {
            cI.add(i);
        }
        Set<Integer> cJ = new HashSet();
        for (int j = 0; j < columnDimension; j++) {
            cJ.add(j);
        }
        try (BufferedReader br = new BufferedReader(new InputStreamReader(in))) {
            String str;
            int z = 0;
            while ((str = br.readLine()) != null) {
                str = str.trim();
                if (str.startsWith("#")) {
                    continue;
                }
                if (str.trim().length() == 0) {
                    continue;
                }
                z++;
                StringTokenizer st = new StringTokenizer(str);
                String row_id = st.nextToken();
                String column_id = st.nextToken();
                double rating = Double.parseDouble(st.nextToken());
                Integer i, j;
                if (rowsMapping.containsKey(row_id)) {
                    i = rowsMapping.get(row_id);
                } else {
                    i = cI.iterator().next();
                    //                        i = cI.get(0);
                    cI.remove(i);
                    rowsMapping.put(row_id, i);
                }
                if (columnsMapping.containsKey(column_id)) {
                    j = columnsMapping.get(column_id);
                } else {
                    j = cJ.iterator().next();
                    //                        j = cJ.get(0);
                    cJ.remove(j);
                    columnsMapping.put(column_id, j);
                }
                setEntry(i, j, rating);
            }
        }

        for (OpenLongToDoubleHashMap.Iterator iterator = getEntries().iterator(); iterator.hasNext();) {
            iterator.advance();
            final long key = iterator.key();
            final int i, j;
            if (isTransposed()) {
                j = (int) (key / getRowDimension());
                i = (int) (key % getRowDimension());
            } else {
                i = (int) (key / getColumnDimension());
                j = (int) (key % getColumnDimension());
            }
            double v = rowNonZeroEntries.get(i);
            rowNonZeroEntries.put(i, v + 1);
            v = columnNonZeroEntries.get(j);
            columnNonZeroEntries.put(j, v + 1);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.pdfhow.diff.UploadServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request//from w w  w. j  a  va  2 s .  c o  m
 *            servlet request
 * @param response
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getParameter("getfile") != null && !request.getParameter("getfile").isEmpty()) {
        File file = new File(
                request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("getfile"));
        if (file.exists()) {
            int bytes = 0;
            ServletOutputStream op = response.getOutputStream();

            response.setContentType(getMimeType(file));
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");

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

            while ((in != null) && ((bytes = in.read(bbuf)) != -1)) {
                op.write(bbuf, 0, bytes);
            }

            in.close();
            op.flush();
            op.close();
        }
    } else if (request.getParameter("delfile") != null && !request.getParameter("delfile").isEmpty()) {
        File file = new File(
                request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("delfile"));
        if (file.exists()) {
            file.delete(); // TODO:check and report success
        }
    } else if (request.getParameter("getthumb") != null && !request.getParameter("getthumb").isEmpty()) {
        File file = new File(
                request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("getthumb"));
        if (file.exists()) {
            System.out.println(file.getAbsolutePath());
            String mimetype = getMimeType(file);
            if (mimetype.endsWith("png") || mimetype.endsWith("jpeg") || mimetype.endsWith("jpg")
                    || mimetype.endsWith("gif")) {
                BufferedImage im = ImageIO.read(file);
                if (im != null) {
                    BufferedImage thumb = Scalr.resize(im, 75);
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    if (mimetype.endsWith("png")) {
                        ImageIO.write(thumb, "PNG", os);
                        response.setContentType("image/png");
                    } else if (mimetype.endsWith("jpeg")) {
                        ImageIO.write(thumb, "jpg", os);
                        response.setContentType("image/jpeg");
                    } else if (mimetype.endsWith("jpg")) {
                        ImageIO.write(thumb, "jpg", os);
                        response.setContentType("image/jpeg");
                    } else {
                        ImageIO.write(thumb, "GIF", os);
                        response.setContentType("image/gif");
                    }
                    ServletOutputStream srvos = response.getOutputStream();
                    response.setContentLength(os.size());
                    response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
                    os.writeTo(srvos);
                    srvos.flush();
                    srvos.close();
                }
            }
        } // TODO: check and report success
    } else {
        PrintWriter writer = response.getWriter();
        writer.write("call POST with multipart form data");
    }
}

From source file:com.csipsimple.backup.SipSharedPreferencesHelper.java

@Override
public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState) {
    boolean forceBackup = (oldState == null);

    long fileModified = 1;
    if (prefsFiles != null) {
        fileModified = prefsFiles.lastModified();
    }//from ww w  .  j  a  v a  2  s  .  com
    try {
        if (!forceBackup) {
            FileInputStream instream = new FileInputStream(oldState.getFileDescriptor());
            DataInputStream in = new DataInputStream(instream);
            long lastModified = in.readLong();
            in.close();

            if (lastModified < fileModified) {
                forceBackup = true;
            }
        }
    } catch (IOException e) {
        Log.e(THIS_FILE, "Cannot manage previous local backup state", e);
        forceBackup = true;
    }

    Log.d(THIS_FILE, "Will backup profiles ? " + forceBackup);
    if (forceBackup) {
        JSONObject settings = SipProfileJson.serializeSipSettings(mContext);
        try {
            writeData(data, settings.toString());
        } catch (IOException e) {
            Log.e(THIS_FILE, "Cannot manage remote backup", e);
        }
    }

    try {
        FileOutputStream outstream = new FileOutputStream(newState.getFileDescriptor());
        DataOutputStream out = new DataOutputStream(outstream);
        out.writeLong(fileModified);
        out.close();
    } catch (IOException e) {
        Log.e(THIS_FILE, "Cannot manage final local backup state", e);
    }

}

From source file:edu.cornell.med.icb.goby.alignments.perms.PermutationReader.java

private void makeIndex(FastBufferedInputStream inputStream) throws IOException {
    input.position(0);/*from ww  w.  j a  v a  2 s  .c o  m*/
    final ObjectArrayList<Block> blocks = new ObjectArrayList<Block>();

    final DataInputStream dataInput = new DataInputStream(
            new FastBufferedInputStream(new FileInputStream(basename + ".perm")));
    try {
        long offset = 0;

        while (dataInput.available() > 0) {

            final Block block = new Block();
            block.offset = offset;
            block.n = dataInput.readInt();
            block.firstSmallIndex = dataInput.readInt();
            dataInput.skip(block.n * 4L);
            blocks.add(block);
            offset += block.n * 4L + 8L;
        }
        Collections.sort(blocks, SMALL_INDEX_COMPARATOR);
        indexBlocks = blocks.toArray(new Block[blocks.size()]);
    } finally {
        dataInput.close();
    }
}

From source file:ro.bmocanu.trafficproxy.peers.PeerCommunicationServer.java

/**
 * {@inheritDoc}//from ww w  . j ava2 s .  com
 */
@Override
protected void internalRun() throws Exception {
    if (!clientSocket.isClosed() && peerChannel.isConnectionUp()) {
        // nothing to do if the connection is still on
        return;
    }

    try {
        LOG.info("Waiting for incoming peer connections");
        clientSocket = serverSocket.accept();

        LOG.info("Peer connection established");
        peerChannel.setInputStream(new DataInputStream(new BufferedInputStream(clientSocket.getInputStream())));
        peerChannel.setOutputStream(
                new DataOutputStream(new BufferedOutputStream(clientSocket.getOutputStream())));
        peerChannel.setConnectionUp(true);

    } catch (SocketTimeoutException exception) {
        // this is ok, it is expected
    }
}

From source file:jp.co.cyberagent.jenkins.plugins.DeployStrategy.java

public String getVersion() {
    File versionFile = new File(mBuild.getWorkspace().getRemote() + "/VERSION");

    if (versionFile.exists()) {
        FileInputStream stream = null;
        DataInputStream in = null;
        InputStreamReader reader = null;
        BufferedReader br = null;
        try {//from ww w . ja  va 2s . c o m
            stream = new FileInputStream(versionFile);
            in = new DataInputStream(stream);
            reader = new InputStreamReader(in);
            br = new BufferedReader(reader);
            return br.readLine();
        } catch (Exception e) {
            getLogger().println(TAG + "Error: " + e.getMessage());
        } finally {
            try {
                if (stream != null)
                    stream.close();
                if (br != null)
                    br.close();
                if (reader != null)
                    reader.close();
                if (in != null)
                    in.close();
            } catch (IOException e) {
                getLogger().println(TAG + "Error: " + e.getMessage());
            }
        }
    }
    return null;
}

From source file:com.rhythm.louie.info.DownloadServlet.java

private void downloadFile(HttpServletRequest request, HttpServletResponse response, String filePath)
        throws IOException {
    if (filePath.isEmpty()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//from  w w w . java  2  s  .  co  m
    }
    File file = new File(filePath);
    int length = 0;
    try (ServletOutputStream outStream = response.getOutputStream()) {
        ServletContext context = getServletConfig().getServletContext();

        String mimetype = context.getMimeType(filePath);

        // sets response content type
        if (mimetype == null) {
            mimetype = "application/octet-stream";
        }
        response.setContentType(mimetype);
        response.setContentLength((int) file.length());
        String fileName = (new File(filePath)).getName();

        // sets HTTP header
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

        byte[] byteBuffer = new byte[4096];
        // reads the file's bytes and writes them to the response stream
        try (DataInputStream in = new DataInputStream(new FileInputStream(file))) {
            // reads the file's bytes and writes them to the response stream
            while ((in != null) && ((length = in.read(byteBuffer)) != -1)) {
                outStream.write(byteBuffer, 0, length);
            }
        }
    }
}

From source file:ja.lingo.engine.mergedindex.ChannelMergedIndex.java

public ChannelMergedIndex(String fileName, Map<String, IDictionaryIndex> indexFileNameToReaderMap)
        throws IOException {
    Arguments.assertNotNull("fileName", fileName);
    Arguments.assertNotNull("indexFileNameToReaderMap", indexFileNameToReaderMap);

    this.fileName = fileName;

    fisMappedByteBufferWrapper = new MappedByteBufferWrapper(fileName);

    ISliceReader sliceReader = new ByteBufferSliceReader(fisMappedByteBufferWrapper.getMappedByteBuffer());

    // read position + fill readerIntIdToReaderMap
    {//w  w  w . j  a v  a 2  s .  c o m
        ByteBuffer buffer = sliceReader.getSlice(SLICE_READER_INT_ID_TO_READER_ID_MAP);
        byte[] bytes = new byte[buffer.limit()];
        buffer.position(0);
        buffer.get(bytes);

        try {
            readerIntIdToReaderMap = _deserializeReaderIdToReaderMap(
                    new DataInputStream(new ByteArrayInputStream(bytes)), indexFileNameToReaderMap);
        } catch (IOException e) {
            Files.close(fisMappedByteBufferWrapper);
            throw e;
        }
    }

    groupsIndexLengthIntReader = new IntBufferIntReader(
            sliceReader.getSlice(SLICE_GROUPS_INDEX_LENGTH_LIST).asIntBuffer());
    groupsIntReader = new IntBufferIntReader(sliceReader.getSlice(SLICE_GROUPS_LIST).asIntBuffer());
}

From source file:com.lightboxtechnologies.spectrum.MRCoffeeClient.java

public void open(File pipe) throws IOException {
    sock.connect(new AFUNIXSocketAddress(pipe));
    in = new DataInputStream(sock.getInputStream());
    out = new DataOutputStream(sock.getOutputStream());
}