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:fr.gael.dhus.network.RegulatedInputStream.java

/**
 * Reads bytes from this byte-input stream into the specified byte array,
 * starting at the given offset./*  w ww  . j a  v  a  2  s .c  o m*/
 * <p>
 * This method implements the general contract of the corresponding
 * <code>{@link InputStream#read(byte[], int, int) read}</code> method of the
 * <code>{@link InputStream}</code> class. As an additional convenience, it
 * attempts to read as many bytes as possible by repeatedly invoking the
 * <code>read</code> method of the underlying stream. This iterated
 * <code>read</code> continues until one of the following conditions becomes
 * true:
 * <ul>
 * <li>The specified number of bytes have been read,
 * <li>The <code>read</code> method of the underlying stream returns
 * <code>-1</code>, indicating end-of-file, or
 * <li>The <code>available</code> method of the underlying stream returns
 * zero, indicating that further input requests would block.
 * </ul>
 * If the first <code>read</code> on the underlying stream returns
 * <code>-1</code> to indicate end-of-file then this method returns
 * <code>-1</code>. Otherwise this method returns the number of bytes
 * actually read.
 * <p>
 * Subclasses of this class are encouraged, but not required, to attempt to
 * read as many bytes as possible in the same fashion.
 *
 * @param b destination buffer.
 * @param off offset at which to start storing bytes.
 * @param len maximum number of bytes to read.
 * @return the number of bytes read, or <code>-1</code> if the end of the
 *         stream has been reached.
 * @exception IOException if this input stream has been closed by invoking
 *               its {@link #close()} method, or an I/O error occurs.
 */
public synchronized int read(byte b[], int off, int len) throws IOException {
    getBufIfOpen(); // Check for closed stream
    if ((off | len | (off + len) | (b.length - (off + len))) < 0) {
        throw new IndexOutOfBoundsException();
    } else if (len == 0) {
        return 0;
    }

    int n = 0;
    int total_nread = 0;
    for (;;) {
        int nread = read1(b, off + n, len - n);
        if (nread <= 0) {
            total_nread = (n == 0) ? nread : n;
            break;
        }
        n += nread;
        if (n >= len) {
            total_nread = n;
            break;
        }
        // if not closed but no bytes available, return
        InputStream input = in;
        if (input != null && input.available() <= 0) {
            total_nread = n;
            break;
        }
    }

    // Acquire from regulated flow
    if ((this.flow != null) && (total_nread > 0)) {
        try {
            this.flow.acquire(total_nread);
        } catch (InterruptedException exception) {
            logger.error(exception);
            this.close();
            throw new IOException(exception);
        } catch (RegulationException exception) {
            logger.error(exception);
            this.close();
            throw exception;
        }
    }

    if (listener != null)
        listener.bytesTransferred(this.flow.getTransferedSize(), total_nread,
                this.connectionParameters.getStreamSize());

    // Return total read number
    return total_nread;
}

From source file:ddf.metrics.plugin.webconsole.MetricsWebConsolePlugin.java

/**
 * Renders the Metrics tab in the Admin GUI console. Retrieves the list of all metrics being
 * collected in the system by invoking the MetricsEndpoint, and then parsing this JSON
 * response to create the table in the Metrics tab that consists of the list of metric names and
 * hyperlinks for each format for each time range that a metric's data can be retrieved.
 *//* w  w  w .  jav a 2 s .c om*/
@SuppressWarnings("rawtypes")
@Override
protected void renderContent(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOGGER.debug("ENTERING: renderContent");

    final PrintWriter pw = response.getWriter();

    String metricsServiceUrl = SystemBaseUrl.constructUrl(METRICS_SERVICE_BASE_URL, true);

    // Call Metrics Endpoint REST service to get list of all of the monitored
    // metrics and their associated hyperlinks to graph their historical data.
    // Response is a JSON-formatted string.
    LOGGER.debug("(NEW) Creating WebClient to URI {}", metricsServiceUrl);
    WebClient client = WebClient.create(metricsServiceUrl);
    client.accept("application/json");
    if ("https".equals(request.getScheme())) {
        configureHttps(client);
    }
    Response metricsListResponse = client.get();
    InputStream is = (InputStream) metricsListResponse.getEntity();
    LOGGER.debug("Response has this many bytes in it: {}", is.available());
    String metricsList = IOUtils.toString(is);
    LOGGER.debug("metricsList = {}", metricsList);

    JSONParser parser = new JSONParser();

    // Useful class for simple JSON to handle collections when parsing
    // (Called internally by the simple JSON parser.parse(...) method)
    ContainerFactory containerFactory = new ContainerFactory() {
        public List creatArrayContainer() {
            return new LinkedList();
        }

        public Map createObjectContainer() {
            return new LinkedHashMap();
        }
    };

    try {
        LOGGER.debug("Parsing JSON metricsList response");

        // JSON-formatted text will map to a Map1<String1, Map2<String2, Map3<String3,String4>>>
        // (Numbers added to end of Map and String types so that each position could be referred
        // to)
        // String1 = metric name, e.g., "catalogQueries"
        // Map2 = mapping of time range to it list of hyperlinks
        // String2 = time range, e.g., "15m"
        // Map3 = hyperlink for each format type (e.g., PNG) for each time range for each metric
        // String3 = display text for hyperlink, e.g., PNG
        // String4 = hyperlink for metric data in specific format, e.g.,
        // http://host:port/.../catalogQueries.png?dateOffset=900
        Map<String, Map<String, Map<String, String>>> json = new TreeMap(
                (Map<String, Map<String, Map<String, String>>>) parser.parse(metricsList, containerFactory));
        Iterator iter = json.entrySet().iterator();

        // Create HTML table of Metric Name and hyperlinks to its associated
        // RRD graphs
        pw.println("<table class=\"nicetable\">");
        pw.println("<tr>");
        pw.println("<th>Metric</th>");

        // Column headers for the time ranges, e.g., 15m, 1h, 4h, etc.
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            Map<String, Map<String, String>> timeRangeData = (Map<String, Map<String, String>>) entry
                    .getValue();
            Set<String> timeRanges = timeRangeData.keySet();
            for (String timeRange : timeRanges) {
                pw.println("<th>" + timeRange + "</th>");
            }
            break; // only need one set of time ranges for column headers
        }
        pw.println("</tr>");

        // List of metric names and associated hyperlinks per format per time range
        int rowCount = 1;
        iter = json.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String metricName = (String) entry.getKey();
            String tableStriping = "odd";
            if ((rowCount % 2) == 0) {
                tableStriping = "even";
            }
            pw.println("<tr class=\"" + tableStriping + " ui-state-default\">");
            pw.println("<td>" + convertCamelCase(metricName) + "</td>");
            Map<String, Map<String, String>> timeRangeData = (Map<String, Map<String, String>>) entry
                    .getValue();

            Iterator metricDataIter = timeRangeData.entrySet().iterator();
            while (metricDataIter.hasNext()) {
                Map.Entry entry2 = (Map.Entry) metricDataIter.next();
                String timeRange = (String) entry2.getKey();

                // For each time range (for each metric), a list of display text and its
                // associated hyperlink
                // is provided, e.g., "1h" and its associated hyperlink with the
                // corresponding dateOffset (in seconds) from current time.
                // Example:
                // http://<host>:<port>/services/internal/metrics?dateOffset=3600
                //
                // key=display text
                // value=URLs
                Map<String, String> metricUrls = (Map<String, String>) entry2.getValue();
                LOGGER.debug("{} -> {}", timeRange, metricUrls);
                pw.println("<td>");

                Iterator metricUrlsIter = metricUrls.entrySet().iterator();
                while (metricUrlsIter.hasNext()) {
                    Map.Entry metricUrl = (Map.Entry) metricUrlsIter.next();
                    String metricUrlCell = "<a class=\"ui-state-default ui-corner-all\" href=\""
                            + metricUrl.getValue() + "\">" + metricUrl.getKey() + "</a>&nbsp;";
                    pw.println(metricUrlCell);
                }
                pw.println("</td>");
            }
            pw.println("</tr>");
            rowCount++;
        }

        LOGGER.debug("==  toJSONString()  ==");
        LOGGER.debug(JSONValue.toJSONString(json));

        // blank line for spacing between tables
        pw.println("<tr><td colspan=\"3\">&nbsp;</td></tr>");

        // Create HTML table for aggregate reports
        pw.println("<tr>");
        pw.println("<th colspan=\"3\">Weekly Reports</th>");
        pw.println("</tr>");
        addWeeklyReportUrls(pw, NUMBER_OF_WEEKLY_REPORTS, metricsServiceUrl);

        // blank line for spacing between tables
        pw.println("<tr><td colspan=\"3\">&nbsp;</td></tr>");

        pw.println("<tr>");
        pw.println("<th colspan=\"3\">Monthly Reports</th>");
        pw.println("</tr>");

        addMonthlyReportUrls(pw, NUMBER_OF_MONTHLY_REPORTS, metricsServiceUrl);

        // blank line for spacing between tables
        pw.println("<tr><td colspan=\"3\">&nbsp;</td></tr>");

        pw.println("<tr>");
        pw.println("<th colspan=\"3\">Yearly Reports</th>");
        pw.println("</tr>");

        addYearlyReportUrls(pw, NUMBER_OF_YEARLY_REPORTS, metricsServiceUrl);

        // blank line for spacing between tables
        pw.println("<tr><td colspan=\"3\">&nbsp;</td></tr>");

        pw.println("</table>");
    } catch (ParseException pe) {
        LOGGER.warn("Parse exception building report structure", pe);
    }

    LOGGER.debug("EXITING: renderContent");
}

From source file:com.kyne.webby.rtk.web.Connection.java

@Override
public void run() {
    InputStream in = null;
    try {/*  ww  w  . j a  v a2  s .  c om*/
        in = this.clientSocket.getInputStream();
        String url = null;
        String params = null;

        final StringBuffer buff = new StringBuffer();
        final int b = in.read();
        if (b < 0) {
            return;
        }
        buff.appendCodePoint(b);
        while (0 != in.available()) {
            buff.appendCodePoint(in.read());
        }
        final String httpContent = buff.toString();
        final StringTokenizer tokenizer = new StringTokenizer(httpContent, "\n");
        final String firstLine = tokenizer.nextToken();
        final String[] splittedFirstLine = firstLine.split(" ");
        if (splittedFirstLine.length > 1) {
            final String requestUrl = (firstLine.split(" "))[1]; //GET /url?params HTTP/1.X   or   //POST /url HTTP/1.X
            final Matcher result = this.urlRegex.matcher(requestUrl);
            if (result.find()) {
                url = result.group(1);
                params = result.group(2);
            } else {
                LogHelper.warn("Invalid URL format : " + requestUrl);
            }
            if (httpContent.startsWith("POST")) {
                String lastLine = null;
                while (tokenizer.hasMoreTokens()) {
                    lastLine = tokenizer.nextToken();
                }
                params = "?" + lastLine;
            }
        } else {
            LogHelper.warn("Empty Request with HttpContent = " + httpContent);
        }

        final boolean isAllowedRessource;
        if (url == null) {
            LogHelper.warn("Null url " + url);
            isAllowedRessource = false;
        } else {
            isAllowedRessource = this.isRestrictedUrl(url) || this.isContextualCallUrl(url)
                    || this.webServer.isAllowedRessource(url) || this.isPredefinedUrl(url);
        }
        if (isAllowedRessource) {
            if (url != null && params != null) {
                this.handleRequest(url, params, this.clientSocket);
            }
        } else {
            this.handleRequest("/404", params, clientSocket); //Forward to 404
        }
    } catch (final SocketException e) {
        /* Pics or it didn't happen ! */
    } catch (final Exception e) {
        LogHelper.error(e.getMessage(), e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (final IOException e) {
                /**/ }
        }
    }
}

From source file:com.guillaumesoft.escapehellprison.PurchaseActivity.java

/**
 * The application key. This is used to decrypt encrypted receipt responses. This should be replaced with the
 * application key obtained from the OUYA developers website.
 *//*from  w w  w .ja  v  a  2 s . co  m*/

byte[] loadApplicationKey() {
    // Create a PublicKey object from the key data downloaded from the developer portal.
    try {
        // Read in the key.der file (downloaded from the developer portal)
        InputStream inputStream = getResources().openRawResource(R.raw.key);
        byte[] applicationKey = new byte[inputStream.available()];
        inputStream.read(applicationKey);
        inputStream.close();
        return applicationKey;
    } catch (Exception e) {
        Log.e(LOG_TAG, "Unable to load application key", e);
    }

    return null;
}

From source file:JavaFiles.AbstractWsToolClient.java

/** Read the contents of an input stream into a byte array.
 * //from   www.j  ava2 s . co  m
 * @param inStream the input steam to read
 * @return the contents of the stream in a byte array
 * @throws IOException if all contents not read
 */
public byte[] readStream(InputStream inStream) throws IOException {
    printDebugMessage("readStream", "Begin", 1);
    byte[] ret = null;
    while (inStream.available() > 0) {
        long length = inStream.available();
        byte[] bytes = new byte[(int) length];
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length && (numRead = inStream.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }
        if (offset < bytes.length) {
            throw new IOException("Unable to read to end of stream");
        }
        printDebugMessage("readStream", "read " + bytes.length + " bytes", 2);
        if (ret == null)
            ret = bytes;
        else {
            byte[] tmp = ret.clone();
            ret = new byte[ret.length + bytes.length];
            System.arraycopy(tmp, 0, ret, 0, tmp.length);
            System.arraycopy(bytes, 0, ret, tmp.length, bytes.length);
        }
    }
    printDebugMessage("readStream", "End", 1);
    return ret;
}

From source file:calliope.db.MongoConnection.java

/**
 * Get an image from the database//  www  .ja va  2 s  .  co  m
 * @param collName the collection name
 * @param docID the docid of the corpix
 * @return the image data
 */
@Override
public byte[] getImageFromDb(String collName, String docID) {
    try {
        connect();
        GridFS gfs = new GridFS(db, collName);
        GridFSDBFile file = gfs.findOne(docID);
        if (file != null) {
            InputStream ins = file.getInputStream();
            long dataLen = file.getLength();
            // this only happens if it is > 2 GB
            if (dataLen > Integer.MAX_VALUE)
                throw new AeseException("file too big (size=" + dataLen + ")");
            byte[] data = new byte[(int) dataLen];
            int offset = 0;
            while (offset < dataLen) {
                int len = ins.available();
                offset += ins.read(data, offset, len);
            }
            return data;
        } else
            throw new FileNotFoundException(docID);
    } catch (Exception e) {
        e.printStackTrace(System.out);
        return null;
    }
}

From source file:core.AbstractTest.java

protected byte[] getResource(String sName) {
    InputStream is = null;
    byte[] abRet = null;

    if ((abRet = mResourcesCache.get(sName)) == null) {
        try {//ww  w  .  j a  v a  2s  .c  om
            is = Play.application().resourceAsStream(sName);
            abRet = new byte[is.available()];
            is.read(abRet);
            if (is.available() > 0) {
                assertFail("Resource too big <" + sName + ">");
            }
        } catch (Exception ex) {
            assertFail("Cannot read resource <" + sName + ">. Due to: " + ex.getMessage());
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception ex) {
                }
            }
        }
        mResourcesCache.put(sName, abRet);
    }

    return abRet;
}

From source file:com.google.blockly.model.BlockFactory.java

/** @return Number of blocks added to the factory. */
private int loadBlocks(InputStream blockIs) throws IOException {
    int blockAddedCount = 0;
    try {//from w  w w .ja  v  a2  s. c o m
        int size = blockIs.available();
        byte[] buffer = new byte[size];
        blockIs.read(buffer);

        String json = new String(buffer, "UTF-8");
        JSONArray blocks = new JSONArray(json);
        for (int i = 0; i < blocks.length(); i++) {
            JSONObject block = blocks.getJSONObject(i);
            String type = block.optString("type");
            if (!TextUtils.isEmpty(type)) {
                mBlockTemplates.put(type, fromJson(type, block));
                ++blockAddedCount;
            } else {
                throw new BlockLoadingException("Block " + i + " has no type and cannot be loaded.");
            }
        }
    } catch (JSONException e) {
        throw new BlockLoadingException(e);
    }

    return blockAddedCount;
}

From source file:fr.gael.dhus.network.RegulatedInputStream.java

/**
 * This method aims to retrieve stream size. Of course, stream size is
 * not always available, but in the case of file, the size is known, 
 * overwise stream is probably aware of possible block size can be served...
 * @param is the input stream to ge the size
 * @return the possible size of the stream
 * @throws IOException when stream access fails.
 *//*www  .ja  v a 2 s.co m*/
private long getStreamSize(InputStream is) throws IOException {
    if (is instanceof FileInputStream) {
        return ((FileInputStream) is).getChannel().size();
    }
    return (long) is.available();
}

From source file:com.epam.wilma.test.server.ExampleHandler.java

private void setAnswer(final Request baseRequest, final HttpServletRequest httpServletRequest,
        final HttpServletResponse httpServletResponse, final String requestBody) throws IOException {
    boolean needVersionAnswer = requestBody.contains("Wilma Test Server");
    if (answerShouldBeSent(requestBody) || needVersionAnswer) {
        byte[] responseBodyAsBytes = null;
        if (((httpServletRequest.getHeader(CONTENT_TYPE) != null)
                && (httpServletRequest.getHeader(CONTENT_TYPE).contains("text/plain")))
                || (needVersionAnswer)) {
            //just send the request back + Wilma-Logger-ID in front, if exists
            String answer = requestBody;
            if (httpServletRequest.getHeader(WILMA_LOGGER_ID) != null) {
                answer = httpServletRequest.getHeader(WILMA_LOGGER_ID) + " " + requestBody;
            }/* www .  j  a v  a 2s .  c o m*/
            httpServletResponse.setContentType("text/plain");
            httpServletResponse.setCharacterEncoding("UTF-8");
            responseBodyAsBytes = answer.getBytes();
            logger.info("Received message:\n-----------\n" + requestBody + "\n-----------");
        } else if (httpServletRequest.getHeader(ACCEPT_HEADER) == null) {
            httpServletResponse.getWriter().println("Missing accept header!");
        } else if (httpServletRequest.getHeader(ACCEPT_HEADER).contains(XML_TYPE)
                || httpServletRequest.getHeader(ACCEPT_HEADER).contains(ANY_TYPE)) {
            InputStream xml = getXmlFromFile(EXAMPLE_XML);
            httpServletResponse.setContentType("application/xml;charset=UTF-8");
            responseBodyAsBytes = (inputStreamConverter.getStringFromStream(xml)).getBytes();
        } else if (httpServletRequest.getHeader(ACCEPT_HEADER).contains(FASTINFOSET_TYPE)) {
            InputStream xml = getXmlFromFile(FIS_RESPONSE);
            httpServletResponse.setContentType("application/fastinfoset");
            httpServletResponse.setCharacterEncoding("UTF-8");
            responseBodyAsBytes = IOUtils.toByteArray(xml, xml.available());
        }
        if (responseBodyAsBytes != null) {
            //first copy wilma message id to the response, if necessary
            if (httpServletRequest.getHeader(WILMA_LOGGER_ID) != null) {
                httpServletResponse.addHeader(WILMA_LOGGER_ID, httpServletRequest.getHeader(WILMA_LOGGER_ID));
            }
            //Encodes response body with gzip if client accepts gzip encoding
            if (httpServletRequest.getHeader(ACCEPT_ENCODING) != null
                    && httpServletRequest.getHeader(ACCEPT_ENCODING).contains(GZIP_TYPE)) {
                ByteArrayOutputStream gzipped = gzipCompressor
                        .compress(new ByteArrayInputStream(responseBodyAsBytes));
                responseBodyAsBytes = gzipped.toByteArray();
                httpServletResponse.addHeader(CONTENT_ENCODING, GZIP_TYPE);
            }
            httpServletResponse.getOutputStream().write(responseBodyAsBytes);
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
        }
    }
}