Example usage for java.io File isDirectory

List of usage examples for java.io File isDirectory

Introduction

In this page you can find the example usage for java.io File isDirectory.

Prototype

public boolean isDirectory() 

Source Link

Document

Tests whether the file denoted by this abstract pathname is a directory.

Usage

From source file:org.craftercms.search.util.SearchIndexUpdater.java

public static void main(String... args) throws IOException {
    OptionParser parser = new OptionParser();
    parser.accepts("h", "prints the help");
    parser.accepts("s", "the Crafter site name").withRequiredArg();
    parser.accepts("u", "the Crafter Search server URL").withRequiredArg();
    parser.accepts("p", "the Crafter site path").withRequiredArg();

    OptionSet options = parser.parse(args);

    if (options.has("h")) {
        parser.printHelpOn(System.out);
    } else {//from ww  w .  j  av a2 s .c  o m
        checkForRequiredOption(options, "s");
        checkForRequiredOption(options, "u");
        checkForRequiredOption(options, "p");

        RestClientSearchService searchService = new RestClientSearchService();
        searchService.setServerUrl(options.valueOf("u").toString());

        String sitePath = options.valueOf("p").toString();
        File siteRoot = new File(sitePath);

        if (!siteRoot.exists()) {
            throw new IllegalArgumentException(
                    "The specified document's path [" + sitePath + "] doesn't exist");
        }
        if (!siteRoot.isDirectory()) {
            throw new IllegalArgumentException(
                    "The specified document's path [" + sitePath + "] is not a " + "directory");
        }

        SearchIndexUpdater searchIndexUpdater = new SearchIndexUpdater();
        searchIndexUpdater.setSiteName(options.valueOf("s").toString());
        searchIndexUpdater.setSiteRoot(siteRoot);
        searchIndexUpdater.setSearchService(searchService);

        searchIndexUpdater.updateIndex();
    }
}

From source file:GIST.IzbirkomExtractor.IzbirkomExtractor.java

/**
 * @param args/*ww w.j a  v a 2 s  .  co  m*/
 */
public static void main(String[] args) {

    // process command-line options
    Options options = new Options();
    options.addOption("n", "noaddr", false, "do not do any address matching (for testing)");
    options.addOption("i", "info", false, "create and populate address information table");
    options.addOption("h", "help", false, "this message");

    // database connection
    options.addOption("s", "server", true, "database server to connect to");
    options.addOption("d", "database", true, "OSM database name");
    options.addOption("u", "user", true, "OSM database user name");
    options.addOption("p", "pass", true, "OSM database password");

    // logging options
    options.addOption("l", "logdir", true, "log file directory (default './logs')");
    options.addOption("e", "loglevel", true, "log level (default 'FINEST')");

    // automatically generate the help statement
    HelpFormatter help_formatter = new HelpFormatter();

    // database URI for connection
    String dburi = null;

    // Information message for help screen
    String info_msg = "IzbirkomExtractor [options] <html_directory>";

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption('h') || cmd.getArgs().length != 1) {
            help_formatter.printHelp(info_msg, options);
            System.exit(1);
        }

        /* prohibit n and i together */
        if (cmd.hasOption('n') && cmd.hasOption('i')) {
            System.err.println("Options 'n' and 'i' cannot be used together.");
            System.exit(1);
        }

        /* require database arguments without -n */
        if (cmd.hasOption('n')
                && (cmd.hasOption('s') || cmd.hasOption('d') || cmd.hasOption('u') || cmd.hasOption('p'))) {
            System.err.println("Options 'n' and does not need any databse parameters.");
            System.exit(1);
        }

        /* require all 4 database options to be used together */
        if (!cmd.hasOption('n')
                && !(cmd.hasOption('s') && cmd.hasOption('d') && cmd.hasOption('u') && cmd.hasOption('p'))) {
            System.err.println(
                    "For database access all of the following arguments have to be specified: server, database, user, pass");
            System.exit(1);
        }

        /* useful variables */
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm");
        String dateString = formatter.format(new Date());

        /* setup logging */
        File logdir = new File(cmd.hasOption('l') ? cmd.getOptionValue('l') : "logs");
        FileUtils.forceMkdir(logdir);
        File log_file_name = new File(
                logdir + "/" + IzbirkomExtractor.class.getName() + "-" + formatter.format(new Date()) + ".log");
        FileHandler log_file = new FileHandler(log_file_name.getPath());

        /* create "latest" link to currently created log file */
        Path latest_log_link = Paths.get(logdir + "/latest");
        Files.deleteIfExists(latest_log_link);
        Files.createSymbolicLink(latest_log_link, Paths.get(log_file_name.getName()));

        log_file.setFormatter(new SimpleFormatter());
        LogManager.getLogManager().reset(); // prevents logging to console
        logger.addHandler(log_file);
        logger.setLevel(cmd.hasOption('e') ? Level.parse(cmd.getOptionValue('e')) : Level.FINEST);

        // open directory with HTML files and create file list
        File dir = new File(cmd.getArgs()[0]);
        if (!dir.isDirectory()) {
            System.err.println("Unable to find directory '" + cmd.getArgs()[0] + "', exiting");
            System.exit(1);
        }
        PathMatcher pmatcher = FileSystems.getDefault()
                .getPathMatcher("glob:?  * ?*.html");
        ArrayList<File> html_files = new ArrayList<>();
        for (Path file : Files.newDirectoryStream(dir.toPath()))
            if (pmatcher.matches(file.getFileName()))
                html_files.add(file.toFile());
        if (html_files.size() == 0) {
            System.err.println("No matching HTML files found in '" + dir.getAbsolutePath() + "', exiting");
            System.exit(1);
        }

        // create csvResultSink
        FileOutputStream csvout_file = new FileOutputStream("parsed_addresses-" + dateString + ".csv");
        OutputStreamWriter csvout = new OutputStreamWriter(csvout_file, "UTF-8");
        ResultSink csvResultSink = new CSVResultSink(csvout, new CSVStrategy('|', '"', '#'));

        // Connect to DB and osmAddressMatcher
        AddressMatcher osmAddressMatcher;
        DBSink dbSink = null;
        DBInfoSink dbInfoSink = null;
        if (cmd.hasOption('n')) {
            osmAddressMatcher = new DummyAddressMatcher();
        } else {
            dburi = "jdbc:postgresql://" + cmd.getOptionValue('s') + "/" + cmd.getOptionValue('d');
            Connection con = DriverManager.getConnection(dburi, cmd.getOptionValue('u'),
                    cmd.getOptionValue('p'));
            osmAddressMatcher = new OsmAddressMatcher(con);
            dbSink = new DBSink(con);
            if (cmd.hasOption('i'))
                dbInfoSink = new DBInfoSink(con);
        }

        /* create resultsinks */
        SinkMultiplexor sm = SinkMultiplexor.newSinkMultiplexor();
        sm.addResultSink(csvResultSink);
        if (dbSink != null) {
            sm.addResultSink(dbSink);
            if (dbInfoSink != null)
                sm.addResultSink(dbInfoSink);
        }

        // create tableExtractor
        TableExtractor te = new TableExtractor(osmAddressMatcher, sm);

        // TODO: printout summary of options: processing date/time, host, directory of HTML files, jdbc uri, command line with parameters

        // iterate through files
        logger.info("Start processing " + html_files.size() + " files in " + dir);
        for (int i = 0; i < html_files.size(); i++) {
            System.err.println("Parsing #" + i + ": " + html_files.get(i));
            te.processHTMLfile(html_files.get(i));
        }

        System.err.println("Processed " + html_files.size() + " HTML files");
        logger.info("Finished processing " + html_files.size() + " files in " + dir);

    } catch (ParseException e1) {
        System.err.println("Failed to parse CLI: " + e1.getMessage());
        help_formatter.printHelp(info_msg, options);
        System.exit(1);
    } catch (IOException e) {
        System.err.println("I/O Exception: " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    } catch (SQLException e) {
        System.err.println("Database '" + dburi + "': " + e.getMessage());
        System.exit(1);
    } catch (ResultSinkException e) {
        System.err.println("Failed to initialize ResultSink: " + e.getMessage());
        System.exit(1);
    } catch (TableExtractorException e) {
        System.err.println("Failed to initialize Table Extractor: " + e.getMessage());
        System.exit(1);
    } catch (CloneNotSupportedException | IllegalAccessException | InstantiationException e) {
        System.err.println("Something really odd happened: " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:com.tamingtext.qa.WikipediaWexIndexer.java

public static void main(String[] args) throws Exception {
    DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
    ArgumentBuilder abuilder = new ArgumentBuilder();
    GroupBuilder gbuilder = new GroupBuilder();

    Option wikipediaFileOpt = obuilder.withLongName("wikiFile").withRequired(true)
            .withArgument(abuilder.withName("wikiFile").withMinimum(1).withMaximum(1).create())
            .withDescription("The path to the wikipedia dump file. "
                    + "May be a directory containing wikipedia dump files. "
                    + "If a directory is specified, files starting with the prefix "
                    + "freebase-segment- are used.")
            .withShortName("w").create();

    Option numDocsOpt = obuilder.withLongName("numDocs").withRequired(false)
            .withArgument(abuilder.withName("numDocs").withMinimum(1).withMaximum(1).create())
            .withDescription("The number of docs to index").withShortName("n").create();

    Option solrURLOpt = obuilder.withLongName("solrURL").withRequired(false)
            .withArgument(abuilder.withName("solrURL").withMinimum(1).withMaximum(1).create())
            .withDescription("The URL where Solr lives").withShortName("s").create();

    Option solrBatchOpt = obuilder.withLongName("batch").withRequired(false)
            .withArgument(abuilder.withName("batch").withMinimum(1).withMaximum(1).create())
            .withDescription("The number of docs to include in each indexing batch").withShortName("b")
            .create();/*from  w  ww .  ja va 2s  . c o  m*/

    Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h")
            .create();

    Group group = gbuilder.withName("Options").withOption(wikipediaFileOpt).withOption(numDocsOpt)
            .withOption(solrURLOpt).withOption(solrBatchOpt).withOption(helpOpt).create();

    Parser parser = new Parser();
    parser.setGroup(group);

    try {
        CommandLine cmdLine = parser.parse(args);

        if (cmdLine.hasOption(helpOpt)) {
            CommandLineUtil.printHelp(group);
            return;
        }

        File file;
        file = new File(cmdLine.getValue(wikipediaFileOpt).toString());
        File[] dumpFiles;
        if (file.isDirectory()) {
            dumpFiles = file.listFiles(new FilenameFilter() {
                public boolean accept(File file, String s) {
                    return s.startsWith("freebase-segment-");
                }
            });
        } else {
            dumpFiles = new File[] { file };
        }

        int numDocs = Integer.MAX_VALUE;
        if (cmdLine.hasOption(numDocsOpt)) {
            numDocs = Integer.parseInt(cmdLine.getValue(numDocsOpt).toString());
        }
        String url = DEFAULT_SOLR_URL;
        if (cmdLine.hasOption(solrURLOpt)) {
            url = cmdLine.getValue(solrURLOpt).toString();
        }
        int batch = 100;
        if (cmdLine.hasOption(solrBatchOpt)) {
            batch = Integer.parseInt(cmdLine.getValue(solrBatchOpt).toString());
        }
        WikipediaWexIndexer indexer = new WikipediaWexIndexer(new CommonsHttpSolrServer(url));
        int total = 0;
        for (int i = 0; i < dumpFiles.length && total < numDocs; i++) {
            File dumpFile = dumpFiles[i];
            log.info("Indexing: " + file + " Num files to index: " + (numDocs - total));
            long start = System.currentTimeMillis();
            int totalFile = indexer.index(dumpFile, numDocs - total, batch);
            long finish = System.currentTimeMillis();
            if (log.isInfoEnabled()) {
                log.info("Indexing " + dumpFile + " took " + (finish - start) + " ms");
            }
            total += totalFile;
            log.info("Done Indexing: " + file + ". Indexed " + totalFile + " docs for that file and " + total
                    + " overall.");

        }
        log.info("Indexed " + total + " docs overall.");
    } catch (OptionException e) {
        log.error("Exception", e);
        CommandLineUtil.printHelp(group);
        return;
    }
}

From source file:appmain.AppMain.java

public static void main(String[] args) {

    try {//  ww w .  ja  v a2 s. co  m
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        UIManager.put("OptionPane.yesButtonText", "Igen");
        UIManager.put("OptionPane.noButtonText", "Nem");
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    try {

        AppMain app = new AppMain();
        app.init();

        File importFolder = new File(DEFAULT_IMPORT_FOLDER);
        if (!importFolder.isDirectory() || !importFolder.exists()) {
            JOptionPane.showMessageDialog(null,
                    "Az IMPORT mappa nem elrhet!\n"
                            + "Ellenrizze az elrsi utat s a jogosultsgokat!\n" + "Mappa: "
                            + importFolder.getAbsolutePath(),
                    "Informci", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        File exportFolder = new File(DEFAULT_EXPORT_FOLDER);
        if (!exportFolder.isDirectory() || !exportFolder.exists()) {
            JOptionPane.showMessageDialog(null,
                    "Az EXPORT mappa nem elrhet!\n"
                            + "Ellenrizze az elrsi utat s a jogosultsgokat!\n" + "Mappa: "
                            + exportFolder.getAbsolutePath(),
                    "Informci", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        List<File> xmlFiles = app.getXMLFiles(importFolder);
        if (xmlFiles == null || xmlFiles.isEmpty()) {
            JOptionPane.showMessageDialog(null,
                    "Nincs beolvasand XML fjl!\n" + "Mappa: " + importFolder.getAbsolutePath(),
                    "Informci", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        StringBuilder fileList = new StringBuilder();
        xmlFiles.stream().forEach(xml -> fileList.append("\n").append(xml.getName()));
        int ret = JOptionPane.showConfirmDialog(null,
                "Beolvassra elksztett fjlok:\n" + fileList + "\n\nIndulhat a feldolgozs?",
                "Megtallt XML fjlok", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

        if (ret == JOptionPane.OK_OPTION) {
            String csvName = "tranzakcio_lista_" + df.format(new Date()) + "_" + System.currentTimeMillis()
                    + ".csv";
            File csv = new File(DEFAULT_EXPORT_FOLDER + "/" + csvName);
            app.writeCSV(csv, Arrays.asList(app.getHeaderLine()));
            xmlFiles.stream().forEach(xml -> {
                List<String> lines = app.readXMLData(xml);
                if (lines != null)
                    app.writeCSV(csv, lines);
            });
            if (csv.isFile() && csv.exists()) {
                JOptionPane.showMessageDialog(null,
                        "A CSV fjl sikeresen elllt!\n" + "Fjl: " + csv.getAbsolutePath(),
                        "Informci", JOptionPane.INFORMATION_MESSAGE);
                app.openFile(csv);
            }
        } else {
            JOptionPane.showMessageDialog(null, "Feldolgozs megszaktva!", "Informci",
                    JOptionPane.INFORMATION_MESSAGE);
        }

    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "Nem kezelt kivtel!\n" + ExceptionUtils.getStackTrace(ex), "Hiba",
                JOptionPane.ERROR_MESSAGE);
    }

}

From source file:at.tlphotography.jAbuseReport.Reporter.java

/**
 * The main method./*  w ww. jav  a2 s .  c  om*/
 *
 * @param args
 *          the arguments
 */
public static void main(String[] args) {
    parseArguments(args);

    File[] directory = new File(logDir).listFiles(); // get the files in the dir

    for (File file : directory) // iterate over the file
    {
        if (!file.isDirectory() && file.getName().contains(logNames)) // if the file is not a dir and the name contains the logName string
        {
            if (file.getName().endsWith(".gz")) // is it zipped?
            {
                content.putAll(readGZFile(file));
            } else {
                content.putAll(readLogFile(file));
            }
        }
    }

    // save the mails to the log lines
    HashMap<String, ArrayList<LogObject>> finalContent = new HashMap<>();

    Iterator<Entry<String, String>> it = content.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String, String> pair = it.next();
        String mail = whoIsLookUp(pair.getKey());

        if (finalContent.containsKey(mail)) {
            finalContent.get(mail).add(new LogObject(pair.getValue()));
        } else {
            ArrayList<LogObject> temp = new ArrayList<LogObject>();
            temp.add(new LogObject(pair.getValue()));
            finalContent.put(mail, temp);
        }

        it.remove();
    }

    // sort them
    Iterator<Entry<String, ArrayList<LogObject>>> it2 = finalContent.entrySet().iterator();
    while (it2.hasNext()) {
        Entry<String, ArrayList<LogObject>> pair = it2.next();
        Collections.sort(pair.getValue());
        println(pair.getKey() + " =");
        for (LogObject obj : pair.getValue()) {
            println(obj.logContent);
        }

        println("\n");
        it2.remove();
    }

}

From source file:com.ibm.jaql.MiniCluster.java

/**
 * @param args/*from ww w.  ja va2s.c om*/
 */
public static void main(String[] args) throws IOException {
    String clusterHome = System.getProperty("hadoop.minicluster.dir");
    if (clusterHome == null) {
        clusterHome = "./minicluster";
        System.setProperty("hadoop.minicluster.dir", clusterHome);
    }
    LOG.info("hadoop.minicluster.dir=" + clusterHome);
    File clusterFile = new File(clusterHome);
    if (!clusterFile.exists()) {
        clusterFile.mkdirs();
    }
    if (!clusterFile.isDirectory()) {
        throw new IOException("minicluster home directory must be a directory: " + clusterHome);
    }
    if (!clusterFile.canRead() || !clusterFile.canWrite()) {
        throw new IOException("minicluster home directory must be readable and writable: " + clusterHome);
    }

    String logDir = System.getProperty("hadoop.log.dir");
    if (logDir == null) {
        logDir = clusterHome + File.separator + "logs";
        System.setProperty("hadoop.log.dir", logDir);
    }
    File logFile = new File(logDir);
    if (!logFile.exists()) {
        logFile.mkdirs();
    }

    String confDir = System.getProperty("hadoop.conf.override");
    if (confDir == null) {
        confDir = clusterHome + File.separator + "conf";
        System.setProperty("hadoop.conf.override", confDir);
    }
    File confFile = new File(confDir);
    if (!confFile.exists()) {
        confFile.mkdirs();
    }

    System.out.println("starting minicluster in " + clusterHome);
    MiniCluster mc = new MiniCluster(args);
    // To find the ports in the 
    // hdfs: search for: Web-server up at: localhost:####
    // mapred: search for: mapred.JobTracker: JobTracker webserver: ####
    Configuration conf = mc.getConf();
    System.out.println("fs.default.name: " + conf.get("fs.default.name"));
    System.out.println("dfs.http.address: " + conf.get("dfs.http.address"));
    System.out.println("mapred.job.tracker.http.address: " + conf.get("mapred.job.tracker.http.address"));

    boolean waitForInterrupt;
    try {
        System.out.println("press enter to end minicluster (or eof to run forever)...");
        waitForInterrupt = System.in.read() < 0; // wait for any input or eof
    } catch (Exception e) {
        // something odd happened.  Just shutdown. 
        LOG.error("error reading from stdin", e);
        waitForInterrupt = false;
    }

    // eof means that we will wait for a kill signal
    while (waitForInterrupt) {
        System.out.println("minicluster is running until interrupted...");
        try {
            Thread.sleep(60 * 60 * 1000);
        } catch (InterruptedException e) {
            waitForInterrupt = false;
        }
    }

    System.out.println("shutting down minicluster...");
    try {
        mc.tearDown();
    } catch (Exception e) {
        LOG.error("error while shutting down minicluster", e);
    }
}

From source file:androidimporter.AndroidImporter.java

public static void main(String[] args) throws ParseException {
    //"/usr/local/apache-ant/bin/ant"
    String antPath = System.getProperty("ANT_PATH", System.getenv("ANT_PATH"));
    if (antPath == null || !new File(antPath).exists()) {
        throw new RuntimeException("Cannot find ant at " + antPath
                + ".  Please specify location to ant via the ANT_PATH environment variable or java system property.");
    }// w ww.  j a v a2s.c o m

    Options opts = new Options()
            .addOption("i", "android-resource-dir", true, "Android project res directory path")
            .addOption("o", "cn1-project-dir", true, "Path to the CN1 output project directory.")
            .addOption("r", "cn1-resource-file", false,
                    "Path to CN1 output .res file.  Defaults to theme.res in project dir")
            .addOption("p", "package", true, "Java package to place GUI forms in.")
            .addOption("h", "help", false, "Usage instructions");

    CommandLineParser parser = new DefaultParser();

    CommandLine line = parser.parse(opts, args);

    if (line.hasOption("help")) {
        showHelp(opts);
        System.exit(0);
    }
    args = line.getArgs();

    if (args.length < 1) {
        System.out.println("No command provided.");
        showHelp(opts);
        System.exit(0);
    }

    switch (args[0]) {
    case "import-project": {

        if (!line.hasOption("android-resource-dir") || !line.hasOption("cn1-project-dir")
                || !line.hasOption("package")) {
            System.out.println("Please provide android-resource-dir, package, and cn1-project-dir options");
            showHelp(opts);
            System.exit(1);
        }
        File resDir = findResDir(new File(line.getOptionValue("android-resource-dir")));
        if (resDir == null || !resDir.isDirectory()) {
            System.out.println("Failed to find android resource directory from provided value");
            showHelp(opts);
            System.exit(1);
        }

        File projDir = new File(line.getOptionValue("cn1-project-dir"));
        File resFile = new File(projDir, "src" + File.separator + "theme.res");
        if (line.hasOption("cn1-resource-file")) {
            resFile = new File(line.getOptionValue("cn1-resource-file"));
        }

        JavaSEPort.setShowEDTViolationStacks(false);
        JavaSEPort.setShowEDTWarnings(false);
        JFrame frm = new JFrame("Placeholder");
        frm.setVisible(false);
        Display.init(frm.getContentPane());
        JavaSEPort.setBaseResourceDir(resFile.getParentFile());
        try {
            System.out.println("About to import project at " + resDir.getAbsolutePath());
            System.out.println("Codename One Output Project: " + projDir.getAbsolutePath());
            System.out.println("Resource file: " + resFile.getAbsolutePath());
            System.out.println("Java Package: " + line.getOptionValue("package"));
            AndroidProjectImporter.importProject(resDir, projDir, resFile, line.getOptionValue("package"));
            Runtime.getRuntime().exec(new String[] { antPath, "init" }, new String[] {},
                    resFile.getParentFile().getParentFile());
            //runAnt(new File(resFile.getParentFile().getParentFile(), "build.xml"), "init");
            System.exit(0);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            System.exit(0);
        }
        break;
    }

    default:
        System.out.println("Unknown command " + args[0]);
        showHelp(opts);
        break;

    }

}

From source file:net.sf.mcf2pdf.Main.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    Options options = new Options();

    Option o = OptionBuilder.hasArg().isRequired()
            .withDescription("Installation location of My CEWE Photobook. REQUIRED.").create('i');
    options.addOption(o);/*from   w  w  w.java2 s  .c  om*/
    options.addOption("h", false, "Prints this help and exits.");
    options.addOption("t", true, "Location of MCF temporary files.");
    options.addOption("w", true, "Location for temporary images generated during conversion.");
    options.addOption("r", true, "Sets the resolution to use for page rendering, in DPI. Default is 150.");
    options.addOption("n", true, "Sets the page number to render up to. Default renders all pages.");
    options.addOption("b", false, "Prevents rendering of binding between double pages.");
    options.addOption("x", false, "Generates only XSL-FO content instead of PDF content.");
    options.addOption("q", false, "Quiet mode - only errors are logged.");
    options.addOption("d", false, "Enables debugging logging output.");

    CommandLine cl;
    try {
        CommandLineParser parser = new PosixParser();
        cl = parser.parse(options, args);
    } catch (ParseException pe) {
        printUsage(options, pe);
        System.exit(3);
        return;
    }

    if (cl.hasOption("h")) {
        printUsage(options, null);
        return;
    }

    if (cl.getArgs().length != 2) {
        printUsage(options,
                new ParseException("INFILE and OUTFILE must be specified. Arguments were: " + cl.getArgList()));
        System.exit(3);
        return;
    }

    File installDir = new File(cl.getOptionValue("i"));
    if (!installDir.isDirectory()) {
        printUsage(options, new ParseException("Specified installation directory does not exist."));
        System.exit(3);
        return;
    }

    File tempDir = null;
    String sTempDir = cl.getOptionValue("t");
    if (sTempDir == null) {
        tempDir = new File(new File(System.getProperty("user.home")), ".mcf");
        if (!tempDir.isDirectory()) {
            printUsage(options, new ParseException("MCF temporary location not specified and default location "
                    + tempDir + " does not exist."));
            System.exit(3);
            return;
        }
    } else {
        tempDir = new File(sTempDir);
        if (!tempDir.isDirectory()) {
            printUsage(options, new ParseException("Specified temporary location does not exist."));
            System.exit(3);
            return;
        }
    }

    File mcfFile = new File(cl.getArgs()[0]);
    if (!mcfFile.isFile()) {
        printUsage(options, new ParseException("MCF input file does not exist."));
        System.exit(3);
        return;
    }
    mcfFile = mcfFile.getAbsoluteFile();

    File tempImages = new File(new File(System.getProperty("user.home")), ".mcf2pdf");
    if (cl.hasOption("w")) {
        tempImages = new File(cl.getOptionValue("w"));
        if (!tempImages.mkdirs() && !tempImages.isDirectory()) {
            printUsage(options,
                    new ParseException("Specified working dir does not exist and could not be created."));
            System.exit(3);
            return;
        }
    }

    int dpi = 150;
    if (cl.hasOption("r")) {
        try {
            dpi = Integer.valueOf(cl.getOptionValue("r")).intValue();
            if (dpi < 30 || dpi > 600)
                throw new IllegalArgumentException();
        } catch (Exception e) {
            printUsage(options,
                    new ParseException("Parameter for option -r must be an integer between 30 and 600."));
        }
    }

    int maxPageNo = -1;
    if (cl.hasOption("n")) {
        try {
            maxPageNo = Integer.valueOf(cl.getOptionValue("n")).intValue();
            if (maxPageNo < 0)
                throw new IllegalArgumentException();
        } catch (Exception e) {
            printUsage(options, new ParseException("Parameter for option -n must be an integer >= 0."));
        }
    }

    boolean binding = true;
    if (cl.hasOption("b")) {
        binding = false;
    }

    OutputStream finalOut;
    if (cl.getArgs()[1].equals("-"))
        finalOut = System.out;
    else {
        try {
            finalOut = new FileOutputStream(cl.getArgs()[1]);
        } catch (IOException e) {
            printUsage(options, new ParseException("Output file could not be created."));
            System.exit(3);
            return;
        }
    }

    // configure logging, if no system property is present
    if (System.getProperty("log4j.configuration") == null) {
        PropertyConfigurator.configure(Main.class.getClassLoader().getResource("log4j.properties"));

        Logger.getRootLogger().setLevel(Level.INFO);
        if (cl.hasOption("q"))
            Logger.getRootLogger().setLevel(Level.ERROR);
        if (cl.hasOption("d"))
            Logger.getRootLogger().setLevel(Level.DEBUG);
    }

    // start conversion to XSL-FO
    // if -x is specified, this is the only thing we do
    OutputStream xslFoOut;
    if (cl.hasOption("x"))
        xslFoOut = finalOut;
    else
        xslFoOut = new ByteArrayOutputStream();

    Log log = LogFactory.getLog(Main.class);

    try {
        new Mcf2FoConverter(installDir, tempDir, tempImages).convert(mcfFile, xslFoOut, dpi, binding,
                maxPageNo);
        xslFoOut.flush();

        if (!cl.hasOption("x")) {
            // convert to PDF
            log.debug("Converting XSL-FO data to PDF");
            byte[] data = ((ByteArrayOutputStream) xslFoOut).toByteArray();
            PdfUtil.convertFO2PDF(new ByteArrayInputStream(data), finalOut, dpi);
            finalOut.flush();
        }
    } catch (Exception e) {
        log.error("An exception has occured", e);
        System.exit(1);
        return;
    } finally {
        if (finalOut instanceof FileOutputStream) {
            try {
                finalOut.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:Delete.java

public static void main(String[] args) {
    String fileName = "file.txt";
    // A File object to represent the filename
    File f = new File(fileName);

    // Make sure the file or directory exists and isn't write protected
    if (!f.exists())
        throw new IllegalArgumentException("Delete: no such file or directory: " + fileName);

    if (!f.canWrite())
        throw new IllegalArgumentException("Delete: write protected: " + fileName);

    // If it is a directory, make sure it is empty
    if (f.isDirectory()) {
        String[] files = f.list();
        if (files.length > 0)
            throw new IllegalArgumentException("Delete: directory not empty: " + fileName);
    }// ww w. j  av  a 2  s .co m

    // Attempt to delete it
    boolean success = f.delete();

    if (!success)
        throw new IllegalArgumentException("Delete: deletion failed");
}

From source file:cmd.freebase2rdf.java

public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        usage();//from   w w  w .  j a  v  a 2 s .  c o  m
    }
    File input = new File(args[0]);
    if (!input.exists())
        error("File " + input.getAbsolutePath() + " does not exist.");
    if (!input.canRead())
        error("Cannot read file " + input.getAbsolutePath());
    if (!input.isFile())
        error("Not a file " + input.getAbsolutePath());
    File output = new File(args[1]);
    if (output.exists())
        error("Output file " + output.getAbsolutePath()
                + " already exists, this program do not override existing files.");
    if (output.canWrite())
        error("Cannot write file " + output.getAbsolutePath());
    if (output.isDirectory())
        error("Not a file " + output.getAbsolutePath());
    if (!output.getName().endsWith(".nt.gz"))
        error("Output filename should end with .nt.gz, this is the only format supported.");

    BufferedReader in = new BufferedReader(
            new InputStreamReader(new BZip2CompressorInputStream(new FileInputStream(input))));
    BufferedOutputStream out = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(output)));
    String line;

    ProgressLogger progressLogger = new ProgressLogger(log, "lines", 100000, 1000000);
    progressLogger.start();
    Freebase2RDF freebase2rdf = null;
    try {
        freebase2rdf = new Freebase2RDF(out);
        while ((line = in.readLine()) != null) {
            freebase2rdf.send(line);
            progressLogger.tick();
        }
    } finally {
        if (freebase2rdf != null)
            freebase2rdf.close();
    }
    print(log, progressLogger);
}