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:com.dumontierlab.pdb2rdf.cluster.ClusterServer.java

public static void main(String[] args) {

    Options options = createOptions();/* w  ww. j  a  v a  2s  . c  o m*/
    CommandLineParser parser = createCliParser();

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

        if (!cmd.hasOption("dir")) {
            LOG.fatal("You need to specify the input directory");
            System.exit(1);
        }
        File inputDir = new File(cmd.getOptionValue("dir"));
        if (!inputDir.exists() || !inputDir.isDirectory()) {
            LOG.fatal("The specified input directory is not a valid directory");
            System.exit(1);
        }

        int port = DEFAULT_PORT;
        if (cmd.hasOption("port")) {
            try {
                port = Integer.parseInt(cmd.getOptionValue("port"));
            } catch (NumberFormatException e) {
                LOG.fatal("Invalid port number", e);
                System.exit(1);
            }
        }
        boolean gzip = cmd.hasOption("gzip");

        try {
            startServer(inputDir, gzip, port);
        } catch (Exception e) {
            LOG.fatal("Unable to start the server.", e);
            System.exit(1);
        }

    } catch (ParseException e) {
        LOG.fatal("Unable understand your command.");
        printUsage();
        System.exit(1);
    }

}

From source file:edu.illinois.cs.cogcomp.nlp.tokenizer.HashCollisionReport.java

/**
 * Read each test file in the directory, tokenize and create the token view. Then check for
 * collisions./*w  w w . ja  va 2s.c  o  m*/
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    if (args.length == 0)
        error("Must pass in the name of a directory with files to test against.");
    File dir = new File(args[0]);
    if (!dir.exists()) {
        error("The directory did not exist : " + dir);
    }
    if (!dir.isDirectory()) {
        error("The path was not a directory : " + dir);
    }
    File[] files = dir.listFiles();
    for (File file : files) {
        if (file.isFile()) {
            String normal = FileUtils.readFileToString(file);
            TextAnnotationBuilder tabldr = new TokenizerTextAnnotationBuilder(new StatefulTokenizer());
            TextAnnotation taNormal = tabldr.createTextAnnotation("test", "normal", normal);
            List<Constituent> normalToks = taNormal.getView(ViewNames.TOKENS).getConstituents();
            HashMap<Integer, Constituent> hashmap = new HashMap<>();

            // add each constituent to the map keyed by it's hashcode. Check first to see if the hashcode
            // is already used, if it is report it.
            for (Constituent c : normalToks) {
                int code = c.hashCode();
                if (hashmap.containsKey(code)) {
                    Constituent dup = hashmap.get(code);
                    System.err.println(c + " == " + dup);
                } else {
                    hashmap.put(code, c);
                }
            }
        }
    }

}

From source file:com.github.thesmartenergy.sparql.generate.generator.CMDGenerator.java

public static void main(String[] args) {

    List<String> formats = Arrays.asList("TTL", "TURTLE", "NTRIPLES", "TRIG", "RDFXML", "JSONLD");

    try {//from   ww w .  j a va  2  s  . com
        CommandLine cl = CMDConfigurations.parseArguments(args);

        String query = "";
        String outputFormat = "TTL";

        if (cl.getArgList().size() == 0) {
            CMDConfigurations.displayHelp();
            return;
        }

        fileManager = FileManager.makeGlobal();
        if (cl.hasOption('l')) {
            Enumeration<String> loggers = LogManager.getLogManager().getLoggerNames();
            while (loggers.hasMoreElements()) {
                java.util.logging.Logger element = LogManager.getLogManager().getLogger(loggers.nextElement());
                element.setLevel(Level.OFF);
            }
            Logger.getRootLogger().setLevel(org.apache.log4j.Level.OFF);

        }
        LOG = Logger.getLogger(CMDGenerator.class);

        //get query file path
        //check if the file exists
        if (cl.hasOption("qf")) {
            String file_path = cl.getOptionValue("qf");
            File f = new File(file_path);
            if (f.exists() && !f.isDirectory()) {
                FileInputStream fisTargetFile = new FileInputStream(f);
                query = IOUtils.toString(fisTargetFile, "UTF-8");
                LOG.debug("\n\nRead SPARQL-Generate Query ..\n" + query + "\n\n");
            } else {
                LOG.error("File " + file_path + " not found.");
            }
        }

        //get query string
        if (cl.hasOption("qs")) {
            query = cl.getOptionValue("qs");
        }
        System.out.println("Query:" + query);

        //get and validate the output format
        if (cl.hasOption("f")) {
            String format = cl.getOptionValue("f");
            if (formats.contains(format)) {
                outputFormat = format;
            } else {
                LOG.error("Invalid output format," + cl.getOptionProperties("f").getProperty("description"));
                return;
            }
        }

        Model configurationModel = null;
        String conf = "";
        if (cl.hasOption("c")) {
            conf = cl.getOptionValue("c");
            configurationModel = ProcessQuery.generateConfiguration(conf);
        }

        String output = ProcessQuery.process(query, conf, outputFormat);
        System.out.println(output);

    } catch (org.apache.commons.cli.ParseException ex) {
        LOG.error(ex);
    } catch (FileNotFoundException ex) {
        LOG.error(ex);
    } catch (IOException ex) {
        LOG.error(ex);
    }

}

From source file:com.tamingtext.classifier.maxent.TestMaxent.java

/**
 * @param args/* w w  w.  j  a  v a 2  s. co m*/
 */
public static void main(String[] args) throws IOException {
    DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
    ArgumentBuilder abuilder = new ArgumentBuilder();
    GroupBuilder gbuilder = new GroupBuilder();

    Option helpOpt = DefaultOptionCreator.helpOption();

    Option inputDirOpt = obuilder.withLongName("input").withRequired(true)
            .withArgument(abuilder.withName("input").withMinimum(1).withMaximum(1).create())
            .withDescription("The input directory").withShortName("i").create();

    Option modelOpt = obuilder.withLongName("model").withRequired(true)
            .withArgument(abuilder.withName("index").withMinimum(1).withMaximum(1).create())
            .withDescription("The directory containing the index model").withShortName("m").create();

    Group group = gbuilder.withName("Options").withOption(helpOpt).withOption(inputDirOpt).withOption(modelOpt)
            .create();

    try {
        Parser parser = new Parser();

        parser.setGroup(group);
        parser.setHelpOption(helpOpt);
        CommandLine cmdLine = parser.parse(args);
        if (cmdLine.hasOption(helpOpt)) {
            CommandLineUtil.printHelp(group);
            return;
        }

        String inputPath = (String) cmdLine.getValue(inputDirOpt);
        File f = new File(inputPath);
        if (!f.isDirectory()) {
            throw new IllegalArgumentException(f + " is not a directory or does not exit");
        }
        File[] inputFiles = FileUtil.buildFileList(f);

        File modelDir = new File((String) cmdLine.getValue(modelOpt));
        execute(inputFiles, modelDir);
    } catch (OptionException e) {
        log.error("Error while parsing options", e);
    }

}

From source file:embedding.ExampleJava2D2PDF.java

/**
 * Main method.//  w  ww  .  j  a v a2  s .  com
 * @param args command-line arguments
 */
public static void main(String[] args) {
    try {
        System.out.println("FOP " + ExampleJava2D2PDF.class.getSimpleName() + "\n");
        System.out.println("Preparing...");

        //Setup directories
        File baseDir = new File(".");
        File outDir = new File(baseDir, "out");
        if (!outDir.isDirectory()) {
            if (!outDir.mkdirs()) {
                throw new IOException("Could not create output directory: " + outDir);
            }
        }

        //Setup output file
        File pdffile = new File(outDir, "ResultJava2D2PDF.pdf");

        System.out.println("Output: PDF (" + pdffile + ")");
        System.out.println();
        System.out.println("Generating...");

        ExampleJava2D2PDF app = new ExampleJava2D2PDF();
        app.generatePDF(pdffile);

        System.out.println("Success!");
    } catch (Throwable t) {
        t.printStackTrace(System.err);
        System.exit(-1);
    }
}

From source file:com.l2jfree.tools.ProjectSettingsSynchronizer.java

public static void main(String[] args) throws IOException {
    final File src = new File(".").getCanonicalFile();
    System.out.println("Copying from: " + src);
    System.out.println();/*from  w ww .j  a  v  a 2  s  .co m*/

    final List<File> destinations = new ArrayList<File>();
    for (File dest : src.getParentFile().listFiles()) {
        if (dest.isHidden() || !dest.isDirectory())
            continue;

        destinations.add(dest);
        System.out.println("Copying to: " + dest);
    }
    System.out.println();

    // .project
    System.out.println(".project");
    System.out.println("================================================================================");
    {
        final List<String> lines = FileUtils.readLines(new File(src, ".project"));

        for (File dest : destinations) {
            lines.set(2, lines.get(2).replaceAll(src.getName(), dest.getName()));
            writeLines(dest, ".project", lines);
            lines.set(2, lines.get(2).replaceAll(dest.getName(), src.getName()));
        }
    }
    System.out.println();

    // .classpath
    System.out.println(".classpath");
    System.out.println("================================================================================");
    {
        final List<String> lines = FileUtils.readLines(new File(src, ".classpath"));

        for (File dest : destinations) {
            if (dest.getName().endsWith("-main") || dest.getName().endsWith("-datapack")) {
                final ArrayList<String> tmp = new ArrayList<String>();

                for (String line : lines)
                    if (!line.contains("classpathentry"))
                        tmp.add(line);

                writeLines(dest, ".classpath", tmp);
                continue;
            }

            writeLines(dest, ".classpath", lines);
        }
    }
    System.out.println();

    // .settings
    System.out.println(".settings");
    System.out.println("================================================================================");
    for (File settingsFile : new File(src, ".settings").listFiles()) {
        if (settingsFile.getName().endsWith(".prefs")) {
            System.out.println(".settings/" + settingsFile.getName());
            System.out.println(
                    "--------------------------------------------------------------------------------");

            final List<String> lines = FileUtils.readLines(settingsFile);

            if (lines.get(0).startsWith("#"))
                lines.remove(0);

            for (File dest : destinations) {
                writeLines(new File(dest, ".settings"), settingsFile.getName(), lines);
            }
            System.out.println();
        }
    }
    System.out.println();
}

From source file:org.atomserver.utils.jetty.StandAloneAtomServer.java

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

    // the System Property "atomserver.home" defines the home directory for the standalone app
    String atomserverHome = System.getProperty("atomserver.home");
    if (StringUtils.isEmpty(atomserverHome)) {
        log.error("The variable \"atomserver.home\" must be defined");
        System.exit(-1);/*from w w w.  j  av  a2s  .  co  m*/
    }
    File atomserverHomeDir = new File(atomserverHome);
    if (!atomserverHomeDir.exists() && !atomserverHomeDir.isDirectory()) {
        log.error("The variable \"atomserver.home\" (" + atomserverHome
                + ") must point to a directory that exists");
    }

    // instantiate the Jetty Server
    Server server = new Server();

    // create a new connector on the declared port, and set it onto the server
    log.debug("atomserver.port = " + System.getProperty("atomserver.port"));
    Connector connector = new SelectChannelConnector();
    connector.setPort(Integer.getInteger("atomserver.port", DEFAULT_PORT));
    server.setConnectors(new Connector[] { connector });

    // create a ClassLoader that points at the conf directories
    log.debug("atomserver.conf.dir = " + System.getProperty("atomserver.conf.dir"));
    log.debug("atomserver.ops.conf.dir = " + System.getProperty("atomserver.ops.conf.dir"));
    ClassLoader classLoader = new ConfigurationAwareClassLoader(StandAloneAtomServer.class.getClassLoader());

    // load the version from the version.properties file
    Properties versionProps = new Properties();
    versionProps.load(classLoader.getResourceAsStream(DEFAULT_VERSIONS_FILE));
    String version = versionProps.getProperty("atomserver.version");

    // create a new webapp, rooted at webapps/atomserver-${version}, with the configured
    // context name
    String servletContextName = System.getProperty("atomserver.servlet.context");
    log.debug("atomserver.servlet.context = " + servletContextName);
    WebAppContext webapp = new WebAppContext(atomserverHome + "/webapps/atomserver-" + version,
            "/" + servletContextName);

    // set the webapp's ClassLoader to be the one that loaded THIS class.  the REASON that
    // this needs to be set is so that when we extract the web application context below we can
    // cast it to WebApplicationContext here
    webapp.setClassLoader(StandAloneAtomServer.class.getClassLoader());

    // set the Jetty server's webapp and start it
    server.setHandler(webapp);
    server.start();

    // if the seed system property was set, use the DBSeeder to populate the server
    String seedDB = System.getProperty("seed.database.with.pets");
    log.debug("seed.database.with.pets = " + seedDB);
    if (!StringUtils.isEmpty(seedDB)) {
        if (Boolean.valueOf(seedDB)) {
            Thread.sleep(2000);

            WebApplicationContext webappContext = WebApplicationContextUtils
                    .getWebApplicationContext(webapp.getServletContext());

            DBSeeder.getInstance(webappContext).seedPets();
        }
    }

    server.join();
}

From source file:de.fatalix.book.importer.CalibriImporter.java

public static void main(String[] args) throws IOException, URISyntaxException, SolrServerException {
    Gson gson = new Gson();
    CalibriImporterConfiguration config = gson.fromJson(args[0], CalibriImporterConfiguration.class);
    File importFolder = new File(config.getImportFolder());
    if (importFolder.isDirectory()) {
        File[] zipFiles = importFolder.listFiles(new FilenameFilter() {

            @Override/*from w w  w . j  av  a 2  s .  c  o m*/
            public boolean accept(File dir, String name) {
                return name.endsWith(".zip");
            }
        });
        for (File zipFile : zipFiles) {
            try {
                processBooks(zipFile.toPath(), config.getSolrCore(), config.getSolrCore(),
                        config.getBatchSize());
                System.out.println("Processed file " + zipFile.getName());
            } catch (IOException ex) {
                ex.printStackTrace();

            }
        }
    } else {
        System.out.println("Import folder: " + importFolder.getAbsolutePath() + " cannot be read!");
    }
}

From source file:com.vitco.Main.java

public static void main(String[] args) throws Exception {
    // display version number on splash screen
    final SplashScreen splash = SplashScreen.getSplashScreen();
    if (splash != null) {
        Graphics2D g = splash.createGraphics();
        if (g != null) {
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
            Font font = Font
                    .createFont(Font.TRUETYPE_FONT,
                            new SaveResourceLoader("resource/font/arcade.ttf").asInputStream())
                    .deriveFont(Font.PLAIN, 42f);
            g.setFont(font);//from  ww  w. jav  a2 s .c  o m
            //g.setFont(g.getFont().deriveFont(9f));
            g.setColor(VitcoSettings.SPLASH_SCREEN_OVERLAY_TEXT_COLOR);
            int width = g.getFontMetrics().stringWidth(VitcoSettings.VERSION_ID);
            g.drawString(VitcoSettings.VERSION_ID, 400 - 20 - width, 110);
            splash.update();
            g.dispose();
        }
    }

    // the JIDE license
    SaveResourceLoader saveResourceLoader = new SaveResourceLoader("resource/jidelicense.txt");
    if (!saveResourceLoader.error) {
        String[] jidelicense = saveResourceLoader.asLines();
        if (jidelicense.length == 3) {
            com.jidesoft.utils.Lm.verifyLicense(jidelicense[0], jidelicense[1], jidelicense[2]);
        }
    }

    // check if we are in debug mode
    if ((args.length > 0) && args[0].equals("debug")) {
        ErrorHandler.setDebugMode();
        debug = true;
    }

    // build the application
    final ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
            "com/vitco/glue/config.xml");

    // for debugging
    if (debug) {
        ((ActionManager) context.getBean("ActionManager")).performValidityCheck();
        ((ComplexActionManager) context.getBean("ComplexActionManager")).performValidityCheck();
    }

    // open vsd file when program is started with "open with"
    MainMenuLogic mainMenuLogic = ((MainMenuLogic) context.getBean("MainMenuLogic"));
    for (String arg : args) {
        if (arg.endsWith(".vsd")) {
            File file = new File(arg);
            if (file.exists() && !file.isDirectory()) {
                mainMenuLogic.openFile(file);
                break;
            }
        }
    }

    // perform shortcut check
    ((ShortcutManager) context.getBean("ShortcutManager")).doSanityCheck(debug);
    //        // test console
    //        final Console console = ((Console) context.getBean("Console"));
    //        new Thread() {
    //            public void run() {
    //                while (true) {
    //                    console.addLine("text");
    //                    try {
    //                        sleep(2000);
    //                    } catch (InterruptedException e) {
    //                       //e.printStackTrace();
    //                    }
    //                }
    //            }
    //        }.start();

    // add a shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            // make reference so Preferences object doesn't get destroyed
            Preferences pref = ((Preferences) context.getBean("Preferences"));
            // trigger @PreDestroy
            context.close();
            // store the preferences (this needs to be done here, b/c
            // some PreDestroys are used to store preferences!)
            pref.save();
        }
    });
}

From source file:com.rabbitmq.examples.FileConsumer.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption(new Option("h", "uri", true, "AMQP URI"));
    options.addOption(new Option("q", "queue", true, "queue name"));
    options.addOption(new Option("t", "type", true, "exchange type"));
    options.addOption(new Option("e", "exchange", true, "exchange name"));
    options.addOption(new Option("k", "routing-key", true, "routing key"));
    options.addOption(new Option("d", "directory", true, "output directory"));

    CommandLineParser parser = new GnuParser();

    try {/*from  www.  java  2s  .c o m*/
        CommandLine cmd = parser.parse(options, args);

        String uri = strArg(cmd, 'h', "amqp://localhost");
        String requestedQueueName = strArg(cmd, 'q', "");
        String exchangeType = strArg(cmd, 't', "direct");
        String exchange = strArg(cmd, 'e', null);
        String routingKey = strArg(cmd, 'k', null);
        String outputDirName = strArg(cmd, 'd', ".");

        File outputDir = new File(outputDirName);
        if (!outputDir.exists() || !outputDir.isDirectory()) {
            System.err.println("Output directory must exist, and must be a directory.");
            System.exit(2);
        }

        ConnectionFactory connFactory = new ConnectionFactory();
        connFactory.setUri(uri);
        Connection conn = connFactory.newConnection();

        final Channel ch = conn.createChannel();

        String queueName = (requestedQueueName.equals("") ? ch.queueDeclare()
                : ch.queueDeclare(requestedQueueName, false, false, false, null)).getQueue();

        if (exchange != null || routingKey != null) {
            if (exchange == null) {
                System.err.println("Please supply exchange name to bind to (-e)");
                System.exit(2);
            }
            if (routingKey == null) {
                System.err.println("Please supply routing key pattern to bind to (-k)");
                System.exit(2);
            }
            ch.exchangeDeclare(exchange, exchangeType);
            ch.queueBind(queueName, exchange, routingKey);
        }

        QueueingConsumer consumer = new QueueingConsumer(ch);
        ch.basicConsume(queueName, consumer);
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            Map<String, Object> headers = delivery.getProperties().getHeaders();
            byte[] body = delivery.getBody();
            Object headerFilenameO = headers.get("filename");
            String headerFilename = (headerFilenameO == null) ? UUID.randomUUID().toString()
                    : headerFilenameO.toString();
            File givenName = new File(headerFilename);
            if (givenName.getName().equals("")) {
                System.out.println("Skipping file with empty name: " + givenName);
            } else {
                File f = new File(outputDir, givenName.getName());
                System.out.print("Writing " + f + " ...");
                FileOutputStream o = new FileOutputStream(f);
                o.write(body);
                o.close();
                System.out.println(" done.");
            }
            ch.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }
    } catch (Exception ex) {
        System.err.println("Main thread caught exception: " + ex);
        ex.printStackTrace();
        System.exit(1);
    }
}