Example usage for java.io DataInputStream readFully

List of usage examples for java.io DataInputStream readFully

Introduction

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

Prototype

public final void readFully(byte b[]) throws IOException 

Source Link

Document

See the general contract of the readFully method of DataInput .

Usage

From source file:com.wso2telco.util.FileUtil.java

/**
 * Read fully into var.//from  ww  w. j  a  v a2  s  .  c om
 *
 * @param fullpath the fullpath
 * @return the string
 */
public static String ReadFullyIntoVar(String fullpath) {

    String result = "";

    try {
        FileInputStream file = new FileInputStream(fullpath);
        DataInputStream in = new DataInputStream(file);
        byte[] b = new byte[in.available()];
        in.readFully(b);
        in.close();
        result = new String(b, 0, b.length, "Cp850");
    } catch (Exception e) {
        log.error("Read fully into var Error" + e);
    }
    return result;
}

From source file:org.fdroid.enigtext.mms.MmsCommunication.java

protected static byte[] parseResponse(HttpEntity entity) throws IOException {
    if (entity == null || entity.getContentLength() == 0)
        return null;

    if (entity.getContentLength() < 0)
        throw new IOException("Unknown content length!");

    byte[] responseBytes = new byte[(int) entity.getContentLength()];
    DataInputStream dataInputStream = new DataInputStream(entity.getContent());
    dataInputStream.readFully(responseBytes);
    dataInputStream.close();//w ww.  j a  v  a 2  s .  c  o m

    entity.consumeContent();
    return responseBytes;
}

From source file:br.com.manish.ahy.kernel.util.FileUtil.java

public static byte[] readFileAsBytes(String path) {

    byte[] fileArray = null;

    try {//from   w w w.j a  v  a 2s  .  c o m
        File file = new File(path);
        if (file.length() > Integer.MAX_VALUE) {
            throw new OopsException("Oversized file :-( can't read it, sorry: " + path);
        }

        fileArray = new byte[(int) file.length()];
        DataInputStream dis;
        dis = new DataInputStream(new FileInputStream(file));
        dis.readFully(fileArray);
        dis.close();

    } catch (Exception e) {
        throw new OopsException(e, "Problems when reading: [" + path + "].");
    }

    return fileArray;
}

From source file:it.cnr.icar.eric.common.security.X509Parser.java

/**
 * Parses a X509Certificate from a DER formatted input stream. Uses the 
 * BouncyCastle provider if available./*w w  w . j  a  va  2s  .com*/
 *
 * @param inStream The DER InputStream with the certificate.
 * @return X509Certificate parsed from stream.
 * @throws JAXRException in case of IOException or CertificateException
 *  while parsing the stream.
 */
public static X509Certificate parseX509Certificate(InputStream inStream) throws JAXRException {
    try {
        //possible options
        // - der x509 generated by keytool -export
        // - der x509 generated by openssh x509 (might require BC provider)

        // Get the CertificateFactory to parse the stream
        // if BouncyCastle provider available, use it
        CertificateFactory cf;
        try {
            Class<?> clazz = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider");
            Constructor<?> constructor = clazz.getConstructor(new Class[] {});
            Provider bcProvider = (Provider) constructor.newInstance(new Object[] {});
            Security.addProvider(bcProvider);
            cf = CertificateFactory.getInstance("X.509", "BC");
        } catch (Exception e) {
            // log error if bc present but failed to instanciate/add provider
            if (!(e instanceof ClassNotFoundException)) {
                log.error(CommonResourceBundle.getInstance()
                        .getString("message.FailedToInstantiateBouncyCastleProvider"));
            }
            // fall back to default provider
            cf = CertificateFactory.getInstance("X.509");
        }

        // Read the stream to a local variable
        DataInputStream dis = new DataInputStream(inStream);
        byte[] bytes = new byte[dis.available()];
        dis.readFully(bytes);
        ByteArrayInputStream certStream = new ByteArrayInputStream(bytes);

        // Parse the cert stream
        int i = 0;
        Collection<? extends Certificate> c = cf.generateCertificates(certStream);
        X509Certificate[] certs = new X509Certificate[c.toArray().length];
        for (Iterator<? extends Certificate> it = c.iterator(); it.hasNext();) {
            certs[i++] = (X509Certificate) it.next();
        }

        // Some logging..
        if (log.isDebugEnabled()) {
            if (c.size() == 1) {
                log.debug("One certificate, no chain.");
            } else {
                log.debug("Certificate chain length: " + c.size());
            }
            log.debug("Subject DN: " + certs[0].getSubjectDN().getName());
            log.debug("Issuer DN: " + certs[0].getIssuerDN().getName());
        }

        // Do we need to return the chain?
        // do we need to verify if cert is self signed / valid?
        return certs[0];
    } catch (CertificateException e) {
        String msg = CommonResourceBundle.getInstance().getString("message.parseX509CertificateStreamFailed",
                new Object[] { e.getClass().getName(), e.getMessage() });
        throw new JAXRException(msg, e);
    } catch (IOException e) {
        String msg = CommonResourceBundle.getInstance().getString("message.parseX509CertificateStreamFailed",
                new Object[] { e.getClass().getName(), e.getMessage() });
        throw new JAXRException(msg, e);
    } finally {
        try {
            inStream.close();
        } catch (IOException e) {
            inStream = null;
        }
    }
}

From source file:com.hernandez.rey.crypto.TripleDES.java

/**
 * Read a TripleDES secret key from the specified file
 * /*w w  w.j ava 2s .  c  o  m*/
 * @param keyFile key file to read
 * @return secret key appropriate for encryption/decryption with 3DES
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws InvalidKeySpecException
 */
public static SecretKey readKey(final File keyFile)
        throws IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
    // Read the raw bytes from the keyfile
    final DataInputStream in = new DataInputStream(new FileInputStream(keyFile));
    final byte[] rawkey = new byte[(int) keyFile.length()];
    in.readFully(rawkey);
    in.close();

    // Convert the raw bytes to a secret key like this
    final DESedeKeySpec keyspec = new DESedeKeySpec(rawkey);
    final SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
    final SecretKey key = keyfactory.generateSecret(keyspec);
    return key;
}

From source file:rlVizLib.messaging.BinaryPayload.java

public static String readRawString(DataInputStream DIS) {
    try {//from   w w  w . j av a2  s .c  o m
        int numBytes = DIS.readInt();
        if (numBytes == 0) {
            return "";
        }
        byte[] theBytes = new byte[numBytes];
        DIS.readFully(theBytes);
        return new String(theBytes);
    } catch (IOException ex) {
        Logger.getLogger(BinaryPayload.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

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

protected static byte[] doDownload(String url, boolean isProxySet, String proxyHost, int proxyPort) {
    AndroidHttpClient client = null;//from w w w . j  a v a  2 s.co m
    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.
            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) {
        Log.d(TAG, "error " + e);
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return null;
}

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

protected static byte[] doDownload(String url, boolean isProxySet, String proxyHost, int proxyPort) {
    if (DEBUG)/*ww  w  .  j a v a2 s .  c  o  m*/
        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:org.mrgeo.utils.StringUtils.java

public static String read(DataInputStream stream) throws IOException {
    int len = stream.readInt();
    if (len == -1) {
        return null;
    } else {/*from   w  ww . j a  v a2 s  . com*/
        byte[] data = new byte[len];
        stream.readFully(data);

        return new String(data, "UTF-8");
    }
}

From source file:org.apache.xmlgraphics.image.codec.png.PNGChunk.java

/**
 * Reads the next chunk from the input stream.
 * @param distream the input stream/*from   w  w  w  . java2 s .c o m*/
 * @return the chunk
 */
public static PNGChunk readChunk(DataInputStream distream) {
    try {
        int length = distream.readInt();
        int type = distream.readInt();
        byte[] data = new byte[length];
        distream.readFully(data);
        int crc = distream.readInt();

        return new PNGChunk(length, type, data, crc);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}