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:eu.fbk.utils.lsa.util.AnvurDev.java

public static void main(String[] args) throws Exception {
    String logConfig = System.getProperty("log-config");
    if (logConfig == null) {
        logConfig = "log-config.txt";
    }//  ww  w.j  a  v a2  s .  co  m

    PropertyConfigurator.configure(logConfig);

    if (args.length != 8) {
        System.out.println(args.length);
        System.out.println(
                "Usage: java -mx2G eu.fbk.utils.lsa.util.AnvurDev root-lsa-en root-lsa-it threshold-lsa size-lsa dim-lsa idf-lsa in-file-tsv fields-tsv\n\n");
        System.exit(1);
    }

    //
    DecimalFormat dec = new DecimalFormat("#.00");

    File enUt = new File(args[0] + "-Ut");
    File enSk = new File(args[0] + "-S");
    File enr = new File(args[0] + "-row");
    File enc = new File(args[0] + "-col");
    File endf = new File(args[0] + "-df");
    File itUt = new File(args[1] + "-Ut");
    File itSk = new File(args[1] + "-S");
    File itr = new File(args[1] + "-row");
    File itc = new File(args[1] + "-col");
    File itdf = new File(args[1] + "-df");

    double threshold = Double.parseDouble(args[2]);
    int size = Integer.parseInt(args[3]);
    int dim = Integer.parseInt(args[4]);
    boolean rescaleIdf = Boolean.parseBoolean(args[5]);

    LSM enLsm = new LSM(enUt, enSk, enr, enc, endf, dim, rescaleIdf);
    LSM itLsm = new LSM(itUt, itSk, itr, itc, itdf, dim, rescaleIdf);

    File in = new File(args[6]);

    if (in.isFile()) {
        run(enLsm, itLsm, args[6], args[7]);
    } else if (in.isDirectory()) {
        FolderScanner fs = new FolderScanner(in);
        fs.setFiler(new TsvFilter());
        int count = 0;
        while (fs.hasNext()) {
            Object[] files = fs.next();
            System.out.println((count++) + " : " + files.length);
            for (int i = 0; i < files.length; i++) {

                String name = ((File) files[i]).getAbsolutePath();
                System.out.println(name);
                run(enLsm, itLsm, name, args[7]);
            } // end for i
        } // end while
    }

}

From source file:eu.fbk.utils.lsa.util.AnvurTest.java

public static void main(String[] args) throws Exception {
    String logConfig = System.getProperty("log-config");
    if (logConfig == null) {
        logConfig = "log-config.txt";
    }/*w  w w  .  j  a va  2s  .com*/

    PropertyConfigurator.configure(logConfig);

    if (args.length != 8) {
        System.out.println(args.length);
        System.out.println(
                "Usage: java -mx2G eu.fbk.utils.lsa.util.AnvurTest root-lsa-en root-lsa-it threshold-lsa size-lsa dim-lsa idf-lsa in-file-tsv fields-tsv\n\n");
        System.exit(1);
    }

    //
    DecimalFormat dec = new DecimalFormat("#.00");

    File enUt = new File(args[0] + "-Ut");
    File enSk = new File(args[0] + "-S");
    File enr = new File(args[0] + "-row");
    File enc = new File(args[0] + "-col");
    File endf = new File(args[0] + "-df");
    File itUt = new File(args[1] + "-Ut");
    File itSk = new File(args[1] + "-S");
    File itr = new File(args[1] + "-row");
    File itc = new File(args[1] + "-col");
    File itdf = new File(args[1] + "-df");

    double threshold = Double.parseDouble(args[2]);
    int size = Integer.parseInt(args[3]);
    int dim = Integer.parseInt(args[4]);
    boolean rescaleIdf = Boolean.parseBoolean(args[5]);

    LSM enLsm = new LSM(enUt, enSk, enr, enc, endf, dim, rescaleIdf);
    LSM itLsm = new LSM(itUt, itSk, itr, itc, itdf, dim, rescaleIdf);

    File in = new File(args[6]);

    if (in.isFile()) {
        run(enLsm, itLsm, args[6], args[7]);
    } else if (in.isDirectory()) {
        FolderScanner fs = new FolderScanner(in);
        fs.setFiler(new TsvFilter());
        int count = 0;
        while (fs.hasNext()) {
            Object[] files = fs.next();
            System.out.println((count++) + " : " + files.length);
            for (int i = 0; i < files.length; i++) {

                String name = ((File) files[i]).getAbsolutePath();
                System.out.println(name);
                run(enLsm, itLsm, name, args[7]);
            } // end for i
        } // end while
    }

}

From source file:act.installer.HMDBParser.java

public static void main(String[] args) throws Exception {
    // Parse the command line options
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*from   w  w  w. j  a  va 2  s  .c  o m*/
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(PubchemParser.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(PubchemParser.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        return;
    }

    File inputDir = new File(cl.getOptionValue(OPTION_INPUT_DIRECTORY));
    if (!inputDir.isDirectory()) {
        System.err.format("Input directory at %s is not a directory\n", inputDir.getAbsolutePath());
        System.exit(1);
    }

    String dbName = cl.getOptionValue(OPTION_DB_NAME, DEFAULT_DB_NAME);
    String dbHost = cl.getOptionValue(OPTION_DB_HOST, DEFAULT_DB_HOST);
    Integer dbPort = Integer.valueOf(cl.getOptionValue(OPTION_DB_PORT, DEFAULT_DB_PORT));

    LOGGER.info("Connecting to %s:%d/%s", dbHost, dbPort, dbName);
    MongoDB db = new MongoDB(dbHost, dbPort, dbName);
    HMDBParser parser = Factory.makeParser(db);

    LOGGER.info("Starting parser");
    parser.run(inputDir);
    LOGGER.info("Done");
}

From source file:it.anyplace.sync.client.Main.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("C", "set-config", true, "set config file for s-client");
    options.addOption("c", "config", false, "dump config");
    options.addOption("sp", "set-peers", true, "set peer, or comma-separated list of peers");
    options.addOption("q", "query", true, "query directory server for device id");
    options.addOption("d", "discovery", true, "discovery local network for device id");
    options.addOption("p", "pull", true, "pull file from network");
    options.addOption("P", "push", true, "push file to network");
    options.addOption("o", "output", true, "set output file/directory");
    options.addOption("i", "input", true, "set input file/directory");
    options.addOption("lp", "list-peers", false, "list peer addresses");
    options.addOption("a", "address", true, "use this peer addresses");
    options.addOption("L", "list-remote", false, "list folder (root) content from network");
    options.addOption("I", "list-info", false, "dump folder info from network");
    options.addOption("li", "list-info", false, "list folder info from local db");
    //        options.addOption("l", "list-local", false, "list folder content from local (saved) index");
    options.addOption("s", "search", true, "search local index for <term>");
    options.addOption("D", "delete", true, "push delete to network");
    options.addOption("M", "mkdir", true, "push directory create to network");
    options.addOption("h", "help", false, "print help");
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("s-client", options);
        return;//from  www .j  a  va2  s .co m
    }

    File configFile = cmd.hasOption("C") ? new File(cmd.getOptionValue("C"))
            : new File(System.getProperty("user.home"), ".s-client.properties");
    logger.info("using config file = {}", configFile);
    ConfigurationService configuration = ConfigurationService.newLoader().loadFrom(configFile);
    FileUtils.cleanDirectory(configuration.getTemp());
    KeystoreHandler.newLoader().loadAndStore(configuration);
    if (cmd.hasOption("c")) {
        logger.info("configuration =\n{}", configuration.newWriter().dumpToString());
    } else {
        logger.trace("configuration =\n{}", configuration.newWriter().dumpToString());
    }
    logger.debug("{}", configuration.getStorageInfo().dumpAvailableSpace());

    if (cmd.hasOption("sp")) {
        List<String> peers = Lists.newArrayList(Lists.transform(
                Arrays.<String>asList(cmd.getOptionValue("sp").split(",")), new Function<String, String>() {
                    @Override
                    public String apply(String input) {
                        return input.trim();
                    }
                }));
        logger.info("set peers = {}", peers);
        configuration.edit().setPeers(Collections.<DeviceInfo>emptyList());
        for (String peer : peers) {
            KeystoreHandler.validateDeviceId(peer);
            configuration.edit().addPeers(new DeviceInfo(peer, null));
        }
        configuration.edit().persistNow();
    }

    if (cmd.hasOption("q")) {
        String deviceId = cmd.getOptionValue("q");
        logger.info("query device id = {}", deviceId);
        List<DeviceAddress> deviceAddresses = new GlobalDiscoveryHandler(configuration).query(deviceId);
        logger.info("server response = {}", deviceAddresses);
    }
    if (cmd.hasOption("d")) {
        String deviceId = cmd.getOptionValue("d");
        logger.info("discovery device id = {}", deviceId);
        List<DeviceAddress> deviceAddresses = new LocalDiscorveryHandler(configuration).queryAndClose(deviceId);
        logger.info("local response = {}", deviceAddresses);
    }

    if (cmd.hasOption("p")) {
        String path = cmd.getOptionValue("p");
        logger.info("file path = {}", path);
        String folder = path.split(":")[0];
        path = path.split(":")[1];
        try (SyncthingClient client = new SyncthingClient(configuration);
                BlockExchangeConnectionHandler connectionHandler = client.connectToBestPeer()) {
            InputStream inputStream = client.pullFile(connectionHandler, folder, path).waitForComplete()
                    .getInputStream();
            String fileName = client.getIndexHandler().getFileInfoByPath(folder, path).getFileName();
            File file;
            if (cmd.hasOption("o")) {
                File param = new File(cmd.getOptionValue("o"));
                file = param.isDirectory() ? new File(param, fileName) : param;
            } else {
                file = new File(fileName);
            }
            FileUtils.copyInputStreamToFile(inputStream, file);
            logger.info("saved file to = {}", file.getAbsolutePath());
        }
    }
    if (cmd.hasOption("P")) {
        String path = cmd.getOptionValue("P");
        File file = new File(cmd.getOptionValue("i"));
        checkArgument(!path.startsWith("/")); //TODO check path syntax
        logger.info("file path = {}", path);
        String folder = path.split(":")[0];
        path = path.split(":")[1];
        try (SyncthingClient client = new SyncthingClient(configuration);
                BlockPusher.FileUploadObserver fileUploadObserver = client.pushFile(new FileInputStream(file),
                        folder, path)) {
            while (!fileUploadObserver.isCompleted()) {
                fileUploadObserver.waitForProgressUpdate();
                logger.debug("upload progress {}", fileUploadObserver.getProgressMessage());
            }
            logger.info("uploaded file to network");
        }
    }
    if (cmd.hasOption("D")) {
        String path = cmd.getOptionValue("D");
        String folder = path.split(":")[0];
        path = path.split(":")[1];
        logger.info("delete path = {}", path);
        try (SyncthingClient client = new SyncthingClient(configuration);
                IndexEditObserver observer = client.pushDelete(folder, path)) {
            observer.waitForComplete();
            logger.info("deleted path");
        }
    }
    if (cmd.hasOption("M")) {
        String path = cmd.getOptionValue("M");
        String folder = path.split(":")[0];
        path = path.split(":")[1];
        logger.info("dir path = {}", path);
        try (SyncthingClient client = new SyncthingClient(configuration);
                IndexEditObserver observer = client.pushDir(folder, path)) {
            observer.waitForComplete();
            logger.info("uploaded dir to network");
        }
    }
    if (cmd.hasOption("L")) {
        try (SyncthingClient client = new SyncthingClient(configuration)) {
            client.waitForRemoteIndexAquired();
            for (String folder : client.getIndexHandler().getFolderList()) {
                try (IndexBrowser indexBrowser = client.getIndexHandler().newIndexBrowserBuilder()
                        .setFolder(folder).build()) {
                    logger.info("list folder = {}", indexBrowser.getFolder());
                    for (FileInfo fileInfo : indexBrowser.listFiles()) {
                        logger.info("\t\t{} {} {}", fileInfo.getType().name().substring(0, 1),
                                fileInfo.getPath(), fileInfo.describeSize());
                    }
                }
            }
        }
    }
    if (cmd.hasOption("I")) {
        try (SyncthingClient client = new SyncthingClient(configuration)) {
            if (cmd.hasOption("a")) {
                String deviceId = cmd.getOptionValue("a").substring(0, 63),
                        address = cmd.getOptionValue("a").substring(64);
                try (BlockExchangeConnectionHandler connection = client.getConnection(
                        DeviceAddress.newBuilder().setDeviceId(deviceId).setAddress(address).build())) {
                    client.getIndexHandler().waitForRemoteIndexAquired(connection);
                }
            } else {
                client.waitForRemoteIndexAquired();
            }
            String folderInfo = "";
            for (String folder : client.getIndexHandler().getFolderList()) {
                folderInfo += "\n\t\tfolder info : " + client.getIndexHandler().getFolderInfo(folder);
                folderInfo += "\n\t\tfolder stats : "
                        + client.getIndexHandler().newFolderBrowser().getFolderStats(folder).dumpInfo() + "\n";
            }
            logger.info("folders:\n{}\n", folderInfo);
        }
    }
    if (cmd.hasOption("li")) {
        try (SyncthingClient client = new SyncthingClient(configuration)) {
            String folderInfo = "";
            for (String folder : client.getIndexHandler().getFolderList()) {
                folderInfo += "\n\t\tfolder info : " + client.getIndexHandler().getFolderInfo(folder);
                folderInfo += "\n\t\tfolder stats : "
                        + client.getIndexHandler().newFolderBrowser().getFolderStats(folder).dumpInfo() + "\n";
            }
            logger.info("folders:\n{}\n", folderInfo);
        }
    }
    if (cmd.hasOption("lp")) {
        try (SyncthingClient client = new SyncthingClient(configuration);
                DeviceAddressSupplier deviceAddressSupplier = client.getDiscoveryHandler()
                        .newDeviceAddressSupplier()) {
            String deviceAddressesStr = "";
            for (DeviceAddress deviceAddress : Lists.newArrayList(deviceAddressSupplier)) {
                deviceAddressesStr += "\n\t\t" + deviceAddress.getDeviceId() + " : "
                        + deviceAddress.getAddress();
            }
            logger.info("device addresses:\n{}\n", deviceAddressesStr);
        }
    }
    if (cmd.hasOption("s")) {
        String term = cmd.getOptionValue("s");
        try (SyncthingClient client = new SyncthingClient(configuration);
                IndexFinder indexFinder = client.getIndexHandler().newIndexFinderBuilder().build()) {
            client.waitForRemoteIndexAquired();
            logger.info("search term = '{}'", term);
            IndexFinder.SearchCompletedEvent event = indexFinder.doSearch(term);
            if (event.hasGoodResults()) {
                logger.info("search results for term = '{}' :", term);
                for (FileInfo fileInfo : event.getResultList()) {
                    logger.info("\t\t{} {} {}", fileInfo.getType().name().substring(0, 1), fileInfo.getPath(),
                            fileInfo.describeSize());
                }
            } else if (event.hasTooManyResults()) {
                logger.info("too many results found for term = '{}'", term);
            } else {
                logger.info("no result found for term = '{}'", term);
            }
        }
    }
    //        if (cmd.hasOption("l")) {
    //            String indexDump = new IndexHandler(configuration).dumpIndex();
    //            logger.info("index dump = \n\n{}\n", indexDump);
    //        }
    IOUtils.closeQuietly(configuration);
}

From source file:FileDemo.java

public static void main(String args[]) {
    File f1 = new File("/java/COPYRIGHT");
    System.out.println("File Name: " + f1.getName());
    System.out.println("Path: " + f1.getPath());
    System.out.println("Abs Path: " + f1.getAbsolutePath());
    System.out.println("Parent: " + f1.getParent());
    System.out.println(f1.exists() ? "exists" : "does not exist");
    System.out.println(f1.canWrite() ? "is writeable" : "is not writeable");
    System.out.println(f1.canRead() ? "is readable" : "is not readable");
    System.out.println("is " + (f1.isDirectory() ? "" : "not" + " a directory"));
    System.out.println(f1.isFile() ? "is normal file" : "might be a named pipe");
    System.out.println(f1.isAbsolute() ? "is absolute" : "is not absolute");
    System.out.println("File last modified: " + f1.lastModified());
    System.out.println("File size: " + f1.length() + " Bytes");
}

From source file:jhc.redsniff.generation.PackageScanningGenerator.java

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

    if (args.length != 5) {
        System.err.println("Args: source-dir package-class-filter parent-class generated-class output-dir");
        System.err.println("");
        System.err.println("    source-dir  : Path to Java source containing matchers to generate sugar for.");
        System.err.println("                  May contain multiple paths, separated by commas.");
        System.err.println("                  e.g. src/java,src/more-java");
        System.err.println(//from  ww w. j ava2 s .  c  o  m
                "    package-class-filter  : base of package to look for classes with methods, eg jhc.selenium.matchers");

        System.err.println("");
        System.err.println(
                "parent-class : Full name of parent class type to examine - eg org.hamcrest.Matcher, jhc.selenium.seeker.Seeker");
        System.err.println("                  e.g. org.myproject.MyMatchers");
        System.err.println("generated-class : Full name of class to generate.");
        System.err.println("                  e.g. org.myproject.MyMatchers");
        System.err.println("");
        System.err.println("     output-dir : Where to output generated code (package subdirs will be");
        System.err.println("                  automatically created).");
        System.err.println("                  e.g. build/generated-code");
        System.exit(-1);
    }

    String srcDirs = args[0];
    String package_name_prefix = args[1];
    String parentClassName = args[2];
    String fullClassName = args[3];
    File outputDir = new File(args[4]);

    String fileName = fullClassName.replace('.', File.separatorChar) + ".java";
    int dotIndex = fullClassName.lastIndexOf(".");
    String packageName = dotIndex == -1 ? "" : fullClassName.substring(0, dotIndex);
    String shortClassName = fullClassName.substring(dotIndex + 1);

    if (!outputDir.isDirectory()) {
        System.err.println("Output directory not found : " + outputDir.getAbsolutePath());
        System.exit(-1);
    }

    Class<?> parentClass = Class.forName(parentClassName);

    File outputFile = new File(outputDir, fileName);
    outputFile.getParentFile().mkdirs();
    File tmpFile = new File(outputDir, fileName + ".tmp");

    SugarGenerator sugarGenerator = new SugarGenerator();
    try {
        sugarGenerator
                .addWriter(new SeleniumFactoryWriter(packageName, shortClassName, new FileWriter(tmpFile)));
        sugarGenerator.addWriter(new QuickReferenceWriter(System.out));

        PackageScanningGenerator pkgScanningGenerator = new PackageScanningGenerator(sugarGenerator,
                PackageScanningGenerator.class.getClassLoader(), parentClass);

        if (srcDirs.trim().length() > 0) {
            for (String srcDir : srcDirs.split(",")) {
                pkgScanningGenerator.addSourceDir(new File(srcDir));
            }
        }
        // could add use of xml just to list filter expressions
        // pkgScanningGenerator.load(new InputSource(configFile));
        pkgScanningGenerator.addClasses(package_name_prefix);

        System.out.println("Generating " + fullClassName);
        sugarGenerator.generate();
        sugarGenerator.close();
        outputFile.delete();
        FileUtils.moveFile(tmpFile, outputFile);

    } finally {
        tmpFile.delete();
        sugarGenerator.close();
    }
}

From source file:org.apache.s4.client.Adapter.java

@SuppressWarnings("static-access")
public static void main(String args[]) throws IOException, InterruptedException {

    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("corehome").hasArg().withDescription("core home").create("c"));

    options.addOption(/*from  w w  w.j  av  a  2  s .  c  o m*/
            OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i"));

    options.addOption(
            OptionBuilder.withArgName("configtype").hasArg().withDescription("configuration type").create("t"));

    options.addOption(OptionBuilder.withArgName("userconfig").hasArg()
            .withDescription("user-defined legacy data adapter configuration file").create("d"));

    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = null;

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException pe) {
        System.err.println(pe.getLocalizedMessage());
        System.exit(1);
    }

    int instanceId = -1;
    if (commandLine.hasOption("i")) {
        String instanceIdStr = commandLine.getOptionValue("i");
        try {
            instanceId = Integer.parseInt(instanceIdStr);
        } catch (NumberFormatException nfe) {
            System.err.println("Bad instance id: %s" + instanceIdStr);
            System.exit(1);
        }
    }

    if (commandLine.hasOption("c")) {
        coreHome = commandLine.getOptionValue("c");
    }

    String configType = "typical";
    if (commandLine.hasOption("t")) {
        configType = commandLine.getOptionValue("t");
    }

    String userConfigFilename = null;
    if (commandLine.hasOption("d")) {
        userConfigFilename = commandLine.getOptionValue("d");
    }

    File userConfigFile = new File(userConfigFilename);
    if (!userConfigFile.isFile()) {
        System.err.println("Bad user configuration file: " + userConfigFilename);
        System.exit(1);
    }

    File coreHomeFile = new File(coreHome);
    if (!coreHomeFile.isDirectory()) {
        System.err.println("Bad core home: " + coreHome);
        System.exit(1);
    }

    if (instanceId > -1) {
        System.setProperty("instanceId", "" + instanceId);
    } else {
        System.setProperty("instanceId", "" + S4Util.getPID());
    }

    String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType;
    String configPath = configBase + File.separatorChar + "client-adapter-conf.xml";
    File configFile = new File(configPath);
    if (!configFile.exists()) {
        System.err.printf("adapter config file %s does not exist\n", configPath);
        System.exit(1);
    }

    // load adapter config xml
    ApplicationContext coreContext;
    coreContext = new FileSystemXmlApplicationContext("file:" + configPath);
    ApplicationContext context = coreContext;

    Adapter adapter = (Adapter) context.getBean("client_adapter");

    ApplicationContext appContext = new FileSystemXmlApplicationContext(
            new String[] { "file:" + userConfigFilename }, context);

    Map<?, ?> inputStubBeanMap = appContext.getBeansOfType(InputStub.class);
    Map<?, ?> outputStubBeanMap = appContext.getBeansOfType(OutputStub.class);

    if (inputStubBeanMap.size() == 0 && outputStubBeanMap.size() == 0) {
        System.err.println("No user-defined input/output stub beans");
        System.exit(1);
    }

    ArrayList<InputStub> inputStubs = new ArrayList<InputStub>(inputStubBeanMap.size());
    ArrayList<OutputStub> outputStubs = new ArrayList<OutputStub>(outputStubBeanMap.size());

    // add all input stubs
    for (Map.Entry<?, ?> e : inputStubBeanMap.entrySet()) {
        String beanName = (String) e.getKey();
        System.out.println("Adding InputStub " + beanName);
        inputStubs.add((InputStub) e.getValue());
    }

    // add all output stubs
    for (Map.Entry<?, ?> e : outputStubBeanMap.entrySet()) {
        String beanName = (String) e.getKey();
        System.out.println("Adding OutputStub " + beanName);
        outputStubs.add((OutputStub) e.getValue());
    }

    adapter.setInputStubs(inputStubs);
    adapter.setOutputStubs(outputStubs);

}

From source file:com.act.lcms.db.analysis.ConfigurableAnalysis.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*from   ww w  . j a va2s  .  com*/
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        return;
    }

    File lcmsDir = new File(cl.getOptionValue(OPTION_DIRECTORY));
    if (!lcmsDir.isDirectory()) {
        System.err.format("File at %s is not a directory\n", lcmsDir.getAbsolutePath());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    Double fontScale = null;
    if (cl.hasOption("font-scale")) {
        try {
            fontScale = Double.parseDouble(cl.getOptionValue("font-scale"));
        } catch (IllegalArgumentException e) {
            System.err.format("Argument for font-scale must be a floating point number.\n");
            System.exit(1);
        }
    }

    File configFile = new File(cl.getOptionValue(OPTION_CONFIG_FILE));
    if (!configFile.isFile()) {
        throw new IllegalArgumentException(
                String.format("Not a regular file at %s", configFile.getAbsolutePath()));
    }
    TSVParser parser = new TSVParser();
    parser.parse(configFile);

    try (DB db = DB.openDBFromCLI(cl)) {
        System.out.format("Loading/updating LCMS scan files into DB\n");
        ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir);

        List<AnalysisStep> steps = new ArrayList<>(parser.getResults().size());
        int i = 0;
        for (Map<String, String> row : parser.getResults()) {
            AnalysisStep step = mapToStep(db, i, row);
            if (step != null) {
                System.out.format("%d: %s '%s' %s %s %f %s\n", step.getIndex(), step.getKind(), step.getLabel(),
                        step.getPlateBarcode(), step.getPlateCoords(), step.getExactMass(),
                        step.getUseFineGrainedMZTolerance());
            }
            steps.add(step);
            i++;
        }

        System.out.format("Running analysis\n");
        runAnalysis(db, lcmsDir, cl.getOptionValue(OPTION_OUTPUT_PREFIX), steps,
                cl.hasOption(OPTION_USE_HEATMAP), fontScale, cl.hasOption(OPTION_USE_SNR));
    }
}

From source file:MainClass.java

public static void main(String args[]) {
    File f1 = new File("MainClass.java");
    System.out.println("File Name:" + f1.getName());
    System.out.println("Path:" + f1.getPath());
    System.out.println("Abs Path:" + f1.getAbsolutePath());
    System.out.println("Parent:" + f1.getParent());
    System.out.println(f1.exists() ? "exists" : "does not exist");
    System.out.println(f1.canWrite() ? "is writeable" : "is not writeable");
    System.out.println(f1.canRead() ? "is readable" : "is not readable");
    System.out.println("is a directory" + f1.isDirectory());
    System.out.println(f1.isFile() ? "is normal file" : "might be a named pipe");
    System.out.println(f1.isAbsolute() ? "is absolute" : "is not absolute");
    System.out.println("File last modified:" + f1.lastModified());
    System.out.println("File size:" + f1.length() + " Bytes");
}

From source file:esiptestbed.mudrod.ontology.process.LocalOntology.java

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

    // boolean options
    Option helpOpt = new Option("h", "help", false, "show this help message");
    // argument options
    Option ontDirOpt = Option.builder(ONT_DIR).required(true).numberOfArgs(1).hasArg(true)
            .desc("A directory containing .owl files.").argName(ONT_DIR).build();

    // create the options
    Options options = new Options();
    options.addOption(helpOpt);// ww  w. j  a va2  s.c om
    options.addOption(ontDirOpt);

    String ontDir;
    CommandLineParser parser = new DefaultParser();
    try {
        CommandLine line = parser.parse(options, args);

        if (line.hasOption(ONT_DIR)) {
            ontDir = line.getOptionValue(ONT_DIR).replace("\\", "/");
        } else {
            ontDir = LocalOntology.class.getClassLoader().getResource("ontology").getFile();
        }
        if (!ontDir.endsWith("/")) {
            ontDir += "/";
        }
    } catch (Exception e) {
        LOG.error("Error whilst processing main method of LocalOntology.", e);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("LocalOntology: 'ontDir' argument is mandatory. ", options, true);
        return;
    }
    File fileDir = new File(ontDir);
    //Fail if the input is not a directory.
    if (fileDir.isDirectory()) {
        List<String> owlFiles = new ArrayList<>();
        for (File owlFile : fileDir.listFiles()) {
            owlFiles.add(owlFile.toString());
        }
        MudrodEngine mEngine = new MudrodEngine();
        Properties props = mEngine.loadConfig();
        Ontology ontology = new OntologyFactory(props).getOntology();
        //convert to correct iput for ontology loading.
        String[] owlArray = new String[owlFiles.size()];
        owlArray = owlFiles.toArray(owlArray);
        ontology.load(owlArray);

        String[] terms = new String[] { "Glacier ice" };
        //Demonstrate that we can do basic ontology heirarchy navigation and log output.
        for (Iterator<OntClass> i = getParser().rootClasses(getModel()); i.hasNext();) {

            //print Ontology Class Hierarchy
            OntClass c = i.next();
            renderHierarchy(System.out, c, new LinkedList<>(), 0);

            for (Iterator<OntClass> subClass = c.listSubClasses(true); subClass.hasNext();) {
                OntClass sub = subClass.next();
                //This means that the search term is present as an OntClass
                if (terms[0].equalsIgnoreCase(sub.getLabel(null))) {
                    //Add the search term(s) above to the term cache.
                    for (int j = 0; j < terms.length; j++) {
                        addSearchTerm(terms[j], sub);
                    }

                    //Query the ontology and return subclasses of the search term(s)
                    for (int k = 0; k < terms.length; k++) {
                        Iterator<String> iter = ontology.subclasses(terms[k]);
                        while (iter.hasNext()) {
                            LOG.info("Subclasses >> " + iter.next());
                        }
                    }

                    //print any synonymic relationships to demonstrate that we can 
                    //undertake synonym-based query expansion
                    for (int l = 0; l < terms.length; l++) {
                        Iterator<String> iter = ontology.synonyms(terms[l]);
                        while (iter.hasNext()) {
                            LOG.info("Synonym >> " + iter.next());
                        }
                    }
                }
            }
        }

        mEngine.end();
    }

}