Example usage for java.io InputStream available

List of usage examples for java.io InputStream available

Introduction

In this page you can find the example usage for java.io InputStream 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, which may be 0, or 0 when end of stream is detected.

Usage

From source file:com.openkm.module.db.base.BaseDocumentModule.java

/**
 * Retrieve the content input stream from a document
 * //from   w w w.  jav a2 s  .  c  om
 * @param user The user who make the content petition.
 * @param docUuid UUID of the document to get the content.
 * @param docPath Path of the document to get the content.
 * @param checkout If the content is retrieved due to a checkout or not.
 * @param extendedSecurity If the extended security DOWNLOAD permission should be evaluated.
 *        This is used to enable the document preview.
 */
public static InputStream getContent(String user, String docUuid, String docPath, boolean checkout,
        boolean extendedSecurity)
        throws IOException, PathNotFoundException, AccessDeniedException, DatabaseException {
    InputStream is = NodeDocumentVersionDAO.getInstance().getCurrentContentByParent(docUuid, extendedSecurity);

    // Activity log
    UserActivity.log(user, (checkout ? "GET_DOCUMENT_CONTENT_CHECKOUT" : "GET_DOCUMENT_CONTENT"), docUuid,
            docPath, Integer.toString(is.available()));

    return is;
}

From source file:org.openo.nfvo.vnfmadapter.service.csm.connect.AbstractSslContext.java

/**readSSLConfToJson
 * @return//  ww  w .  j  a  v a  2  s .com
 * @throws IOException
 * @since NFVO 0.5
 */
public static JSONObject readSSLConfToJson() throws IOException {
    JSONObject sslJson = null;
    InputStream ins = null;
    BufferedInputStream bins = null;
    String fileContent = "";

    String fileName = SystemEnvVariablesFactory.getInstance().getAppRoot()
            + System.getProperty("file.separator") + "etc" + System.getProperty("file.separator") + "conf"
            + System.getProperty("file.separator") + "sslconf.json";

    try {
        ins = new FileInputStream(fileName);
        bins = new BufferedInputStream(ins);

        byte[] contentByte = new byte[ins.available()];
        int num = bins.read(contentByte);

        if (num > 0) {
            fileContent = new String(contentByte);
        }
        sslJson = JSONObject.fromObject(fileContent);
    } catch (FileNotFoundException e) {
        LOG.error(fileName + "is not found!", e);
    } catch (Exception e) {
        LOG.error("read sslconf file fail.please check if the 'sslconf.json' is exist.");
    } finally {
        if (ins != null) {
            ins.close();
        }
        if (bins != null) {
            bins.close();
        }
    }

    return sslJson;
}

From source file:com.zotoh.core.io.StreamUte.java

/**
 * @param inp//from  w  ww .  ja  va2  s  . c  om
 * @return
 * @throws IOException
 */
public static int available(InputStream inp) throws IOException {
    return inp == null ? 0 : inp.available();
}

From source file:edu.vt.middleware.crypt.util.CryptReader.java

/**
 * Reads a certificate chain of the default certificate type from an input
 * stream containing data in any of the following formats:
 *
 * <ul>/*from   w w  w .  ja  v  a  2s.c om*/
 *   <li>Sequence of DER-encoded certificates</li>
 *   <li>Concatenation of PEM-encoded certificates</li>
 *   <li>PKCS#7 certificate chain</li>
 * </ul>
 *
 * @param  chainStream  Stream containing certificate chain data.
 * @param  type  Type of certificate to read, e.g. X.509.
 *
 * @return  Array of certificates in the order in which they appear in the
 * stream.
 *
 * @throws  CryptException  On certificate read or format errors.
 */
public static Certificate[] readCertificateChain(final InputStream chainStream, final String type)
        throws CryptException {
    final CertificateFactory cf = CryptProvider.getCertificateFactory(type);
    InputStream in = chainStream;
    if (!chainStream.markSupported()) {
        in = new BufferedInputStream(chainStream);
    }

    final List<Certificate> certList = new ArrayList<Certificate>();
    try {
        while (in.available() > 0) {
            final Certificate cert = cf.generateCertificate(in);
            if (cert != null) {
                certList.add(cert);
            }
        }
    } catch (CertificateException e) {
        throw new CryptException("Certificate read/format error.", e);
    } catch (IOException e) {
        throw new CryptException("Stream I/O error.");
    }
    return certList.toArray(new Certificate[certList.size()]);
}

From source file:com.cloud.utils.ssh.SshHelper.java

public static Pair<Boolean, String> sshExecute(String host, int port, String user, File pemKeyFile,
        String password, String command, int connectTimeoutInMs, int kexTimeoutInMs, int waitResultTimeoutInMs)
        throws Exception {

    com.trilead.ssh2.Connection conn = null;
    com.trilead.ssh2.Session sess = null;
    try {/*w  w  w.ja v  a2s .co  m*/
        conn = new com.trilead.ssh2.Connection(host, port);
        conn.connect(null, connectTimeoutInMs, kexTimeoutInMs);

        if (pemKeyFile == null) {
            if (!conn.authenticateWithPassword(user, password)) {
                String msg = "Failed to authentication SSH user " + user + " on host " + host;
                s_logger.error(msg);
                throw new Exception(msg);
            }
        } else {
            if (!conn.authenticateWithPublicKey(user, pemKeyFile, password)) {
                String msg = "Failed to authentication SSH user " + user + " on host " + host;
                s_logger.error(msg);
                throw new Exception(msg);
            }
        }
        sess = openConnectionSession(conn);

        sess.execCommand(command);

        InputStream stdout = sess.getStdout();
        InputStream stderr = sess.getStderr();

        byte[] buffer = new byte[8192];
        StringBuffer sbResult = new StringBuffer();

        int currentReadBytes = 0;
        while (true) {
            throwSshExceptionIfStdoutOrStdeerIsNull(stdout, stderr);

            if ((stdout.available() == 0) && (stderr.available() == 0)) {
                int conditions = sess
                        .waitForCondition(
                                ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA
                                        | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS,
                                waitResultTimeoutInMs);

                throwSshExceptionIfConditionsTimeout(conditions);

                if ((conditions & ChannelCondition.EXIT_STATUS) != 0) {
                    break;
                }

                if (canEndTheSshConnection(waitResultTimeoutInMs, sess, conditions)) {
                    break;
                }

            }

            while (stdout.available() > 0) {
                currentReadBytes = stdout.read(buffer);
                sbResult.append(new String(buffer, 0, currentReadBytes));
            }

            while (stderr.available() > 0) {
                currentReadBytes = stderr.read(buffer);
                sbResult.append(new String(buffer, 0, currentReadBytes));
            }
        }

        String result = sbResult.toString();

        if (StringUtils.isBlank(result)) {
            try {
                result = IOUtils.toString(stdout, StandardCharsets.UTF_8);
            } catch (IOException e) {
                s_logger.error("Couldn't get content of input stream due to: " + e.getMessage());
                return new Pair<Boolean, String>(false, result);
            }
        }

        if (sess.getExitStatus() == null) {
            //Exit status is NOT available. Returning failure result.
            s_logger.error(String.format(
                    "SSH execution of command %s has no exit status set. Result output: %s", command, result));
            return new Pair<Boolean, String>(false, result);
        }

        if (sess.getExitStatus() != null && sess.getExitStatus().intValue() != 0) {
            s_logger.error(String.format(
                    "SSH execution of command %s has an error status code in return. Result output: %s",
                    command, result));
            return new Pair<Boolean, String>(false, result);
        }

        return new Pair<Boolean, String>(true, result);
    } finally {
        if (sess != null)
            sess.close();

        if (conn != null)
            conn.close();
    }
}

From source file:org.xmlactions.common.io.ResourceUtils.java

public static byte[] readInputStream(InputStream inputStream) throws IOException {

    int size = inputStream.available();
    int amountRead = 0;
    if (size > 0) {
        byte[] inBuffer = new byte[size];
        byte[] data = new byte[size];
        int dataIndex = 0;
        while (dataIndex < size) {
            amountRead = inputStream.read(inBuffer, 0, size);
            Memory.copy(inBuffer, data, dataIndex, amountRead);
            dataIndex += amountRead;/* w ww .  jav  a  2 s .  co m*/
        }
        return (data);
    } else {
        return (null);
    }
}

From source file:org.xmlactions.common.io.ResourceUtils.java

public static byte[] blockReadInputStream(InputStream inputStream, int sizeToRead) throws Exception {

    int size = inputStream.available();
    if (size > sizeToRead) {
        size = sizeToRead; // only read this much data at a time
    }/*w w  w  .  ja  v a2 s  .co m*/
    int amountRead = 0;
    if (size > 0) {
        byte[] inBuffer = new byte[size];
        byte[] data = new byte[size];
        int dataIndex = 0;
        while (dataIndex < size) {
            amountRead = inputStream.read(inBuffer, 0, size);
            new Memory().copy(inBuffer, data, dataIndex, amountRead);
            dataIndex += amountRead;
        }
        return (data);
    } else {
        return (null);
    }
}

From source file:module.signature.util.XAdESValidator.java

private static void loadNeededCerts() {

    try {//from   w  w w. j a  va2 s  . com
        InputStream keyStoreIS = XAdESValidator.class.getResourceAsStream("/resources/certs/cc-keystore");
        cartaoCidadaoKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        cartaoCidadaoKeyStore.load(keyStoreIS, "123456".toCharArray());

        InputStream tsaCertIS = XAdESValidator.class.getResourceAsStream("/resources/certs/tsaCert.cer");

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while (tsaCertIS.available() != 0) {
            //not the fastest way to do it.. but who cares 
            baos.write(tsaCertIS.read());
        }
        tsaCert = new X509CertificateHolder(baos.toByteArray());

    } catch (KeyStoreException e) {
        logger.error("Error loading the needed certificates", e);
    } catch (NoSuchAlgorithmException e) {
        logger.error("Error loading the needed certificates", e);
    } catch (CertificateException e) {
        logger.error("Error loading the needed certificates", e);
    } catch (IOException e) {
        logger.error("Error loading the needed certificates", e);
    }
}

From source file:com.zotoh.core.io.StreamUte.java

/**
 * Tests if both streams are the same or different at byte level.
 * //from  w  w w  .ja  v  a  2  s.com
 * @param s1
 * @param s2
 * @return
 */
public static boolean different(InputStream s1, InputStream s2) {

    if (s1 != null && s2 != null)
        try {
            int a2 = s2.available();
            int a1 = s1.available();

            if (a1 != a2)
                return true;

            byte[] b2 = new byte[4096];
            byte[] b1 = new byte[4096];
            int c1, c2;
            while (true) {
                c2 = s2.read(b2, 0, b2.length);
                c1 = s1.read(b1, 0, b1.length);

                if (c1 != c2) {
                    return true;
                }

                for (int i = 0; i < c1; ++i) {
                    if (b1[i] != b2[i]) {
                        return true;
                    }
                }

                if (c1 <= 0 || c2 <= 0) {
                    break;
                }
            }

            return false;
        } catch (Exception e) {
        } finally {
            close(s1);
            close(s2);
        }

    return (s1 == null && s2 == null) ? false : true;
}

From source file:eu.annocultor.common.Utils.java

public static void copy(InputStream src, File dst) throws IOException {
    if (src == null)
        throw new NullPointerException("Source should not be NULL.");

    if (dst == null)
        throw new NullPointerException("Dest should not be NULL.");

    OutputStream out = new FileOutputStream(dst);
    while (src.available() != 0) {
        out.write(src.read());/*from w w  w .j a v a2 s . c  om*/
    }
    out.close();
}