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:TestFuseDFS.java

/**
 * Dump the given intput stream to stderr
 *//*from ww w.j ava  2 s.  co  m*/
private static void dumpInputStream(InputStream is) throws IOException {
    int len;
    do {
        byte b[] = new byte[is.available()];
        len = is.read(b);
        System.out.println("Read " + len + " bytes");
        System.out.write(b, 0, b.length);
    } while (len > 0);
}

From source file:com.github.consiliens.harv.util.Utils.java

/**
 * Calculate SHA-256 value of given input stream. Save input stream to file
 * using the digest for a name. Return the digest value as a string
 **//*  w w w  .  j av  a  2  s  . c  o  m*/
public static String streamToFile(final InputStream input, final String entityParentFolder) {
    String fileName = null;

    try {
        final byte[] dataBytes = new byte[input.available()];
        ByteStreams.readFully(input, dataBytes);

        // shasum -a 256 file.txt
        final MessageDigest sha256 = MessageDigest.getInstance(SHA256);
        final byte[] digest = ByteStreams.getDigest(ByteStreams.newInputStreamSupplier(dataBytes), sha256);

        fileName = Hex.encodeHexString(digest);
        Files.write(dataBytes, new File(entityParentFolder, fileName));
    } catch (final Exception e) {
        e.printStackTrace();
    }

    return fileName;
}

From source file:com.dlshouwen.core.api.controller.ApiController.java

/**
 * base64//from  w w  w . j  av  a  2  s.c  om
 * @param path
 * @return 
 */
public static String GetImageStr(String path) {//Base64??
    InputStream in = null;
    byte[] data = null;
    //?
    try {
        URL url = new URL(path);
        HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
        httpUrl.connect();
        in = httpUrl.getInputStream();
        data = new byte[in.available()];
        in.read(data);
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    //Base64?
    BASE64Encoder encoder = new BASE64Encoder();
    return encoder.encode(data);//Base64?
}

From source file:net.vexelon.myglob.utils.Utils.java

/**
 * Reads an input stream into a byte array
 * @param source/*from  ww  w.  jav  a 2 s. c  om*/
 * @return Byte array of input stream data
 * @throws IOException
 */
public static byte[] read(InputStream source) throws IOException {
    ReadableByteChannel srcChannel = Channels.newChannel(source);
    ByteArrayOutputStream baos = new ByteArrayOutputStream(
            source.available() > 0 ? source.available() : BUFFER_PAGE_SIZE);
    WritableByteChannel destination = Channels.newChannel(baos);

    try {
        ByteBuffer buffer = ByteBuffer.allocate(BUFFER_PAGE_SIZE);
        while (srcChannel.read(buffer) > 0) {
            buffer.flip();
            while (buffer.hasRemaining()) {
                destination.write(buffer);
            }
            buffer.clear();
        }
        return baos.toByteArray();
    } catch (IOException e) {
        throw e;
    } finally {
        try {
            if (srcChannel != null)
                srcChannel.close();
        } catch (IOException e) {
        }
        try {
            if (source != null)
                source.close();
        } catch (IOException e) {
        }
        try {
            if (destination != null)
                destination.close();
        } catch (IOException e) {
        }
    }
}

From source file:com.shenit.commons.utils.DataUtils.java

/**
 * ?InputStream//from  w ww. j a  v a  2  s  .c om
 * 
 * @param is
 * @return
 */
public static byte[] readAll(InputStream is) {
    if (is == null)
        return null;
    byte[] data = null;
    try {
        data = new byte[is.available()];
        is.read(data);
    } catch (Exception ex) {
        if (LOG.isWarnEnabled())
            LOG.warn("[readAll] Read all bytes from input stream failed", ex);
    }
    return data;
}

From source file:net.redstonelamp.gui.RedstoneLampGUI.java

private static void addHistory(File file) {
    File config = new File("redstonelamp-gui-config.json");
    if (!config.isFile()) {
        try {//from   w w  w .j  a v  a2  s .  co  m
            InputStream is = RedstoneLampGUI.class.getResourceAsStream("redfstonelamp-gui-config.json");
            OutputStream os = new FileOutputStream(config);
            IOUtils.copy(is, os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    try {
        InputStream is = new FileInputStream(config);
        byte[] buffer = new byte[is.available()];
        is.read(buffer);
        is.close();
        try {
            JSONObject json = new JSONObject(new String(buffer));
            JSONArray array = json.getJSONArray("history");
            JSONObject object = new JSONObject();
            object.put("path", file.getCanonicalPath());
            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

/**
 * Retrieve the content input stream from a document
 * /*  w  w w .  ja v  a 2  s  .c  om*/
 * @param user The user who make the content petition.
 * @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 docPath, boolean checkout, boolean extendedSecurity)
        throws IOException, PathNotFoundException, AccessDeniedException, DatabaseException {
    String docUuid = NodeBaseDAO.getInstance().getUuidFromPath(docPath);
    InputStream is = NodeDocumentVersionDAO.getInstance().getCurrentContentByParent(docUuid);

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

    return is;
}

From source file:com.optimusinfo.elasticpath.cortex.common.Utils.java

/**
 * Returns the string corresponding to the data in the input stream
 * //w w w . j  a  v  a 2 s. co  m
 * @param inputStream
 * @return the corresponding string for the corresponding inputstream
 */
public static String getStringFromInputStream(InputStream inputStream) {
    if (inputStream != null) {
        String configJson = null;
        try {
            int size = inputStream.available();
            byte[] buffer = new byte[size];
            inputStream.read(buffer);
            configJson = new String(buffer);
            inputStream.close();
            return configJson;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:com.cloud.test.utils.TestClient.java

private static String sshTest(String host) {
    if (host == null) {
        s_logger.info("Did not receive a host back from test, ignoring ssh test");
        return null;
    }/*from   w  w w  . j  a va2s  .  com*/

    // We will retry 5 times before quitting
    int retry = 0;

    while (true) {
        try {
            if (retry > 0) {
                s_logger.info("Retry attempt : " + retry + " ...sleeping 120 seconds before next attempt");
                Thread.sleep(120000);
            }

            s_logger.info("Attempting to SSH into linux host " + host + " with retry attempt: " + retry);

            Connection conn = new Connection(host);
            conn.connect(null, 60000, 60000);

            s_logger.info("SSHed successfully into linux host " + host);

            boolean isAuthenticated = conn.authenticateWithPassword("root", "password");

            if (isAuthenticated == false) {
                return "Authentication failed";
            }
            boolean success = false;
            Session sess = conn.openSession();
            s_logger.info("Executing : wget http://172.16.0.220/dump.bin");
            sess.execCommand("wget http://172.16.0.220/dump.bin && ls -al dump.bin");

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

            byte[] buffer = new byte[8192];
            while (true) {
                if ((stdout.available() == 0) && (stderr.available() == 0)) {
                    int conditions = sess.waitForCondition(
                            ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF,
                            120000);

                    if ((conditions & ChannelCondition.TIMEOUT) != 0) {
                        s_logger.info("Timeout while waiting for data from peer.");
                        return null;
                    }

                    if ((conditions & ChannelCondition.EOF) != 0) {
                        if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
                            break;
                        }
                    }
                }

                while (stdout.available() > 0) {
                    success = true;
                    int len = stdout.read(buffer);
                    if (len > 0) // this check is somewhat paranoid
                        s_logger.info(new String(buffer, 0, len));
                }

                while (stderr.available() > 0) {
                    int len = stderr.read(buffer);
                }
            }

            sess.close();
            conn.close();

            if (success) {
                return null;
            } else {
                retry++;
                if (retry == MAX_RETRY_LINUX) {
                    return "SSH Linux Network test fail";
                }
            }
        } catch (Exception e) {
            retry++;
            if (retry == MAX_RETRY_LINUX) {
                return "SSH Linux Network test fail with error " + e.getMessage();
            }
        }
    }
}

From source file:com.cloud.test.utils.TestClient.java

private static String sshWinTest(String host) {
    if (host == null) {
        s_logger.info("Did not receive a host back from test, ignoring win ssh test");
        return null;
    }/*from  ww  w  .  j a v a2 s  .co m*/

    // We will retry 5 times before quitting
    int retry = 0;

    while (true) {
        try {
            if (retry > 0) {
                s_logger.info("Retry attempt : " + retry + " ...sleeping 300 seconds before next attempt");
                Thread.sleep(300000);
            }

            s_logger.info("Attempting to SSH into windows host " + host + " with retry attempt: " + retry);

            Connection conn = new Connection(host);
            conn.connect(null, 60000, 60000);

            s_logger.info("SSHed successfully into windows host " + host);
            boolean success = false;
            boolean isAuthenticated = conn.authenticateWithPassword("vmops", "vmops");
            if (isAuthenticated == false) {
                return "Authentication failed";
            }
            SCPClient scp = new SCPClient(conn);

            scp.put("wget.exe", "");

            Session sess = conn.openSession();
            s_logger.info("Executing : wget http://172.16.0.220/dump.bin");
            sess.execCommand("wget http://172.16.0.220/dump.bin && dir dump.bin");

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

            byte[] buffer = new byte[8192];
            while (true) {
                if ((stdout.available() == 0) && (stderr.available() == 0)) {
                    int conditions = sess.waitForCondition(
                            ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF,
                            120000);

                    if ((conditions & ChannelCondition.TIMEOUT) != 0) {
                        s_logger.info("Timeout while waiting for data from peer.");
                        return null;
                    }

                    if ((conditions & ChannelCondition.EOF) != 0) {
                        if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
                            break;
                        }
                    }
                }

                while (stdout.available() > 0) {
                    success = true;
                    int len = stdout.read(buffer);
                    if (len > 0) // this check is somewhat paranoid
                        s_logger.info(new String(buffer, 0, len));
                }

                while (stderr.available() > 0) {
                    int len = stderr.read(buffer);
                }
            }
            sess.close();
            conn.close();

            if (success) {
                return null;
            } else {
                retry++;
                if (retry == MAX_RETRY_WIN) {
                    return "SSH Windows Network test fail";
                }
            }
        } catch (Exception e) {
            retry++;
            if (retry == MAX_RETRY_WIN) {
                return "SSH Windows Network test fail with error " + e.getMessage();
            }
        }
    }
}