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:org.openxdata.server.servlet.WMDownloadServlet.java

private void downloadForms(HttpServletResponse response, int studyId) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    formDownloadService.downloadForms(studyId, dos, "", "");
    baos.flush();//from  w w  w  .  ja va 2  s  .  co m
    dos.flush();
    byte[] data = baos.toByteArray();
    baos.close();
    dos.close();
    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));

    PrintWriter out = response.getWriter();
    out.println("<study>");

    try {
        dis.readByte(); //reads the size of the studies

        while (true) {
            String value = dis.readUTF();
            out.println("<form>" + value + "</form>");
        }
    } catch (EOFException exe) {
        //exe.printStackTrace();
    }

    out.println("</study>");
    out.flush();
    dis.close();
}

From source file:net.mms_projects.copy_it.server.push.android.GCMRunnable.java

public void run() {
    try {//w  ww.j  a  v  a 2  s. co m
        URL url = new URL(GCM_URL);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod(POST);
        conn.setRequestProperty(CONTENT_TYPE, Page.ContentTypes.JSON_TYPE);
        conn.setRequestProperty(AUTHORIZATION, KEY);
        final String output_json = full.toString();
        System.err.println("Input json: " + output_json);
        conn.setRequestProperty(CONTENT_LENGTH, String.valueOf(output_json.length()));
        conn.setDoOutput(true);
        conn.setDoInput(true);
        DataOutputStream outputstream = new DataOutputStream(conn.getOutputStream());
        outputstream.writeBytes(output_json);
        outputstream.close();
        DataInputStream input = new DataInputStream(conn.getInputStream());
        StringBuilder builder = new StringBuilder(input.available());
        for (int c = input.read(); c != -1; c = input.read())
            builder.append((char) c);
        input.close();
        output = new JSONObject(builder.toString());
        System.err.println("Output json: " + output.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.android.server.location.GpsXtraDownloader.java

protected static byte[] doDownload(String url, boolean isProxySet, String proxyHost, int proxyPort) {
    if (DEBUG)/*from  w ww  .  j  a va2s  .  c om*/
        Log.d(TAG, "Downloading XTRA data from " + url);

    AndroidHttpClient client = null;
    try {
        client = AndroidHttpClient.newInstance("Android");
        HttpUriRequest req = new HttpGet(url);

        if (isProxySet) {
            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            ConnRouteParams.setDefaultProxy(req.getParams(), proxy);
        }

        req.addHeader("Accept", "*/*, application/vnd.wap.mms-message, application/vnd.wap.sic");

        req.addHeader("x-wap-profile",
                "http://www.openmobilealliance.org/tech/profiles/UAPROF/ccppschema-20021212#");

        HttpResponse response = client.execute(req);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != 200) { // HTTP 200 is success.
            if (DEBUG)
                Log.d(TAG, "HTTP error: " + status.getReasonPhrase());
            return null;
        }

        HttpEntity entity = response.getEntity();
        byte[] body = null;
        if (entity != null) {
            try {
                if (entity.getContentLength() > 0) {
                    body = new byte[(int) entity.getContentLength()];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        dis.readFully(body);
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "Unexpected IOException.", e);
                        }
                    }
                }
            } finally {
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        }
        return body;
    } catch (Exception e) {
        if (DEBUG)
            Log.d(TAG, "error " + e);
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return null;
}

From source file:com.netflix.aegisthus.tools.SSTableExport.java

public static void exportStream(Descriptor.Version version) throws IOException {
    export(new SSTableScanner(new DataInputStream(System.in), version));
}

From source file:fr.insalyon.creatis.vip.core.server.rpc.GetFileServiceImpl.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {/*from w ww .  j  a v  a2 s.c o  m*/
        User user = CoreDAOFactory.getDAOFactory().getUserDAO()
                .getUserBySession(req.getParameter(CoreConstants.COOKIES_SESSION));

        String filepath = req.getParameter("filepath");

        if (filepath != null && !filepath.isEmpty()) {

            File file = new File(Server.getInstance().getWorkflowsPath() + filepath);

            boolean isDir = false;
            if (file.isDirectory()) {
                String zipName = file.getAbsolutePath() + ".zip";
                FolderZipper.zipFolder(file.getAbsolutePath(), zipName);
                filepath = zipName;
                file = new File(zipName);
                isDir = true;
            }

            logger.info("(" + user.getEmail() + ") Downloading file '" + filepath + "'.");
            int length = 0;
            ServletOutputStream op = resp.getOutputStream();
            ServletContext context = getServletConfig().getServletContext();
            String mimetype = context.getMimeType(file.getName());

            resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
            resp.setContentLength((int) file.length());
            resp.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

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

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

            in.close();
            op.flush();
            op.close();

            if (isDir) {
                FileUtils.deleteQuietly(file);
            }
        }

    } catch (DAOException ex) {
        throw new ServletException(ex);
    }
}

From source file:com.facebook.buck.rules.HttpArtifactCache.java

public CacheResult fetchImpl(RuleKey ruleKey, File file) throws IOException {
    Request request = createRequestBuilder(ruleKey.toString()).get().build();
    Response response = fetchCall(request);

    if (response.code() == HttpURLConnection.HTTP_NOT_FOUND) {
        LOGGER.info("fetch(%s): cache miss", ruleKey);
        return CacheResult.MISS;
    }// www .java 2s  . c om

    if (response.code() != HttpURLConnection.HTTP_OK) {
        LOGGER.warn("fetch(%s): unexpected response: %d", ruleKey, response.code());
        return CacheResult.MISS;
    }

    // The hash code shipped with the artifact to/from the cache.
    HashCode expectedHashCode, actualHashCode;

    // Setup a temporary file, which sits next to the destination, to write to and
    // make sure all parent dirs exist.
    Path path = file.toPath();
    projectFilesystem.createParentDirs(path);
    Path temp = projectFilesystem.createTempFile(path.getParent(), path.getFileName().toString(), ".tmp");

    // Open the stream to server just long enough to read the hash code and artifact.
    try (DataInputStream input = new DataInputStream(response.body().byteStream())) {

        // First, extract the size of the file data portion, which we put in the beginning of
        // the artifact.
        long length = input.readLong();

        // Now, write the remaining response data to the temp file, while grabbing the hash.
        try (BoundedInputStream boundedInput = new BoundedInputStream(input, length);
                HashingInputStream hashingInput = new HashingInputStream(hashFunction, boundedInput);
                OutputStream output = projectFilesystem.newFileOutputStream(temp)) {
            ByteStreams.copy(hashingInput, output);
            actualHashCode = hashingInput.hash();
        }

        // Lastly, extract the hash code from the end of the request data.
        byte[] hashCodeBytes = new byte[hashFunction.bits() / Byte.SIZE];
        ByteStreams.readFully(input, hashCodeBytes);
        expectedHashCode = HashCode.fromBytes(hashCodeBytes);

        // We should be at the end of output -- verify this.  Also, we could just try to read a
        // single byte here, instead of all remaining input, but some network stack implementations
        // require that we exhaust the input stream before the connection can be reusable.
        try (OutputStream output = ByteStreams.nullOutputStream()) {
            if (ByteStreams.copy(input, output) != 0) {
                LOGGER.warn("fetch(%s): unexpected end of input", ruleKey);
                return CacheResult.MISS;
            }
        }
    }

    // Now form the checksum on the file we got and compare it to the checksum form the
    // the HTTP header.  If it's incorrect, log this and return a miss.
    if (!expectedHashCode.equals(actualHashCode)) {
        LOGGER.warn("fetch(%s): artifact had invalid checksum", ruleKey);
        projectFilesystem.deleteFileAtPath(temp);
        return CacheResult.MISS;
    }

    // Finally, move the temp file into it's final place.
    projectFilesystem.move(temp, path, StandardCopyOption.REPLACE_EXISTING);

    LOGGER.info("fetch(%s): cache hit", ruleKey);
    return CacheResult.HTTP_HIT;
}

From source file:net.minecraftforge.fml.repackage.com.nothome.delta.GDiffPatcher.java

/**
 * Patches to an output stream./*from www  .  j av a  2  s  . c om*/
 */
public void patch(SeekableSource source, InputStream patch, OutputStream out) throws IOException {

    DataOutputStream outOS = new DataOutputStream(out);
    DataInputStream patchIS = new DataInputStream(patch);

    // the magic string is 'd1 ff d1 ff' + the version number
    if (patchIS.readUnsignedByte() != 0xd1 || patchIS.readUnsignedByte() != 0xff
            || patchIS.readUnsignedByte() != 0xd1 || patchIS.readUnsignedByte() != 0xff
            || patchIS.readUnsignedByte() != 0x04) {

        throw new PatchException("magic string not found, aborting!");
    }

    while (true) {
        int command = patchIS.readUnsignedByte();
        if (command == EOF)
            break;
        int length;
        int offset;

        if (command <= DATA_MAX) {
            append(command, patchIS, outOS);
            continue;
        }

        switch (command) {
        case DATA_USHORT: // ushort, n bytes following; append
            length = patchIS.readUnsignedShort();
            append(length, patchIS, outOS);
            break;
        case DATA_INT: // int, n bytes following; append
            length = patchIS.readInt();
            append(length, patchIS, outOS);
            break;
        case COPY_USHORT_UBYTE:
            offset = patchIS.readUnsignedShort();
            length = patchIS.readUnsignedByte();
            copy(offset, length, source, outOS);
            break;
        case COPY_USHORT_USHORT:
            offset = patchIS.readUnsignedShort();
            length = patchIS.readUnsignedShort();
            copy(offset, length, source, outOS);
            break;
        case COPY_USHORT_INT:
            offset = patchIS.readUnsignedShort();
            length = patchIS.readInt();
            copy(offset, length, source, outOS);
            break;
        case COPY_INT_UBYTE:
            offset = patchIS.readInt();
            length = patchIS.readUnsignedByte();
            copy(offset, length, source, outOS);
            break;
        case COPY_INT_USHORT:
            offset = patchIS.readInt();
            length = patchIS.readUnsignedShort();
            copy(offset, length, source, outOS);
            break;
        case COPY_INT_INT:
            offset = patchIS.readInt();
            length = patchIS.readInt();
            copy(offset, length, source, outOS);
            break;
        case COPY_LONG_INT:
            long loffset = patchIS.readLong();
            length = patchIS.readInt();
            copy(loffset, length, source, outOS);
            break;
        default:
            throw new IllegalStateException("command " + command);
        }
    }
    outOS.flush();
}

From source file:ml.shifu.shifu.util.IndependentTreeModelUtils.java

public boolean convertZipSpecToBinary(File zipSpecFile, File outputGbtFile) {
    ZipInputStream zipInputStream = null;
    FileOutputStream fos = null;/*from  w  ww.j a  v a2s  . c o m*/

    try {
        zipInputStream = new ZipInputStream(new FileInputStream(zipSpecFile));
        IndependentTreeModel treeModel = null;
        List<List<TreeNode>> trees = null;

        ZipEntry zipEntry = null;
        do {
            zipEntry = zipInputStream.getNextEntry();
            if (zipEntry != null) {
                if (zipEntry.getName().equals(MODEL_CONF)) {
                    ByteArrayOutputStream byos = new ByteArrayOutputStream();
                    IOUtils.copy(zipInputStream, byos);
                    treeModel = JSONUtils.readValue(new ByteArrayInputStream(byos.toByteArray()),
                            IndependentTreeModel.class);
                } else if (zipEntry.getName().equals(MODEL_TREES)) {
                    DataInputStream dataInputStream = new DataInputStream(zipInputStream);
                    int size = dataInputStream.readInt();
                    trees = new ArrayList<List<TreeNode>>(size);
                    for (int i = 0; i < size; i++) {
                        int forestSize = dataInputStream.readInt();
                        List<TreeNode> forest = new ArrayList<TreeNode>(forestSize);
                        for (int j = 0; j < forestSize; j++) {
                            TreeNode treeNode = new TreeNode();
                            treeNode.readFields(dataInputStream);
                            forest.add(treeNode);
                        }
                        trees.add(forest);
                    }
                }
            }
        } while (zipEntry != null);

        if (treeModel != null && CollectionUtils.isNotEmpty(trees)) {
            treeModel.setTrees(trees);
            fos = new FileOutputStream(outputGbtFile);
            treeModel.saveToInputStream(fos);
        } else {
            return false;
        }
    } catch (IOException e) {
        logger.error("Error occurred when convert the zip format model to binary.", e);
        return false;
    } finally {
        IOUtils.closeQuietly(zipInputStream);
        IOUtils.closeQuietly(fos);
    }

    return true;
}

From source file:ReadWriteStreams.java

public void readStream() {
    try {//  ww  w . j a  v a 2s.c  o  m
        // Careful: Make sure this is big enough!
        // Better yet, test and reallocate if necessary      
        byte[] recData = new byte[50];

        // Read from the specified byte array
        ByteArrayInputStream strmBytes = new ByteArrayInputStream(recData);

        // Read Java data types from the above byte array
        DataInputStream strmDataType = new DataInputStream(strmBytes);

        for (int i = 1; i <= rs.getNumRecords(); i++) {
            // Get data into the byte array
            rs.getRecord(i, recData, 0);

            // Read back the data types      
            System.out.println("Record #" + i);
            System.out.println("UTF: " + strmDataType.readUTF());
            System.out.println("Boolean: " + strmDataType.readBoolean());
            System.out.println("Int: " + strmDataType.readInt());
            System.out.println("--------------------");

            // Reset so read starts at beginning of array 
            strmBytes.reset();
        }

        strmBytes.close();
        strmDataType.close();

    } catch (Exception e) {
        db(e.toString());
    }
}

From source file:com.vimukti.accounter.license.LicenseManager.java

private byte[] checkAndGetLicenseText(String licenseContent) {
    byte[] licenseText;
    try {/*from w w w .jav  a2  s .c  o m*/
        byte[] decodedBytes = Base64.decodeBase64(licenseContent.getBytes());
        ByteArrayInputStream in = new ByteArrayInputStream(decodedBytes);
        DataInputStream dIn = new DataInputStream(in);
        int textLength = dIn.readInt();
        licenseText = new byte[textLength];
        dIn.read(licenseText);
        byte[] hash = new byte[dIn.available()];
        dIn.read(hash);
        try {
            Signature signature = Signature.getInstance("SHA1withDSA");
            signature.initVerify(PUBLIC_KEY);
            signature.update(licenseText);
            if (!signature.verify(hash)) {
                throw new LicenseException("Failed to verify the license.");
            }

        } catch (InvalidKeyException e) {
            throw new LicenseException(e);
        } catch (SignatureException e) {
            throw new LicenseException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new LicenseException(e);
        }

    } catch (IOException e) {
        throw new LicenseException(e);
    }

    return licenseText;
}