Example usage for java.io DataInputStream available

List of usage examples for java.io DataInputStream available

Introduction

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

Prototype

public int available() throws IOException 

Source Link

Document

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next caller of a method for this input stream.

Usage

From source file:com.wso2telco.services.bw.FileUtil.java

public static String ReadFullyIntoVar(String fullpath) {

    String result = "";

    try {//from   w  w w  . ja v  a2  s . c o m
        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) {
        e.printStackTrace();
    }
    return result;
}

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

/**
 * Read fully into var.//w ww  .  j a v  a 2 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:cfa.vo.interop.EncodeDoubleArray.java

private static double[] byteToDouble(byte[] data) throws IOException {

    int len = data.length;

    if (len % WORDSIZE != 0) {
        throw new IOException("Array length is not divisible by wordsize");
    }//from w w w  . j  ava  2 s .  c om

    int size = len / WORDSIZE;
    double[] result = new double[size];

    DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(data));

    try {

        int ii = 0;
        while (inputStream.available() > 0) {
            result[ii] = inputStream.readDouble();
            ii++;
        }

    } catch (EOFException e) {
        throw new IOException("Unable to read from dataInputStream, found EOF");

    } catch (IOException e) {
        throw new IOException("Unable to read from dataInputStream, IO error");
    }

    return result;

}

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.//from  ww  w.  j av  a 2  s.  c  om
 *
 * @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:org.wso2.carbon.registry.handler.test.HandlerAddTestCase.java

public static String fileReader(String fileName) {
    String fileContent = "";
    try {/*from  w w w .j  av  a2s. c  o  m*/
        // Open the file that is the first
        // command line parameter
        FileInputStream fstream = new FileInputStream(fileName);

        // Convert our input stream to a
        // DataInputStream
        DataInputStream in = new DataInputStream(fstream);

        // Continue to read lines while
        // there are still some left to read

        while (in.available() != 0) {
            fileContent = fileContent + (in.readLine());
        }

        in.close();
    } catch (Exception e) {
        System.err.println("File input error");
    }
    return fileContent;

}

From source file:org.codice.opendx.TestNITFInputTransformer.java

private static byte[] getThumbnailBytes() throws IOException {
    DataInputStream is = new DataInputStream(new FileInputStream(
            Thread.currentThread().getContextClassLoader().getResource("binfile.dat").getFile()));
    byte[] thumbnail = new byte[is.available()];
    is.readFully(thumbnail);// w  w w . j  av  a 2  s  .co  m
    is.close();
    return thumbnail;
}

From source file:com.chintans.venturebox.util.Utils.java

private static String getStreamLines(final InputStream is) {
    String out = null;/*from w w  w .j a va2 s.  co  m*/
    StringBuffer buffer = null;
    final DataInputStream dis = new DataInputStream(is);

    try {
        if (dis.available() > 0) {
            buffer = new StringBuffer(dis.readLine());
            while (dis.available() > 0) {
                buffer.append("\n").append(dis.readLine());
            }
        }
        dis.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    if (buffer != null) {
        out = buffer.toString();
    }
    return out;
}

From source file:com.solace.samples.cloudfoundry.securesession.controller.SolaceController.java

/**
 * This utility function installs a certificate into the JRE's trusted
 * store. Normally you would not do this, but this is provided to
 * demonstrate how to use TLS, and have the client validate a self-signed
 * server certificate.//from   ww  w.j  av a  2 s  .co m
 *
 * @throws Exception
 */
private static void importCertificate() throws Exception {

    File file = new File(CERTIFICATE_FILE_NAME);
    logger.info("Loading certificate from " + file.getAbsolutePath());

    // This loads the KeyStore from the default location
    // (i.e. default for a Clound Foundry app) using the default password.
    FileInputStream is = new FileInputStream(TRUST_STORE);
    char[] password = TRUST_STORE_PASSWORD.toCharArray();
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(is, password);
    is.close();

    // Create an ByteArrayInputStream stream from the
    FileInputStream fis = new FileInputStream(CERTIFICATE_FILE_NAME);
    DataInputStream dis = new DataInputStream(fis);
    byte[] bytes = new byte[dis.available()];
    dis.readFully(bytes);
    dis.close();
    ByteArrayInputStream certstream = new ByteArrayInputStream(bytes);

    // This takes that Byte Array and creates a certificate out of it.
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Certificate certs = cf.generateCertificate(certstream);

    // Finally, store the new certificate in the keystore.
    keystore.setCertificateEntry(CERTIFICATE_ALIAS, certs);

    // Save the new keystore contents
    FileOutputStream out = new FileOutputStream(TRUST_STORE);
    keystore.store(out, password);
    out.close();

}

From source file:com.headwire.aem.tooling.intellij.util.Util.java

public static long getModificationStamp(VirtualFile file) {
    long ret = -1;
    Long temporary = file.getUserData(Util.MODIFICATION_DATE_KEY);
    if (temporary == null || temporary <= 0) {
        if (file instanceof NewVirtualFile) {
            final DataInputStream is = MODIFICATION_STAMP_FILE_ATTRIBUTE.readAttribute(file);
            if (is != null) {
                try {
                    try {
                        if (is.available() > 0) {
                            String value = IOUtil.readString(is);
                            ret = convertToLong(value, ret);
                            if (ret > 0) {
                                file.putUserData(Util.MODIFICATION_DATE_KEY, ret);
                            }//from   ww w  .  j  a  v a  2 s. co  m
                        }
                    } finally {
                        is.close();
                    }
                } catch (IOException e) {
                    // Ignore it but we might need to throw an exception
                    String message = e.getMessage();
                }
            }
        }
    }
    return ret;
}

From source file:org.locationtech.geomesa.bigtable.spark.BigtableInputFormatBase.java

public static BigtableExtendedScan stringToScan(String encoded) throws IOException {
    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(Base64.getDecoder().decode(encoded)));
    int tableLength = dis.readInt();
    byte[] table = new byte[tableLength];
    dis.read(table, 0, tableLength);//ww w. j  a  va  2 s .  c  o  m
    int available = dis.available();
    byte[] rowsetbytes = new byte[available];
    dis.readFully(rowsetbytes);
    RowSet rs = RowSet.parseFrom(rowsetbytes);
    BigtableExtendedScan scan = new BigtableExtendedScan();
    rs.getRowRangesList().forEach(scan::addRange);
    scan.setAttribute(Scan.SCAN_ATTRIBUTES_TABLE_NAME, table);
    return scan;
}