Example usage for java.io BufferedInputStream available

List of usage examples for java.io BufferedInputStream available

Introduction

In this page you can find the example usage for java.io BufferedInputStream available.

Prototype

public synchronized 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 by the next invocation of a method for this input stream.

Usage

From source file:net.momodalo.app.vimtouch.VimTouch.java

private void defaultButtons(boolean force) {
    File file = new File(getQuickbarFile());

    if (!force && file.exists())
        return;//from ww w.  j a  v a 2s.c  o  m

    try {
        BufferedInputStream is = new BufferedInputStream(getResources().openRawResource(R.raw.quickbar));
        FileWriter fout = new FileWriter(file);
        while (is.available() > 0) {
            fout.write(is.read());
        }
        fout.close();
    } catch (Exception e) {
        Log.e(LOG_TAG, "install default quickbar", e);
    }

}

From source file:org.seasar.dbflute.logic.replaceschema.loaddata.impl.DfAbsractDataWriter.java

protected boolean processBinary(File dataFile, String tableName, String columnName, String value,
        PreparedStatement ps, int bindCount, Map<String, DfColumnMeta> columnInfoMap) throws SQLException {
    if (value == null) {
        return false; // basically no way
    }/*w  ww  . j  ava 2 s . c o  m*/
    final DfColumnMeta columnInfo = columnInfoMap.get(columnName);
    if (columnInfo != null) {
        final Class<?> columnType = getBindType(tableName, columnInfo);
        if (columnType != null) {
            if (!byte[].class.isAssignableFrom(columnType)) {
                return false;
            }
            // the value should be a path to a binary file
            // from data file's current directory
            final String path;
            final String trimmedValue = value.trim();
            if (trimmedValue.startsWith("/")) { // means absolute path
                path = trimmedValue;
            } else {
                final String dataFilePath = Srl.replace(dataFile.getAbsolutePath(), "\\", "/");
                final String baseDirPath = Srl.substringLastFront(dataFilePath, "/");
                path = baseDirPath + "/" + trimmedValue;
            }
            final File binaryFile = new File(path);
            if (!binaryFile.exists()) {
                throwLoadDataBinaryFileNotFoundException(tableName, columnName, path);
            }
            final List<Byte> byteList = new ArrayList<Byte>();
            BufferedInputStream bis = null;
            try {
                bis = new BufferedInputStream(new FileInputStream(binaryFile));
                for (int availableSize; (availableSize = bis.available()) > 0;) {
                    final byte[] bytes = new byte[availableSize];
                    bis.read(bytes);
                    for (byte b : bytes) {
                        byteList.add(b);
                    }
                }
                byte[] bytes = new byte[byteList.size()];
                for (int i = 0; i < byteList.size(); i++) {
                    bytes[i] = byteList.get(i);
                }
                ps.setBytes(bindCount, bytes);
            } catch (IOException e) {
                throwLoadDataBinaryFileReadFailureException(tableName, columnName, path, e);
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException ignored) {
                    }
                }
            }
            return true;
        }
    }
    // unsupported when meta data is not found
    return false;
}

From source file:org.wso2.carbon.connector.integration.test.amazonsns.AmazonsnsConnectorIntegrationTest.java

/**
 * Gets the file content./* www.j a  v a2  s . c o  m*/
 *
 * @param path the path
 * @return the file content
 * @throws IOException Signals that an I/O exception has occurred.
 */
private String getFileContent(String path) throws IOException {

    String fileContent;
    BufferedInputStream bfist = new BufferedInputStream(new FileInputStream(path));

    byte[] buf = new byte[bfist.available()];
    bfist.read(buf);
    fileContent = new String(buf);

    if (bfist != null) {
        bfist.close();
    }
    return fileContent;
}

From source file:org.xerela.net.sim.telnet.TelnetTest.java

/**
 * /*  www  .  j  av a  2  s . c  o  m*/
 * @throws Exception
 */
public void testTelnet() throws Exception {
    /*     Start:
     *   +------------+
     * ,-! Send Input !
     * ! +------------+
     * !     | 
     * ! +------------+
     * ! ! Read Input !------. no
     * ! +------------+       \
     * !yes   |                |
     * ! +------------+ no +------------+ yes +------+
     * `-! IsCorrect? !----! IsTooLong? !-----! FAIL !
     *   +------------+    +------------+     +------+
     * 
     */
    IpAddress local = IpAddress.getIpAddress(Util.getLocalHost(), null);

    TelnetClient client = new TelnetClient();
    client.connect(local.getRealAddress());

    RecordingLoader recordingLoader = RecordingLoader.getInstance();
    Configuration config = ConfigurationService.getInstance()
            .findConfigurationFile(ConfigurationService.DEFAULT_CONFIG);

    WorkingConfig wc = config.getDefaultOperationWorkingConfig();

    // create the operation manually first so that we can easily get the records
    RecordingOperation operation = (RecordingOperation) recordingLoader.createOperation(wc, local, local);
    Interaction[] interactions = operation.getInteractions();
    operation.tearDown();

    BufferedInputStream in = new BufferedInputStream(client.getInputStream());
    PrintStream out = new PrintStream(client.getOutputStream(), true);

    byte[] bbuf = new byte[2048];

    CharSequenceBuffer cbuf = new CharSequenceBuffer();
    for (int i = 0; i < interactions.length; i++) {
        Interaction currInteraction = interactions[i];

        String proto = currInteraction.getCliProtocol();
        if (!proto.equals("Telnet")) {
            /*
             * Because the recording might have other protocols we should stop when we encounter one.
             * The recording may not behave properly if we continue as we are.
             * If we got through at least 10 interactions then this test is probably still valid.
             */
            assertTrue(
                    "At least 10 telnet interction should have been handled.  Maybe this test should be run with another recording.",
                    i > 10);
            System.err.println(
                    "Continueing could disrupt the validity of this test.  This test will only support Telnet operations.");
            break;
        }

        // The timeout will be four times the expected time or 4 seconds, whichever is longer.
        Long interactionTime = currInteraction.getEndTime() - currInteraction.getStartTime();
        long time = Math.max((long) (interactionTime * wc.getRateMultiplier()) * 4, 4000);
        long start = System.currentTimeMillis();

        CharSequence input = currInteraction.getCliCommand();
        CharSequence response = currInteraction.getCliResponse();
        if (!input.equals("No input sent") && !input.equals("")) {
            out.println(input);
        }

        cbuf.reset();
        while (true) {
            int len = 0;
            if (in.available() <= 0) {
                try {
                    Thread.sleep(250);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (in.available() <= 0) {
                    if (System.currentTimeMillis() - start > time) {
                        // isTooLong
                        fail("Timeout reached waiting for response for interaction '"
                                + currInteraction.getCliCommand() + "'");
                    }
                    continue;
                }
            }
            len = in.read(bbuf);
            cbuf.write(bbuf, 0, len);

            // isCorrect?
            if (compare(cbuf, response)) {
                break;
            } else if (System.currentTimeMillis() - start > time) {
                // isTooLong
                fail("Timeout reached waiting for response for interaction '" + currInteraction.getCliCommand()
                        + "'");
            }
        }
    }
}

From source file:org.wso2.connector.integration.test.base.ConnectorIntegrationTestBase.java

/**
 * Method to read in contents of a file as String
 * /*from  www  .  j  a  v  a2  s  .  c  o  m*/
 * @param path file path.
 * @return String contents of file
 * @throws IOException
 */
private String getFileContent(String path) throws IOException {

    String fileContent = null;
    BufferedInputStream bfist = new BufferedInputStream(new FileInputStream(path));

    try {
        byte[] buf = new byte[bfist.available()];
        bfist.read(buf);
        fileContent = new String(buf);
    } catch (IOException ioe) {
        log.error("Error reading request from file.", ioe);
    } finally {
        if (bfist != null) {
            bfist.close();
        }
    }

    return fileContent;

}

From source file:ch.cyberduck.core.Path.java

/**
 * Updates the current number of bytes transferred in the status reference.
 *
 * @param in       The stream to read from
 * @param out      The stream to write to
 * @param listener The stream listener to notify about bytes received and sent
 * @param limit    Transfer only up to this length
 * @param status   Transfer status//from w w w.ja v a  2 s .c  o m
 * @throws IOException                 Write not completed due to a I/O problem
 * @throws ConnectionCanceledException When transfer is interrupted by user setting the
 *                                     status flag to cancel.
 */
protected void transfer(final InputStream in, final OutputStream out, final StreamListener listener,
        final long limit, final TransferStatus status) throws IOException {
    final BufferedInputStream bi = new BufferedInputStream(in);
    final BufferedOutputStream bo = new BufferedOutputStream(out);
    try {
        final int chunksize = Preferences.instance().getInteger("connection.chunksize");
        final byte[] chunk = new byte[chunksize];
        long bytesTransferred = 0;
        while (!status.isCanceled()) {
            final int read = bi.read(chunk, 0, chunksize);
            if (-1 == read) {
                if (log.isDebugEnabled()) {
                    log.debug("End of file reached");
                }
                // End of file
                status.setComplete();
                break;
            } else {
                status.addCurrent(read);
                listener.bytesReceived(read);
                bo.write(chunk, 0, read);
                listener.bytesSent(read);
                bytesTransferred += read;
                if (limit == bytesTransferred) {
                    if (log.isDebugEnabled()) {
                        log.debug(String.format("Limit %d reached reading from stream", limit));
                    }
                    // Part reached
                    if (0 == bi.available()) {
                        // End of file
                        status.setComplete();
                    }
                    break;
                }
            }
        }
    } finally {
        bo.flush();
    }
    if (status.isCanceled()) {
        throw new ConnectionCanceledException("Interrupted transfer");
    }
}

From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.dta.DTAFileReader.java

/**
 *
 * @param stream/*  w ww.  j  a v  a 2s .co  m*/
 */
private void decodeValueLabels(BufferedInputStream stream) throws IOException {

    dbgLog.fine("***** decodeValueLabels(): start *****");

    if (stream == null) {
        throw new IllegalArgumentException("stream == null!");
    }

    if (stream.available() != 0) {
        if ((Integer) smd.getFileInformation().get("releaseNumber") <= 105) {
            parseValueLabelsRelease105(stream);
        } else if ((Integer) smd.getFileInformation().get("releaseNumber") >= 105) {
            parseValueLabelsReleasel108(stream);
        }
    } else {
        dbgLog.fine("no value-label table: end of file");

    }
    dbgLog.fine("***** decodeValueLabels(): end *****");
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.dta.DTAFileReader.java

/**
 *
 * @param stream// w w  w.j  a va2s  . c  om
 */
private void decodeValueLabels(BufferedInputStream stream) throws IOException {

    dbgLog.fine("decodeValueLabels(): start");

    if (stream == null) {
        throw new IllegalArgumentException("stream == null!");
    }

    if (stream.available() != 0) {
        if (releaseNumber <= 105) {
            parseValueLabelsRelease105(stream);
        } else {
            parseValueLabelsReleasel108(stream);
        }
    } else {
        dbgLog.fine("no value-label table: end of file");
    }
    dbgLog.fine("decodeValueLabels(): end");
}

From source file:org.wso2.connector.integration.test.base.ConnectorIntegrationTestBase.java

/**
 * This method de-serialize XML object graph. In addition if there are parameterized strings such as
 * <code>%s(accessToken)</code> in the XML file, those will be parsed and and replace with the values
 * specified in the Connection Properties resource file or the parameter map passed in to this method. <br>
 * <br>//from w ww.  j a  v a2 s.c  o  m
 * <b>Example XML file.</b><br>
 * 
 * <pre>
 * {@code
 * <?xml version="1.0" encoding="UTF-8"?> 
 * <java class="java.beans.XMLDecoder"> 
 *  <object class="test.base.Person"> 
 *   <void property="address"> 
 *    <object class="test.base.Address"> 
 *     <void property="city"> 
 *      <string>Test City</string> 
 *     </void> 
 *     <void property="country"> 
 *      <string>Test Country</string> 
 *     </void> 
 *     <void property="street"> 
 *      <string>Test street</string> 
 *     </void> 
 *    </object> 
 *   </void> 
 *  <void property="age"> 
 *    <int>20</int> 
 *   </void> 
 *   <void property="name"> 
 *    <string>Test Person Name</string> 
 *   </void> 
 *  </object> 
 * </java>
 *  }
 * </pre>
 * 
 * @param filePath file name including path to the XML serialized file.
 * @param paramMap map containing key value pairs where key being the parameter specified in the XML file
 *        if parameter in XML is <code>%s(accessToken)</code>, the key should be just
 *        <code>accessToken</code>.
 * @return the de-serialized object, user can cast this to the object type specified in the XML.
 * @throws IOException if file path is null or empty as well as if there's any exception while reading the
 *         XML file.
 */
protected Object loadObjectFromFile(String fileName, Map<String, String> paramMap) throws IOException {

    String filePath = pathToRequestsDirectory + fileName;
    if (filePath == null || filePath.isEmpty()) {
        throw new IOException("File path cannot be null or empty.");
    }

    Object retObj = null;
    BufferedInputStream bi = null;
    XMLDecoder decoder = null;

    try {
        bi = new BufferedInputStream(new FileInputStream(filePath));
        byte[] buf = new byte[bi.available()];
        bi.read(buf);
        String content = new String(buf);

        if (connectorProperties != null) {
            // We don't need to change the original connection properties in case same key is sent with
            // different value.
            Properties prop = (Properties) connectorProperties.clone();
            if (paramMap != null) {
                prop.putAll(paramMap);
            }
            Matcher matcher = Pattern.compile("%s\\(([A-Za-z0-9]*)\\)", Pattern.DOTALL).matcher(content);
            while (matcher.find()) {
                String key = matcher.group(1);
                content = content.replaceAll("%s\\(" + key + "\\)",
                        Matcher.quoteReplacement(prop.getProperty(key)));
            }
        }

        ByteArrayInputStream in = new ByteArrayInputStream(content.getBytes(Charset.defaultCharset()));

        decoder = new XMLDecoder(in);
        retObj = decoder.readObject();
    } finally {
        if (bi != null) {
            bi.close();
        }
        if (decoder != null) {
            decoder.close();
        }
    }

    return retObj;
}

From source file:org.wso2.carbon.connector.integration.test.eloqua.EloquaConnectorIntegrationTest.java

/**
 * Method to read in contents of a file as String
 *
 * @param path/*from   w  ww .  ja v a2s.c  om*/
 * @return String contents of file
 * @throws IOException
 */
private String getFileContent(String path) throws IOException {
    String fileContent = null;
    BufferedInputStream bfist = new BufferedInputStream(new FileInputStream(path));
    try {
        byte[] buf = new byte[bfist.available()];
        bfist.read(buf);
        fileContent = new String(buf);
    } catch (IOException ioe) {
        log.error("Error reading request from file.", ioe);
    } finally {
        if (bfist != null) {
            bfist.close();
        }
    }
    return fileContent;
}