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

public static int readSCSocketBytes(InputStream is, int timeoutMS, byte[] buffer, int maxLen) throws Exception {
    int ret = 0, timeout = -2, bytesAvailable = 0, curRead = 0, waitCount = 0;
    boolean haveData = false;

    while (timeout < timeoutMS) {
        bytesAvailable = is.available();
        if (bytesAvailable > 0) {
            haveData = true;//from   w w  w  .  j a v a 2 s.  co m
            waitCount = 0;
            curRead = ((bytesAvailable > (maxLen - ret)) ? (maxLen - ret) : bytesAvailable);
            curRead = is.read(buffer, ret, curRead);
            ret += curRead;
            if (ret >= maxLen) {
                return ret;
            }
        } else {
            if (timeoutMS == -1) {
                break;
            }

            Thread.sleep(100);
            if (timeoutMS != 0) {
                timeout += 100;
            } else if ((haveData == true) && (waitCount++ > HAVE_DATA_WAIT_RETRIES)) {
                break;
            }
        }
    }
    return ret;
}

From source file:Main.java

public static String highlight(final List<String> lines, final String meta, final String prog,
        final String encoding) throws IOException {
    final File tmpIn = new File(System.getProperty("java.io.tmpdir"),
            String.format("txtmark_code_%d_%d.in", ID, IN_COUNT.incrementAndGet()));
    final File tmpOut = new File(System.getProperty("java.io.tmpdir"),
            String.format("txtmark_code_%d_%d.out", ID, OUT_COUNT.incrementAndGet()));

    try {/*from  ww  w . java  2s . co m*/

        final Writer w = new OutputStreamWriter(new FileOutputStream(tmpIn), encoding);

        try {
            for (final String s : lines) {
                w.write(s);
                w.write('\n');
            }
        } finally {
            w.close();
        }

        final List<String> command = new ArrayList<String>();

        command.add(prog);
        command.add(meta);
        command.add(tmpIn.getAbsolutePath());
        command.add(tmpOut.getAbsolutePath());

        final ProcessBuilder pb = new ProcessBuilder(command);
        final Process p = pb.start();
        final InputStream pIn = p.getInputStream();
        final byte[] buffer = new byte[2048];

        int exitCode = 0;
        for (;;) {
            if (pIn.available() > 0) {
                pIn.read(buffer);
            }
            try {
                exitCode = p.exitValue();
            } catch (final IllegalThreadStateException itse) {
                continue;
            }
            break;
        }

        if (exitCode == 0) {
            final Reader r = new InputStreamReader(new FileInputStream(tmpOut), encoding);
            try {
                final StringBuilder sb = new StringBuilder();
                for (;;) {
                    final int c = r.read();
                    if (c >= 0) {
                        sb.append((char) c);
                    } else {
                        break;
                    }
                }
                return sb.toString();
            } finally {
                r.close();
            }
        }

        throw new IOException("Exited with exit code: " + exitCode);
    } finally {
        tmpIn.delete();
        tmpOut.delete();
    }
}

From source file:com.cprassoc.solr.auth.util.Utils.java

public static byte[] streamToBytes(InputStream in) {
    byte result[] = new byte[0];
    try {//from w  ww. ja va2  s .  c om
        result = new byte[in.available()];
        in.read(result);
    } catch (Exception e) {
        // e.printStackTrace();
    }
    return result;
}

From source file:com.mk4droid.IMC_Utils.GEO.java

/**
 * Draw polygon borders on the map defining the municipality
 * /*from w w  w . ja va2 s . c  o  m*/
 * @param mgmap
 * @param resources
 */
public static Polygon MakeBorders(GoogleMap mgmap, Resources res) {

    String str = "";
    // parse from raw.polygoncoords.txt
    try {
        InputStream in_s = res.openRawResource(R.raw.polygoncoords);
        byte[] b = new byte[in_s.available()];
        in_s.read(b);
        str = new String(b);
    } catch (Exception e) {
        Log.e("Error", "can't read polygon.");
    }

    Polygon mPoly = null;

    if (options == null) {
        if (str.length() > 0) {
            String[] points = str.split(" ");
            options = new PolygonOptions();
            for (int i = 0; i < points.length; i = i + 2)
                options.add(new LatLng(Double.parseDouble(points[i + 1]), Double.parseDouble(points[i])));
        }
    }

    if (mgmap != null)
        mPoly = mgmap.addPolygon(
                options.strokeWidth(4).strokeColor(Color.BLACK).fillColor(Color.argb(10, 0, 100, 0)));

    return mPoly;
}

From source file:com.anitech.resting.http.request.RequestDataMassager.java

private static StringEntity massageJSONData(Object inputData) throws RestingException {
    logger.debug("Inside massageJSONData!");
    StringEntity stringEntity = null;// w ww  . j a  v  a  2s.c om
    if (inputData instanceof Map<?, ?>) {
        try {
            logger.debug("Map>" + new JSONObject((Map<?, ?>) inputData).toJSONString());
            stringEntity = new StringEntity(new JSONObject((Map<?, ?>) inputData).toJSONString());
        } catch (UnsupportedEncodingException e) {
            throw new RestingException(e);
        }
    } else if (inputData instanceof String) {
        logger.debug("String>" + inputData);
        try {
            stringEntity = new StringEntity((String) inputData);
        } catch (UnsupportedEncodingException e) {
            throw new RestingException(e);
        }
    } else if (inputData instanceof StringBuffer || inputData instanceof StringBuilder) {
        logger.debug("String Buffer/Builder>" + inputData.toString());
        try {
            stringEntity = new StringEntity((String) inputData.toString());
        } catch (UnsupportedEncodingException e) {
            throw new RestingException(e);
        }
    } else if (inputData instanceof File) {
        try {
            logger.debug("File>"
                    + new String(Files.readAllBytes(((File) inputData).toPath()), Charset.defaultCharset()));
            byte[] bytes = Files.readAllBytes(((File) inputData).toPath());
            stringEntity = new StringEntity(new String(bytes, Charset.defaultCharset()));
        } catch (IOException e) {
            throw new RestingException(e);
        }
    } else if (inputData instanceof InputStream) {
        InputStream inputStream = ((InputStream) inputData);
        try {
            byte[] buffer = new byte[inputStream.available()];
            int length = inputStream.read(buffer);
            logger.debug("InputStream>" + new String(buffer, 0, length, Charset.defaultCharset()));
            stringEntity = new StringEntity(new String(buffer, 0, length, Charset.defaultCharset()));
        } catch (IOException e) {
            throw new RestingException(e);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } else {
        logger.error("Unparseable data format found in inputs!");
        throw new RestingException("Unparseable data format found in inputs!");
    }
    return stringEntity;
}

From source file:com.anitech.resting.http.request.RequestDataMassager.java

private static StringEntity massageXMLData(Object inputData) throws RestingException {
    logger.debug("Inside massageXMLData!");
    StringEntity stringEntity = null;/*from w w w .  java  2s .co  m*/
    if (inputData instanceof Map<?, ?>) {
        try {
            String xmlString = RestingUtil.covertMapToXML((Map<?, ?>) inputData,
                    RestingConstants.REQUEST_XML_ROOT);
            logger.debug("Map>" + xmlString);
            stringEntity = new StringEntity(xmlString);
        } catch (UnsupportedEncodingException e) {
            throw new RestingException(e);
        }
    } else if (inputData instanceof String) {
        logger.debug("String>" + inputData);
        try {
            stringEntity = new StringEntity((String) inputData);
        } catch (UnsupportedEncodingException e) {
            throw new RestingException(e);
        }
    } else if (inputData instanceof StringBuffer || inputData instanceof StringBuilder) {
        logger.debug("String Buffer/Builder>" + inputData.toString());
        try {
            stringEntity = new StringEntity((String) inputData.toString());
        } catch (UnsupportedEncodingException e) {
            throw new RestingException(e);
        }
    } else if (inputData instanceof File) {
        try {
            logger.debug("File>"
                    + new String(Files.readAllBytes(((File) inputData).toPath()), Charset.defaultCharset()));
            byte[] bytes = Files.readAllBytes(((File) inputData).toPath());
            stringEntity = new StringEntity(new String(bytes, Charset.defaultCharset()));
        } catch (IOException e) {
            throw new RestingException(e);
        }
    } else if (inputData instanceof InputStream) {
        InputStream inputStream = ((InputStream) inputData);
        try {
            byte[] buffer = new byte[inputStream.available()];
            int length = inputStream.read(buffer);
            logger.debug("InputStream>" + new String(buffer, 0, length, Charset.defaultCharset()));
            stringEntity = new StringEntity(new String(buffer, 0, length, Charset.defaultCharset()));
        } catch (IOException e) {
            throw new RestingException(e);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } else {
        logger.error("Unparseable data format found in inputs!");
        throw new RestingException("Unparseable data format found in inputs!");
    }
    return stringEntity;
}

From source file:Main.java

public static String createExternalStoragePrivateFile(Context appCtx, InputStream is, String fileName) {

    File file = new File(appCtx.getExternalFilesDir(null), fileName);

    try {//  w  ww.j a va2 s.com
        //InputStream is = appCtx.getResources().openRawResource(R.raw.calipso);
        OutputStream os = new FileOutputStream(file);
        byte[] data = new byte[is.available()];
        is.read(data);
        os.write(data);
        is.close();
        os.close();
    } catch (IOException e) {
        // Unable to create file, likely because external storage is
        // not currently mounted.
        Log.w("ExternalStorage", "Error writing " + file, e);
    }

    return file.getPath();
}

From source file:com.vmware.identity.rest.core.server.util.VerificationUtil.java

private static String getMD5(ContainerRequestContext context) {
    if (!context.hasEntity()) {
        return "";
    }/*from   w  w w  . j a va  2 s  .c  o  m*/

    InputStream in = context.getEntityStream();

    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream(in.available());

        final byte[] data = new byte[ReaderWriter.BUFFER_SIZE];
        int len = 0;

        while ((len = in.read(data)) > 0) {
            out.write(data, 0, len);
        }

        // Reset our entity stream since we consumed it and it may need to be read for object marshalling
        context.setEntityStream(new ByteArrayInputStream(out.toByteArray()));

        return RequestSigner.computeMD5(out.toString());
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:jp.go.nict.langrid.servicesupervisor.frontend.FrontEnd.java

static String getCallTree(String protocolId, InputStream body) throws IOException {
    if (body.available() == 0)
        return "";
    if (protocolId == null || protocolId.equals(Protocols.SOAP_RPCENCODED)) {
        return getSoapRpcencodedCallTree(body);
    } else if (protocolId.equals(Protocols.PROTOBUF_RPC)) {
        return getProtobufRpcCallTree(body);
    } else if (protocolId.equals(Protocols.JSON_RPC)) {
        return getJsonRpcCallTree(body);
    }/*ww w . j  a v a 2  s.c o  m*/
    return "";
}

From source file:Main.java

/**
 * Reads all bytes from an input stream into a byte array.
 * Does not close the stream./*  w  ww. java 2 s  .  c  om*/
 *
 * @param in the input stream to read from
 * @return a byte array containing all the bytes from the stream
 * @throws IOException if an I/O error occurs
 */
public static byte[] toByteArray(InputStream in) throws IOException {
    // Presize the ByteArrayOutputStream since we know how large it will need
    // to be, unless that value is less than the default ByteArrayOutputStream
    // size (32).
    ByteArrayOutputStream out = new ByteArrayOutputStream(Math.max(32, in.available()));
    copy(in, out);
    return out.toByteArray();
}