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.erudika.para.rest.RestUtils.java

/**
 * Returns a Response with the entity object inside it and 200 status code.
 * If there was and error the status code is different than 200.
 * @param is the entity input stream/*  ww w.j  a  va  2s . c o  m*/
 * @param type the type to convert the entity into, for example a Map.
 * @return response with 200 or error status
 */
public static Response getEntity(InputStream is, Class<?> type) {
    Object entity;
    try {
        if (is != null && is.available() > 0) {
            if (is.available() > Config.MAX_ENTITY_SIZE_BYTES) {
                return getStatusResponse(Response.Status.BAD_REQUEST, "Request is too large - the maximum is "
                        + (Config.MAX_ENTITY_SIZE_BYTES / 1024) + " KB.");
            }
            entity = ParaObjectUtils.getJsonReader(type).readValue(is);
        } else {
            return getStatusResponse(Response.Status.BAD_REQUEST, "Missing request body.");
        }
    } catch (JsonMappingException e) {
        return getStatusResponse(Response.Status.BAD_REQUEST, e.getMessage());
    } catch (JsonParseException e) {
        return getStatusResponse(Response.Status.BAD_REQUEST, e.getMessage());
    } catch (IOException e) {
        logger.error(null, e);
        return getStatusResponse(Response.Status.INTERNAL_SERVER_ERROR, e.toString());
    }

    return Response.ok(entity).build();
}

From source file:com.quarterfull.newsAndroid.NewsDetailFragment.java

static String getTextFromAssets(String fileName, Context context) {
    InputStream input;
    try {/* w  ww  .ja  va2s .  c  o  m*/
        input = context.getAssets().open(fileName);
        int size = input.available();
        byte[] buffer = new byte[size];
        input.read(buffer);
        input.close();

        // byte buffer into a string
        return new String(buffer);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return "";
}

From source file:com.ikon.omr.OMRHelper.java

/**
 * process/*from w  ww .  j av a 2  s.c o  m*/
 */
public static Map<String, String> process(File fileToProcess, long omId) throws IOException, OMRException,
        DatabaseException, InvalidFileStructureException, InvalidImageIndexException, UnsupportedTypeException,
        MissingParameterException, WrongParameterException {
    Map<String, String> values = new HashMap<String, String>();
    Omr omr = OmrDAO.getInstance().findByPk(omId);
    InputStream asc = new ByteArrayInputStream(omr.getAscFileContent());
    InputStream config = new ByteArrayInputStream(omr.getConfigFileContent());
    InputStream fields = new ByteArrayInputStream(omr.getFieldsFileContent());

    if (asc != null && asc.available() > 0 && config != null && config.available() > 0 && fields != null
            && fields.available() > 0) {
        Gray8Image grayimage = ImageUtil.readImage(fileToProcess.getCanonicalPath());
        if (grayimage == null) {
            throw new OMRException("Not able to process the image as gray image");
        }

        ImageManipulation image = new ImageManipulation(grayimage);
        image.locateConcentricCircles();
        image.readConfig(config);
        image.readFields(fields);
        image.readAscTemplate(asc);
        image.searchMarks();
        File dataFile = FileUtils.createTempFile();
        image.saveData(dataFile.getCanonicalPath());

        // Parse data file

        FileInputStream dfStream = new FileInputStream(dataFile);
        DataInputStream in = new DataInputStream(dfStream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;

        while ((strLine = br.readLine()) != null) {
            // format key=value ( looking for first = )
            String key = "";
            String value = "";

            if (strLine.contains("=")) {
                key = strLine.substring(0, strLine.indexOf("="));
                value = strLine.substring(strLine.indexOf("=") + 1);
                value = value.trim();
            }

            if (!key.equals("")) {
                if (value.equals("")) {
                    IOUtils.closeQuietly(br);
                    IOUtils.closeQuietly(in);
                    IOUtils.closeQuietly(dfStream);
                    IOUtils.closeQuietly(asc);
                    IOUtils.closeQuietly(config);
                    IOUtils.closeQuietly(fields);
                    throw new OMRException("Empty value");
                }

                if (omr.getProperties().contains(key)) {
                    values.put(key, value);
                }
            }
        }

        IOUtils.closeQuietly(br);
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(dfStream);
        IOUtils.closeQuietly(asc);
        IOUtils.closeQuietly(config);
        IOUtils.closeQuietly(fields);
        FileUtils.deleteQuietly(dataFile);
        return values;
    } else {
        throw new OMRException("Error asc, config or fields files not found");
    }
}

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

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

From source file:http.ServerExample.java

public static ArrayList<String> getProcess(String user, String password, String host, String cmd)
        throws IOException, JSchException, InterruptedException {
    System.out.println("From getProcess " + user + " " + password + " " + host + " ");
    ArrayList<String> processList = new ArrayList<String>();

    List<String> myList = new ArrayList<String>();

    JSch jsch = new JSch();
    String command = cmd; //"sh /opt/emms/emsam/bin/show_emsam_status.sh\n"; 

    Session session;//from   w  w  w .  j a v a  2 s  .c  o  m
    session = jsch.getSession(user, host, 26);
    session.setPassword(password);
    session.setConfig("StrictHostKeyChecking", "no");
    //      session.connect(30 * 1000);
    try {
        session.connect(0);
    } catch (Exception e) {
        System.out.println("Exception in connection ");
        e.printStackTrace();

        list = processList;
        return processList;
    }
    //      session.connect(0);
    Channel channel = session.openChannel("shell");
    ByteArrayInputStream is = new ByteArrayInputStream(command.getBytes());
    channel.setInputStream(is);

    InputStream inStream = channel.getInputStream();
    BufferedReader fromChannel = new BufferedReader(new InputStreamReader(inStream, "UTF-8"));
    OutputStream outStream = channel.getOutputStream();

    String result = new String();
    String[] entries = new String[40];

    try {

        channel.connect(15 * 1000);
        Thread.sleep(3 * 1000);

        byte[] tmp = new byte[2048];
        while (true) {
            while (inStream.available() > 0) {
                int i = inStream.read(tmp, 0, 2048);
                if (i < 0)
                    break;
                result = new String(tmp, 0, i);

                myList = (Arrays.asList(result.split("\n")));
                //                                      myList = myList.subList(5, myList.size()-1);

                for (int j = 1; j < myList.size(); j++) {

                    if (myList.get(j).toString().contains("S")) {
                        processList.add(myList.get(j));
                    }

                }

            }

            if (inStream.available() == 0) {
                break;
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        channel.disconnect();
        session.disconnect();
        list = processList;
        return processList;

    }

}

From source file:com.lm.lic.manager.util.GenUtil.java

public static byte[] extractBytesFromInputStream(InputStream is) throws IOException {

    long length = is.available();
    if (length > Integer.MAX_VALUE) {
        return null;
    }/*from  w  ww.  j a v a2 s.c  om*/

    byte[] bytes = new byte[(int) length];

    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
        offset += numRead;
    }

    if (offset < bytes.length) {
        throw new IOException("Malformed file");
    }
    is.close();

    return bytes;
}

From source file:com.ikon.util.WebUtils.java

/**
 * Send file to client browser.// w ww . j  a v a 2  s. c om
 * 
 * @throws IOException If there is a communication error.
 */
public static void sendFile(HttpServletRequest request, HttpServletResponse response, String fileName,
        String mimeType, boolean inline, InputStream is) throws IOException {
    log.debug("sendFile({}, {}, {}, {}, {}, {})",
            new Object[] { request, response, fileName, mimeType, inline, is });
    prepareSendFile(request, response, fileName, mimeType, inline);

    // Set length
    response.setContentLength(is.available());
    log.debug("File: {}, Length: {}", fileName, is.available());

    ServletOutputStream sos = response.getOutputStream();
    IOUtils.copy(is, sos);
    sos.flush();
    sos.close();
}

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

private static List<File> getServerDirectories() {
    File config = new File("redstonelamp-gui-config.json");
    if (!config.isFile()) {
        try {// ww w .  ja v a  2s.c  om
            InputStream is = RedstoneLampGUI.class.getResourceAsStream("redfstonelamp-gui-config.json");
            OutputStream os = new FileOutputStream(config);
            IOUtils.copy(is, os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    List<File> out = new ArrayList<>();
    StringBuilder configContents = new StringBuilder();
    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");
            for (int i = 0; i < array.length(); i++) {
                JSONObject object = array.getJSONObject(i);
                out.add(new File(object.getString("path")));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return out;
}

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

/**
 * Retrieve the content input stream from a document path
 *///w  w  w  . j  av  a 2  s . c o  m
public static InputStream getContent(Session session, String docPath, boolean checkout)
        throws javax.jcr.PathNotFoundException, javax.jcr.RepositoryException, IOException {
    Node documentNode = session.getRootNode().getNode(docPath.substring(1));
    InputStream is = getContent(session, documentNode);

    // Activity log
    UserActivity.log(session.getUserID(), (checkout ? "GET_DOCUMENT_CONTENT_CHECKOUT" : "GET_DOCUMENT_CONTENT"),
            documentNode.getUUID(), docPath, Integer.toString(is.available()));

    return is;
}

From source file:com.glaf.core.util.IOUtils.java

/**
 * write.//  ww w . j a  v  a2s  .c o m
 * 
 * @param is
 *            InputStream instance.
 * @param os
 *            OutputStream instance.
 * @param bufferSize
 *            buffer size.
 * @return count.
 * @throws IOException.
 */
public static long write(InputStream is, OutputStream os, int bufferSize) throws IOException {
    int read;
    long total = 0;
    byte[] buff = new byte[bufferSize];
    while (is.available() > 0) {
        read = is.read(buff, 0, buff.length);
        if (read > 0) {
            os.write(buff, 0, read);
            total += read;
        }
    }
    return total;
}