Example usage for java.io File exists

List of usage examples for java.io File exists

Introduction

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

Prototype

public boolean exists() 

Source Link

Document

Tests whether the file or directory denoted by this abstract pathname exists.

Usage

From source file:com.pari.nm.utils.backup.BackupRestore.java

/**
 * @param args//  w ww . j a v  a  2s.c  om
 */
public static void main(String[] args) {
    com.maverick.ssh.LicenseManager.addLicense("----BEGIN 3SP LICENSE----\r\n" + "Product : J2SSH Maverick\r\n"
            + "Licensee: Pari Networks Inc.\r\n" + "Comments: Sreenivas Devalla\r\n"
            + "Type    : Foundation License\r\n" + "Created : 20-Jun-2007\r\n" + "\r\n"
            + "3787201A027FCA5BA600F3CF9CCEF4C85068187D70F94ABC\r\n"
            + "E7D7280AAFB06CE499DC968A4CB25795475D5B79FDDD6CB4\r\n"
            + "7971A60E947E84A4DADFAB2F89E2F52470182ED2EF429A2F\r\n"
            + "2EC6D8B49CAF167605A7F56C4EB736ECA7150819FCF04DC6\r\n"
            + "01B1404EA9BC83BEAA4AB2F4FC7AB344BEC08CF9DDDAAA34\r\n"
            + "EC80C1C14FA8BB1A8B47E86D393FAECD3C0E7C450E0D1FE3\r\n" + "----END 3SP LICENSE----\r\n");
    String mode = null;
    BufferedReader br = null;

    if (args.length < 9) {
        System.err.println("BackUpDatabase: Invalid Syntax.");
        System.err.println(
                "Usage - java BackUpDatabase <ftpserver> <ftpuser> <ftppassword> <ftpdir> <ftpfile> <localdir>  <backup | recovery> ");
        System.exit(-1);
    }

    try {

        mode = args[8];
        System.out.println("Request received with mode :" + mode + "\n");
        // BackupRestore tbk = BackupRestore.getInstance();
        BackupRestore tbk = new BackupRestore();
        if ((mode != null) && (mode.length() > 0) && mode.equalsIgnoreCase("recovery")) {
            File restoreDir = new File(args[7], args[6].substring(0, args[6].length() - 4));
            System.out.println("Restore Directory :" + restoreDir + "\n");
            if (!restoreDir.exists()) {
                try {
                    FTPServerType serverType = FTPServerType.valueOf(FTPServerType.class, args[0]);
                    System.out.println("Fetching the backup File :" + args[6] + "\n");
                    System.out.println("Please wait, it may take sometime....." + "\n");

                    if (tbk.fetchAndExtractBackupFile(serverType, args[1], Integer.parseInt(args[2]), args[3],
                            args[4], args[5], args[6], args[7]) == null) {
                        System.err.println("Error : Failed to fetch the backup File.\n");
                        System.exit(-1);
                    }
                    System.out.println("Successfully fetched the backup File :" + args[6] + "\n");
                } catch (Exception e) {
                    System.out.println(
                            "Error : Exception while fetching the backup file.Failed to restore the backup File.\n");
                    e.printStackTrace();
                    System.exit(-1);
                }
            }
            try {
                Thread.sleep(10000);
            } catch (Exception ee) {
                ee.printStackTrace();
            }

            System.out.println("Starting recovery ...\n");

            if (!File.separator.equals("\\")) {
                System.out.println("Stopping the Pari Server process.\n");
                Process p = Runtime.getRuntime().exec("killall -9 pari_server");
                MyReader min = new MyReader(p.getInputStream());
                MyReader merr = new MyReader(p.getErrorStream());

                try {
                    min.join(20000);
                } catch (Exception ee) {
                }

                try {
                    merr.join(20000);
                } catch (Exception ex) {
                }
            }

            if (!File.separator.equals("\\")) {
                System.out.println("Stopping the Pari Server process.\n");
                // Process p = Runtime.getRuntime().exec("killall -9 pari_server");
                Process p = Runtime.getRuntime().exec("/etc/init.d/dash stop");
                MyReader min = new MyReader(p.getInputStream());
                MyReader merr = new MyReader(p.getErrorStream());

                try {
                    min.join(20000);
                } catch (Exception ee) {
                }

                try {
                    merr.join(20000);
                } catch (Exception ex) {
                }
            }
            System.out.println("Start recovering the backup file.\n");
            if (tbk.doRecovery(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7])) {
                System.out.println("Done recovering...\n");
                validateCSPCInstanace();
            } else {
                System.out.println("Failed to recover the backup File...\n");
            }

            try {
                Process p = null;
                String cmd = "";

                if (File.separator == "\\") {
                    cmd = "cmd /k start_server.cmd > pari.out 2>&1";
                } else {
                    cmd = "/etc/init.d/dash start";
                }

                System.err.println(cmd);
                Runtime.getRuntime().exec(cmd);
                Boolean flag = false;
                int count = 0;
                String[] nccmStatusCheckCmd = { "/bin/sh", "-c",
                        "netstat -an  | grep 42605 | grep LISTEN | wc -l" };

                do {
                    count++;
                    Thread.sleep(60000);
                    // The command output will be 1 if NCCM server started and Listening on port 42605 otherwise it
                    // will return 0
                    p = Runtime.getRuntime().exec(nccmStatusCheckCmd);
                    int ex = -1;
                    try {
                        ex = p.waitFor();
                    } catch (InterruptedException e) {
                        System.out.println("Normal execution, exception: " + e);
                    }
                    System.out.println("Normal execution, exit value: " + ex);
                    br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                    String thisLine = null;
                    while ((thisLine = br.readLine()) != null) {
                        System.out.println("Command Execution Result:" + thisLine);
                        if (thisLine.equals("1")) {
                            flag = true;
                            break;
                        }
                    }
                    System.out.println("Count - " + count);
                    BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                    while ((thisLine = error.readLine()) != null) {
                        System.out.println(thisLine);
                    }

                } while ((!flag) && count < 30);

                if (flag) {
                    // System.out.println("NCCM Server came to listening state: after " + count + " mins");
                    // Runtime.getRuntime().exec("sh $DASH_HOME/webui/tomcat/bin/shutdown.sh");
                    Thread.sleep(60000);
                    System.out.println("NCCM Server came to listening state: after " + count + " mins");
                    // Runtime.getRuntime().exec("sh $DASH_HOME/webui/tomcat/bin/startup.sh");
                } else {
                    System.out.println("NCCM Server didn't come to listening state: last " + count + " mins");
                    System.out.println("Please verify NCCM Server and start tomcat server manually.");
                }
                System.exit(1);
            } catch (Exception ee) {
                ee.printStackTrace();
            }
        } else if ((mode != null) && (mode.length() > 0) && mode.equalsIgnoreCase("ftplist")) {
            PariFTP pftp = new PariFTP("10.100.1.20", "guest", "guest", "/");
            String[] list = pftp.getRemoteListing();

            System.out.println("List of Files\n");

            for (int i = 0; (list != null) && (i < list.length); i++) {
                System.out.println(list[i] + "\n");
            }
        } else {
            System.out.println("Mode \t" + mode + "\t not supported\n");
        }

        System.exit(-1);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null) {
                br.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.termmed.reconciliation.RelationshipReconciliation.java

/**
 * The main method.//  w  w w . j a  va 2 s  . co m
 *
 * @param args the arguments
 */
public static void main(String[] args) {

    logger = Logger.getLogger("com.termmed.reconciliation.RelationshipReconciliation");
    try {

        File file = new File(I_Constants.RUN_CONFIGURATION_FILE);
        if (!file.exists()) {
            logger.info("Error happened getting params. Params file doesn't exist");
            System.exit(0);
        }

        RelationshipReconciliation cc = new RelationshipReconciliation(file);
        cc.execute();
        cc = null;

    } catch (Exception e) {
        e.printStackTrace();
    }
    System.exit(0);
}

From source file:com.zimbra.perf.chart.ChartUtil.java

public static void main(String[] args) throws Exception {
    CommandLineParser clParser = new GnuParser();
    Options opts = getOptions();// ww w .  j a va  2s .c o m
    try {
        CommandLine cl = clParser.parse(opts, args);

        if (cl.hasOption('h'))
            usage(opts);
        if (!cl.hasOption('s') && !cl.hasOption('d'))
            usage(opts, "-s and -d options are required");
        if (!cl.hasOption('s'))
            usage(opts, "Missing required -s option");

        if (!cl.hasOption('d'))
            usage(opts, "Missing required -d option");

        String[] confs = cl.getOptionValues(OPT_CONF);
        if (confs == null || confs.length == 0)
            usage(opts, "Missing --" + OPT_CONF + " option");
        File[] confFiles = new File[confs.length];
        for (int i = 0; i < confs.length; i++) {
            File conf = new File(confs[i]);
            if (!conf.exists()) {
                System.err.printf("Configuration file %s does not exist\n", conf.getAbsolutePath());
                System.exit(1);
            }
            confFiles[i] = conf;
        }

        String[] srcDirStrs = cl.getOptionValues(OPT_SRCDIR);
        if (srcDirStrs == null || srcDirStrs.length == 0)
            usage(opts, "Missing --" + OPT_SRCDIR + " option");
        List<File> srcDirsList = new ArrayList<File>(srcDirStrs.length);
        for (int i = 0; i < srcDirStrs.length; i++) {
            File srcDir = new File(srcDirStrs[i]);
            if (srcDir.exists())
                srcDirsList.add(srcDir);
            else
                System.err.printf("Source directory %s does not exist\n", srcDir.getAbsolutePath());
        }
        if (srcDirsList.size() < 1)
            usage(opts, "No valid source directory found");
        File[] srcDirs = new File[srcDirsList.size()];
        srcDirsList.toArray(srcDirs);

        String destDirStr = cl.getOptionValue(OPT_DESTDIR);
        if (destDirStr == null)
            usage(opts, "Missing --" + OPT_DESTDIR + " option");
        File destDir = new File(destDirStr);
        if (!destDir.exists()) {
            boolean created = destDir.mkdirs();
            if (!created) {
                System.err.printf("Unable to create destination directory %s\n", destDir.getAbsolutePath());
                System.exit(1);
            }
        }
        if (!destDir.canWrite()) {
            System.err.printf("Destination directory %s is not writable\n", destDir.getAbsolutePath());
            System.exit(1);
        }

        String title = cl.getOptionValue(OPT_TITLE);
        if (title == null)
            title = srcDirs[0].getAbsoluteFile().getName();

        Date startAt = parseTimestampOption(cl, opts, OPT_START_AT);
        Date endAt = parseTimestampOption(cl, opts, OPT_END_AT);
        Date aggStartAt = parseTimestampOption(cl, opts, OPT_AGGREGATE_START_AT);
        Date aggEndAt = parseTimestampOption(cl, opts, OPT_AGGREGATE_END_AT);

        boolean noSummary = cl.hasOption('n');
        ChartUtil app = new ChartUtil(confFiles, srcDirs, destDir, title, startAt, endAt, aggStartAt, aggEndAt,
                noSummary);
        app.doit();
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println();
        usage(opts);
    }
}

From source file:de.unileipzig.ub.indexer.App.java

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

    // create Options object
    Options options = new Options();

    options.addOption("h", "help", false, "display this help");

    options.addOption("f", "filename", true, "name of the JSON file whose content should be indexed");
    options.addOption("i", "index", true, "the name of the target index");
    options.addOption("d", "doctype", true, "the name of the doctype (title, local, ...)");

    options.addOption("t", "host", true, "elasticsearch hostname (default: 0.0.0.0)");
    options.addOption("p", "port", true, "transport port (that's NOT the http port, default: 9300)");
    options.addOption("c", "cluster", true, "cluster name (default: elasticsearch_mdma)");

    options.addOption("b", "bulksize", true, "number of docs sent in one request (default: 3000)");
    options.addOption("v", "verbose", false, "show processing speed while indexing");
    options.addOption("s", "status", false, "only show status of index for file");

    options.addOption("r", "repair", false, "attempt to repair recoverable inconsistencies on the go");
    options.addOption("e", "debug", false, "set logging level to debug");
    options.addOption("l", "logfile", true, "logfile - in not specified only log to stdout");

    options.addOption("m", "memcached", true, "host and port of memcached (default: localhost:11211)");
    options.addOption("z", "latest-flag-on", true,
            "enable latest flag according to field (within content, e.g. 001)");
    options.addOption("a", "flat", false, "flat-mode: do not check for inconsistencies");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;//w  w  w .  j ava 2 s. c  o m

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException ex) {
        logger.error(ex);
        System.exit(1);
    }

    // setup logging
    Properties systemProperties = System.getProperties();
    systemProperties.put("net.spy.log.LoggerImpl", "net.spy.memcached.compat.log.Log4JLogger");
    System.setProperties(systemProperties);
    Logger.getLogger("net.spy.memcached").setLevel(Level.ERROR);

    Properties props = new Properties();
    props.load(props.getClass().getResourceAsStream("/log4j.properties"));

    if (cmd.hasOption("debug")) {
        props.setProperty("log4j.logger.de.unileipzig", "DEBUG");
    }

    if (cmd.hasOption("logfile")) {
        props.setProperty("log4j.rootLogger", "INFO, stdout, F");
        props.setProperty("log4j.appender.F", "org.apache.log4j.FileAppender");
        props.setProperty("log4j.appender.F.File", cmd.getOptionValue("logfile"));
        props.setProperty("log4j.appender.F.layout", "org.apache.log4j.PatternLayout");
        props.setProperty("log4j.appender.F.layout.ConversionPattern", "%5p | %d | %F | %L | %m%n");
    }

    PropertyConfigurator.configure(props);

    InetAddress addr = InetAddress.getLocalHost();
    String memcachedHostAndPort = addr.getHostAddress() + ":11211";
    if (cmd.hasOption("m")) {
        memcachedHostAndPort = cmd.getOptionValue("m");
    }

    // setup caching
    try {
        if (memcachedClient == null) {
            memcachedClient = new MemcachedClient(
                    new ConnectionFactoryBuilder().setFailureMode(FailureMode.Cancel).build(),
                    AddrUtil.getAddresses("0.0.0.0:11211"));
            try {
                // give client and server 500ms
                Thread.sleep(300);
            } catch (InterruptedException ex) {
            }

            Collection availableServers = memcachedClient.getAvailableServers();
            logger.info(availableServers);
            if (availableServers.size() == 0) {
                logger.info("no memcached servers found");
                memcachedClient.shutdown();
                memcachedClient = null;
            } else {
                logger.info(availableServers.size() + " memcached server(s) detected, fine.");
            }
        }
    } catch (IOException ex) {
        logger.warn("couldn't create a connection, bailing out: " + ex.getMessage());
    }

    // process options

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("indexer", options, true);
        quit(0);
    }

    boolean verbose = false;
    if (cmd.hasOption("verbose")) {
        verbose = true;
    }

    // ES options
    String[] hosts = new String[] { "0.0.0.0" };
    int port = 9300;
    String clusterName = "elasticsearch_mdma";
    int bulkSize = 3000;

    if (cmd.hasOption("host")) {
        hosts = cmd.getOptionValues("host");
    }
    if (cmd.hasOption("port")) {
        port = Integer.parseInt(cmd.getOptionValue("port"));
    }
    if (cmd.hasOption("cluster")) {
        clusterName = cmd.getOptionValue("cluster");
    }
    if (cmd.hasOption("bulksize")) {
        bulkSize = Integer.parseInt(cmd.getOptionValue("bulksize"));
        if (bulkSize < 1 || bulkSize > 100000) {
            logger.error("bulksize must be between 1 and 100,000");
            quit(1);
        }
    }

    // ES Client
    final Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "elasticsearch_mdma")
            .build();
    final TransportClient client = new TransportClient(settings);
    for (String host : hosts) {
        client.addTransportAddress(new InetSocketTransportAddress(host, port));
    }

    if (cmd.hasOption("filename") && cmd.hasOption("index") && cmd.hasOption("doctype")) {

        final String filename = cmd.getOptionValue("filename");

        final File _file = new File(filename);
        if (_file.length() == 0) {
            logger.info(_file.getAbsolutePath() + " is empty, skipping");
            quit(0); // file is empty
        }

        // for flat mode: leave a stampfile beside the json to 
        // indicate previous successful processing
        File directory = new File(filename).getParentFile();
        File stampfile = new File(directory, DigestUtils.shaHex(filename) + ".indexed");

        long start = System.currentTimeMillis();
        long lineCount = 0;

        final String indexName = cmd.getOptionValue("index");
        final String docType = cmd.getOptionValue("doctype");
        BulkRequestBuilder bulkRequest = client.prepareBulk();

        try {
            if (cmd.hasOption("flat")) {
                // flat mode
                // .........
                if (stampfile.exists()) {
                    logger.info("SKIPPING, since it seems this file has already " + "been imported (found: "
                            + stampfile.getAbsolutePath() + ")");
                    quit(0);
                }
            } else {

                final String srcSHA1 = extractSrcSHA1(filename);

                logger.debug(filename + " srcsha1: " + srcSHA1);

                long docsInIndex = getIndexedRecordCount(client, indexName, srcSHA1);
                logger.debug(filename + " indexed: " + docsInIndex);

                long docsInFile = getLineCount(filename);
                logger.debug(filename + " lines: " + docsInFile);

                // in non-flat-mode, indexing would take care
                // of inconsistencies
                if (docsInIndex == docsInFile) {
                    logger.info("UP-TO DATE: " + filename + " (" + docsInIndex + ", " + srcSHA1 + ")");
                    client.close();
                    quit(0);
                }

                if (docsInIndex > 0) {
                    logger.warn("INCONSISTENCY DETECTED: " + filename + ": indexed:" + docsInIndex + " lines:"
                            + docsInFile);

                    if (!cmd.hasOption("r")) {
                        logger.warn(
                                "Please re-run indexer with --repair flag or delete residues first with: $ curl -XDELETE "
                                        + hosts[0] + ":9200/" + indexName
                                        + "/_query -d ' {\"term\" : { \"meta.srcsha1\" : \"" + srcSHA1
                                        + "\" }}'");
                        client.close();
                        quit(1);
                    } else {
                        logger.info("Attempting to clear residues...");
                        // attempt to repair once
                        DeleteByQueryResponse dbqr = client.prepareDeleteByQuery(indexName)
                                .setQuery(termQuery("meta.srcsha1", srcSHA1)).execute().actionGet();

                        Iterator<IndexDeleteByQueryResponse> it = dbqr.iterator();
                        long deletions = 0;
                        while (it.hasNext()) {
                            IndexDeleteByQueryResponse response = it.next();
                            deletions += 1;
                        }
                        logger.info("Deleted residues of " + filename);
                        logger.info("Refreshing [" + indexName + "]");
                        RefreshResponse refreshResponse = client.admin().indices()
                                .refresh(new RefreshRequest(indexName)).actionGet();

                        long indexedAfterDelete = getIndexedRecordCount(client, indexName, srcSHA1);
                        logger.info(indexedAfterDelete + " docs remained");
                        if (indexedAfterDelete > 0) {
                            logger.warn("Not all residues cleaned. Try to fix this manually: $ curl -XDELETE "
                                    + hosts[0] + ":9200/" + indexName
                                    + "/_query -d ' {\"term\" : { \"meta.srcsha1\" : \"" + srcSHA1 + "\" }}'");
                            quit(1);
                        } else {
                            logger.info("Residues are gone. Now trying to reindex: " + filename);
                        }
                    }
                }
            }

            logger.info("INDEXING-REQUIRED: " + filename);
            if (cmd.hasOption("status")) {
                quit(0);
            }

            HashSet idsInBatch = new HashSet();

            String idField = null;
            if (cmd.hasOption("z")) {
                idField = cmd.getOptionValue("z");
            }

            final FileReader fr = new FileReader(filename);
            final BufferedReader br = new BufferedReader(fr);

            String line;
            // one line is one document
            while ((line = br.readLine()) != null) {

                // "Latest-Flag" machine
                // This gets obsolete with a "flat" index
                if (cmd.hasOption("z")) {
                    // flag that indicates, whether the document
                    // about to be indexed will be the latest
                    boolean willBeLatest = true;

                    // check if there is a previous (lower meta.timestamp) document with 
                    // the same identifier (whatever that may be - queried under "content")
                    final String contentIdentifier = getContentIdentifier(line, idField);
                    idsInBatch.add(contentIdentifier);

                    // assumed in meta.timestamp
                    final Long timestamp = Long.parseLong(getTimestamp(line));

                    logger.debug("Checking whether record is latest (line: " + lineCount + ")");
                    logger.debug(contentIdentifier + ", " + timestamp);

                    // get all docs, which match the contentIdentifier
                    // by filter, which doesn't score
                    final TermFilterBuilder idFilter = new TermFilterBuilder("content." + idField,
                            contentIdentifier);
                    final TermFilterBuilder kindFilter = new TermFilterBuilder("meta.kind", docType);
                    final AndFilterBuilder afb = new AndFilterBuilder();
                    afb.add(idFilter).add(kindFilter);
                    final FilteredQueryBuilder fb = filteredQuery(matchAllQuery(), afb);

                    final SearchResponse searchResponse = client.prepareSearch(indexName)
                            .setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setQuery(fb).setFrom(0)
                            .setSize(1200) // 3 years and 105 days assuming daily updates at the most
                            .setExplain(false).execute().actionGet();

                    final SearchHits searchHits = searchResponse.getHits();

                    logger.debug("docs with this id in the index: " + searchHits.getTotalHits());

                    for (final SearchHit hit : searchHits.getHits()) {
                        final String docId = hit.id();
                        final Map<String, Object> source = hit.sourceAsMap();
                        final Map meta = (Map) source.get("meta");
                        final Long docTimestamp = Long.parseLong(meta.get("timestamp").toString());
                        // if the indexed doc timestamp is lower the the current one, 
                        // remove any latest flag
                        if (timestamp >= docTimestamp) {
                            source.remove("latest");
                            final ObjectMapper mapper = new ObjectMapper();
                            // put the updated doc back
                            // IndexResponse response = 
                            client.prepareIndex(indexName, docType).setCreate(false).setId(docId)
                                    .setSource(mapper.writeValueAsBytes(source))
                                    .execute(new ActionListener<IndexResponse>() {
                                        public void onResponse(IndexResponse rspns) {
                                            logger.debug("Removed latest flag from " + contentIdentifier + ", "
                                                    + docTimestamp + ", " + hit.id() + " since (" + timestamp
                                                    + " > " + docTimestamp + ")");
                                        }

                                        public void onFailure(Throwable thrwbl) {
                                            logger.error("Could not remove flag from " + hit.id() + ", "
                                                    + contentIdentifier);
                                        }
                                    });
                            // .execute()
                            //.actionGet();
                        } else {
                            logger.debug("Doc " + hit.id() + " is newer (" + docTimestamp + ")");
                            willBeLatest = false;
                        }
                    }

                    if (willBeLatest) {
                        line = setLatestFlag(line);
                        logger.info("Setting latest flag on " + contentIdentifier + ", " + timestamp);
                    }

                    // end of latest-flag machine
                    // beware - this will be correct as long as there
                    // are no dups within one bulk!
                }

                bulkRequest.add(client.prepareIndex(indexName, docType).setSource(line));
                lineCount++;
                logger.debug("Added line " + lineCount + " to BULK");
                logger.debug(line);

                if (lineCount % bulkSize == 0) {

                    if (idsInBatch.size() != bulkSize && cmd.hasOption("z")) {
                        logger.error(
                                "This batch has duplications in the ID. That's not bad for the index, just makes the latest flag fuzzy");
                        logger.error(
                                "Bulk size was: " + bulkSize + ", but " + idsInBatch.size() + " IDs (only)");
                    }
                    idsInBatch.clear();

                    logger.debug("Issuing BULK request");

                    final long actionCount = bulkRequest.numberOfActions();
                    final BulkResponse bulkResponse = bulkRequest.execute().actionGet();
                    final long tookInMillis = bulkResponse.getTookInMillis();

                    if (bulkResponse.hasFailures()) {
                        logger.fatal("FAILED, bulk not indexed. exiting now.");
                        Iterator<BulkItemResponse> it = bulkResponse.iterator();
                        while (it.hasNext()) {
                            BulkItemResponse bir = it.next();
                            if (bir.isFailed()) {
                                Failure failure = bir.getFailure();
                                logger.fatal("id: " + failure.getId() + ", message: " + failure.getMessage()
                                        + ", type: " + failure.getType() + ", index: " + failure.getIndex());
                            }
                        }
                        quit(1);
                    } else {
                        if (verbose) {
                            final double elapsed = System.currentTimeMillis() - start;
                            final double speed = (lineCount / elapsed * 1000);
                            logger.info("OK (" + filename + ") " + lineCount + " docs indexed (" + actionCount
                                    + "/" + tookInMillis + "ms" + "/" + String.format("%.2f", speed) + "r/s)");
                        }
                    }
                    bulkRequest = client.prepareBulk();
                }
            }

            // handle the remaining items
            final long actionCount = bulkRequest.numberOfActions();
            if (actionCount > 0) {
                final BulkResponse bulkResponse = bulkRequest.execute().actionGet();
                final long tookInMillis = bulkResponse.getTookInMillis();

                if (bulkResponse.hasFailures()) {
                    logger.fatal("FAILED, bulk not indexed. exiting now.");
                    Iterator<BulkItemResponse> it = bulkResponse.iterator();
                    while (it.hasNext()) {
                        BulkItemResponse bir = it.next();
                        if (bir.isFailed()) {
                            Failure failure = bir.getFailure();
                            logger.fatal("id: " + failure.getId() + ", message: " + failure.getMessage()
                                    + ", type: " + failure.getType() + ", index: " + failure.getIndex());
                        }
                    }
                    quit(1);
                } else {

                    // trigger update now
                    RefreshResponse refreshResponse = client.admin().indices()
                            .refresh(new RefreshRequest(indexName)).actionGet();

                    if (verbose) {
                        final double elapsed = System.currentTimeMillis() - start;
                        final double speed = (lineCount / elapsed * 1000);
                        logger.info("OK (" + filename + ") " + lineCount + " docs indexed (" + actionCount + "/"
                                + tookInMillis + "ms" + "/" + String.format("%.2f", speed) + "r/s)");
                    }

                }

            }

            br.close();
            client.close();
            final double elapsed = (System.currentTimeMillis() - start) / 1000;
            final double speed = (lineCount / elapsed);
            logger.info("indexing (" + filename + ") " + lineCount + " docs took " + elapsed + "s (speed: "
                    + String.format("%.2f", speed) + "r/s)");
            if (cmd.hasOption("flat")) {
                try {
                    FileUtils.touch(stampfile);
                } catch (IOException ioe) {
                    logger.warn(".indexed files not created. Will reindex everything everytime.");
                }
            }
        } catch (IOException e) {
            client.close();
            logger.error(e);
            quit(1);
        } finally {
            client.close();
        }
    }
    quit(0);
}

From source file:CommandLineInterpreter.java

/**
 * Main method, command line input will get parsed here.
 *
 * @param args/*from w w w . j  a  v  a  2 s  .  c  o  m*/
 */
public static void main(String[] args) {
    // // test-arguments:
    // args = new String[] { "1.9", "-gui" };

    boolean success = false;
    if (args.length == 1) {
        String arg = args[0].trim().replaceAll("[-]+", "");
        if (arg.equals("help") || arg.equals("h"))
            printHelp(null);
    }

    if (args.length == 0) {
        printHelp("ONE ARGUMENT NEEDED");
    } else {
        try {
            boolean guiAlert = false;
            Float minVersion = null;
            File resourcesFile = null;

            // ------------------------------------------------ //
            // --
            // ------------------------------------------------ //
            final String minJavaVersionArgument = args[0];
            if (!minJavaVersionArgument.trim().isEmpty()) {
                try {
                    minVersion = Float.parseFloat(minJavaVersionArgument);
                } catch (Exception e) {
                    // do nothing
                }
            }
            if (minVersion == null || minVersion > 2 || minVersion < 1.6) {
                printHelp("VERSION STRING IS NOT VALID");
            }

            // ------------------------------------------------ //
            // --
            // ------------------------------------------------ //
            for (int i = 1; i < (args.length <= 3 ? args.length : 3); i++) {
                final String argument = args[i].trim();
                if (argument.equals("-gui")) {
                    guiAlert = true;
                } else {
                    String resourcesFilePath = argument;
                    if (!resourcesFilePath.isEmpty()) {
                        resourcesFile = new File(resourcesFilePath);
                        if (!resourcesFile.exists() || !resourcesFile.isFile() || !resourcesFile.canRead()) {
                            printHelp("RESOURCES FILE IS NOT VALID\n[" + resourcesFile.getAbsolutePath() + "]");
                        }
                    }
                }
            }
            // ------------------------------------------------ //
            // --
            // ------------------------------------------------ //

            success = checkJREVersion(minVersion, guiAlert);

            if (success && resourcesFile != null) {
                success = checkResources(resourcesFile, guiAlert);
            }

        } catch (Exception e) {
            success = false;
            e.printStackTrace();
        }
    }

    if (!success) {
        // set error exit code
        System.exit(1);
    }
}

From source file:IndexService.IndexServer.java

public static void main(String[] args) {
    File stop = new File("/tmp/.indexstop");
    File running = new File("/tmp/.indexrunning");
    if (args != null && args.length > 0 && args[0].equals("stop")) {
        try {//from w  ww. ja  va2  s . co m
            stop.createNewFile();
            running.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }

    if (running.exists() && (System.currentTimeMillis() - running.lastModified() < 15000)) {
        long time = running.lastModified();
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (running.lastModified() == time) {
            running.delete();
        } else {
            return;
        }
    }

    if (stop.exists()) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (stop.exists())
            stop.delete();
    }

    Configuration conf = new Configuration();
    IndexServer server = new IndexServer(conf);
    if (args != null && args.length > 0 && args[0].equals("test")) {
        server.testmode = true;
    }
    server.start();
    try {
        running.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
    new UserCmdProc(server).start();

    while (true) {
        stop = new File("/tmp/.indexstop");
        if (stop.exists()) {
            server.close();
            running.delete();
            stop.delete();
            break;
        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        running.setLastModified(System.currentTimeMillis());

    }
}

From source file:net.rptools.maptool.client.MapTool.java

public static void main(String[] args) {
    if (MAC_OS_X) {
        // On OSX the menu bar at the top of the screen can be enabled at any time, but the
        // title (ie. name of the application) has to be set before the GUI is initialized (by
        // creating a frame, loading a splash screen, etc).  So we do it here.
        System.setProperty("apple.laf.useScreenMenuBar", "true");
        System.setProperty("com.apple.mrj.application.apple.menu.about.name", "About MapTool...");
        System.setProperty("apple.awt.brushMetalLook", "true");
    }/*w  w  w.j a  va2s . c  om*/
    // Before anything else, create a place to store all the data
    try {
        AppUtil.getAppHome();
    } catch (Throwable t) {
        t.printStackTrace();

        // Create an empty frame so there's something to click on if the dialog goes in the background
        JFrame frame = new JFrame();
        SwingUtil.centerOnScreen(frame);
        frame.setVisible(true);

        String errorCreatingDir = "Error creating data directory";
        log.error(errorCreatingDir, t);
        JOptionPane.showMessageDialog(frame, t.getMessage(), errorCreatingDir, JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }
    verifyJavaVersion();

    configureLogging();

    // System properties
    System.setProperty("swing.aatext", "true");
    // System.setProperty("sun.java2d.opengl", "true");

    final SplashScreen splash = new SplashScreen(SPLASH_IMAGE, getVersion());
    splash.showSplashScreen();

    // Protocol handlers
    // cp:// is registered by the RPTURLStreamHandlerFactory constructor (why?)
    RPTURLStreamHandlerFactory factory = new RPTURLStreamHandlerFactory();
    factory.registerProtocol("asset", new AssetURLStreamHandler());
    URL.setURLStreamHandlerFactory(factory);

    final Toolkit tk = Toolkit.getDefaultToolkit();
    tk.getSystemEventQueue().push(new MapToolEventQueue());

    // LAF
    try {
        // If we are running under Mac OS X then save native menu bar look & feel components
        // Note the order of creation for the AppMenuBar, this specific chronology
        // allows the system to set up system defaults before we go and modify things.
        // That is, please don't move these lines around unless you test the result on windows and mac
        String lafname;
        if (MAC_OS_X) {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            menuBar = new AppMenuBar();
            lafname = "net.rptools.maptool.client.TinyLookAndFeelMac";
            UIManager.setLookAndFeel(lafname);
            macOSXicon();
        }
        // If running on Windows based OS, CJK font is broken when using TinyLAF.
        //         else if (WINDOWS) {
        //            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        //            menuBar = new AppMenuBar();
        //         }
        else {
            lafname = "de.muntjak.tinylookandfeel.TinyLookAndFeel";
            UIManager.setLookAndFeel(lafname);
            menuBar = new AppMenuBar();
        }
        // After the TinyLAF library is initialized, look to see if there is a Default.theme
        // in our AppHome directory and load it if there is.  Unfortunately, changing the
        // search path for the default theme requires subclassing TinyLAF and because
        // we have both the original and a Mac version that gets cumbersome.  (Really
        // the Mac version should use the default and then install the keystroke differences
        // but what we have works and I'm loathe to go playing with it at 1.3b87 -- yes, 87!)
        File f = AppUtil.getAppHome("config");
        if (f.exists()) {
            File f2 = new File(f, "Default.theme");
            if (f2.exists()) {
                if (Theme.loadTheme(f2)) {
                    // re-install the Tiny Look and Feel
                    UIManager.setLookAndFeel(lafname);

                    // Update the ComponentUIs for all Components. This
                    // needs to be invoked for all windows.
                    //SwingUtilities.updateComponentTreeUI(rootComponent);
                }
            }
        }

        com.jidesoft.utils.Lm.verifyLicense("Trevor Croft", "rptools", "5MfIVe:WXJBDrToeLWPhMv3kI2s3VFo");
        LookAndFeelFactory.addUIDefaultsCustomizer(new LookAndFeelFactory.UIDefaultsCustomizer() {
            public void customize(UIDefaults defaults) {
                // Remove red border around menus
                defaults.put("PopupMenu.foreground", Color.lightGray);
            }
        });
        LookAndFeelFactory.installJideExtension(LookAndFeelFactory.XERTO_STYLE);

        /****************************************************************************
         * For TinyLAF 1.3.04 this is how the color was changed for a
         * button.
         */
        // Theme.buttonPressedColor[Theme.style] = new ColorReference(Color.gray);

        /****************************************************************************
         * And this is how it's done in TinyLAF 1.4.0 (no idea about the
         * intervening versions).
         */
        Theme.buttonPressedColor = new SBReference(Color.GRAY, 0, -6, SBReference.SUB3_COLOR);

        configureJide();
    } catch (Exception e) {
        MapTool.showError("msg.error.lafSetup", e);
        System.exit(1);
    }

    /**
     * This is a tweak that makes the Chinese version work better.
     * <p>
     * Consider reviewing <a
     * href="http://en.wikipedia.org/wiki/CJK_characters"
     * >http://en.wikipedia.org/wiki/CJK_characters</a> before making
     * changes. And http://www.scarfboy.com/coding/unicode-tool is also a
     * really cool site.
     */
    if (Locale.CHINA.equals(Locale.getDefault())) {
        // The following font name appears to be "Sim Sun".  It can be downloaded
        // from here:  http://fr.cooltext.com/Fonts-Unicode-Chinese
        Font f = new Font("\u65B0\u5B8B\u4F53", Font.PLAIN, 12);
        FontUIResource fontRes = new FontUIResource(f);
        for (Enumeration<Object> keys = UIManager.getDefaults().keys(); keys.hasMoreElements();) {
            Object key = keys.nextElement();
            Object value = UIManager.get(key);
            if (value instanceof FontUIResource)
                UIManager.put(key, fontRes);
        }
    }

    // Draw frame contents on resize
    tk.setDynamicLayout(true);

    EventQueue.invokeLater(new Runnable() {
        public void run() {
            initialize();
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    clientFrame.setVisible(true);
                    splash.hideSplashScreen();
                    EventQueue.invokeLater(new Runnable() {
                        public void run() {
                            postInitialize();
                        }
                    });
                }
            });
        }
    });
    // new Thread(new HeapSpy()).start();
}

From source file:com.telefonica.iot.cygnus.nodes.CygnusApplication.java

/**
 * Main application to be run when this CygnusApplication is invoked. The only differences with the original one
 * are the CygnusApplication is used instead of the Application one, and the Management Interface port option in
 * the command line.// ww  w  .ja  v  a 2 s.  co  m
 * @param args
 */
public static void main(String[] args) {
    try {
        // Print Cygnus starting trace including version
        LOGGER.info("Starting Cygnus, version " + CommonUtils.getCygnusVersion() + "."
                + CommonUtils.getLastCommit());

        // Define the options to be read
        Options options = new Options();

        Option option = new Option("n", "name", true, "the name of this agent");
        option.setRequired(true);
        options.addOption(option);

        option = new Option("f", "conf-file", true, "specify a conf file");
        option.setRequired(true);
        options.addOption(option);

        option = new Option(null, "no-reload-conf", false, "do not reload conf file if changed");
        options.addOption(option);

        option = new Option("h", "help", false, "display help text");
        options.addOption(option);

        option = new Option("p", "mgmt-if-port", true, "the management interface port");
        option.setRequired(false);
        options.addOption(option);

        option = new Option("g", "gui-port", true, "the GUI port");
        option.setRequired(false);
        options.addOption(option);

        option = new Option("t", "polling-interval", true, "polling interval");
        option.setRequired(false);
        options.addOption(option);

        // Read the options
        CommandLineParser parser = new GnuParser();
        CommandLine commandLine = parser.parse(options, args);

        File configurationFile = new File(commandLine.getOptionValue('f'));
        String agentName = commandLine.getOptionValue('n');
        boolean reload = !commandLine.hasOption("no-reload-conf");

        if (commandLine.hasOption('h')) {
            new HelpFormatter().printHelp("cygnus-flume-ng agent", options, true);
            return;
        } // if

        int apiPort = DEF_MGMT_IF_PORT;

        if (commandLine.hasOption('p')) {
            apiPort = new Integer(commandLine.getOptionValue('p'));
        } // if

        int guiPort = DEF_GUI_PORT;

        if (commandLine.hasOption('g')) {
            guiPort = new Integer(commandLine.getOptionValue('g'));
        } else {
            guiPort = 0; // this disables the GUI for the time being
        } // if else

        int pollingInterval = DEF_POLLING_INTERVAL;

        if (commandLine.hasOption('t')) {
            pollingInterval = new Integer(commandLine.getOptionValue('t'));
        } // if

        // the following is to ensure that by default the agent will fail on startup if the file does not exist
        if (!configurationFile.exists()) {
            // if command line invocation, then need to fail fast
            if (System.getProperty(Constants.SYSPROP_CALLED_FROM_SERVICE) == null) {
                String path = configurationFile.getPath();

                try {
                    path = configurationFile.getCanonicalPath();
                } catch (IOException e) {
                    LOGGER.error(
                            "Failed to read canonical path for file: " + path + ". Details=" + e.getMessage());
                } // try catch

                throw new ParseException("The specified configuration file does not exist: " + path);
            } // if
        } // if

        List<LifecycleAware> components = Lists.newArrayList();
        CygnusApplication application;

        if (reload) {
            LOGGER.debug(
                    "no-reload-conf was not set, thus the configuration file will be polled each 30 seconds");
            EventBus eventBus = new EventBus(agentName + "-event-bus");
            PollingPropertiesFileConfigurationProvider configurationProvider = new PollingPropertiesFileConfigurationProvider(
                    agentName, configurationFile, eventBus, pollingInterval);
            components.add(configurationProvider);
            application = new CygnusApplication(components);
            eventBus.register(application);
        } else {
            LOGGER.debug("no-reload-conf was set, thus the configuration file will only be read this time");
            PropertiesFileConfigurationProvider configurationProvider = new PropertiesFileConfigurationProvider(
                    agentName, configurationFile);
            application = new CygnusApplication();
            application.handleConfigurationEvent(configurationProvider.getConfiguration());
        } // if else

        // use the agent name as component name in the logs through log4j Mapped Diagnostic Context (MDC)
        MDC.put(CommonConstants.LOG4J_COMP, commandLine.getOptionValue('n'));

        // start the Cygnus application
        application.start();

        // wait until the references to Flume components are not null
        try {
            while (sourcesRef == null || channelsRef == null || sinksRef == null) {
                LOGGER.info("Waiting for valid Flume components references...");
                Thread.sleep(1000);
            } // while
        } catch (InterruptedException e) {
            LOGGER.error("There was an error while waiting for Flume components references. Details: "
                    + e.getMessage());
        } // try catch

        // start the Management Interface, passing references to Flume components
        LOGGER.info("Starting a Jetty server listening on port " + apiPort + " (Management Interface)");
        mgmtIfServer = new JettyServer(apiPort, guiPort, new ManagementInterface(configurationFile, sourcesRef,
                channelsRef, sinksRef, apiPort, guiPort));
        mgmtIfServer.start();

        // create a hook "listening" for shutdown interrupts (runtime.exit(int), crtl+c, etc)
        Runtime.getRuntime().addShutdownHook(new AgentShutdownHook("agent-shutdown-hook", supervisorRef));

        // start YAFS
        YAFS yafs = new YAFS();
        yafs.start();
    } catch (IllegalArgumentException e) {
        LOGGER.error("A fatal error occurred while running. Exception follows. Details=" + e.getMessage());
    } catch (ParseException e) {
        LOGGER.error("A fatal error occurred while running. Exception follows. Details=" + e.getMessage());
    } // try catch // try catch
}

From source file:net.massbank.validator.RecordValidator.java

public static void main(String[] args) {
    RequestDummy request;/*from  w w w .  j  av  a2s.  com*/

    PrintStream out = System.out;

    Options lvOptions = new Options();
    lvOptions.addOption("h", "help", false, "show this help.");
    lvOptions.addOption("r", "recdata", true,
            "points to the recdata directory containing massbank records. Reads all *.txt files in there.");

    CommandLineParser lvParser = new BasicParser();
    CommandLine lvCmd = null;
    try {
        lvCmd = lvParser.parse(lvOptions, args);
        if (lvCmd.hasOption('h')) {
            printHelp(lvOptions);
            return;
        }
    } catch (org.apache.commons.cli.ParseException pvException) {
        System.out.println(pvException.getMessage());
    }

    String recDataPath = lvCmd.getOptionValue("recdata");

    // ---------------------------------------------
    // ????
    // ---------------------------------------------

    final String baseUrl = MassBankEnv.get(MassBankEnv.KEY_BASE_URL);
    final String dbRootPath = "./";
    final String dbHostName = MassBankEnv.get(MassBankEnv.KEY_DB_HOST_NAME);
    final String tomcatTmpPath = ".";
    final String tmpPath = (new File(tomcatTmpPath + sdf.format(new Date()))).getPath() + File.separator;
    GetConfig conf = new GetConfig(baseUrl);
    int recVersion = 2;
    String selDbName = "";
    Object up = null; // Was: file Upload
    boolean isResult = true;
    String upFileName = "";
    boolean upResult = false;
    DatabaseAccess db = null;

    try {
        // ----------------------------------------------------
        // ???
        // ----------------------------------------------------
        // if (FileUpload.isMultipartContent(request)) {
        // (new File(tmpPath)).mkdir();
        // String os = System.getProperty("os.name");
        // if (os.indexOf("Windows") == -1) {
        // isResult = FileUtil.changeMode("777", tmpPath);
        // if (!isResult) {
        // out.println(msgErr("[" + tmpPath
        // + "]  chmod failed."));
        // return;
        // }
        // }
        // up = new FileUpload(request, tmpPath);
        // }

        // ----------------------------------------------------
        // ?DB????
        // ----------------------------------------------------
        List<String> dbNameList = Arrays.asList(conf.getDbName());
        ArrayList<String> dbNames = new ArrayList<String>();
        dbNames.add("");
        File[] dbDirs = (new File(dbRootPath)).listFiles();
        if (dbDirs != null) {
            for (File dbDir : dbDirs) {
                if (dbDir.isDirectory()) {
                    int pos = dbDir.getName().lastIndexOf("\\");
                    String dbDirName = dbDir.getName().substring(pos + 1);
                    pos = dbDirName.lastIndexOf("/");
                    dbDirName = dbDirName.substring(pos + 1);
                    if (dbNameList.contains(dbDirName)) {
                        // DB???massbank.conf???DB????
                        dbNames.add(dbDirName);
                    }
                }
            }
        }
        if (dbDirs == null || dbNames.size() == 0) {
            out.println(msgErr("[" + dbRootPath + "] directory not exist."));
            return;
        }
        Collections.sort(dbNames);

        // ----------------------------------------------------
        // ?
        // ----------------------------------------------------
        // if (FileUpload.isMultipartContent(request)) {
        // HashMap<String, String[]> reqParamMap = new HashMap<String,
        // String[]>();
        // reqParamMap = up.getRequestParam();
        // if (reqParamMap != null) {
        // for (Map.Entry<String, String[]> req : reqParamMap
        // .entrySet()) {
        // if (req.getKey().equals("ver")) {
        // try {
        // recVersion = Integer
        // .parseInt(req.getValue()[0]);
        // } catch (NumberFormatException nfe) {
        // }
        // } else if (req.getKey().equals("db")) {
        // selDbName = req.getValue()[0];
        // }
        // }
        // }
        // } else {
        // if (request.getParameter("ver") != null) {
        // try {
        // recVersion = Integer.parseInt(request
        // .getParameter("ver"));
        // } catch (NumberFormatException nfe) {
        // }
        // }
        // selDbName = request.getParameter("db");
        // }
        // if (selDbName == null || selDbName.equals("")
        // || !dbNames.contains(selDbName)) {
        // selDbName = dbNames.get(0);
        // }

        // ---------------------------------------------
        // 
        // ---------------------------------------------
        out.println("Database: ");
        for (int i = 0; i < dbNames.size(); i++) {
            String dbName = dbNames.get(i);
            out.print("dbName");
            if (dbName.equals(selDbName)) {
                out.print(" selected");
            }
            if (i == 0) {
                out.println("------------------");
            } else {
                out.println(dbName);
            }
        }
        out.println("Record Version : ");
        out.println(recVersion);

        out.println("Record Archive :");

        // ---------------------------------------------
        // 
        // ---------------------------------------------
        //         HashMap<String, Boolean> upFileMap = up.doUpload();
        //         if (upFileMap != null) {
        //            for (Map.Entry<String, Boolean> e : upFileMap.entrySet()) {
        //               upFileName = e.getKey();
        //               upResult = e.getValue();
        //               break;
        //            }
        //            if (upFileName.equals("")) {
        //               out.println(msgErr("please select file."));
        //               isResult = false;
        //            } else if (!upResult) {
        //               out.println(msgErr("[" + upFileName
        //                     + "] upload failed."));
        //               isResult = false;
        //            } else if (!upFileName.endsWith(ZIP_EXTENSION)
        //                  && !upFileName.endsWith(MSBK_EXTENSION)) {
        //               out.println(msgErr("please select ["
        //                     + UPLOAD_RECDATA_ZIP
        //                     + "] or ["
        //                     + UPLOAD_RECDATA_MSBK + "]."));
        //               up.deleteFile(upFileName);
        //               isResult = false;
        //            }
        //         } else {
        //            out.println(msgErr("server error."));
        //            isResult = false;
        //         }
        //         up.deleteFileItem();
        //         if (!isResult) {
        //            return;
        //         }

        // ---------------------------------------------
        // ???
        // ---------------------------------------------
        //         final String upFilePath = (new File(tmpPath + File.separator
        //               + upFileName)).getPath();
        //         isResult = FileUtil.unZip(upFilePath, tmpPath);
        //         if (!isResult) {
        //            out.println(msgErr("["
        //                  + upFileName
        //                  + "]  extraction failed. possibility of time-out."));
        //            return;
        //         }

        // ---------------------------------------------
        // ??
        // ---------------------------------------------
        final String recPath = (new File(dbRootPath + File.separator + selDbName)).getPath();
        File tmpRecDir = new File(recDataPath);
        if (!tmpRecDir.isDirectory()) {
            tmpRecDir.mkdirs();
        }

        // ---------------------------------------------
        // ???
        // ---------------------------------------------
        // data?
        //         final String recDataPath = (new File(tmpPath + File.separator
        //               + RECDATA_DIR_NAME)).getPath()
        //               + File.separator;
        //
        //         if (!(new File(recDataPath)).isDirectory()) {
        //            if (upFileName.endsWith(ZIP_EXTENSION)) {
        //               out.println(msgErr("["
        //                     + RECDATA_DIR_NAME
        //                     + "]  directory is not included in the up-loading file."));
        //            } else if (upFileName.endsWith(MSBK_EXTENSION)) {
        //               out.println(msgErr("The uploaded file is not record data."));
        //            }
        //            return;
        //         }

        // ---------------------------------------------
        // DB
        // ---------------------------------------------
        //         db = new DatabaseAccess(dbHostName, selDbName);
        //         isResult = db.open();
        //         if (!isResult) {
        //            db.close();
        //            out.println(msgErr("not connect to database."));
        //            return;
        //         }

        // ---------------------------------------------
        // ??
        // ---------------------------------------------
        TreeMap<String, String> resultMap = validationRecord(db, out, recDataPath, recPath, recVersion);
        if (resultMap.size() == 0) {
            return;
        }

        // ---------------------------------------------
        // ?
        // ---------------------------------------------
        isResult = dispResult(out, resultMap);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (db != null) {
            db.close();
        }
        File tmpDir = new File(tmpPath);
        if (tmpDir.exists()) {
            FileUtil.removeDir(tmpDir.getPath());
        }
    }

}

From source file:com.leshazlewood.scms.cli.Main.java

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

    CommandLineParser parser = new PosixParser();

    Options options = new Options();
    options.addOption(CONFIG).addOption(DEBUG).addOption(HELP).addOption(VERSION);

    boolean debug = false;
    File sourceDir = toFile(System.getProperty("user.dir"));
    File configFile = null;
    File destDir = null;//from   ww  w  .j  a va2  s .c o  m

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

        if (line.hasOption(VERSION.getOpt())) {
            printVersionAndExit();
        }
        if (line.hasOption(HELP.getOpt())) {
            printHelpAndExit(options, null, debug, 0);
        }
        if (line.hasOption(DEBUG.getOpt())) {
            debug = true;
        }
        if (line.hasOption(CONFIG.getOpt())) {
            String configFilePath = line.getOptionValue(CONFIG.getOpt());
            configFile = toFile(configFilePath);
        }

        String[] remainingArgs = line.getArgs();
        if (remainingArgs == null) {
            printHelpAndExit(options, null, debug, -1);
        }

        assert remainingArgs != null;

        if (remainingArgs.length == 1) {
            String workingDirPath = System.getProperty("user.dir");
            sourceDir = toFile(workingDirPath);
            destDir = toFile(remainingArgs[0]);
        } else if (remainingArgs.length == 2) {
            sourceDir = toFile(remainingArgs[0]);
            destDir = toFile((remainingArgs[1]));
        } else {
            printHelpAndExit(options, null, debug, -1);
        }

        assert sourceDir != null;
        assert destDir != null;

        if (configFile == null) {
            configFile = new File(sourceDir, DEFAULT_CONFIG_FILE_NAME);
        }

        if (configFile.exists()) {
            if (configFile.isDirectory()) {
                throw new IllegalArgumentException(
                        "Expected configuration file " + configFile + " is a directory, not a file.");
            }
        } else {
            String msg = "Configuration file not found.  Create a default " + DEFAULT_CONFIG_FILE_NAME
                    + " file in your source directory or specify the " + CONFIG
                    + " option to provide the file location.";
            throw new IllegalStateException(msg);
        }

        SiteExporter siteExporter = new SiteExporter();
        siteExporter.setSourceDir(sourceDir);
        siteExporter.setDestDir(destDir);
        siteExporter.setConfigFile(configFile);
        siteExporter.init();
        siteExporter.execute();

    } catch (IllegalArgumentException iae) {
        exit(iae, debug);
    } catch (IllegalStateException ise) {
        exit(ise, debug);
    } catch (Exception e) {
        printHelpAndExit(options, e, debug, -1);
    }
}