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:com.alphabetbloc.accessmrs.services.SyncAdapter.java

/**
 * Downloads a stream of Patient Table and Obs Table from OpenMRS, stores it
 * to temp file/*from  w  w w. j a  v  a 2 s.com*/
 * 
 * @param httpclient
 * 
 * @return the temporary file
 */
private File downloadObsStream(HttpClient client, SyncResult syncResult) {

    // No accurate download size on stream, so hack periodic update
    SyncManager.sLoopCount.set(10);
    SyncManager.sLoopProgress.set(0);
    mExecutor.schedule(new Runnable() {
        public void run() {
            // increase 1%/7s (i.e. slower than 1min timeout)
            SyncManager.sLoopProgress.getAndIncrement();
            if (SyncManager.sLoopProgress.get() < 9)
                mExecutor.schedule(this, 7000, TimeUnit.MILLISECONDS);
        }
    }, 1000, TimeUnit.MILLISECONDS);

    // Download File
    File tempFile = null;
    try {
        tempFile = File.createTempFile(".omrs", "-stream", mContext.getFilesDir());
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tempFile));
        DataInputStream dis = NetworkUtils.getOdkStream(client, NetworkUtils.getPatientDownloadUrl());

        if (App.DEBUG)
            Log.v("SYNC BENCHMARK", "Download with buffer size=\n" + 8192);
        if (dis != null) {

            byte[] buffer = new byte[8192]; // increasing this from 4096 to
            // improve performance (testing)
            int count = 0;
            while ((count = dis.read(buffer)) > 0) {
                bos.write(buffer, 0, count);
            }

            bos.close();
            dis.close();
        }

    } catch (Exception e) {
        FileUtils.deleteFile(tempFile.getAbsolutePath());
        e.printStackTrace();
        ++syncResult.stats.numIoExceptions;
        return null;
    }

    return tempFile;
}

From source file:org.eclipse.gyrex.cloud.internal.queue.Message.java

/**
 * Creates a new instance./*from   ww  w  .j  a v  a2 s  . c om*/
 * 
 * @param zooKeeperQueue
 * @param messageId
 * @param record
 * @param stat
 * @throws IOException
 */
public Message(final String messageId, final ZooKeeperQueue zooKeeperQueue, final byte[] record,
        final Stat stat) throws IOException {
    this.messageId = messageId;
    this.zooKeeperQueue = zooKeeperQueue;
    queueId = zooKeeperQueue.id;
    zkNodeDataVersion = stat.getVersion();

    final DataInputStream din = new DataInputStream(new ByteArrayInputStream(record));

    // serialized format version
    final int formatVersion = din.readInt();
    if (formatVersion != 1)
        throw new IllegalArgumentException(String
                .format("invalid record data: version mismatch (expected %d, found %d)", 1, formatVersion));

    // timeout
    invisibleTimeoutTS = din.readLong();

    // body size
    final int length = din.readInt();

    // body
    body = new byte[length];
    final int read = din.read(body);
    if (read != length)
        throw new IllegalArgumentException(
                String.format("invalid record data: body size mismatch (expected %d, read %d)", length, read));
}

From source file:org.apache.hadoop.hbase.rest.TestTableScan.java

/**
 * Read protobuf stream./*w  w  w.j a v a  2  s  .  c  o  m*/
 * @param inputStream the input stream
 * @return The number of rows in the cell set model.
 * @throws IOException Signals that an I/O exception has occurred.
 */
public int readProtobufStream(InputStream inputStream) throws IOException {
    DataInputStream stream = new DataInputStream(inputStream);
    CellSetModel model = null;
    int rowCount = 0;
    try {
        while (true) {
            byte[] lengthBytes = new byte[2];
            int readBytes = stream.read(lengthBytes);
            if (readBytes == -1) {
                break;
            }
            assertEquals(2, readBytes);
            int length = Bytes.toShort(lengthBytes);
            byte[] cellset = new byte[length];
            stream.read(cellset);
            model = new CellSetModel();
            model.getObjectFromMessage(cellset);
            checkRowsNotNull(model);
            rowCount = rowCount + TestScannerResource.countCellSet(model);
        }
    } catch (EOFException exp) {
        exp.printStackTrace();
    } finally {
        stream.close();
    }
    return rowCount;
}

From source file:com.drive.student.xutils.HttpUtils.java

/**
 * Server/*ww w  .  ja  v  a  2s. co  m*/
 *
 * @param urlStr
 *            ?
 * @param serverFileName
 *            ????? image.jpg
 * @param uploadFile
 *            ? /sdcard/a.jpg
 */
public void uploadFile(String urlStr, String serverFileName, File uploadFile) {
    try {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setChunkedStreamingMode(1024 * 1024);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Content-Type", "multipart/form-data;file=" + uploadFile.getName());
        conn.setRequestProperty("filename", uploadFile.getName());
        OutputStream out = new DataOutputStream(conn.getOutputStream());
        DataInputStream in = new DataInputStream(new FileInputStream(uploadFile));
        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
        }
        in.close();
        out.flush();
        out.close();

        int response = conn.getResponseCode();

        if (response == 200) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            LogUtil.e("hxk", "upload file success-->>");
        } else {
            LogUtil.e("hxk", "upload file fail-->> response = " + response);
        }
    } catch (Exception e) {
        e.printStackTrace();
        LogUtil.e("hxk", "upload file fail-->>");
    }
}

From source file:org.mrgeo.vector.mrsvector.VectorTile.java

protected static BlobHeader parseHeader(final DataInputStream dis) throws IOException {
    final int len = dis.readInt();
    final byte[] blobHeader = new byte[len];
    dis.read(blobHeader);

    return BlobHeader.parseFrom(blobHeader);
}

From source file:org.mrgeo.vector.mrsvector.VectorTile.java

protected static InputStream parseBlob(final DataInputStream dis, final BlobHeader header) throws IOException {
    final byte[] blob = new byte[header.getDatasize()];
    dis.read(blob);

    final Blob b = Blob.parseFrom(blob);

    InputStream blobData;/*from  w w  w  . j ava 2  s  . c  o m*/
    if (b.hasZlibData()) {
        blobData = new InflaterInputStream(b.getZlibData().newInput());
    } else {
        blobData = b.getRaw().newInput();
    }

    return blobData;
}

From source file:org.apache.accumulo.core.client.mock.MockTableOperationsImpl.java

@Override
public void importDirectory(String tableName, String dir, String failureDir, boolean setTime)
        throws IOException, AccumuloException, AccumuloSecurityException, TableNotFoundException {
    long time = System.currentTimeMillis();
    MockTable table = acu.tables.get(tableName);
    if (table == null) {
        throw new TableNotFoundException(null, tableName, "The table was not found");
    }// w  w  w.j a va2s  . c o  m
    Path importPath = new Path(dir);
    Path failurePath = new Path(failureDir);

    FileSystem fs = acu.getFileSystem();
    /*
     * check preconditions
     */
    // directories are directories
    if (fs.isFile(importPath)) {
        throw new IOException("Import path must be a directory.");
    }
    if (fs.isFile(failurePath)) {
        throw new IOException("Failure path must be a directory.");
    }
    // failures are writable
    Path createPath = failurePath.suffix("/.createFile");
    FSDataOutputStream createStream = null;
    try {
        createStream = fs.create(createPath);
    } catch (IOException e) {
        throw new IOException("Error path is not writable.");
    } finally {
        if (createStream != null) {
            createStream.close();
        }
    }
    fs.delete(createPath, false);
    // failures are empty
    FileStatus[] failureChildStats = fs.listStatus(failurePath);
    if (failureChildStats.length > 0) {
        throw new IOException("Error path must be empty.");
    }
    /*
     * Begin the import - iterate the files in the path
     */
    for (FileStatus importStatus : fs.listStatus(importPath)) {
        try {
            FileSKVIterator importIterator = FileOperations.getInstance().openReader(
                    importStatus.getPath().toString(), true, fs, fs.getConf(),
                    AccumuloConfiguration.getDefaultConfiguration());
            while (importIterator.hasTop()) {
                Key key = importIterator.getTopKey();
                Value value = importIterator.getTopValue();
                if (setTime) {
                    key.setTimestamp(time);
                }
                Mutation mutation = new Mutation(key.getRow());
                if (!key.isDeleted()) {
                    mutation.put(key.getColumnFamily(), key.getColumnQualifier(),
                            new ColumnVisibility(key.getColumnVisibilityData().toArray()), key.getTimestamp(),
                            value);
                } else {
                    mutation.putDelete(key.getColumnFamily(), key.getColumnQualifier(),
                            new ColumnVisibility(key.getColumnVisibilityData().toArray()), key.getTimestamp());
                }
                table.addMutation(mutation);
                importIterator.next();
            }
        } catch (Exception e) {
            FSDataOutputStream failureWriter = null;
            DataInputStream failureReader = null;
            try {
                failureWriter = fs.create(failurePath.suffix("/" + importStatus.getPath().getName()));
                failureReader = fs.open(importStatus.getPath());
                int read = 0;
                byte[] buffer = new byte[1024];
                while (-1 != (read = failureReader.read(buffer))) {
                    failureWriter.write(buffer, 0, read);
                }
            } finally {
                if (failureReader != null)
                    failureReader.close();
                if (failureWriter != null)
                    failureWriter.close();
            }
        }
        fs.delete(importStatus.getPath(), true);
    }
}

From source file:com.inter.trade.view.slideplayview.util.AbFileUtil.java

/**
 * ??byte[].//from   www.  j  a  v  a2s . c o m
 * @param imgByte byte[]
 * @param fileName ?????.jpg
 * @param type ???AbConstant
 * @param newWidth 
 * @param newHeight 
 * @return Bitmap 
 */
public static Bitmap getBitmapFormByte(byte[] imgByte, String fileName, int type, int newWidth, int newHeight) {
    FileOutputStream fos = null;
    DataInputStream dis = null;
    ByteArrayInputStream bis = null;
    Bitmap b = null;
    File file = null;
    try {
        if (imgByte != null) {
            File sdcardDir = Environment.getExternalStorageDirectory();
            String path = sdcardDir.getAbsolutePath() + downPathImageDir;
            file = new File(path + fileName);

            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            int readLength = 0;
            bis = new ByteArrayInputStream(imgByte);
            dis = new DataInputStream(bis);
            byte[] buffer = new byte[1024];

            while ((readLength = dis.read(buffer)) != -1) {
                fos.write(buffer, 0, readLength);
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                }
            }
            fos.flush();

            b = getBitmapFromSD(file, type, newWidth, newHeight);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (dis != null) {
            try {
                dis.close();
            } catch (Exception e) {
            }
        }
        if (bis != null) {
            try {
                bis.close();
            } catch (Exception e) {
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (Exception e) {
            }
        }
    }
    return b;
}

From source file:com.ephesoft.gxt.foldermanager.server.UploadDownloadFilesServlet.java

private void downloadFile(HttpServletRequest req, HttpServletResponse response,
        String currentFileDownloadPath) {
    DataInputStream in = null;
    ServletOutputStream outStream = null;
    try {//from  w w w .j  a v a 2  s  .  c  om
        outStream = response.getOutputStream();
        File file = new File(currentFileDownloadPath);
        int length = 0;
        String mimetype = "application/octet-stream";
        response.setContentType(mimetype);
        response.setContentLength((int) file.length());
        String fileName = file.getName();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        byte[] byteBuffer = new byte[1024];
        in = new DataInputStream(new FileInputStream(file));
        while ((in != null) && ((length = in.read(byteBuffer)) != -1)) {
            outStream.write(byteBuffer, 0, length);
        }
    } catch (IOException e) {
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
        if (outStream != null) {
            try {
                outStream.flush();
            } catch (IOException e) {
            }
            try {
                outStream.close();
            } catch (IOException e) {
            }

        }
    }
}

From source file:com.ephesoft.dcma.gwt.foldermanager.server.UploadDownloadFilesServlet.java

private void downloadFile(HttpServletResponse response, String currentFileDownloadPath) {
    LOG.info(DOWNLOADING_FILE_FROM_PATH + currentFileDownloadPath);
    DataInputStream inputStream = null;
    ServletOutputStream outStream = null;
    try {//w w  w  . ja  v a  2  s.c o m
        outStream = response.getOutputStream();
        File file = new File(currentFileDownloadPath);
        int length = 0;
        String mimetype = APPLICATION_OCTET_STREAM;
        response.setContentType(mimetype);
        response.setContentLength((int) file.length());
        String fileName = file.getName();
        response.setHeader(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + fileName + CLOSING_QUOTES);
        byte[] byteBuffer = new byte[1024];
        inputStream = new DataInputStream(new FileInputStream(file));
        length = inputStream.read(byteBuffer);
        while ((inputStream != null) && (length != -1)) {
            outStream.write(byteBuffer, 0, length);
            length = inputStream.read(byteBuffer);
        }
        LOG.info(DOWNLOAD_COMPLETED_FOR_FILEPATH + currentFileDownloadPath);
    } catch (IOException e) {
        LOG.error(EXCEPTION_OCCURED_WHILE_DOWNLOADING_A_FILE_FROM_THE_FILE_PATH + currentFileDownloadPath);
        LOG.error(e.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                LOG.error(UNABLE_TO_CLOSE_INPUT_STREAM_FOR_FILE_DOWNLOAD);
            }
        }
        if (outStream != null) {
            try {
                outStream.flush();
            } catch (IOException e) {
                LOG.error(UNABLE_TO_FLUSH_OUTPUT_STREAM_FOR_DOWNLOAD);
            }
            try {
                outStream.close();
            } catch (IOException e) {
                LOG.error(UNABLE_TO_CLOSE_OUTPUT_STREAM_FOR_DOWNLOAD);
            }

        }
    }
}