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:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSaxSybaseLoaderCLI.CFAsteriskSaxSybaseLoaderCLI.java

public static void main(String args[]) {
    final String S_ProcName = "CFAsteriskSaxSybaseLoaderCLI.main() ";
    initConsoleLog();/*from w ww  .  ja va 2  s .c o m*/
    int numArgs = args.length;
    if (numArgs >= 2) {
        String homeDirName = System.getProperty("HOME");
        if (homeDirName == null) {
            homeDirName = System.getProperty("user.home");
            if (homeDirName == null) {
                log.message(S_ProcName + "ERROR: Home directory not set");
                return;
            }
        }
        File homeDir = new File(homeDirName);
        if (!homeDir.exists()) {
            log.message(S_ProcName + "ERROR: Home directory \"" + homeDirName + "\" does not exist");
            return;
        }
        if (!homeDir.isDirectory()) {
            log.message(S_ProcName + "ERROR: Home directory \"" + homeDirName + "\" is not a directory");
            return;
        }
        CFAsteriskConfigurationFile cFAsteriskConfig = new CFAsteriskConfigurationFile();
        String cFAsteriskConfigFileName = homeDir.getPath() + File.separator + ".cfasterisksybaserc";
        cFAsteriskConfig.setFileName(cFAsteriskConfigFileName);
        File cFAsteriskConfigFile = new File(cFAsteriskConfigFileName);
        if (!cFAsteriskConfigFile.exists()) {
            cFAsteriskConfig.setDbServer("localhost");
            cFAsteriskConfig.setDbPort(2345);
            cFAsteriskConfig.setDbDatabase("CFAst24");
            cFAsteriskConfig.setDbUserName("sa");
            cFAsteriskConfig.setDbPassword("edit-me-please");
            cFAsteriskConfig.save();
            log.message(S_ProcName + "INFO: Created configuration file " + cFAsteriskConfigFileName
                    + ", please edit configuration and restart.");
            return;
        }
        if (!cFAsteriskConfigFile.isFile()) {
            log.message(S_ProcName + "ERROR: Proposed configuration file " + cFAsteriskConfigFileName
                    + " is not a file.");
            return;
        }
        if (!cFAsteriskConfigFile.canRead()) {
            log.message(S_ProcName + "ERROR: Permission denied attempting to read configuration file "
                    + cFAsteriskConfigFileName);
            return;
        }
        cFAsteriskConfig.load();
        boolean fastExit = false;
        CFAsteriskClientConfigurationFile cFDbTestClientConfig = new CFAsteriskClientConfigurationFile();
        String cFDbTestClientConfigFileName = homeDir.getPath() + File.separator + ".cfdbtestclientrc";
        cFDbTestClientConfig.setFileName(cFDbTestClientConfigFileName);
        File cFDbTestClientConfigFile = new File(cFDbTestClientConfigFileName);
        if (!cFDbTestClientConfigFile.exists()) {
            String cFDbTestKeyStoreFileName = homeDir.getPath() + File.separator + ".msscfjceks";
            cFDbTestClientConfig.setKeyStore(cFDbTestKeyStoreFileName);
            InetAddress localHost;
            try {
                localHost = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                localHost = null;
            }
            if (localHost == null) {
                log.message(S_ProcName + "ERROR: LocalHost is null");
                return;
            }
            String hostName = localHost.getHostName();
            if ((hostName == null) || (hostName.length() <= 0)) {
                log.message("ERROR: LocalHost.HostName is null or empty");
                return;
            }
            String userName = System.getProperty("user.name");
            if ((userName == null) || (userName.length() <= 0)) {
                log.message("ERROR: user.name is null or empty");
                return;
            }
            String deviceName = hostName.replaceAll("[^\\w]", "_").toLowerCase() + "-"
                    + userName.replaceAll("[^\\w]", "_").toLowerCase();
            cFDbTestClientConfig.setDeviceName(deviceName);
            cFDbTestClientConfig.save();
            log.message(S_ProcName + "INFO: Created CFAsterisk client configuration file "
                    + cFDbTestClientConfigFileName);
            fastExit = true;
        }
        if (!cFDbTestClientConfigFile.isFile()) {
            log.message(S_ProcName + "ERROR: Proposed client configuration file " + cFDbTestClientConfigFileName
                    + " is not a file.");
            fastExit = true;
        }
        if (!cFDbTestClientConfigFile.canRead()) {
            log.message(S_ProcName + "ERROR: Permission denied attempting to read client configuration file "
                    + cFDbTestClientConfigFileName);
            fastExit = true;
        }
        cFDbTestClientConfig.load();

        if (fastExit) {
            return;
        }

        // Configure logging
        Properties sysProps = System.getProperties();
        sysProps.setProperty("log4j.rootCategory", "WARN");
        sysProps.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

        Logger httpLogger = Logger.getLogger("org.apache.http");
        httpLogger.setLevel(Level.WARN);

        ICFAsteriskSchema cFAsteriskSchema = new CFAsteriskSybaseSchema();
        cFAsteriskSchema.setConfigurationFile(cFAsteriskConfig);
        ICFAsteriskSchemaObj cFAsteriskSchemaObj = new CFAsteriskSchemaObj();
        cFAsteriskSchemaObj.setBackingStore(cFAsteriskSchema);
        CFAsteriskSaxLoaderCLI cli = new CFAsteriskSaxSybaseLoaderCLI();
        CFAsteriskSaxLoader loader = cli.getSaxLoader();
        loader.setSchemaObj(cFAsteriskSchemaObj);
        cFAsteriskSchema.connect();
        String url = args[1];
        if (numArgs >= 5) {
            cli.setClusterName(args[2]);
            cli.setTenantName(args[3]);
            cli.setSecUserName(args[4]);
        } else {
            cli.setClusterName("default");
            cli.setTenantName("system");
            cli.setSecUserName("system");
        }
        loader.setUseCluster(cli.getClusterObj());
        loader.setUseTenant(cli.getTenantObj());
        try {
            cFAsteriskSchema.beginTransaction();
            cFAsteriskSchemaObj.setSecCluster(cli.getClusterObj());
            cFAsteriskSchemaObj.setSecTenant(cli.getTenantObj());
            cFAsteriskSchemaObj.setSecUser(cli.getSecUserObj());
            cFAsteriskSchemaObj.setSecSession(cli.getSecSessionObj());
            CFSecurityAuthorization auth = new CFSecurityAuthorization();
            auth.setSecCluster(cFAsteriskSchemaObj.getSecCluster());
            auth.setSecTenant(cFAsteriskSchemaObj.getSecTenant());
            auth.setSecSession(cFAsteriskSchemaObj.getSecSession());
            cFAsteriskSchemaObj.setAuthorization(auth);
            applyLoaderOptions(loader, args[0]);
            if (numArgs >= 5) {
                cli.evaluateRemainingArgs(args, 5);
            } else {
                cli.evaluateRemainingArgs(args, 2);
            }
            loader.parseFile(url);
            cFAsteriskSchema.commit();
            cFAsteriskSchema.disconnect(true);
        } catch (Exception e) {
            log.message(S_ProcName + "EXCEPTION: Could not parse XML file \"" + url + "\": " + e.getMessage());
            e.printStackTrace(System.out);
        } catch (Error e) {
            log.message(S_ProcName + "ERROR: Could not parse XML file \"" + url + "\": " + e.getMessage());
            e.printStackTrace(System.out);
        } finally {
            if (cFAsteriskSchema.isConnected()) {
                cFAsteriskSchema.rollback();
                cFAsteriskSchema.disconnect(false);
            }
        }
    } else {
        log.message(S_ProcName
                + "ERROR: Expected at least two argument specifying the loader options and the name of the XML file to parse.  The first argument may be empty.");
    }
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSaxPgSqlLoaderCLI.CFAsteriskSaxPgSqlLoaderCLI.java

public static void main(String args[]) {
    final String S_ProcName = "CFAsteriskSaxPgSqlLoaderCLI.main() ";
    initConsoleLog();//from www  . j a v a 2  s  . co m
    int numArgs = args.length;
    if (numArgs >= 2) {
        String homeDirName = System.getProperty("HOME");
        if (homeDirName == null) {
            homeDirName = System.getProperty("user.home");
            if (homeDirName == null) {
                log.message(S_ProcName + "ERROR: Home directory not set");
                return;
            }
        }
        File homeDir = new File(homeDirName);
        if (!homeDir.exists()) {
            log.message(S_ProcName + "ERROR: Home directory \"" + homeDirName + "\" does not exist");
            return;
        }
        if (!homeDir.isDirectory()) {
            log.message(S_ProcName + "ERROR: Home directory \"" + homeDirName + "\" is not a directory");
            return;
        }
        CFAsteriskConfigurationFile cFAsteriskConfig = new CFAsteriskConfigurationFile();
        String cFAsteriskConfigFileName = homeDir.getPath() + File.separator + ".cfasteriskpgsqlrc";
        cFAsteriskConfig.setFileName(cFAsteriskConfigFileName);
        File cFAsteriskConfigFile = new File(cFAsteriskConfigFileName);
        if (!cFAsteriskConfigFile.exists()) {
            cFAsteriskConfig.setDbServer("127.0.0.1");
            cFAsteriskConfig.setDbPort(5432);
            cFAsteriskConfig.setDbDatabase("CFAst24");
            cFAsteriskConfig.setDbUserName("postgres");
            cFAsteriskConfig.setDbPassword("edit-me-please");
            cFAsteriskConfig.save();
            log.message(S_ProcName + "INFO: Created configuration file " + cFAsteriskConfigFileName
                    + ", please edit configuration and restart.");
            return;
        }
        if (!cFAsteriskConfigFile.isFile()) {
            log.message(S_ProcName + "ERROR: Proposed configuration file " + cFAsteriskConfigFileName
                    + " is not a file.");
            return;
        }
        if (!cFAsteriskConfigFile.canRead()) {
            log.message(S_ProcName + "ERROR: Permission denied attempting to read configuration file "
                    + cFAsteriskConfigFileName);
            return;
        }
        cFAsteriskConfig.load();
        boolean fastExit = false;
        CFAsteriskClientConfigurationFile cFDbTestClientConfig = new CFAsteriskClientConfigurationFile();
        String cFDbTestClientConfigFileName = homeDir.getPath() + File.separator + ".cfdbtestclientrc";
        cFDbTestClientConfig.setFileName(cFDbTestClientConfigFileName);
        File cFDbTestClientConfigFile = new File(cFDbTestClientConfigFileName);
        if (!cFDbTestClientConfigFile.exists()) {
            String cFDbTestKeyStoreFileName = homeDir.getPath() + File.separator + ".msscfjceks";
            cFDbTestClientConfig.setKeyStore(cFDbTestKeyStoreFileName);
            InetAddress localHost;
            try {
                localHost = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                localHost = null;
            }
            if (localHost == null) {
                log.message(S_ProcName + "ERROR: LocalHost is null");
                return;
            }
            String hostName = localHost.getHostName();
            if ((hostName == null) || (hostName.length() <= 0)) {
                log.message("ERROR: LocalHost.HostName is null or empty");
                return;
            }
            String userName = System.getProperty("user.name");
            if ((userName == null) || (userName.length() <= 0)) {
                log.message("ERROR: user.name is null or empty");
                return;
            }
            String deviceName = hostName.replaceAll("[^\\w]", "_").toLowerCase() + "-"
                    + userName.replaceAll("[^\\w]", "_").toLowerCase();
            cFDbTestClientConfig.setDeviceName(deviceName);
            cFDbTestClientConfig.save();
            log.message(S_ProcName + "INFO: Created CFAsterisk client configuration file "
                    + cFDbTestClientConfigFileName);
            fastExit = true;
        }
        if (!cFDbTestClientConfigFile.isFile()) {
            log.message(S_ProcName + "ERROR: Proposed client configuration file " + cFDbTestClientConfigFileName
                    + " is not a file.");
            fastExit = true;
        }
        if (!cFDbTestClientConfigFile.canRead()) {
            log.message(S_ProcName + "ERROR: Permission denied attempting to read client configuration file "
                    + cFDbTestClientConfigFileName);
            fastExit = true;
        }
        cFDbTestClientConfig.load();

        if (fastExit) {
            return;
        }

        // Configure logging
        Properties sysProps = System.getProperties();
        sysProps.setProperty("log4j.rootCategory", "WARN");
        sysProps.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

        Logger httpLogger = Logger.getLogger("org.apache.http");
        httpLogger.setLevel(Level.WARN);

        ICFAsteriskSchema cFAsteriskSchema = new CFAsteriskPgSqlSchema();
        cFAsteriskSchema.setConfigurationFile(cFAsteriskConfig);
        ICFAsteriskSchemaObj cFAsteriskSchemaObj = new CFAsteriskSchemaObj();
        cFAsteriskSchemaObj.setBackingStore(cFAsteriskSchema);
        CFAsteriskSaxLoaderCLI cli = new CFAsteriskSaxPgSqlLoaderCLI();
        CFAsteriskSaxLoader loader = cli.getSaxLoader();
        loader.setSchemaObj(cFAsteriskSchemaObj);
        cFAsteriskSchema.connect();
        String url = args[1];
        if (numArgs >= 5) {
            cli.setClusterName(args[2]);
            cli.setTenantName(args[3]);
            cli.setSecUserName(args[4]);
        } else {
            cli.setClusterName("default");
            cli.setTenantName("system");
            cli.setSecUserName("system");
        }
        loader.setUseCluster(cli.getClusterObj());
        loader.setUseTenant(cli.getTenantObj());
        try {
            cFAsteriskSchema.beginTransaction();
            cFAsteriskSchemaObj.setSecCluster(cli.getClusterObj());
            cFAsteriskSchemaObj.setSecTenant(cli.getTenantObj());
            cFAsteriskSchemaObj.setSecUser(cli.getSecUserObj());
            cFAsteriskSchemaObj.setSecSession(cli.getSecSessionObj());
            CFSecurityAuthorization auth = new CFSecurityAuthorization();
            auth.setSecCluster(cFAsteriskSchemaObj.getSecCluster());
            auth.setSecTenant(cFAsteriskSchemaObj.getSecTenant());
            auth.setSecSession(cFAsteriskSchemaObj.getSecSession());
            cFAsteriskSchemaObj.setAuthorization(auth);
            applyLoaderOptions(loader, args[0]);
            if (numArgs >= 5) {
                cli.evaluateRemainingArgs(args, 5);
            } else {
                cli.evaluateRemainingArgs(args, 2);
            }
            loader.parseFile(url);
            cFAsteriskSchema.commit();
            cFAsteriskSchema.disconnect(true);
        } catch (Exception e) {
            log.message(S_ProcName + "EXCEPTION: Could not parse XML file \"" + url + "\": " + e.getMessage());
            e.printStackTrace(System.out);
        } catch (Error e) {
            log.message(S_ProcName + "ERROR: Could not parse XML file \"" + url + "\": " + e.getMessage());
            e.printStackTrace(System.out);
        } finally {
            if (cFAsteriskSchema.isConnected()) {
                cFAsteriskSchema.rollback();
                cFAsteriskSchema.disconnect(false);
            }
        }
    } else {
        log.message(S_ProcName
                + "ERROR: Expected at least two argument specifying the loader options and the name of the XML file to parse.  The first argument may be empty.");
    }
}

From source file:de.unibi.techfak.bibiserv.util.codegen.Main.java

public static void main(String[] args) {
    // check &   validate cmdline options
    OptionGroup opt_g = getCMDLineOptionsGroups();
    Options opt = getCMDLineOptions();/*w w  w. j av a  2 s  .  com*/
    opt.addOptionGroup(opt_g);

    CommandLineParser cli = new DefaultParser();
    try {
        CommandLine cl = cli.parse(opt, args);

        if (cl.hasOption("v")) {
            VerboseOutputFilter.SHOW_VERBOSE = true;
        }

        switch (opt_g.getSelected()) {
        case "V":
            try {
                URL jarUrl = Main.class.getProtectionDomain().getCodeSource().getLocation();
                String jarPath = URLDecoder.decode(jarUrl.getFile(), "UTF-8");
                JarFile jarFile = new JarFile(jarPath);
                Manifest m = jarFile.getManifest();
                StringBuilder versionInfo = new StringBuilder();
                for (Object key : m.getMainAttributes().keySet()) {
                    versionInfo.append(key).append(":").append(m.getMainAttributes().getValue(key.toString()))
                            .append("\n");
                }
                System.out.println(versionInfo.toString());
            } catch (Exception e) {
                log.error("Version info could not be read.");
            }
            break;
        case "h":
            HelpFormatter help = new HelpFormatter();
            String header = ""; //TODO: missing infotext 
            StringBuilder footer = new StringBuilder("Supported configuration properties :");
            help.printHelp("CodeGen -h | -V | -g  [...]", header, opt, footer.toString());
            break;
        case "g":
            // target dir
            if (cl.hasOption("t")) {
                File target = new File(cl.getOptionValue("t"));
                if (target.isDirectory() && target.canExecute() && target.canWrite()) {
                    config.setProperty("target.dir", cl.getOptionValue("t"));
                } else {
                    log.error("Target dir '{}' is inaccessible!", cl.getOptionValue("t"));
                    break;
                }
            } else {
                config.setProperty("target.dir", System.getProperty("java.io.tmpdir"));
            }

            // project dir
            if (cl.hasOption("p")) {
                File project = new File(cl.getOptionValue("p"));
                if (!project.exists()) {
                    if (!project.mkdirs()) {
                        log.error("Project dir '{}' can't be created!", cl.getOptionValue("p"));
                        break;
                    }
                }

                if (project.isDirectory() && project.canExecute() && project.canWrite()) {
                    config.setProperty("project.dir", cl.getOptionValue("p"));
                } else {
                    log.error("Project dir '{}' is inaccessible!", cl.getOptionValue("p"));
                    break;
                }
            }

            generateAppfromXML(cl.getOptionValue("g"));
            break;
        }
    } catch (ParseException e) {
        log.error("ParseException occurred while parsing cmdline arguments!\n{}", e.getLocalizedMessage());
    }

}

From source file:net.metanotion.sqlc.SqlcPhp.java

public static void main(final String[] args) throws Exception {
    final Args arg = (new ArgsToStruct<>(Args.class)).getInstance(args);
    final File f = new File(arg.source);

    final Iterable<String> srcPathes = java.util.Collections.emptyList(); // TO DO - until it can be cleaned up.

    final SQLC.ClassInfo ir = new SQLC.ClassInfo();
    if (f.isDirectory()) {
        SQLC.treewalk(ir, f, srcPathes);
    } else {//from www . j a v  a 2  s .  com
        SQLC.processFile(ir, arg.source, srcPathes);
    }
    for (final SQLClass q : ir.classes) {
        SqlcPhp.compile(arg.out, q, ir.sm, ir.implicits, ir.exceptions);
    }
    if (ir.implicits.size() > 0) {
        SqlcPhp.generateStructs(arg.out, ir.sm, ir.implicits, ir.implicitDocs);
        //SQLC.generateExceptions(outputFolder, ir.exceptions, ir.inheritanceMap, ir.implicits, ir.implicitDocs, ir.implicitVisibility);
    }
}

From source file:com.rackspacecloud.client.cloudfiles.sample.FilesCopy.java

public static void main(String args[]) throws NoSuchAlgorithmException, FilesException {
    //Build the command line options
    Options options = addCommandLineOptions();

    if (args.length <= 0)
        printHelp(options);/*from ww w.j ava  2  s . co  m*/

    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help"))
            printHelp(options);

        if (line.hasOption("file") && line.hasOption("folder")) {
            System.err.println("Can not use both -file and -folder on the command line at the same time.");
            System.exit(-1);
        } //if (line.hasOption("file") && line.hasOption("folder"))

        if (line.hasOption("download")) {
            if (line.hasOption("folder")) {
                String localFolder = FilenameUtils.normalize(line.getOptionValue("folder"));
                String containerName = null;
                if (StringUtils.isNotBlank(localFolder)) {
                    File localFolderObj = new File(localFolder);
                    if (localFolderObj.exists() && localFolderObj.isDirectory()) {
                        if (line.hasOption("container")) {
                            containerName = line.getOptionValue("container");
                            if (!StringUtils.isNotBlank(containerName)) {
                                System.err.println(
                                        "You must provide a valid value for the  Container to upload to !");
                                System.exit(-1);
                            } //if (!StringUtils.isNotBlank(ontainerName))                            
                        } else {
                            System.err.println(
                                    "You must provide the -container for a copy operation to work as expected.");
                            System.exit(-1);
                        }

                        System.out.println("Downloading all objects from: " + containerName
                                + " to local folder: " + localFolder);

                        getContainerObjects(localFolderObj, containerName);

                    } else {
                        if (!localFolderObj.exists()) {
                            System.err.println("The local folder: " + localFolder
                                    + " does not exist.  Create it first and then run this command.");
                        }

                        if (!localFolderObj.isDirectory()) {
                            System.err.println(
                                    "The local folder name supplied : " + localFolder + " is not a folder !");
                        }

                        System.exit(-1);
                    }
                }
            }
            System.exit(0);
        } //if (line.hasOption("download"))

        if (line.hasOption("folder")) {
            String containerName = null;
            String folderPath = null;

            if (line.hasOption("container")) {
                containerName = line.getOptionValue("container");
                if (!StringUtils.isNotBlank(containerName)) {
                    System.err.println("You must provide a valid value for the  Container to upload to !");
                    System.exit(-1);
                } //if (!StringUtils.isNotBlank(containerName))

            } else {
                System.err.println("You must provide the -container for a copy operation to work as expected.");
                System.exit(-1);
            }

            folderPath = line.getOptionValue("folder");
            if (StringUtils.isNotBlank(folderPath)) {
                File folder = new File(FilenameUtils.normalize(folderPath));
                if (folder.isDirectory()) {
                    if (line.hasOption("z")) {
                        System.out.println("Zipping: " + folderPath);
                        System.out.println("Nested folders are ignored !");

                        File zipedFolder = zipFolder(folder);
                        String mimeType = FilesConstants.getMimetype(ZIPEXTENSION);
                        copyToCreateContainerIfNeeded(zipedFolder, mimeType, containerName);
                    } else {
                        File[] files = folder.listFiles();
                        for (File f : files) {
                            String mimeType = FilesConstants
                                    .getMimetype(FilenameUtils.getExtension(f.getName()));
                            System.out.println("Uploading :" + f.getName() + " to " + folder.getName());
                            copyToCreateContainerIfNeeded(f, mimeType, containerName);
                            System.out.println(
                                    "Upload :" + f.getName() + " to " + folder.getName() + " completed.");
                        }
                    }
                } else {
                    System.err.println("You must provide a valid folder value for the -folder option !");
                    System.err.println("The value provided is: " + FilenameUtils.normalize(folderPath));
                    System.exit(-1);
                }

            }
        } //if (line.hasOption("folder"))

        if (line.hasOption("file")) {
            String containerName = null;
            String fileNamePath = null;

            if (line.hasOption("container")) {
                containerName = line.getOptionValue("container");
                if (!StringUtils.isNotBlank(containerName) || containerName.indexOf('/') != -1) {
                    System.err.println("You must provide a valid value for the  Container to upload to !");
                    System.exit(-1);
                } //if (!StringUtils.isNotBlank(containerName))
            } else {
                System.err.println("You must provide the -container for a copy operation to work as expected.");
                System.exit(-1);
            }

            fileNamePath = line.getOptionValue("file");
            if (StringUtils.isNotBlank(fileNamePath)) {
                String fileName = FilenameUtils.normalize(fileNamePath);
                String fileExt = FilenameUtils.getExtension(fileNamePath);
                String mimeType = FilesConstants.getMimetype(fileExt);
                File file = new File(fileName);

                if (line.hasOption("z")) {
                    logger.info("Zipping " + fileName);
                    if (!file.isDirectory()) {
                        File zippedFile = zipFile(file);
                        mimeType = FilesConstants.getMimetype(ZIPEXTENSION);
                        copyTo(zippedFile, mimeType, containerName);
                        zippedFile.delete();
                    }

                } //if (line.hasOption("z"))
                else {

                    logger.info("Uploading " + fileName + ".");
                    if (!file.isDirectory())
                        copyTo(file, mimeType, containerName);
                    else {
                        System.err.println(
                                "The path you provided is a folder.  For uploading folders use the -folder option.");
                        System.exit(-1);
                    }
                }
            } //if (StringUtils.isNotBlank(file))
            else {
                System.err.println("You must provide a valid value for the file to upload !");
                System.exit(-1);
            }
        } //if (line.hasOption("file"))
    } //end try        
    catch (ParseException err) {
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
        err.printStackTrace(System.err);
    } //catch( ParseException err )
    catch (FilesAuthorizationException err) {
        logger.fatal("FilesAuthorizationException : Failed to login to your  account !" + err);
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
    } //catch (FilesAuthorizationException err)

    catch (Exception err) {
        logger.fatal("IOException : " + err);
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
    } //catch ( IOException err)
}

From source file:com.mosso.client.cloudfiles.sample.FilesCopy.java

public static void main(String args[]) throws NoSuchAlgorithmException, FilesException {
    //Build the command line options
    Options options = addCommandLineOptions();

    if (args.length <= 0)
        printHelp(options);// w ww . j a va 2 s .  c  om

    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help"))
            printHelp(options);

        if (line.hasOption("file") && line.hasOption("folder")) {
            System.err.println("Can not use both -file and -folder on the command line at the same time.");
            System.exit(-1);
        } //if (line.hasOption("file") && line.hasOption("folder"))

        if (line.hasOption("download")) {
            if (line.hasOption("folder")) {
                String localFolder = FilenameUtils.normalize(line.getOptionValue("folder"));
                String containerName = null;
                if (StringUtils.isNotBlank(localFolder)) {
                    File localFolderObj = new File(localFolder);
                    if (localFolderObj.exists() && localFolderObj.isDirectory()) {
                        if (line.hasOption("container")) {
                            containerName = line.getOptionValue("container");
                            if (!StringUtils.isNotBlank(containerName)) {
                                System.err.println(
                                        "You must provide a valid value for the  Container to upload to !");
                                System.exit(-1);
                            } //if (!StringUtils.isNotBlank(ontainerName))                            
                        } else {
                            System.err.println(
                                    "You must provide the -container for a copy operation to work as expected.");
                            System.exit(-1);
                        }

                        System.out.println("Downloading all objects from: " + containerName
                                + " to local folder: " + localFolder);

                        getContainerObjects(localFolderObj, containerName);

                    } else {
                        if (!localFolderObj.exists()) {
                            System.err.println("The local folder: " + localFolder
                                    + " does not exist.  Create it first and then run this command.");
                        }

                        if (!localFolderObj.isDirectory()) {
                            System.err.println(
                                    "The local folder name supplied : " + localFolder + " is not a folder !");
                        }

                        System.exit(-1);
                    }
                }
            }
            System.exit(0);
        } //if (line.hasOption("download"))

        if (line.hasOption("folder")) {
            String containerName = null;
            String folderPath = null;

            if (line.hasOption("container")) {
                containerName = line.getOptionValue("container");
                if (!StringUtils.isNotBlank(containerName)) {
                    System.err.println("You must provide a valid value for the  Container to upload to !");
                    System.exit(-1);
                } //if (!StringUtils.isNotBlank(containerName))

            } else {
                System.err.println("You must provide the -container for a copy operation to work as expected.");
                System.exit(-1);
            }

            folderPath = line.getOptionValue("folder");
            if (StringUtils.isNotBlank(folderPath)) {
                File folder = new File(FilenameUtils.normalize(folderPath));
                if (folder.isDirectory()) {
                    if (line.hasOption("z")) {
                        System.out.println("Zipping: " + folderPath);
                        System.out.println("Nested folders are ignored !");

                        File zipedFolder = zipFolder(folder);
                        String mimeType = FilesConstants.getMimetype(ZIPEXTENSION);
                        copyToCreateContainerIfNeeded(zipedFolder, mimeType, containerName);
                    } else {
                        File[] files = folder.listFiles();
                        for (File f : files) {
                            String mimeType = FilesConstants
                                    .getMimetype(FilenameUtils.getExtension(f.getName()));
                            System.out.println("Uploading :" + f.getName() + " to " + folder.getName());
                            copyToCreateContainerIfNeeded(f, mimeType, containerName);
                            System.out.println(
                                    "Upload :" + f.getName() + " to " + folder.getName() + " completed.");
                        }
                    }
                } else {
                    System.err.println("You must provide a valid folder value for the -folder option !");
                    System.err.println("The value provided is: " + FilenameUtils.normalize(folderPath));
                    System.exit(-1);
                }

            }
        } //if (line.hasOption("folder"))

        if (line.hasOption("file")) {
            String containerName = null;
            String fileNamePath = null;

            if (line.hasOption("container")) {
                containerName = line.getOptionValue("container");
                if (!StringUtils.isNotBlank(containerName) || containerName.indexOf('/') != -1) {
                    System.err.println("You must provide a valid value for the  Container to upload to !");
                    System.exit(-1);
                } //if (!StringUtils.isNotBlank(containerName))
            } else {
                System.err.println("You must provide the -container for a copy operation to work as expected.");
                System.exit(-1);
            }

            fileNamePath = line.getOptionValue("file");
            if (StringUtils.isNotBlank(fileNamePath)) {
                String fileName = FilenameUtils.normalize(fileNamePath);
                String fileExt = FilenameUtils.getExtension(fileNamePath);
                String mimeType = FilesConstants.getMimetype(fileExt);
                File file = new File(fileName);

                if (line.hasOption("z")) {
                    logger.info("Zipping " + fileName);
                    if (!file.isDirectory()) {
                        File zippedFile = zipFile(file);
                        mimeType = FilesConstants.getMimetype(ZIPEXTENSION);
                        copyTo(zippedFile, mimeType, containerName);
                        zippedFile.delete();
                    }

                } //if (line.hasOption("z"))
                else {

                    logger.info("Uploading " + fileName + ".");
                    if (!file.isDirectory())
                        copyTo(file, mimeType, containerName);
                    else {
                        System.err.println(
                                "The path you provided is a folder.  For uploading folders use the -folder option.");
                        System.exit(-1);
                    }
                }
            } //if (StringUtils.isNotBlank(file))
            else {
                System.err.println("You must provide a valid value for the file to upload !");
                System.exit(-1);
            }
        } //if (line.hasOption("file"))
    } //end try        
    catch (ParseException err) {
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
        err.printStackTrace(System.err);
    } //catch( ParseException err )
    catch (FilesAuthorizationException err) {
        logger.fatal("FilesAuthorizationException : Failed to login to your  account !" + err);
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
    } //catch (FilesAuthorizationException err)

    catch (IOException err) {
        logger.fatal("IOException : " + err);
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
    } //catch ( IOException err)
}

From source file:au.com.jwatmuff.eventmanager.Main.java

/**
 * Main method./*from   w  ww  .j a v  a2s .  c o m*/
 */
public static void main(String args[]) {
    LogUtils.setupUncaughtExceptionHandler();

    /* Set timeout for RMI connections - TODO: move to external file */
    System.setProperty("sun.rmi.transport.tcp.handshakeTimeout", "2000");
    updateRmiHostName();

    /*
     * Set up menu bar for Mac
     */
    System.setProperty("apple.laf.useScreenMenuBar", "true");
    System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Event Manager");

    /*
     * Set look and feel to 'system' style
     */
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        log.info("Failed to set system look and feel");
    }

    /*
     * Set workingDir to a writable folder for storing competitions, settings etc.
     */
    String applicationData = System.getenv("APPDATA");
    if (applicationData != null) {
        workingDir = new File(applicationData, "EventManager");
        if (workingDir.exists() || workingDir.mkdirs()) {
            // redirect logging to writable folder
            LogUtils.reconfigureFileAppenders("log4j.properties", workingDir);
        } else {
            workingDir = new File(".");
        }
    }

    // log version for debugging
    log.info("Running version: " + VISIBLE_VERSION + " (Internal: " + VERSION + ")");

    /*
     * Copy license if necessary
     */
    File license1 = new File("license.lic");
    File license2 = new File(workingDir, "license.lic");
    if (license1.exists() && !license2.exists()) {
        try {
            FileUtils.copyFile(license1, license2);
        } catch (IOException e) {
            log.warn("Failed to copy license from " + license1 + " to " + license2, e);
        }
    }
    if (license1.exists() && license2.exists()) {
        if (license1.lastModified() > license2.lastModified()) {
            try {
                FileUtils.copyFile(license1, license2);
            } catch (IOException e) {
                log.warn("Failed to copy license from " + license1 + " to " + license2, e);
            }
        }
    }

    /*
     * Check if run lock exists, if so ask user if it is ok to continue
     */
    if (!obtainRunLock(false)) {
        int response = JOptionPane.showConfirmDialog(null,
                "Unable to obtain run-lock.\nPlease ensure that no other instances of EventManager are running before continuing.\nDo you wish to continue?",
                "Run-lock detected", JOptionPane.YES_NO_OPTION);
        if (response == JOptionPane.YES_OPTION)
            obtainRunLock(true);
        else
            System.exit(0);
    }

    try {
        LoadWindow loadWindow = new LoadWindow();
        loadWindow.setVisible(true);

        loadWindow.addMessage("Reading settings..");

        /*
         * Read properties from file
         */
        final Properties props = new Properties();
        try {
            Properties defaultProps = PropertiesLoaderUtils
                    .loadProperties(new ClassPathResource("eventmanager.properties"));
            props.putAll(defaultProps);
        } catch (IOException ex) {
            log.error(ex);
        }

        props.putAll(System.getProperties());

        File databaseStore = new File(workingDir, "comps");
        int rmiPort = Integer.parseInt(props.getProperty("eventmanager.rmi.port"));

        loadWindow.addMessage("Loading Peer Manager..");
        log.info("Loading Peer Manager");

        ManualDiscoveryService manualDiscoveryService = new ManualDiscoveryService();
        JmDNSRMIPeerManager peerManager = new JmDNSRMIPeerManager(rmiPort, new File(workingDir, "peerid.dat"));
        peerManager.addDiscoveryService(manualDiscoveryService);

        monitorNetworkInterfaceChanges(peerManager);

        loadWindow.addMessage("Loading Database Manager..");
        log.info("Loading Database Manager");

        DatabaseManager databaseManager = new SQLiteDatabaseManager(databaseStore, peerManager);
        LicenseManager licenseManager = new LicenseManager(workingDir);

        loadWindow.addMessage("Loading Load Competition Dialog..");
        log.info("Loading Load Competition Dialog");

        LoadCompetitionWindow loadCompetitionWindow = new LoadCompetitionWindow(databaseManager, licenseManager,
                peerManager);
        loadCompetitionWindow.setTitle(WINDOW_TITLE);

        loadWindow.dispose();
        log.info("Starting Load Competition Dialog");

        while (true) {
            // reset permission checker to use our license
            licenseManager.updatePermissionChecker();

            GUIUtils.runModalJFrame(loadCompetitionWindow);

            if (loadCompetitionWindow.getSuccess()) {
                DatabaseInfo info = loadCompetitionWindow.getSelectedDatabaseInfo();

                if (!databaseManager.checkLock(info.id)) {
                    String message = "EventManager did not shut down correctly the last time this competition was open. To avoid potential data corruption, you are advised to take the following steps:\n"
                            + "1) Do NOT open this competition\n" + "2) Create a backup of this competition\n"
                            + "3) Delete the competition from this computer\n"
                            + "4) If possible, reload this competition from another computer on the network\n"
                            + "5) Alternatively, you may manually load the backup onto all computers on the network, ensuring the 'Preserve competition ID' option is checked.";
                    String title = "WARNING: Potential Data Corruption Detected";

                    int status = JOptionPane.showOptionDialog(null, message, title, JOptionPane.YES_NO_OPTION,
                            JOptionPane.ERROR_MESSAGE, null,
                            new Object[] { "Cancel (recommended)", "Open anyway" }, "Cancel (recommended)");

                    if (status == 0)
                        continue; // return to load competition window
                }

                SynchronizingWindow syncWindow = new SynchronizingWindow();
                syncWindow.setVisible(true);
                long t = System.nanoTime();
                DistributedDatabase database = databaseManager.activateDatabase(info.id, info.passwordHash);
                long dt = System.nanoTime() - t;
                log.debug(String.format("Initial sync in %dms",
                        TimeUnit.MILLISECONDS.convert(dt, TimeUnit.NANOSECONDS)));
                syncWindow.dispose();

                if (loadCompetitionWindow.isNewDatabase()) {
                    GregorianCalendar calendar = new GregorianCalendar();
                    Date today = calendar.getTime();
                    calendar.set(Calendar.MONTH, Calendar.DECEMBER);
                    calendar.set(Calendar.DAY_OF_MONTH, 31);
                    Date endOfYear = new java.sql.Date(calendar.getTimeInMillis());

                    CompetitionInfo ci = new CompetitionInfo();
                    ci.setName(info.name);
                    ci.setStartDate(today);
                    ci.setEndDate(today);
                    ci.setAgeThresholdDate(endOfYear);
                    //ci.setPasswordHash(info.passwordHash);
                    License license = licenseManager.getLicense();
                    if (license != null) {
                        ci.setLicenseName(license.getName());
                        ci.setLicenseType(license.getType().toString());
                        ci.setLicenseContact(license.getContactPhoneNumber());
                    }
                    database.add(ci);
                }

                // Set PermissionChecker to use database's license type
                String competitionLicenseType = database.get(CompetitionInfo.class, null).getLicenseType();
                PermissionChecker.setLicenseType(LicenseType.valueOf(competitionLicenseType));

                TransactionNotifier notifier = new TransactionNotifier();
                database.setListener(notifier);

                MainWindow mainWindow = new MainWindow();
                mainWindow.setDatabase(database);
                mainWindow.setNotifier(notifier);
                mainWindow.setPeerManager(peerManager);
                mainWindow.setLicenseManager(licenseManager);
                mainWindow.setManualDiscoveryService(manualDiscoveryService);
                mainWindow.setTitle(WINDOW_TITLE);
                mainWindow.afterPropertiesSet();

                TestUtil.setActivatedDatabase(database);

                // show main window (modally)
                GUIUtils.runModalJFrame(mainWindow);

                // shutdown procedures

                // System.exit();

                database.shutdown();
                databaseManager.deactivateDatabase(1500);

                if (mainWindow.getDeleteOnExit()) {
                    for (File file : info.localDirectory.listFiles())
                        if (!file.isDirectory())
                            file.delete();
                    info.localDirectory.deleteOnExit();
                }
            } else {
                // This can cause an RuntimeException - Peer is disconnected
                peerManager.stop();
                System.exit(0);
            }
        }
    } catch (Throwable e) {
        log.error("Error in main function", e);
        String message = e.getMessage();
        if (message == null)
            message = "";
        if (message.length() > 100)
            message = message.substring(0, 97) + "...";
        GUIUtils.displayError(null,
                "An unexpected error has occured.\n\n" + e.getClass().getSimpleName() + "\n" + message);
        System.exit(0);
    }
}

From source file:eu.ensure.aging.AgingSimulator.java

public static void main(String[] args) {

    Options options = new Options();
    options.addOption("n", "flip-bit-in-name", true, "Flip bit in first byte of name of first file");
    options.addOption("u", "flip-bit-in-uname", true, "Flip bit in first byte of username of first file");
    options.addOption("c", "update-checksum", true, "Update header checksum (after prior bit flips)");

    Properties properties = new Properties();
    CommandLineParser parser = new PosixParser();
    try {/*from   w  w w  .  ja v a  2  s  .  c o  m*/
        CommandLine line = parser.parse(options, args);

        //
        if (line.hasOption("flip-bit-in-name")) {
            properties.put("flip-bit-in-name", line.getOptionValue("flip-bit-in-name"));
        } else {
            // On by default (if not explicitly de-activated above)
            properties.put("flip-bit-in-name", "true");
        }

        //
        if (line.hasOption("flip-bit-in-uname")) {
            properties.put("flip-bit-in-uname", line.getOptionValue("flip-bit-in-uname"));
        } else {
            properties.put("flip-bit-in-uname", "false");
        }

        //
        if (line.hasOption("update-checksum")) {
            properties.put("update-checksum", line.getOptionValue("update-checksum"));
        } else {
            properties.put("update-checksum", "false");
        }

        String[] fileArgs = line.getArgs();

        if (fileArgs.length < 1) {
            printHelp(options, System.err);
            System.exit(1);
        }

        String srcPath = fileArgs[0];

        File srcAIP = new File(srcPath);
        if (!srcAIP.exists()) {
            String info = "The source path does not locate a file: " + srcPath;
            System.err.println(info);
            System.exit(1);
        }

        if (srcAIP.isDirectory()) {
            String info = "The source path locates a directory, not a file: " + srcPath;
            System.err.println(info);
            System.exit(1);
        }

        if (!srcAIP.canRead()) {
            String info = "Cannot read source file: " + srcPath;
            System.err.println(info);
            System.exit(1);
        }

        boolean doReplace = false;
        File destAIP = null;

        if (fileArgs.length > 1) {
            String destPath = fileArgs[1];
            destAIP = new File(destPath);

            if (destAIP.exists()) {
                String info = "The destination path locates an existing file: " + destPath;
                System.err.println(info);
                System.exit(1);
            }
        } else {
            doReplace = true;
            try {
                destAIP = File.createTempFile("tmp-aged-aip-", ".tar");
            } catch (IOException ioe) {
                String info = "Failed to create temporary file: ";
                info += ioe.getMessage();
                System.err.println(info);
                System.exit(1);
            }
        }

        String info = "Age simulation\n";
        info += "  Reading from " + srcAIP.getName() + "\n";
        if (doReplace) {
            info += "  and replacing it's content";
        } else {
            info += "  Writing to " + destAIP.getName();
        }
        System.out.println(info);

        //
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new BufferedInputStream(new FileInputStream(srcAIP));
            os = new BufferedOutputStream(new FileOutputStream(destAIP));

            simulateAging(srcAIP.getName(), is, os, properties);

        } catch (FileNotFoundException fnfe) {
            info = "Could not locate file: " + fnfe.getMessage();
            System.err.println(info);
        } finally {
            try {
                if (null != os)
                    os.close();
                if (null != is)
                    is.close();
            } catch (IOException ignore) {
            }
        }

        //
        if (doReplace) {
            File renamedOriginal = new File(srcAIP.getName() + "-backup");
            srcAIP.renameTo(renamedOriginal);

            ReadableByteChannel rbc = null;
            WritableByteChannel wbc = null;
            try {
                rbc = Channels.newChannel(new FileInputStream(destAIP));
                wbc = Channels.newChannel(new FileOutputStream(srcAIP));
                FileIO.fastChannelCopy(rbc, wbc);
            } catch (FileNotFoundException fnfe) {
                info = "Could not locate temporary output file: " + fnfe.getMessage();
                System.err.println(info);
            } catch (IOException ioe) {
                info = "Could not copy temporary output file over original AIP: " + ioe.getMessage();
                System.err.println(info);
            } finally {
                try {
                    if (null != wbc)
                        wbc.close();
                    if (null != rbc)
                        rbc.close();

                    destAIP.delete();
                } catch (IOException ignore) {
                }
            }
        }
    } catch (ParseException pe) {
        String info = "Failed to parse command line: " + pe.getMessage();
        System.err.println(info);
        printHelp(options, System.err);
        System.exit(1);
    }
}

From source file:com.threadswarm.imagefeedarchiver.driver.CommandLineDriver.java

public static void main(String[] args) throws InterruptedException, ExecutionException, ParseException {
    // define available command-line options
    Options options = new Options();
    options.addOption("h", "help", false, "display usage information");
    options.addOption("u", "url", true, "RSS feed URL");
    options.addOption("a", "user-agent", true, "User-Agent header value to use when making HTTP requests");
    options.addOption("o", "output-directory", true, "output directory for downloaded images");
    options.addOption("t", "thread-count", true, "number of worker threads, defaults to cpu-count + 1");
    options.addOption("d", "delay", true, "delay between image downloads (in milliseconds)");
    options.addOption("p", "notrack", false, "tell websites that you don't wish to be tracked (DNT)");
    options.addOption("s", "https", false, "Rewrite image URLs to leverage SSL/TLS");

    CommandLineParser commandLineParser = new BasicParser();
    CommandLine commandLine = commandLineParser.parse(options, args);

    // print usage information if 'h'/'help' or no-args were given
    if (args.length == 0 || commandLine.hasOption("h")) {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp("java -jar ImageFeedArchiver.jar", options);
        return; //abort execution
    }/* w  w w. j  a  v  a2  s . c om*/

    URI rssFeedUri = null;
    if (commandLine.hasOption("u")) {
        String rssFeedUrlString = commandLine.getOptionValue("u");
        try {
            rssFeedUri = FeedUtils.getUriFromUrlString(rssFeedUrlString);
        } catch (MalformedURLException | URISyntaxException e) {
            LOGGER.error("The Feed URL you supplied was malformed or violated syntax rules.. exiting", e);
            System.exit(1);
        }
        LOGGER.info("Target RSS feed URL: {}", rssFeedUri);
    } else {
        throw new IllegalStateException("RSS feed URL was not specified!");
    }

    File outputDirectory = null;
    if (commandLine.hasOption("o")) {
        outputDirectory = new File(commandLine.getOptionValue("o"));
        if (!outputDirectory.isDirectory())
            throw new IllegalArgumentException("output directory must be a *directory*!");
        LOGGER.info("Using output directory: '{}'", outputDirectory);
    } else {
        throw new IllegalStateException("output directory was not specified!");
    }

    String userAgentString = null;
    if (commandLine.hasOption("a")) {
        userAgentString = commandLine.getOptionValue("a");
        LOGGER.info("Setting 'User-Agent' header value to '{}'", userAgentString);
    }

    int threadCount;
    if (commandLine.hasOption("t")) {
        threadCount = Integer.parseInt(commandLine.getOptionValue("t"));
    } else {
        threadCount = Runtime.getRuntime().availableProcessors() + 1;
    }
    LOGGER.info("Using {} worker threads", threadCount);

    long downloadDelay = 0;
    if (commandLine.hasOption("d")) {
        String downloadDelayString = commandLine.getOptionValue("d");
        downloadDelay = Long.parseLong(downloadDelayString);
    }
    LOGGER.info("Using a download-delay of {} milliseconds", downloadDelay);

    boolean doNotTrackRequested = commandLine.hasOption("p");

    boolean forceHttps = commandLine.hasOption("s");

    ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/applicationContext.xml");
    ((ConfigurableApplicationContext) context).registerShutdownHook();

    HttpClient httpClient = (HttpClient) context.getBean("httpClient");
    if (userAgentString != null)
        httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, userAgentString);

    ProcessedRssItemDAO processedRssItemDAO = (ProcessedRssItemDAO) context.getBean("processedRssItemDAO");

    CommandLineDriver.Builder driverBuilder = new CommandLineDriver.Builder(rssFeedUri);
    driverBuilder.setDoNotTrackRequested(doNotTrackRequested).setOutputDirectory(outputDirectory)
            .setDownloadDelay(downloadDelay).setThreadCount(threadCount).setHttpClient(httpClient)
            .setForceHttps(forceHttps).setProcessedRssItemDAO(processedRssItemDAO);

    CommandLineDriver driver = driverBuilder.build();
    driver.run();
}

From source file:com.zimbra.cs.lmtpserver.utils.LmtpInject.java

public static void main(String[] args) {
    CliUtil.toolSetup();//from ww  w.  j  a  v a2s.c o m
    CommandLine cl = parseArgs(args);

    if (cl.hasOption("h")) {
        usage(null);
    }
    boolean quietMode = cl.hasOption("q");
    int threads = 1;
    if (cl.hasOption("t")) {
        threads = Integer.valueOf(cl.getOptionValue("t")).intValue();
    }

    String host = null;
    if (cl.hasOption("a")) {
        host = cl.getOptionValue("a");
    } else {
        host = "localhost";
    }

    int port;
    Protocol proto = null;
    if (cl.hasOption("smtp")) {
        proto = Protocol.SMTP;
        port = 25;
    } else
        port = 7025;
    if (cl.hasOption("p"))
        port = Integer.valueOf(cl.getOptionValue("p")).intValue();

    String[] recipients = cl.getOptionValues("r");
    String sender = cl.getOptionValue("s");
    boolean tracingEnabled = cl.hasOption("T");

    int everyN;
    if (cl.hasOption("N")) {
        everyN = Integer.valueOf(cl.getOptionValue("N")).intValue();
    } else {
        everyN = 100;
    }

    // Process files from the -d option.
    List<File> files = new ArrayList<File>();
    if (cl.hasOption("d")) {
        File dir = new File(cl.getOptionValue("d"));
        if (!dir.isDirectory()) {
            System.err.format("%s is not a directory.\n", dir.getPath());
            System.exit(1);
        }
        File[] fileArray = dir.listFiles();
        if (fileArray == null || fileArray.length == 0) {
            System.err.format("No files found in directory %s.\n", dir.getPath());
        }
        Collections.addAll(files, fileArray);
    }

    // Process files specified as arguments.
    for (String arg : cl.getArgs()) {
        files.add(new File(arg));
    }

    // Validate file content.
    if (!cl.hasOption("noValidation")) {
        Iterator<File> i = files.iterator();
        while (i.hasNext()) {
            InputStream in = null;
            File file = i.next();
            boolean valid = false;
            try {
                in = new FileInputStream(file);
                if (FileUtil.isGzipped(file)) {
                    in = new GZIPInputStream(in);
                }
                in = new BufferedInputStream(in); // Required for RFC 822 check
                if (!EmailUtil.isRfc822Message(in)) {
                    System.err.format("%s does not contain a valid RFC 822 message.\n", file.getPath());
                } else {
                    valid = true;
                }
            } catch (IOException e) {
                System.err.format("Unable to validate %s: %s.\n", file.getPath(), e.toString());
            } finally {
                ByteUtil.closeStream(in);
            }
            if (!valid) {
                i.remove();
            }
        }
    }

    if (files.size() == 0) {
        System.err.println("No files to inject.");
        System.exit(1);
    }

    if (!quietMode) {
        System.out.format(
                "Injecting %d message(s) to %d recipient(s).  Server %s, port %d, using %d thread(s).\n",
                files.size(), recipients.length, host, port, threads);
    }

    int totalFailed = 0;
    int totalSucceeded = 0;
    long startTime = System.currentTimeMillis();
    boolean verbose = cl.hasOption("v");
    boolean skipTLSCertValidation = cl.hasOption("skipTLSCertValidation");

    LmtpInject injector = null;
    try {
        injector = new LmtpInject(threads, sender, recipients, files, host, port, proto, quietMode,
                tracingEnabled, verbose, skipTLSCertValidation);
    } catch (Exception e) {
        mLog.error("Unable to initialize LmtpInject", e);
        System.exit(1);
    }

    injector.setReportEvery(everyN);
    injector.markStartTime();
    try {
        injector.run();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }

    int succeeded = injector.getSuccessCount();
    int failedThisTime = injector.getFailureCount();
    long elapsedMS = System.currentTimeMillis() - startTime;
    double elapsed = elapsedMS / 1000.0;
    double msPerMsg = 0.0;
    double msgSizeKB = 0.0;
    if (succeeded > 0) {
        msPerMsg = elapsedMS;
        msPerMsg /= succeeded;
        msgSizeKB = injector.mFileSizeTotal / 1024.0;
        msgSizeKB /= succeeded;
    }
    double msgPerSec = ((double) succeeded / (double) elapsedMS) * 1000;
    if (!quietMode) {
        System.out.println();
        System.out.printf(
                "LmtpInject Finished\n" + "submitted=%d failed=%d\n" + "%.2fs, %.2fms/msg, %.2fmsg/s\n"
                        + "average message size = %.2fKB\n",
                succeeded, failedThisTime, elapsed, msPerMsg, msgPerSec, msgSizeKB);
    }

    totalFailed += failedThisTime;
    totalSucceeded += succeeded;

    if (totalFailed != 0)
        System.exit(1);
}