Example usage for java.io FileInputStream close

List of usage examples for java.io FileInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this file input stream and releases any system resources associated with the stream.

Usage

From source file:net.sf.jsignpdf.InstallCert.java

/**
 * The main - whole logic of Install Cert Tool.
 * //from w ww.  java  2 s  .  co m
 * @param args
 * @throws Exception
 */
public static void main(String[] args) {
    String host;
    int port;
    char[] passphrase;

    System.out.println("InstallCert - Install CA certificate to Java Keystore");
    System.out.println("=====================================================");

    final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    try {
        if ((args.length == 1) || (args.length == 2)) {
            String[] c = args[0].split(":");
            host = c[0];
            port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
            String p = (args.length == 1) ? "changeit" : args[1];
            passphrase = p.toCharArray();
        } else {
            String tmpStr;
            do {
                System.out.print("Enter hostname or IP address: ");
                tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null);
            } while (tmpStr == null);
            host = tmpStr;
            System.out.print("Enter port number [443]: ");
            tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null);
            port = tmpStr == null ? 443 : Integer.parseInt(tmpStr);
            System.out.print("Enter keystore password [changeit]: ");
            tmpStr = reader.readLine();
            String p = "".equals(tmpStr) ? "changeit" : tmpStr;
            passphrase = p.toCharArray();
        }

        char SEP = File.separatorChar;
        final File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
        final File file = new File(dir, "cacerts");

        System.out.println("Loading KeyStore " + file + "...");
        InputStream in = new FileInputStream(file);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(in, passphrase);
        in.close();

        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory factory = context.getSocketFactory();

        System.out.println("Opening connection to " + host + ":" + port + "...");
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            System.out.println("Starting SSL handshake...");
            socket.startHandshake();
            socket.close();
            System.out.println();
            System.out.println("No errors, certificate is already trusted");
        } catch (SSLException e) {
            System.out.println();
            System.out.println("Certificate is not yet trusted.");
            //        e.printStackTrace(System.out);
        }

        X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.out.println("Could not obtain server certificate chain");
            return;
        }

        System.out.println();
        System.out.println("Server sent " + chain.length + " certificate(s):");
        System.out.println();
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        for (int i = 0; i < chain.length; i++) {
            X509Certificate cert = chain[i];
            System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN());
            System.out.println("   Issuer  " + cert.getIssuerDN());
            sha1.update(cert.getEncoded());
            System.out.println("   sha1    " + toHexString(sha1.digest()));
            md5.update(cert.getEncoded());
            System.out.println("   md5     " + toHexString(md5.digest()));
            System.out.println();
        }

        System.out.print("Enter certificate to add to trusted keystore or 'q' to quit [1]: ");
        String line = reader.readLine().trim();
        int k = -1;
        try {
            k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
        } catch (NumberFormatException e) {
        }

        if (k < 0 || k >= chain.length) {
            System.out.println("KeyStore not changed");
        } else {
            try {
                System.out.println("Creating keystore backup");
                final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                final File backupFile = new File(dir,
                        CACERTS_KEYSTORE + "." + dateFormat.format(new java.util.Date()));
                final FileInputStream fis = new FileInputStream(file);
                final FileOutputStream fos = new FileOutputStream(backupFile);
                IOUtils.copy(fis, fos);
                fis.close();
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Installing certificate...");

            X509Certificate cert = chain[k];
            String alias = host + "-" + (k + 1);
            ks.setCertificateEntry(alias, cert);

            OutputStream out = new FileOutputStream(file);
            ks.store(out, passphrase);
            out.close();

            System.out.println();
            System.out.println(cert);
            System.out.println();
            System.out.println("Added certificate to keystore '" + file + "' using alias '" + alias + "'");
        }
    } catch (Exception e) {
        System.out.println();
        System.out.println("----------------------------------------------");
        System.out.println("Problem occured during installing certificate:");
        e.printStackTrace();
        System.out.println("----------------------------------------------");
    }
    System.out.println("Press Enter to finish...");
    try {
        reader.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static void main(String args[]) throws IOException {
    FileInputStream f1 = new FileInputStream("ByteArrayIOApp.java");
    FileInputStream f2 = new FileInputStream("FileIOApp.java");
    SequenceInputStream inStream = new SequenceInputStream(f1, f2);
    boolean eof = false;
    int byteCount = 0;
    while (!eof) {
        int c = inStream.read();
        if (c == -1)
            eof = true;/*from   w  w  w . j  ava 2 s .c o  m*/
        else {
            System.out.print((char) c);
            ++byteCount;
        }
    }
    System.out.println(byteCount + " bytes were read");
    inStream.close();
    f1.close();
    f2.close();
}

From source file:fr.inria.edelweiss.kgdqp.core.CentralizedInferrencingNoSpin.java

public static void main(String args[])
        throws ParseException, EngineException, InterruptedException, IOException, LoadException {

    List<String> endpoints = new ArrayList<String>();
    String queryPath = null;//  ww w.ja  v a  2 s.c om
    boolean rulesSelection = false;
    File rulesDir = null;
    File ontDir = null;

    /////////////////
    Graph graph = Graph.create();
    QueryProcess exec = QueryProcess.create(graph);

    Options options = new Options();
    Option helpOpt = new Option("h", "help", false, "print this message");
    //        Option queryOpt = new Option("q", "query", true, "specify the sparql query file");
    //        Option endpointOpt = new Option("e", "endpoint", true, "a federated sparql endpoint URL");
    Option versionOpt = new Option("v", "version", false, "print the version information and exit");
    Option rulesOpt = new Option("r", "rulesDir", true, "directory containing the inference rules");
    Option ontOpt = new Option("o", "ontologiesDir", true,
            "directory containing the ontologies for rules selection");
    //        Option locOpt = new Option("c", "centralized", false, "performs centralized inferences");
    Option dataOpt = new Option("l", "load", true, "data file or directory to be loaded");
    //        Option selOpt = new Option("s", "rulesSelection", false, "if set to true, only the applicable rules are run");
    //        options.addOption(queryOpt);
    //        options.addOption(endpointOpt);
    options.addOption(helpOpt);
    options.addOption(versionOpt);
    options.addOption(rulesOpt);
    options.addOption(ontOpt);
    //        options.addOption(selOpt);
    //        options.addOption(locOpt);
    options.addOption(dataOpt);

    String header = "Corese/KGRAM rule engine experiment command line interface";
    String footer = "\nPlease report any issue to alban.gaignard@cnrs.fr, olivier.corby@inria.fr";

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("kgdqp", header, options, footer, true);
        System.exit(0);
    }
    if (cmd.hasOption("o")) {
        rulesSelection = true;
        String ontDirPath = cmd.getOptionValue("o");
        ontDir = new File(ontDirPath);
        if (!ontDir.isDirectory()) {
            logger.warn(ontDirPath + " is not a valid directory path.");
            System.exit(0);
        }
    }
    if (!cmd.hasOption("r")) {
        logger.info("You must specify a path for inference rules directory !");
        System.exit(0);
    }

    if (cmd.hasOption("l")) {
        String[] dataPaths = cmd.getOptionValues("l");
        for (String path : dataPaths) {
            Load ld = Load.create(graph);
            ld.load(path);
            logger.info("Loaded " + path);
        }
    }

    if (cmd.hasOption("v")) {
        logger.info("version 3.0.4-SNAPSHOT");
        System.exit(0);
    }

    String rulesDirPath = cmd.getOptionValue("r");
    rulesDir = new File(rulesDirPath);
    if (!rulesDir.isDirectory()) {
        logger.warn(rulesDirPath + " is not a valid directory path.");
        System.exit(0);
    }

    // Local rules graph initialization
    Graph rulesG = Graph.create();
    Load ld = Load.create(rulesG);

    if (rulesSelection) {
        // Ontology loading
        if (ontDir.isDirectory()) {
            for (File o : ontDir.listFiles()) {
                logger.info("Loading " + o.getAbsolutePath());
                ld.load(o.getAbsolutePath());
            }
        }
    }

    // Rules loading
    if (rulesDir.isDirectory()) {
        for (File r : rulesDir.listFiles()) {
            if (r.getAbsolutePath().endsWith(".rq")) {
                logger.info("Loading " + r.getAbsolutePath());
                //                ld.load(r.getAbsolutePath());

                //                    byte[] encoded = Files.readAllBytes(Paths.get(r.getAbsolutePath()));
                //                    String construct = new String(encoded, "UTF-8"); //StandardCharsets.UTF_8);

                FileInputStream f = new FileInputStream(r);
                QueryLoad ql = QueryLoad.create();
                String construct = ql.read(f);
                f.close();

                SPINProcess sp = SPINProcess.create();
                String spinConstruct = sp.toSpin(construct);

                ld.load(new ByteArrayInputStream(spinConstruct.getBytes()), Load.TURTLE_FORMAT);
                logger.info("Rules graph size : " + rulesG.size());

            }
        }
    }

    // Rule engine initialization
    RuleEngine ruleEngine = RuleEngine.create(graph);
    ruleEngine.set(exec);
    ruleEngine.setOptimize(true);
    ruleEngine.setConstructResult(true);
    ruleEngine.setTrace(true);

    StopWatch sw = new StopWatch();
    logger.info("Federated graph size : " + graph.size());
    logger.info("Rules graph size : " + rulesG.size());

    // Rule selection
    logger.info("Rules selection");
    QueryProcess localKgram = QueryProcess.create(rulesG);
    ArrayList<String> applicableRules = new ArrayList<String>();
    sw.start();
    String rulesSelQuery = "";
    if (rulesSelection) {
        rulesSelQuery = pertinentRulesQuery;
    } else {
        rulesSelQuery = allRulesQuery;
    }
    Mappings maps = localKgram.query(rulesSelQuery);
    logger.info("Rules selected in " + sw.getTime() + " ms");
    logger.info("Applicable rules : " + maps.size());

    // Selected rule loading
    for (Mapping map : maps) {
        IDatatype dt = (IDatatype) map.getValue("?res");
        String rule = dt.getLabel();
        //loading rule in the rule engine
        //            logger.info("Adding rule : ");
        //            System.out.println("-------");
        //            System.out.println(rule);
        //            System.out.println("");
        //            if (! rule.toLowerCase().contains("sameas")) {
        applicableRules.add(rule);
        ruleEngine.addRule(rule);
        //            }
    }

    // Rules application on distributed sparql endpoints
    logger.info("Rules application (" + applicableRules.size() + " rules)");
    ExecutorService threadPool = Executors.newCachedThreadPool();
    RuleEngineThread ruleThread = new RuleEngineThread(ruleEngine);
    sw.reset();
    sw.start();

    //        ruleEngine.process();
    threadPool.execute(ruleThread);
    threadPool.shutdown();

    //monitoring loop
    while (!threadPool.isTerminated()) {
        //            System.out.println("******************************");
        //            System.out.println(Util.jsonDqpCost(QueryProcessDQP.queryCounter, QueryProcessDQP.queryVolumeCounter, QueryProcessDQP.sourceCounter, QueryProcessDQP.sourceVolumeCounter));
        //            System.out.println("Rule engine running for " + sw.getTime() + " ms");
        //            System.out.println("Federated graph size : " + graph.size());
        System.out.println(sw.getTime() + " , " + graph.size());
        Thread.sleep(5000);
    }

    logger.info("Federated graph size : " + graph.size());
    //        logger.info(Util.jsonDqpCost(QueryProcessDQP.queryCounter, QueryProcessDQP.queryVolumeCounter, QueryProcessDQP.sourceCounter, QueryProcessDQP.sourceVolumeCounter));

    //        TripleFormat f = TripleFormat.create(graph, true);
    //        f.write("/tmp/gAll.ttl");
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    FileInputStream in = new FileInputStream(args[0]);
    X509CRL crl = (X509CRL) cf.generateCRL(in);
    Set s = crl.getRevokedCertificates();
    if (s != null && s.isEmpty() == false) {
        Iterator t = s.iterator();
        while (t.hasNext()) {
            X509CRLEntry entry = (X509CRLEntry) t.next();
            System.out.println("serial number = " + entry.getSerialNumber().toString(16));
            System.out.println("revocation date = " + entry.getRevocationDate());
            System.out.println("extensions = " + entry.hasExtensions());
        }/*  ww w . java2 s.  c  o  m*/
    }
    in.close();
}

From source file:com.enjoyxstudy.selenium.autoexec.AutoExecServer.java

/**
 * @param args/*from  ww  w  .  jav a  2s.  c om*/
 * @throws Exception
 */
public static void main(String[] args) throws Exception {

    String command = null;
    if (args.length == 0) {
        command = COMMAND_STARTUP;
    } else if (args[0].equals(COMMAND_STARTUP)) {
        command = COMMAND_STARTUP;
    } else if (args[0].equals(COMMAND_SHUTDOWN)) {
        command = COMMAND_SHUTDOWN;
    }

    if (command == null) {
        throw new IllegalArgumentException();
    }

    String propertyFile = DEFAULT_PROPERTY_FILE_NAME; // default
    if (args.length == 2) {
        propertyFile = args[1];
    }
    final Properties properties = new Properties();
    FileInputStream inputStream = new FileInputStream(propertyFile);
    try {
        properties.load(inputStream);
    } finally {
        inputStream.close();
    }

    if (command.equals(COMMAND_STARTUP)) {

        new Thread(new Runnable() {
            public void run() {
                try {

                    AutoExecServer autoExecServer = new AutoExecServer();

                    autoExecServer.startup(properties);
                    autoExecServer.runningLoop();
                    autoExecServer.destroy();

                } catch (Exception e) {
                    log.error("Error", e);
                    e.printStackTrace();
                } finally {
                    System.exit(0);
                }
            }
        }).start();

    } else {

        StringBuilder commandURL = new StringBuilder("http://localhost:");
        commandURL.append(
                PropertiesUtils.getInt(properties, "port", RemoteControlConfiguration.getDefaultPort()));
        commandURL.append(CONTEXT_PATH_COMMAND);

        RemoteControlClient client = new RemoteControlClient(commandURL.toString());

        client.stopServer();
    }
}

From source file:MainClass.java

public static void main(String args[]) {
    try {//from  w w  w  .  j av  a 2 s  . co m

        FileInputStream fis = new FileInputStream("fileName.dat");

        // Create a data input stream
        DataInputStream dis = new DataInputStream(fis);

        // Read and display data
        System.out.println(dis.readBoolean());
        System.out.println(dis.readByte());
        System.out.println(dis.readChar());
        System.out.println(dis.readDouble());
        System.out.println(dis.readFloat());
        System.out.println(dis.readInt());
        System.out.println(dis.readLong());
        System.out.println(dis.readShort());

        // Close file input stream
        fis.close();
    } catch (Exception e) {
        System.out.println("Exception: " + e);
    }
}

From source file:ftp_server.FileUploadDemo.java

public static void main(String[] args) {
    FTPClient client = new FTPClient();
    FileInputStream fis = null;
    try {//from   w ww  .ja  v a  2  s  . c o m
        client.connect("shamalmahesh.net78.net");
        client.login("a9959679", "9P3IckDo");
        //
        // Create an InputStream of the file to be uploaded
        //
        String filename = "hello.txt";
        fis = new FileInputStream(filename);
        //
        // Store file to server
        //
        client.storeFile(filename, fis);
        client.logout();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:Main.java

public static void main(String args[]) throws IOException {
    SequenceInputStream inStream;
    FileInputStream f1 = new FileInputStream("ByteArrayIOApp.java");
    FileInputStream f2 = new FileInputStream("FileIOApp.java");
    inStream = new SequenceInputStream(f1, f2);
    boolean eof = false;
    int byteCount = 0;
    System.out.println(inStream.available());
    while (!eof) {
        int c = inStream.read();
        if (c == -1)
            eof = true;//from   w ww  .ja v a 2s  .c o  m
        else {
            System.out.print((char) c);
            ++byteCount;
        }
    }
    System.out.println(inStream.available());
    System.out.println(byteCount + " bytes were read");
    inStream.close();
    f1.close();
    f2.close();
}

From source file:BGrep.java

public static void main(String[] args) {
    String encodingName = "UTF-8"; // Default to UTF-8 encoding
    int flags = Pattern.MULTILINE; // Default regexp flags

    try { // Fatal exceptions are handled after this try block
        // First, process any options
        int nextarg = 0;
        while (args[nextarg].charAt(0) == '-') {
            String option = args[nextarg++];
            if (option.equals("-e")) {
                encodingName = args[nextarg++];
            } else if (option.equals("-i")) { // case-insensitive matching
                flags |= Pattern.CASE_INSENSITIVE;
            } else if (option.equals("-s")) { // Strict Unicode processing
                flags |= Pattern.UNICODE_CASE; // case-insensitive Unicode
                flags |= Pattern.CANON_EQ; // canonicalize Unicode
            } else {
                System.err.println("Unknown option: " + option);
                usage();//  www .ja v  a  2 s .  c  o m
            }
        }

        // Get the Charset for converting bytes to chars
        Charset charset = Charset.forName(encodingName);

        // Next argument must be a regexp. Compile it to a Pattern object
        Pattern pattern = Pattern.compile(args[nextarg++], flags);

        // Require that at least one file is specified
        if (nextarg == args.length)
            usage();

        // Loop through each of the specified filenames
        while (nextarg < args.length) {
            String filename = args[nextarg++];
            CharBuffer chars; // This will hold complete text of the file
            try { // Handle per-file errors locally
                // Open a FileChannel to the named file
                FileInputStream stream = new FileInputStream(filename);
                FileChannel f = stream.getChannel();

                // Memory-map the file into one big ByteBuffer. This is
                // easy but may be somewhat inefficient for short files.
                ByteBuffer bytes = f.map(FileChannel.MapMode.READ_ONLY, 0, f.size());

                // We can close the file once it is is mapped into memory.
                // Closing the stream closes the channel, too.
                stream.close();

                // Decode the entire ByteBuffer into one big CharBuffer
                chars = charset.decode(bytes);
            } catch (IOException e) { // File not found or other problem
                System.err.println(e); // Print error message
                continue; // and move on to the next file
            }

            // This is the basic regexp loop for finding all matches in a
            // CharSequence. Note that CharBuffer implements CharSequence.
            // A Matcher holds state for a given Pattern and text.
            Matcher matcher = pattern.matcher(chars);
            while (matcher.find()) { // While there are more matches
                // Print out details of the match
                System.out.println(filename + ":" + // file name
                        matcher.start() + ": " + // character pos
                        matcher.group()); // matching text
            }
        }
    }
    // These are the things that can go wrong in the code above
    catch (UnsupportedCharsetException e) { // Bad encoding name
        System.err.println("Unknown encoding: " + encodingName);
    } catch (PatternSyntaxException e) { // Bad pattern
        System.err.println("Syntax error in search pattern:\n" + e.getMessage());
    } catch (ArrayIndexOutOfBoundsException e) { // Wrong number of arguments
        usage();
    }
}

From source file:net.itransformers.postDiscoverer.core.ReportManager.java

public static void main(String[] args) throws IOException {

    File projectDir = new File(".");
    File scriptPath = new File("postDiscoverer/src/main/resources/postDiscoverer/conf/groovy/");

    ResourceManagerFactory resourceManagerFactory = new XmlResourceManagerFactory(
            "iDiscover/resourceManager/xmlResourceManager/src/main/resources/xmlResourceManager/conf/xml/resource.xml");
    Map<String, String> resourceManagerParams = new HashMap<>();
    resourceManagerParams.put("projectPath", projectDir.getAbsolutePath());
    ResourceManager resourceManager = resourceManagerFactory.createResourceManager("xml",
            resourceManagerParams);/*w w w .  j  a  v a  2  s  .  c o  m*/

    Map<String, String> params = new HashMap<String, String>();
    params.put("protocol", "telnet");
    params.put("deviceName", "R1");
    params.put("deviceType", "CISCO");
    params.put("address", "10.17.1.5");
    params.put("port", "23");

    ResourceType resource = resourceManager.findFirstResourceBy(params);
    List connectParameters = resource.getConnectionParams();

    for (int i = 0; i < connectParameters.size(); i++) {
        ConnectionParamsType connParamsType = (ConnectionParamsType) connectParameters.get(i);

        String connectionType = connParamsType.getConnectionType();
        if (connectionType.equalsIgnoreCase(params.get("protocol"))) {

            for (ParamType param : connParamsType.getParam()) {
                params.put(param.getName(), param.getValue());
            }

        }
    }

    File postDiscoveryConfing = new File(
            projectDir + "/postDiscoverer/src/main/resources/postDiscoverer/conf/xml/reportGenerator.xml");
    if (!postDiscoveryConfing.exists()) {
        System.out.println("File missing: " + postDiscoveryConfing.getAbsolutePath());
        return;
    }

    ReportGeneratorType reportGenerator = null;

    FileInputStream is = new FileInputStream(postDiscoveryConfing);
    try {
        reportGenerator = JaxbMarshalar.unmarshal(ReportGeneratorType.class, is);
    } catch (JAXBException e) {
        logger.info(e); //To change body of catch statement use File | Settings | File Templates.
    } finally {
        is.close();
    }

    ReportManager reportManager = new ReportManager(reportGenerator, scriptPath.getPath(), projectDir,
            "postDiscoverer/conf/xslt/table_creator.xslt");
    StringBuffer report = null;

    HashMap<String, Object> groovyExecutorParams = new HashMap<String, Object>();

    for (String s : params.keySet()) {
        groovyExecutorParams.put(s, params.get(s));
    }

    try {
        report = reportManager.reportExecutor(
                new File("/Users/niau/Projects/Projects/netTransformer10/version1/post-discovery"),
                groovyExecutorParams);
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }
    if (report != null) {
        System.out.println(report.toString());

    } else {
        System.out.println("Report generation failed!");

    }
}