Example usage for java.io FileInputStream available

List of usage examples for java.io FileInputStream available

Introduction

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

Prototype

public int available() throws IOException 

Source Link

Document

Returns an estimate of the number of remaining 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:org.apache.hadoop.mapred.TestConcatenatedCompressedInput.java

/**
 * Extended bzip2 test, similar to BuiltInGzipDecompressor test above.
 *//*  w  w  w.  ja  v  a2 s  .  c  o  m*/
@Test
public void testMoreBzip2() throws IOException {
    JobConf jobConf = new JobConf(defaultConf);

    CompressionCodec bzip2 = new BZip2Codec();
    ReflectionUtils.setConf(bzip2, jobConf);
    localFs.delete(workDir, true);

    System.out.println(COLOR_BR_MAGENTA + "testMoreBzip2() using non-native CBZip2InputStream (presumably)"
            + COLOR_NORMAL);

    // copy single-member test file to HDFS
    String fn1 = "testConcatThenCompress.txt" + bzip2.getDefaultExtension();
    Path fnLocal1 = new Path(System.getProperty("test.concat.data", "/tmp"), fn1);
    Path fnHDFS1 = new Path(workDir, fn1);
    localFs.copyFromLocalFile(fnLocal1, fnHDFS1);

    // copy multiple-member test file to HDFS
    String fn2 = "testCompressThenConcat.txt" + bzip2.getDefaultExtension();
    Path fnLocal2 = new Path(System.getProperty("test.concat.data", "/tmp"), fn2);
    Path fnHDFS2 = new Path(workDir, fn2);
    localFs.copyFromLocalFile(fnLocal2, fnHDFS2);

    FileInputFormat.setInputPaths(jobConf, workDir);

    // here's first pair of BlockDecompressorStreams:
    final FileInputStream in1 = new FileInputStream(fnLocal1.toString());
    final FileInputStream in2 = new FileInputStream(fnLocal2.toString());
    assertEquals("concat bytes available", 2567, in1.available());
    assertEquals("concat bytes available", 3056, in2.available());

    /*
        // FIXME
        // The while-loop below dies at the beginning of the 2nd concatenated
        // member (after 17 lines successfully read) with:
        //
        //   java.io.IOException: bad block header
        //   at org.apache.hadoop.io.compress.bzip2.CBZip2InputStream.initBlock(
        //   CBZip2InputStream.java:527)
        //
        // It is not critical to concatenated-gzip support, HADOOP-6835, so it's
        // simply commented out for now (and HADOOP-6852 filed).  If and when the
        // latter issue is resolved--perhaps by fixing an error here--this code
        // should be reenabled.  Note that the doMultipleBzip2BufferSizes() test
        // below uses the same testCompressThenConcat.txt.bz2 file but works fine.
            
        CompressionInputStream cin2 = bzip2.createInputStream(in2);
        LineReader in = new LineReader(cin2);
        Text out = new Text();
            
        int numBytes, totalBytes=0, lineNum=0;
        while ((numBytes = in.readLine(out)) > 0) {
          ++lineNum;
          totalBytes += numBytes;
        }
        in.close();
        assertEquals("total uncompressed bytes in concatenated test file",
         5346, totalBytes);
        assertEquals("total uncompressed lines in concatenated test file",
         84, lineNum);
     */

    // test CBZip2InputStream with lots of different input-buffer sizes
    doMultipleBzip2BufferSizes(jobConf, false);

    // no native version of bzip2 codec (yet?)
    //doMultipleBzip2BufferSizes(jobConf, true);
}

From source file:com.irccloud.android.activity.BaseActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_logout:
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Logout");
        builder.setMessage("Would you like to logout of IRCCloud?");

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            @Override/* www  .  j  a  v a  2s.  c om*/
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("Logout", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                conn.logout();
                if (mGoogleApiClient.isConnected()) {
                    Auth.CredentialsApi.disableAutoSignIn(mGoogleApiClient)
                            .setResultCallback(new ResultCallback<Status>() {
                                @Override
                                public void onResult(Status status) {
                                    Intent i = new Intent(BaseActivity.this, LoginActivity.class);
                                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startActivity(i);
                                    finish();
                                }
                            });
                } else {
                    Intent i = new Intent(BaseActivity.this, LoginActivity.class);
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(i);
                    finish();
                }
            }
        });
        AlertDialog dialog = builder.create();
        dialog.setOwnerActivity(this);
        dialog.show();
        break;
    case R.id.menu_settings:
        Intent i = new Intent(this, PreferencesActivity.class);
        startActivity(i);
        break;
    case R.id.menu_feedback:
        try {
            String bugReport = "Briefly describe the issue below:\n\n\n\n\n" + "===========\n"
                    + ((NetworkConnection.getInstance().getUserInfo() != null)
                            ? ("UID: " + NetworkConnection.getInstance().getUserInfo().id + "\n")
                            : "")
                    + "App version: " + getPackageManager().getPackageInfo(getPackageName(), 0).versionName
                    + " (" + getPackageManager().getPackageInfo(getPackageName(), 0).versionCode + ")\n"
                    + "Device: " + Build.MODEL + "\n" + "Android version: " + Build.VERSION.RELEASE + "\n"
                    + "Firmware fingerprint: " + Build.FINGERPRINT + "\n";

            File logsDir = new File(getFilesDir(),
                    ".Fabric/com.crashlytics.sdk.android.crashlytics-core/log-files/");
            File log = null;
            File output = null;
            if (logsDir.exists()) {
                long max = Long.MIN_VALUE;
                for (File f : logsDir.listFiles()) {
                    if (f.lastModified() > max) {
                        max = f.lastModified();
                        log = f;
                    }
                }

                if (log != null) {
                    File f = new File(getFilesDir(), "logs");
                    f.mkdirs();
                    output = new File(f, LOG_FILENAME);
                    byte[] b = new byte[1];

                    FileOutputStream out = new FileOutputStream(output);
                    FileInputStream is = new FileInputStream(log);
                    is.skip(5);

                    while (is.available() > 0 && is.read(b, 0, 1) > 0) {
                        if (b[0] == ' ') {
                            while (is.available() > 0 && is.read(b, 0, 1) > 0) {
                                out.write(b);
                                if (b[0] == '\n')
                                    break;
                            }
                        }
                    }
                    is.close();
                    out.close();
                }
            }

            Intent email = new Intent(Intent.ACTION_SEND);
            email.setData(Uri.parse("mailto:"));
            email.setType("message/rfc822");
            email.putExtra(Intent.EXTRA_EMAIL, new String[] { "IRCCloud Team <team@irccloud.com>" });
            email.putExtra(Intent.EXTRA_TEXT, bugReport);
            email.putExtra(Intent.EXTRA_SUBJECT, "IRCCloud for Android");
            if (log != null) {
                email.putExtra(Intent.EXTRA_STREAM,
                        FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", output));
            }
            startActivityForResult(Intent.createChooser(email, "Send Feedback:"), 0);
        } catch (Exception e) {
            Toast.makeText(this, "Unable to generate email report: " + e.getMessage(), Toast.LENGTH_SHORT)
                    .show();
            Crashlytics.logException(e);
            NetworkConnection.printStackTraceToCrashlytics(e);
        }
        break;
    }
    return super.onOptionsItemSelected(item);
}

From source file:org.pentaho.di.core.row.ValueDataUtil.java

public static String createChecksum(ValueMetaInterface metaA, Object dataA, String type) {
    String md5Hash = null;/*from   w ww . j av a 2s.  co  m*/
    FileInputStream in = null;
    try {
        in = new FileInputStream(dataA.toString());
        int bytes = in.available();
        byte[] buffer = new byte[bytes];
        in.read(buffer);

        StringBuffer md5HashBuff = new StringBuffer(32);
        byte[] b = MessageDigest.getInstance(type).digest(buffer);
        int len = b.length;
        for (int x = 0; x < len; x++) {
            md5HashBuff.append(String.format("%02x", b[x]));
        }

        md5Hash = md5HashBuff.toString();

    } catch (Exception e) {
        // ignore - should likely log the exception
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (Exception e) {
            // Ignore
        }
    }

    return md5Hash;
}

From source file:net.rim.ejde.internal.core.ContextManager.java

public BlackBerryProperties loadModelFromStore(File file) {
    BlackBerryProperties blackBerryProperties = null;

    if (null == file || !file.exists() || !file.isFile()) {
        return null;
    }//from w w  w  . j  a va  2s.  c om
    log.trace("loading " + file.getPath());
    FileInputStream fileInputStream = null;

    try {
        fileInputStream = new FileInputStream(file);

        if (0 < fileInputStream.available()) {
            XStream xStream = getXStream();
            blackBerryProperties = (BlackBerryProperties) xStream.fromXML(fileInputStream);
        } else {
            blackBerryProperties = new BlackBerryProperties();
        }
    } catch (Throwable t) {
        log.debug("", t);
    } finally {
        if (null != fileInputStream) {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                log.error("Error closing input stream", e);
            }
        }
    }
    log.trace("finished loading " + file.getPath());
    return blackBerryProperties;
}

From source file:net.itransformers.idiscover.v2.core.discovererIntegrationTest.mplsLab.IntegrationTestsMplsLab.java

@Test
public void testR1() throws TransformerException, IOException, SAXException, ParserConfigurationException {
    new NodeDiscoverer() {

        @Override/*  w  ww. j  av a  2  s .  c om*/
        public NodeDiscoveryResult discover(ConnectionDetails connectionDetails) {

            FileInputStream is = null;
            try {
                is = new FileInputStream(
                        "iDiscover/netDiscoverer/src/test/resources/raw-data-mpls-lab/raw-data-R1.xml");
            } catch (FileNotFoundException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
            byte[] data = new byte[0];
            try {
                data = new byte[is.available()];
                is.read(data);

            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }

            rawdata.setData(data);

            NodeDiscoveryResult result = new NodeDiscoveryResult(null, null);
            //String devName = walker.getDeviceName(resource);
            result.setDiscoveredData("rawData", rawdata.getData());
            DiscoveredDeviceData discoveredDeviceData = discoveryHelper.parseDeviceRawData(rawdata,
                    discoveryTypes, null);
            result.setDiscoveredData("deviceData", discoveredDeviceData);

            Map<String, Integer> neighbourTypeCounts = fillInNeighbourTree(discoveredDeviceData.getObject());

            //deviceLogger.handleDevice(result.getNodeId(),rawdata,discoveredDeviceData,resource);
            // xmlTopologyDeviceLogger.handleDevice(result.getNodeId(),rawdata,discoveredDeviceData,resource);

            System.out.println(neighbourTypeCounts);
            Assert.assertEquals((Object) 3, neighbourTypeCounts.get("CDP"));
            Assert.assertEquals((Object) 1, neighbourTypeCounts.get("r_ISIS"));
            Assert.assertEquals((Object) 1, neighbourTypeCounts.get("Slash31"));
            Assert.assertEquals((Object) 1, neighbourTypeCounts.get("Slash30"));
            Assert.assertEquals((Object) 1, neighbourTypeCounts.get("ARP"));

            return result;
        }
    }.discover(null);
}

From source file:net.itransformers.idiscover.v2.core.discovererIntegrationTest.mplsLab.IntegrationTestsMplsLab.java

public void testR4() throws TransformerException, IOException, SAXException, ParserConfigurationException {
    new NodeDiscoverer() {
        @Override//from w  ww. j a v a 2 s  .c om
        public NodeDiscoveryResult discover(ConnectionDetails connectionDetails) {

            //                resource = new Resource("R4", "10.17.1.13", resourceParams);
            //                resource.setDeviceType("CISCO");

            FileInputStream is = null;
            try {
                is = new FileInputStream(
                        "iDiscover/netDiscoverer/src/test/resources/raw-data-mpls-lab/raw-data-R4.xml");
            } catch (FileNotFoundException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
            byte[] data = new byte[0];
            try {
                data = new byte[is.available()];
                is.read(data);

            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }

            rawdata.setData(data);

            NodeDiscoveryResult result = new NodeDiscoveryResult("R4", null);
            //String devName = walker.getDeviceName(resource);
            result.setDiscoveredData("rawData", rawdata.getData());
            DiscoveredDeviceData discoveredDeviceData = discoveryHelper.parseDeviceRawData(rawdata,
                    discoveryTypes, null);
            result.setDiscoveredData("deviceData", discoveredDeviceData);

            Map<String, Integer> neighbourTypeCounts = fillInNeighbourTree(discoveredDeviceData.getObject());
            //                deviceLogger.handleDevice(result.getNodeId(),rawdata,discoveredDeviceData,resource);
            // xmlTopologyDeviceLogger.handleDevice(result.getNodeId(),rawdata,discoveredDeviceData,resource);

            System.out.println(neighbourTypeCounts);

            Assert.assertEquals((Object) 3, neighbourTypeCounts.get("CDP"));
            Assert.assertEquals((Object) 1, neighbourTypeCounts.get("r_OSPF"));
            Assert.assertEquals((Object) 2, neighbourTypeCounts.get("r_ISIS"));
            Assert.assertEquals((Object) 2, neighbourTypeCounts.get("Slash30"));

            return result;
        }
    }.discover(null);
}

From source file:net.itransformers.idiscover.v2.core.discovererIntegrationTest.mplsLab.IntegrationTestsMplsLab.java

public void testR3() throws TransformerException, IOException, SAXException, ParserConfigurationException {
    new NodeDiscoverer() {

        @Override/*w w  w .j  a va2s  . c o m*/
        public NodeDiscoveryResult discover(ConnectionDetails connectionDetails) {

            //                resource = new Resource("R3", "10.17.1.13", resourceParams);
            //                resource.setDeviceType("CISCO");

            FileInputStream is = null;
            try {
                is = new FileInputStream(
                        "iDiscover/netDiscoverer/src/test/resources/raw-data-mpls-lab/raw-data-R3.xml");
            } catch (FileNotFoundException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
            byte[] data = new byte[0];
            try {
                data = new byte[is.available()];
                is.read(data);

            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }

            rawdata.setData(data);

            NodeDiscoveryResult result = new NodeDiscoveryResult("R3", null);
            //String devName = walker.getDeviceName(resource);
            result.setDiscoveredData("rawData", rawdata.getData());
            DiscoveredDeviceData discoveredDeviceData = discoveryHelper.parseDeviceRawData(rawdata,
                    discoveryTypes, null);
            result.setDiscoveredData("deviceData", discoveredDeviceData);

            Map<String, Integer> neighbourTypeCounts = fillInNeighbourTree(discoveredDeviceData.getObject());
            //                deviceLogger.handleDevice(result.getNodeId(),rawdata,discoveredDeviceData,resource);
            // xmlTopologyDeviceLogger.handleDevice(result.getNodeId(),rawdata,discoveredDeviceData,resource);

            System.out.println(neighbourTypeCounts);

            Assert.assertEquals((Object) 4, neighbourTypeCounts.get("CDP"));
            Assert.assertEquals((Object) 4, neighbourTypeCounts.get("r_OSPF"));

            Assert.assertEquals((Object) 1, neighbourTypeCounts.get("ARP"));

            return result;
        }
    }.discover(null);
}

From source file:net.itransformers.idiscover.v2.core.discovererIntegrationTest.mplsLab.IntegrationTestsMplsLab.java

public void testR5() throws TransformerException, IOException, SAXException, ParserConfigurationException {
    new NodeDiscoverer() {
        @Override/*ww w .ja v a  2 s .c  o m*/
        public NodeDiscoveryResult discover(ConnectionDetails connectionDetails) {
            //                resource = new Resource("R5", "10.17.1.13", resourceParams);
            //                resource.setDeviceType("CISCO");

            FileInputStream is = null;
            try {
                is = new FileInputStream(
                        "iDiscover/netDiscoverer/src/test/resources/raw-data-mpls-lab/raw-data-R5.xml");
            } catch (FileNotFoundException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
            byte[] data = new byte[0];
            try {
                data = new byte[is.available()];
                is.read(data);

            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }

            rawdata.setData(data);

            NodeDiscoveryResult result = new NodeDiscoveryResult("R5", null);
            //String devName = walker.getDeviceName(resource);
            result.setDiscoveredData("rawData", rawdata.getData());
            DiscoveredDeviceData discoveredDeviceData = discoveryHelper.parseDeviceRawData(rawdata,
                    discoveryTypes, null);
            result.setDiscoveredData("deviceData", discoveredDeviceData);

            Map<String, Integer> neighbourTypeCounts = fillInNeighbourTree(discoveredDeviceData.getObject());
            //deviceLogger.handleDevice(result.getNodeId(),rawdata,discoveredDeviceData,resource);
            // xmlTopologyDeviceLogger.handleDevice(result.getNodeId(),rawdata,discoveredDeviceData,resource);

            System.out.println(neighbourTypeCounts);

            Assert.assertEquals((Object) 3, neighbourTypeCounts.get("CDP"));
            Assert.assertEquals((Object) 1, neighbourTypeCounts.get("r_OSPF"));
            Assert.assertEquals((Object) 2, neighbourTypeCounts.get("r_ISIS"));
            Assert.assertEquals((Object) 1, neighbourTypeCounts.get("Slash30"));

            Assert.assertEquals((Object) 1, neighbourTypeCounts.get("ARP"));

            return result;
        }
    }.discover(null);
}

From source file:com.android.mms.ui.ConversationList.java

private String getLaunchMode(String filename) {
    String launchMode = "";
    try {//from w w w  .j  a  v a2s .  co m
        File mFile = new File(filename);
        if (mFile.exists()) {
            FileInputStream is = new FileInputStream(filename);
            int length = is.available();
            byte buffer[] = new byte[length];
            is.read(buffer);
            launchMode = EncodingUtils.getString(buffer, "UTF-8");
            is.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return launchMode;
}

From source file:net.itransformers.idiscover.v2.core.discovererIntegrationTest.mplsLab.IntegrationTestsMplsLab.java

@Test
public void testR2() throws TransformerException, IOException, SAXException, ParserConfigurationException {
    new NodeDiscoverer() {

        @Override/*www  .j  av a2 s . c  om*/
        public NodeDiscoveryResult discover(ConnectionDetails connectionDetails) {

            //                resource = new Resource("R2", "10.17.1.13", resourceParams);
            //                resource.setDeviceType("CISCO");

            try {
            } catch (Exception e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }

            FileInputStream is = null;
            try {
                is = new FileInputStream(
                        "iDiscover/netDiscoverer/src/test/resources/raw-data-mpls-lab/raw-data-R2.xml");
            } catch (FileNotFoundException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
            byte[] data = new byte[0];
            try {
                data = new byte[is.available()];
                is.read(data);

            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }

            rawdata.setData(data);

            NodeDiscoveryResult result = new NodeDiscoveryResult("R2", null);
            //String devName = walker.getDeviceName(resource);
            result.setDiscoveredData("rawData", rawdata.getData());
            DiscoveredDeviceData discoveredDeviceData = discoveryHelper.parseDeviceRawData(rawdata,
                    discoveryTypes, null);
            result.setDiscoveredData("deviceData", discoveredDeviceData);

            Map<String, Integer> neighbourTypeCounts = fillInNeighbourTree(discoveredDeviceData.getObject());
            //                deviceLogger.handleDevice(result.getNodeId(),rawdata,discoveredDeviceData,resource);
            // xmlTopologyDeviceLogger.handleDevice(result.getNodeId(),rawdata,discoveredDeviceData,resource);

            System.out.println(neighbourTypeCounts);

            Assert.assertEquals((Object) 3, neighbourTypeCounts.get("CDP"));
            Assert.assertEquals((Object) 2, neighbourTypeCounts.get("r_ISIS"));
            Assert.assertEquals((Object) 1, neighbourTypeCounts.get("r_OSPF"));

            Assert.assertEquals((Object) 2, neighbourTypeCounts.get("Slash30"));

            return result;
        }
    }.discover(null);
}