Example usage for java.io IOException getMessage

List of usage examples for java.io IOException getMessage

Introduction

In this page you can find the example usage for java.io IOException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:lucene.IndexFiles.java

/** Index all text files under a directory. */
public static void main(String[] args) {
    String usage = "java org.apache.lucene.demo.IndexFiles"
            + " [-index INDEX_PATH] [-docs DOCS_PATH] [-update]\n\n"
            + "This indexes the documents in DOCS_PATH, creating a Lucene index"
            + "in INDEX_PATH that can be searched with SearchFiles";
    String indexPath = "E:/index26";
    // is DFR//from   w ww  .  j a  v a  2 s .c  o  m
    //2 is normal
    //3 is ib with h3
    //4 is ib with h2 with porter stemmer
    //5 is ib with h2 with s stemmer
    //6 is ib with h2 without stemmer
    //7 is  without stemmer without <p
    //8 is basic with all tags
    //9 is ib with h2 and stopwords without stemmer
    //10 like  without ib, lower tags
    //11 like 10 with lower tags p, br and hr
    //12 like 11 with tags closed
    //13 is closed tags with punctuation replace and whitespace tokenizer with hyphen cared for
    //14 std tokenizer with hyphen taken cared for with stemmer
    //15 like 14 without stemming
    //16 like 15 with LMD
    //17 like 11 with LMD
    //18 with count of lower and upper delimiters of split
    //19 like 18 with (?i) to ignore case in all and valipas > 9
    //20 with (?i) in all
    //21 is fresh 19
    //22 is legalspans with LMD
    //23 is fresh 19 without 0 pass
    //24 is legalspans with InB2
    //25 is 23
    //26 is 25 with s stemmer and 0
    //27 is legalspans demo of 50 passages
    //28 is modified legal span and fast
    //29 is 28 with s-stemming
    //30 is 28 with porter stemming
    String docsPath = "E:/documents/text";
    boolean create = true;
    for (int i = 0; i < args.length; i++) {
        if ("-index".equals(args[i])) {
            indexPath = args[i + 1];
            i++;
        } else if ("-docs".equals(args[i])) {
            docsPath = args[i + 1];
            i++;
        } else if ("-update".equals(args[i])) {
            create = false;
        }
    }

    if (docsPath == null) {
        System.err.println("Usage: " + usage);
        System.exit(1);
    }

    final Path docDir = Paths.get(docsPath);
    if (!Files.isReadable(docDir)) {
        System.out.println("Document directory dhfndk '" + docDir.toAbsolutePath()
                + "' does not exist or is not readable, please check the path");
        System.exit(1);
    }

    Date start = new Date();
    try {
        System.out.println("Indexing to directory '" + indexPath + "'...");

        Directory dir = FSDirectory.open(Paths.get(indexPath));
        //Analyzer analyzer = new StandardAnalyzer();
        //IndexWriterConfig iwc = new IndexWriterConfig(analyzer);

        StandardAnalyzer analyzer = new StandardAnalyzer();
        //Directory dir = new RAMDirectory();
        IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
        /*IBSimilarity similarity = new IBSimilarity(
              new DistributionLL(),//1 
              //new DistributionSPL(),//2
              new LambdaDF(),//1 
              //new LambdaTTF(), //2
              new NormalizationH2());*/
        /*DFRSimilarity similarity = new DFRSimilarity( ///////INB2 Similarity
          new BasicModelIn(),
          new AfterEffectL(),
          new NormalizationH1());*/
        LMDirichletSimilarity similarity = new LMDirichletSimilarity();//////// LMD Model
        iwc.setSimilarity(similarity);
        IndexWriter writer = new IndexWriter(dir, iwc);

        if (create) {
            // Create a new index in the directory, removing any
            // previously indexed documents:
            iwc.setOpenMode(OpenMode.CREATE);
        } else {
            // Add new documents to an existing index:
            iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
        }
        System.out.println("Test 1");

        // Optional: for better indexing performance, if you
        // are indexing many documents, increase the RAM
        // buffer.  But if you do this, increase the max heap
        // size to the JVM (eg add -Xmx512m or -Xmx1g):
        //
        // iwc.setRAMBufferSizeMB(256.0);

        //IndexWriter writer = new IndexWriter(dir, iwc);
        System.out.println("Test 2");
        indexDocs(writer, docDir);
        System.out.println("Test 3");

        // NOTE: if you want to maximize search performance,
        // you can optionally call forceMerge here.  This can be
        // a terribly costly operation, so generally it's only
        // worth it when your index is relatively static (ie
        // you're done adding documents to it):
        //
        // writer.forceMerge(1);

        writer.close();

        Date end = new Date();
        System.out.println(end.getTime() - start.getTime() + " total milliseconds");

    } catch (IOException e) {
        System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage());
    }
}

From source file:com.cws.esolutions.security.main.PasswordUtility.java

public static void main(final String[] args) {
    final String methodName = PasswordUtility.CNAME + "#main(final String[] args)";

    if (DEBUG) {/*  w ww.  j a  v  a  2 s.c o m*/
        DEBUGGER.debug("Value: {}", methodName);
    }

    if (args.length == 0) {
        HelpFormatter usage = new HelpFormatter();
        usage.printHelp(PasswordUtility.CNAME, options, true);

        System.exit(1);
    }

    BufferedReader bReader = null;
    BufferedWriter bWriter = null;

    try {
        // load service config first !!
        SecurityServiceInitializer.initializeService(PasswordUtility.SEC_CONFIG, PasswordUtility.LOG_CONFIG,
                false);

        if (DEBUG) {
            DEBUGGER.debug("Options options: {}", options);

            for (String arg : args) {
                DEBUGGER.debug("Value: {}", arg);
            }
        }

        CommandLineParser parser = new PosixParser();
        CommandLine commandLine = parser.parse(options, args);

        if (DEBUG) {
            DEBUGGER.debug("CommandLineParser parser: {}", parser);
            DEBUGGER.debug("CommandLine commandLine: {}", commandLine);
            DEBUGGER.debug("CommandLine commandLine.getOptions(): {}", (Object[]) commandLine.getOptions());
            DEBUGGER.debug("CommandLine commandLine.getArgList(): {}", commandLine.getArgList());
        }

        final SecurityConfigurationData secConfigData = PasswordUtility.svcBean.getConfigData();
        final SecurityConfig secConfig = secConfigData.getSecurityConfig();
        final PasswordRepositoryConfig repoConfig = secConfigData.getPasswordRepo();
        final SystemConfig systemConfig = secConfigData.getSystemConfig();

        if (DEBUG) {
            DEBUGGER.debug("SecurityConfigurationData secConfig: {}", secConfigData);
            DEBUGGER.debug("SecurityConfig secConfig: {}", secConfig);
            DEBUGGER.debug("RepositoryConfig secConfig: {}", repoConfig);
            DEBUGGER.debug("SystemConfig systemConfig: {}", systemConfig);
        }

        if (commandLine.hasOption("encrypt")) {
            if ((StringUtils.isBlank(repoConfig.getPasswordFile()))
                    || (StringUtils.isBlank(repoConfig.getSaltFile()))) {
                System.err.println("The password/salt files are not configured. Entries will not be stored!");
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            final String entryName = commandLine.getOptionValue("entry");
            final String username = commandLine.getOptionValue("username");
            final String password = commandLine.getOptionValue("password");
            final String salt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength());

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
                DEBUGGER.debug("String password: {}", password);
                DEBUGGER.debug("String salt: {}", salt);
            }

            final String encodedSalt = PasswordUtils.base64Encode(salt);
            final String encodedUserName = PasswordUtils.base64Encode(username);
            final String encryptedPassword = PasswordUtils.encryptText(password, salt,
                    secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                    secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                    systemConfig.getEncoding());
            final String encodedPassword = PasswordUtils.base64Encode(encryptedPassword);

            if (DEBUG) {
                DEBUGGER.debug("String encodedSalt: {}", encodedSalt);
                DEBUGGER.debug("String encodedUserName: {}", encodedUserName);
                DEBUGGER.debug("String encodedPassword: {}", encodedPassword);
            }

            if (commandLine.hasOption("store")) {
                try {
                    new File(passwordFile.getParent()).mkdirs();
                    new File(saltFile.getParent()).mkdirs();

                    boolean saltFileExists = (saltFile.exists()) ? true : saltFile.createNewFile();

                    if (DEBUG) {
                        DEBUGGER.debug("saltFileExists: {}", saltFileExists);
                    }

                    // write the salt out first
                    if (!(saltFileExists)) {
                        throw new IOException("Unable to create salt file");
                    }

                    boolean passwordFileExists = (passwordFile.exists()) ? true : passwordFile.createNewFile();

                    if (!(passwordFileExists)) {
                        throw new IOException("Unable to create password file");
                    }

                    if (commandLine.hasOption("replace")) {
                        File[] files = new File[] { saltFile, passwordFile };

                        if (DEBUG) {
                            DEBUGGER.debug("File[] files: {}", (Object) files);
                        }

                        for (File file : files) {
                            if (DEBUG) {
                                DEBUGGER.debug("File: {}", file);
                            }

                            String currentLine = null;
                            File tmpFile = new File(FileUtils.getTempDirectory() + "/" + "tmpFile");

                            if (DEBUG) {
                                DEBUGGER.debug("File tmpFile: {}", tmpFile);
                            }

                            bReader = new BufferedReader(new FileReader(file));
                            bWriter = new BufferedWriter(new FileWriter(tmpFile));

                            while ((currentLine = bReader.readLine()) != null) {
                                if (!(StringUtils.equals(currentLine.trim().split(",")[0], entryName))) {
                                    bWriter.write(currentLine + System.getProperty("line.separator"));
                                    bWriter.flush();
                                }
                            }

                            bWriter.close();

                            FileUtils.deleteQuietly(file);
                            FileUtils.copyFile(tmpFile, file);
                            FileUtils.deleteQuietly(tmpFile);
                        }
                    }

                    FileUtils.writeStringToFile(saltFile, entryName + "," + encodedUserName + "," + encodedSalt
                            + System.getProperty("line.separator"), true);
                    FileUtils.writeStringToFile(passwordFile, entryName + "," + encodedUserName + ","
                            + encodedPassword + System.getProperty("line.separator"), true);
                } catch (IOException iox) {
                    ERROR_RECORDER.error(iox.getMessage(), iox);
                }
            }

            System.out.println("Entry Name " + entryName + " stored.");
        }

        if (commandLine.hasOption("decrypt")) {
            String saltEntryName = null;
            String saltEntryValue = null;
            String decryptedPassword = null;
            String passwordEntryName = null;

            if ((StringUtils.isEmpty(commandLine.getOptionValue("entry"))
                    && (StringUtils.isEmpty(commandLine.getOptionValue("username"))))) {
                throw new ParseException("No entry or username was provided to decrypt.");
            }

            if (StringUtils.isEmpty(commandLine.getOptionValue("username"))) {
                throw new ParseException("no entry provided to decrypt");
            }

            String entryName = commandLine.getOptionValue("entry");
            String username = commandLine.getOptionValue("username");

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            if ((!(saltFile.canRead())) || (!(passwordFile.canRead()))) {
                throw new IOException(
                        "Unable to read configured password/salt file. Please check configuration and/or permissions.");
            }

            for (String lineEntry : FileUtils.readLines(saltFile, systemConfig.getEncoding())) {
                saltEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String saltEntryName: {}", saltEntryName);
                }

                if (StringUtils.equals(saltEntryName, entryName)) {
                    saltEntryValue = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    break;
                }
            }

            if (StringUtils.isEmpty(saltEntryValue)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            for (String lineEntry : FileUtils.readLines(passwordFile, systemConfig.getEncoding())) {
                passwordEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String passwordEntryName: {}", passwordEntryName);
                }

                if (StringUtils.equals(passwordEntryName, saltEntryName)) {
                    String decodedPassword = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    decryptedPassword = PasswordUtils.decryptText(decodedPassword, saltEntryValue,
                            secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                            secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                            systemConfig.getEncoding());

                    break;
                }
            }

            if (StringUtils.isEmpty(decryptedPassword)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            System.out.println(decryptedPassword);
        } else if (commandLine.hasOption("encode")) {
            System.out.println(PasswordUtils.base64Encode((String) commandLine.getArgList().get(0)));
        } else if (commandLine.hasOption("decode")) {
            System.out.println(PasswordUtils.base64Decode((String) commandLine.getArgList().get(0)));
        }
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        System.err.println("An error occurred during processing: " + iox.getMessage());
        System.exit(1);
    } catch (ParseException px) {
        ERROR_RECORDER.error(px.getMessage(), px);

        System.err.println("An error occurred during processing: " + px.getMessage());
        System.exit(1);
    } catch (SecurityException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        System.err.println("An error occurred during processing: " + sx.getMessage());
        System.exit(1);
    } catch (SecurityServiceException ssx) {
        ERROR_RECORDER.error(ssx.getMessage(), ssx);
        System.exit(1);
    } finally {
        try {
            if (bReader != null) {
                bReader.close();
            }

            if (bWriter != null) {
                bReader.close();
            }
        } catch (IOException iox) {
        }
    }

    System.exit(0);
}

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./*from www.j  av  a2s  .  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:ZipImploder.java

/**
 * Main command line entry point.//from  ww w .j  a va  2s  . co  m
 * 
 * @param args
 */
public static void main(final String[] args) {
    if (args.length == 0) {
        printHelp();
        System.exit(0);
    }
    String zipName = null;
    String jarName = null;
    String manName = null;
    String sourceDir = null;
    String leadDir = null;
    boolean jarActive = false, manActive = false, zipActive = false, sourceDirActive = false,
            leadDirActive = false;
    boolean verbose = false;
    boolean noDirs = false;
    // process arguments
    for (int i = 0; i < args.length; i++) {
        String arg = args[i];
        if (arg.charAt(0) == '-') { // switch
            arg = arg.substring(1);
            if (arg.equalsIgnoreCase("jar")) {
                jarActive = true;
                manActive = false;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("manifest")) {
                jarActive = false;
                manActive = true;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("zip")) {
                zipActive = true;
                manActive = false;
                jarActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("dir")) {
                jarActive = false;
                manActive = false;
                zipActive = false;
                sourceDirActive = true;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("lead")) {
                jarActive = false;
                manActive = false;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = true;
            } else if (arg.equalsIgnoreCase("noDirs")) {
                noDirs = true;
                jarActive = false;
                manActive = false;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("verbose")) {
                verbose = true;
                jarActive = false;
                manActive = false;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else {
                reportError("Invalid switch - " + arg);
            }
        } else {
            if (jarActive) {
                if (jarName != null) {
                    reportError("Duplicate value - " + arg);
                }
                jarName = arg;
            } else if (manActive) {
                if (manName != null) {
                    reportError("Duplicate value - " + arg);
                }
                manName = arg;
            } else if (zipActive) {
                if (zipName != null) {
                    reportError("Duplicate value - " + arg);
                }
                zipName = arg;
            } else if (sourceDirActive) {
                if (sourceDir != null) {
                    reportError("Duplicate value - " + arg);
                }
                sourceDir = arg;
            } else if (leadDirActive) {
                if (leadDir != null) {
                    reportError("Duplicate value - " + arg);
                }
                leadDir = arg;
            } else {
                reportError("Too many parameters - " + arg);
            }
        }
    }
    if (sourceDir == null || (zipName == null && jarName == null)) {
        reportError("Missing parameters");
    }
    if (manName != null && zipName != null) {
        reportError("Manifests not supported on ZIP files");
    }
    if (leadDir == null) {
        leadDir = new File(sourceDir).getAbsolutePath().replace('\\', '/') + '/';
    }
    if (verbose) {
        System.out.println("Effective command: " + ZipImploder.class.getName()
                + (jarName != null ? " -jar " + jarName + (manName != null ? " -manifest " + manName : "") : "")
                + (zipName != null ? " -zip " + zipName : "") + " -dir " + sourceDir + " -lead " + leadDir
                + (noDirs ? " -noDirs" : "") + (verbose ? " -verbose" : ""));
    }
    try {
        ZipImploder zi = new ZipImploder(verbose);
        if (leadDir != null) {
            zi.setBaseDir(leadDir);
        }
        if (manName != null) {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(manName));
            try {
                zi.setManifest(new Manifest(bis));
            } finally {
                bis.close();
            }
        }
        zi.setIncludeDirs(!noDirs);
        zi.process(zipName, jarName, sourceDir);
        if (verbose) {
            System.out.println("\nDone Directories=" + zi.getDirCount() + " Files=" + zi.getFileCount());
        }
    } catch (IOException ioe) {
        System.err.println("Exception - " + ioe.getMessage());
        // ioe.printStackTrace(); // *** debug ***
        System.exit(2);
    }
}

From source file:io.aos.protocol.http.httpcommon.ElementalPoolingHttpGet.java

public static void main(String... args) throws Exception {

    final HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params, "Test/1.1");
    HttpProtocolParams.setUseExpectContinue(params, true);

    final HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Required protocol interceptors
            new RequestContent(), new RequestTargetHost(),
            // Recommended protocol interceptors
            new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

    final HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    final BasicConnPool pool = new BasicConnPool(new BasicConnFactory(params));
    pool.setDefaultMaxPerRoute(2);// w w w. j a v a 2s  .c  om
    pool.setMaxTotal(2);

    HttpHost[] targets = { new HttpHost("www.google.com", 80), new HttpHost("www.yahoo.com", 80),
            new HttpHost("www.apache.com", 80) };

    class WorkerThread extends Thread {

        private final HttpHost target;

        WorkerThread(final HttpHost target) {
            super();
            this.target = target;
        }

        @Override
        public void run() {
            try {
                Future<BasicPoolEntry> future = pool.lease(this.target, null);

                boolean reusable = false;
                BasicPoolEntry entry = future.get();
                try {
                    HttpClientConnection conn = entry.getConnection();
                    HttpContext context = new BasicHttpContext(null);
                    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
                    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, this.target);

                    BasicHttpRequest request = new BasicHttpRequest("GET", "/");
                    System.out.println(">> Request URI: " + request.getRequestLine().getUri());

                    request.setParams(params);
                    httpexecutor.preProcess(request, httpproc, context);
                    HttpResponse response = httpexecutor.execute(request, conn, context);
                    response.setParams(params);
                    httpexecutor.postProcess(response, httpproc, context);

                    System.out.println("<< Response: " + response.getStatusLine());
                    System.out.println(EntityUtils.toString(response.getEntity()));

                    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
                    reusable = connStrategy.keepAlive(response, context);
                } catch (IOException ex) {
                    throw ex;
                } catch (HttpException ex) {
                    throw ex;
                } finally {
                    if (reusable) {
                        System.out.println("Connection kept alive...");
                    }
                    pool.release(entry, reusable);
                }
            } catch (Exception ex) {
                System.out.println("Request to " + this.target + " failed: " + ex.getMessage());
            }
        }

    }
    ;

    WorkerThread[] workers = new WorkerThread[targets.length];
    for (int i = 0; i < workers.length; i++) {
        workers[i] = new WorkerThread(targets[i]);
    }
    for (int i = 0; i < workers.length; i++) {
        workers[i].start();
    }
    for (int i = 0; i < workers.length; i++) {
        workers[i].join();
    }
}

From source file:org.yamj.filescanner.FileScanner.java

public static void main(String[] args) throws IOException {
    System.setProperty("file.name", LOG_FILENAME);
    PropertyConfigurator.configure("config/log4j.properties");

    // Get the current directory
    String yamjHome = ClassTools.checkSystemProperty("yamj3.home", (new File(".")).getCanonicalPath());

    try {//w w  w .j a va2  s.  co  m
        // This is a temporary fix until the yamj3.home can be read from the servlet
        ClassTools.checkSystemProperty("yamj3.home", (new File(yamjHome)).getCanonicalPath());
    } catch (IOException ex) {
        ClassTools.checkSystemProperty("yamj3.home", yamjHome);
    }

    YamjInfo yi = new YamjInfo(FileScanner.class);
    yi.printHeader(LOG);
    CmdLineParser parser = getCmdLineParser();

    ExitType status;
    try {
        parser.parse(args);

        if (parser.userWantsHelp()) {
            help(parser);
            status = SUCCESS;
        } else {
            FileScanner main = new FileScanner();
            status = main.execute(parser);
        }
    } catch (CmdLineException ex) {
        LOG.error("Failed to parse command line options: {}", ex.getMessage());
        help(parser);
        status = CMDLINE_ERROR;
    }
    System.exit(status.getReturn());
}

From source file:com.blackboard.WebdavBulkDeleterClient.java

public static void main(String[] args) {
    if (System.getProperty("log4j.configuration") != null) {
        PropertyConfigurator.configure(System.getProperty("log4j.configuration"));
    } else {/*www  .j  a  va  2s  .c  o m*/
        BasicConfigurator.configure();
    }

    // Perform command line parsing in an as friendly was as possible. 
    // Could be improved
    CommandLineParser parser = new PosixParser();
    Options options = new Options();

    // Use a map to store our options and loop over it to check and parse options via
    // addAllOptions() and verifyOptions() below
    Map<String, String> optionsAvailable = new HashMap<String, String>();
    optionsAvailable.put("deletion-list", "The file containing the list of courses to delete");
    optionsAvailable.put("user", "User with deletion privileges, usually bbsupport");
    optionsAvailable.put("password", "Password - ensure you escape any shell characters");
    optionsAvailable.put("url", "The Learn URL - usually https://example.com/bbcswebdav/courses");

    options = addAllOptions(options, optionsAvailable);

    options.addOption(OptionBuilder.withLongOpt("no-verify-ssl").withDescription("Don't verify SSL")
            .hasArg(false).create());

    CommandLine line = null;
    try {
        line = parser.parse(options, args);
        verifyOptions(line, optionsAvailable);
    } catch (ParseException e) {
        // Detailed reason will be printed by verifyOptions above
        logger.fatal("Incorrect options specified, exiting...");
        System.exit(1);
    }

    Scanner scanner = null;
    try {
        scanner = new Scanner(new File(line.getOptionValue("deletion-list")));
    } catch (FileNotFoundException e) {
        logger.fatal("Cannot open file : " + e.getLocalizedMessage());
        System.exit(1);
    }

    // By default we verify SSL certs
    boolean verifyCertStatus = true;
    if (line.hasOption("no-verify-ssl")) {
        verifyCertStatus = false;
    }

    // Loop through deletion list and delete courses if they exist.
    LearnServer instance;
    try {
        logger.debug("Attempting to open connection");
        instance = new LearnServer(line.getOptionValue("user"), line.getOptionValue("password"),
                line.getOptionValue("url"), verifyCertStatus);
        String currentCourse = null;
        logger.debug("Connection open");
        while (scanner.hasNextLine()) {
            currentCourse = scanner.nextLine();
            if (instance.exists(currentCourse)) {
                try {
                    instance.deleteCourse(currentCourse);
                    logger.info("Processing " + currentCourse + " : Result - Deletion Successful");
                } catch (IOException ioe) {
                    logger.error("Processing " + currentCourse + " : Result - Could not Delete ("
                            + ioe.getLocalizedMessage() + ")");
                }
            } else {
                logger.info("Processing " + currentCourse + " : Result - Course does not exist");
            }
        }
    } catch (IllegalArgumentException e) {
        logger.fatal(e.getLocalizedMessage());
        System.exit(1);
    } catch (IOException ioe) {
        logger.debug(ioe);
        logger.fatal(ioe.getMessage());
    }

}

From source file:com.mycompany.mavenproject4.NewMain.java

/**
 * @param args the command line arguments
 *///  w ww  .j a v  a 2s . c  om
public static void main(String[] args) {
    System.out.println("Enter your choice do you want to work with 1.postgre 2.Redis 3.Mongodb");
    InputStreamReader IORdatabase = new InputStreamReader(System.in);
    BufferedReader BIOdatabase = new BufferedReader(IORdatabase);
    String databasechoice = null;
    try {
        databasechoice = BIOdatabase.readLine();
    } catch (Exception E7) {
        System.out.println(E7.getMessage());
    }

    // loading data from the CSV file 

    CsvReader Employees = null;

    try {
        Employees = new CsvReader("CSVFile\\Employees.csv");
    } catch (FileNotFoundException EB) {
        System.out.println(EB.getMessage());
    }
    int ColumnCount = 3;
    int RowCount = 100;
    int iloop = 0;

    try {
        Employees = new CsvReader("CSVFile\\Employees.csv");
    } catch (FileNotFoundException E) {
        System.out.println(E.getMessage());
    }

    String[][] Dataarray = new String[RowCount][ColumnCount];
    try {
        while (Employees.readRecord()) {
            String v;
            String[] x;
            v = Employees.getRawRecord();
            x = v.split(",");
            for (int j = 0; j < ColumnCount; j++) {
                String value = null;
                int z = j;
                value = x[z];
                try {
                    Dataarray[iloop][j] = value;
                } catch (Exception E) {
                    System.out.println(E.getMessage());
                }
                // System.out.println(Dataarray[iloop][j]);
            }
            iloop = iloop + 1;
        }
    } catch (IOException Em) {
        System.out.println(Em.getMessage());
    }

    Employees.close();

    // connection to Database 
    switch (databasechoice) {
    // postgre code goes here 
    case "1":

        Connection Conn = null;
        Statement Stmt = null;
        URI dbUri = null;
        String choice = null;
        InputStreamReader objin = new InputStreamReader(System.in);
        BufferedReader objbuf = new BufferedReader(objin);
        try {
            Class.forName("org.postgresql.Driver");
        } catch (Exception E1) {
            System.out.println(E1.getMessage());
        }
        String username = "ldoiarosfrzrua";
        String password = "HBkE_pJpK5mMIg3p2q1_odmEFX";
        String dbUrl = "jdbc:postgresql://ec2-54-83-53-120.compute-1.amazonaws.com:5432/d6693oljh5cco4?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory";

        // now update data in the postgress Database 

        // for(int i=0;i<RowCount;i++)
        // {
        //       try 
        //          {

        //         Conn= DriverManager.getConnection(dbUrl, username, password);    
        //           Stmt = Conn.createStatement();
        //           String Connection_String = "insert into EmployeeDistinct (name,jobtitle,department) values (' "+ Dataarray[i][0]+" ',' "+ Dataarray[i][1]+" ',' "+ Dataarray[i][2]+" ')";
        //         Stmt.executeUpdate(Connection_String);
        //       
        //        }
        //        catch(SQLException E4)
        //         {
        //             System.out.println(E4.getMessage());
        //          }
        // }

        // Quering with the Database 

        System.out.println("1. Display Data ");
        System.out.println("2. Select data based on primary key");
        System.out.println("3. Select data based on Other attributes e.g Name");
        System.out.println("Enter your Choice ");
        try {
            choice = objbuf.readLine();
        } catch (IOException E) {
            System.out.println(E.getMessage());
        }
        switch (choice) {
        case "1":
            try {
                Conn = DriverManager.getConnection(dbUrl, username, password);
                Stmt = Conn.createStatement();
                String Connection_String = " Select * from EmployeeDistinct;";
                ResultSet objRS = Stmt.executeQuery(Connection_String);
                while (objRS.next()) {
                    System.out.println("Employee ID: " + objRS.getInt("EmployeeID"));
                    System.out.println("Employee Name: " + objRS.getString("Name"));
                    System.out.println("Employee City: " + objRS.getString("Jobtitle"));
                    System.out.println("Employee City: " + objRS.getString("Department"));
                }

            } catch (Exception E2) {
                System.out.println(E2.getMessage());
            }

            break;

        case "2":

            System.out.println("Enter the Primary Key");
            InputStreamReader objkey = new InputStreamReader(System.in);
            BufferedReader objbufkey = new BufferedReader(objkey);
            int key = 0;
            try {
                key = Integer.parseInt(objbufkey.readLine());
            } catch (IOException E) {
                System.out.println(E.getMessage());
            }
            try {
                Conn = DriverManager.getConnection(dbUrl, username, password);
                Stmt = Conn.createStatement();
                String Connection_String = " Select * from EmployeeDistinct where EmployeeID=" + key + ";";
                ResultSet objRS = Stmt.executeQuery(Connection_String);
                while (objRS.next()) {
                    System.out.println("Employee Name: " + objRS.getString("Name"));
                    System.out.println("Employee City: " + objRS.getString("Jobtitle"));
                    System.out.println("Employee City: " + objRS.getString("Department"));
                }

            } catch (Exception E2) {
                System.out.println(E2.getMessage());
            }
            break;

        case "3":
            String Name = null;
            System.out.println("Enter Name to find the record");
            InputStreamReader objname = new InputStreamReader(System.in);
            BufferedReader objbufname = new BufferedReader(objname);

            try {
                Name = (objbufname.readLine()).toString();
            } catch (IOException E) {
                System.out.println(E.getMessage());
            }
            try {
                Conn = DriverManager.getConnection(dbUrl, username, password);
                Stmt = Conn.createStatement();
                String Connection_String = " Select * from EmployeeDistinct where Name=" + "'" + Name + "'"
                        + ";";

                ResultSet objRS = Stmt.executeQuery(Connection_String);
                while (objRS.next()) {
                    System.out.println("Employee ID: " + objRS.getInt("EmployeeID"));
                    System.out.println("Employee City: " + objRS.getString("Jobtitle"));
                    System.out.println("Employee City: " + objRS.getString("Department"));
                }

            } catch (Exception E2) {
                System.out.println(E2.getMessage());
            }
            break;
        }
        try {
            Conn.close();
        } catch (SQLException E6) {
            System.out.println(E6.getMessage());
        }
        break;

    // Redis code goes here 

    case "2":
        int Length = 0;
        String ID = null;
        Length = 100;

        // Connection to Redis 
        Jedis jedis = new Jedis("pub-redis-18017.us-east-1-4.6.ec2.redislabs.com", 18017);
        jedis.auth("7EFOisRwMu8zvhin");
        System.out.println("Connected to Redis");

        // Storing values in the database 

        //  System.out.println("Storing values in the Database might take a minute ");

        // for(int i=0;i<Length;i++)
        // { 
        // Store data in redis 
        //     int j=i+1;
        //  jedis.hset("Employe:" + j , "Name", Dataarray[i][0]);
        //   jedis.hset("Employe:" + j , "Jobtitle ", Dataarray[i][1]);
        //  jedis.hset("Employe:" + j , "Department", Dataarray[i][2]);

        //  }

        System.out.println("Search by 1.primary key,2.Name 3.display first 20");
        InputStreamReader objkey = new InputStreamReader(System.in);
        BufferedReader objbufkey = new BufferedReader(objkey);
        String interimChoice1 = null;
        try {
            interimChoice1 = objbufkey.readLine();
        } catch (IOException E) {
            System.out.println(E.getMessage());
        }
        switch (interimChoice1) {
        case "1":
            System.out.print("Get details using the primary Key");
            InputStreamReader IORKey = new InputStreamReader(System.in);
            BufferedReader BIORKey = new BufferedReader(IORKey);
            String ID1 = null;
            try {
                ID1 = BIORKey.readLine();
            } catch (IOException E3) {
                System.out.println(E3.getMessage());
            }

            Map<String, String> properties = jedis.hgetAll("Employe:" + Integer.parseInt(ID1));
            for (Map.Entry<String, String> entry : properties.entrySet()) {
                System.out.println("Name:" + jedis.hget("Employee:" + Integer.parseInt(ID1), "Name"));
                System.out.println("Jobtitle:" + jedis.hget("Employee:" + Integer.parseInt(ID1), "Jobtitle"));
                System.out
                        .println("Department:" + jedis.hget("Employee:" + Integer.parseInt(ID1), "Department"));
            }
            break;

        case "2":
            System.out.print("Get details using Department");
            InputStreamReader IORName1 = new InputStreamReader(System.in);
            BufferedReader BIORName1 = new BufferedReader(IORName1);

            String ID2 = null;
            try {
                ID2 = BIORName1.readLine();
            } catch (IOException E3) {
                System.out.println(E3.getMessage());
            }
            for (int i = 0; i < 100; i++) {
                Map<String, String> properties3 = jedis.hgetAll("Employe:" + i);
                for (Map.Entry<String, String> entry : properties3.entrySet()) {
                    String value = entry.getValue();
                    if (entry.getValue().equals(ID2)) {
                        System.out.println("Name:" + jedis.hget("Employee:" + i, "Name"));
                        System.out.println("Jobtitle:" + jedis.hget("Employee:" + i, "Jobtitle"));
                        System.out.println("Department:" + jedis.hget("Employee:" + i, "Department"));
                    }

                }
            }

            //for (Map.Entry<String, String> entry : properties1.entrySet())
            //{
            //System.out.println(entry.getKey() + "---" + entry.getValue());
            // }
            break;

        case "3":
            for (int i = 1; i < 21; i++) {
                Map<String, String> properties3 = jedis.hgetAll("Employe:" + i);
                for (Map.Entry<String, String> entry : properties3.entrySet()) {

                    // System.out.println(jedis.hget("Employee:" + i,"Name"));
                    System.out.println("Name:" + jedis.hget("Employee:" + i, "Name"));
                    System.out.println("Jobtitle:" + jedis.hget("Employee:" + i, "Jobtitle"));
                    System.out.println("Department:" + jedis.hget("Employee:" + i, "Department"));

                }
            }
            break;
        }

        break;

    // mongo db code goes here 

    case "3":
        MongoClient mongo = new MongoClient(
                new MongoClientURI("mongodb://root2:12345@ds055564.mongolab.com:55564/heroku_766dnj8c"));
        DB db;
        db = mongo.getDB("heroku_766dnj8c");
        // storing values in the database 
        //  for(int i=0;i<100;i++)
        // {
        //     BasicDBObject document = new BasicDBObject();
        //    document.put("_id", i+1);
        //    document.put("Name", Dataarray[i][0]);
        //    document.put("Jobtitle", Dataarray[i][1]);    
        //    document.put("Department", Dataarray[i][2]);    
        //    db.getCollection("EmployeeRaw").insert(document);

        // }
        System.out.println("Search by 1.primary key,2.Name 3.display first 20");
        InputStreamReader objkey6 = new InputStreamReader(System.in);
        BufferedReader objbufkey6 = new BufferedReader(objkey6);
        String interimChoice = null;
        try {
            interimChoice = objbufkey6.readLine();
        } catch (IOException E) {
            System.out.println(E.getMessage());
        }
        switch (interimChoice) {
        case "1":
            System.out.println("Enter the Primary Key");
            InputStreamReader IORPkey = new InputStreamReader(System.in);
            BufferedReader BIORPkey = new BufferedReader(IORPkey);
            int Pkey = 0;
            try {
                Pkey = Integer.parseInt(BIORPkey.readLine());
            } catch (IOException E) {
                System.out.println(E.getMessage());
            }
            BasicDBObject inQuery = new BasicDBObject();
            inQuery.put("_id", Pkey);
            DBCursor cursor = db.getCollection("EmployeeRaw").find(inQuery);
            while (cursor.hasNext()) {
                // System.out.println(cursor.next());
                System.out.println(cursor.next());
            }
            break;
        case "2":
            System.out.println("Enter the Name to Search");
            InputStreamReader objName = new InputStreamReader(System.in);
            BufferedReader objbufName = new BufferedReader(objName);
            String Name = null;
            try {
                Name = objbufName.readLine();
            } catch (IOException E) {
                System.out.println(E.getMessage());
            }
            BasicDBObject inQuery1 = new BasicDBObject();
            inQuery1.put("Name", Name);
            DBCursor cursor1 = db.getCollection("EmployeeRaw").find(inQuery1);
            while (cursor1.hasNext()) {
                // System.out.println(cursor.next());
                System.out.println(cursor1.next());
            }
            break;

        case "3":
            for (int i = 1; i < 21; i++) {
                BasicDBObject inQuerya = new BasicDBObject();
                inQuerya.put("_id", i);
                DBCursor cursora = db.getCollection("EmployeeRaw").find(inQuerya);
                while (cursora.hasNext()) {
                    // System.out.println(cursor.next());
                    System.out.println(cursora.next());
                }
            }
            break;
        }
        break;

    }

}

From source file:com.frostvoid.trekwar.server.TrekwarServer.java

public static void main(String[] args) {
    // load language
    try {/*w  ww .  j  a  v  a  2  s.co m*/
        lang = new Language(Language.ENGLISH);
    } catch (IOException ioe) {
        System.err.println("FATAL ERROR: Unable to load language file!");
        System.exit(1);
    }

    System.out.println(lang.get("trekwar_server") + " " + VERSION);
    System.out.println("==============================================".substring(0,
            lang.get("trekwar_server").length() + 1 + VERSION.length()));

    // Handle parameters
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("file").withLongOpt("galaxy").hasArg()
            .withDescription("the galaxy file to load").create("g")); //"g", "galaxy", true, "the galaxy file to load");
    options.addOption(OptionBuilder.withArgName("port number").withLongOpt("port").hasArg()
            .withDescription("the port number to bind to (default 8472)").create("p"));
    options.addOption(OptionBuilder.withArgName("number").withLongOpt("save-interval").hasArg()
            .withDescription("how often (in turns) to save the galaxy to disk (default: 5)").create("s"));
    options.addOption(OptionBuilder.withArgName("log level").withLongOpt("log").hasArg()
            .withDescription("sets the log level: ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF")
            .create("l"));
    options.addOption("h", "help", false, "prints this help message");

    CommandLineParser cliParser = new BasicParser();

    try {
        CommandLine cmd = cliParser.parse(options, args);
        String portStr = cmd.getOptionValue("p");
        String galaxyFileStr = cmd.getOptionValue("g");
        String saveIntervalStr = cmd.getOptionValue("s");
        String logLevelStr = cmd.getOptionValue("l");

        if (cmd.hasOption("h")) {
            HelpFormatter help = new HelpFormatter();
            help.printHelp("TrekwarServer", options);
            System.exit(0);
        }

        if (cmd.hasOption("g") && galaxyFileStr != null) {
            galaxyFileName = galaxyFileStr;
        } else {
            throw new ParseException("galaxy file not specified");
        }

        if (cmd.hasOption("p") && portStr != null) {
            port = Integer.parseInt(portStr);
            if (port < 1 || port > 65535) {
                throw new NumberFormatException(lang.get("port_number_out_of_range"));
            }
        } else {
            port = 8472;
        }

        if (cmd.hasOption("s") && saveIntervalStr != null) {
            saveInterval = Integer.parseInt(saveIntervalStr);
            if (saveInterval < 1 || saveInterval > 100) {
                throw new NumberFormatException("Save Interval out of range (1-100)");
            }
        } else {
            saveInterval = 5;
        }

        if (cmd.hasOption("l") && logLevelStr != null) {
            if (logLevelStr.equalsIgnoreCase("finest")) {
                LOG.setLevel(Level.FINEST);
            } else if (logLevelStr.equalsIgnoreCase("finer")) {
                LOG.setLevel(Level.FINER);
            } else if (logLevelStr.equalsIgnoreCase("fine")) {
                LOG.setLevel(Level.FINE);
            } else if (logLevelStr.equalsIgnoreCase("config")) {
                LOG.setLevel(Level.CONFIG);
            } else if (logLevelStr.equalsIgnoreCase("info")) {
                LOG.setLevel(Level.INFO);
            } else if (logLevelStr.equalsIgnoreCase("warning")) {
                LOG.setLevel(Level.WARNING);
            } else if (logLevelStr.equalsIgnoreCase("severe")) {
                LOG.setLevel(Level.SEVERE);
            } else if (logLevelStr.equalsIgnoreCase("off")) {
                LOG.setLevel(Level.OFF);
            } else if (logLevelStr.equalsIgnoreCase("all")) {
                LOG.setLevel(Level.ALL);
            } else {
                System.err.println("ERROR: invalid log level: " + logLevelStr);
                System.err.println("Run again with -h flag to see valid log level values");
                System.exit(1);
            }
        } else {
            LOG.setLevel(Level.INFO);
        }
        // INIT LOGGING
        try {
            LOG.setUseParentHandlers(false);
            initLogging();
        } catch (IOException ex) {
            System.err.println("Unable to initialize logging to file");
            System.err.println(ex);
            System.exit(1);
        }

    } catch (Exception ex) {
        System.err.println("ERROR: " + ex.getMessage());
        System.err.println("use -h for help");
        System.exit(1);
    }

    LOG.log(Level.INFO, "Trekwar2 server " + VERSION + " starting up");

    // LOAD GALAXY
    File galaxyFile = new File(galaxyFileName);
    if (galaxyFile.exists()) {
        try {
            long timer = System.currentTimeMillis();
            LOG.log(Level.INFO, "Loading galaxy file {0}", galaxyFileName);
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(galaxyFile));
            galaxy = (Galaxy) ois.readObject();
            timer = System.currentTimeMillis() - timer;
            LOG.log(Level.INFO, "Galaxy file loaded in {0} ms", timer);
            ois.close();
        } catch (IOException ioe) {
            LOG.log(Level.SEVERE, "IO error while trying to load galaxy file", ioe);
        } catch (ClassNotFoundException cnfe) {
            LOG.log(Level.SEVERE, "Unable to find class while loading galaxy", cnfe);
        }
    } else {
        System.err.println("Error: file " + galaxyFileName + " not found");
        System.exit(1);
    }

    // if turn == 0 (start of game), execute first turn to update fog of war.
    if (galaxy.getCurrentTurn() == 0) {
        TurnExecutor.executeTurn(galaxy);
    }

    LOG.log(Level.INFO, "Current turn  : {0}", galaxy.getCurrentTurn());
    LOG.log(Level.INFO, "Turn speed    : {0} seconds", galaxy.getTurnSpeed() / 1000);
    LOG.log(Level.INFO, "Save Interval : {0}", saveInterval);
    LOG.log(Level.INFO, "Users / max   : {0} / {1}",
            new Object[] { galaxy.getUserCount(), galaxy.getMaxUsers() });

    // START SERVER
    try {
        server = new ServerSocket(port);
        LOG.log(Level.INFO, "Server listening on port {0}", port);
    } catch (BindException be) {
        LOG.log(Level.SEVERE, "Error: Unable to bind to port {0}", port);
        System.err.println(be);
        System.exit(1);
    } catch (IOException ioe) {
        LOG.log(Level.SEVERE, "Error: IO error while binding to port {0}", port);
        System.err.println(ioe);
        System.exit(1);
    }

    galaxy.startup();

    Thread timerThread = new Thread(new Runnable() {

        @Override
        @SuppressWarnings("SleepWhileInLoop")
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                    // && galaxy.getLoggedInUsers().size() > 0 will make server pause when nobody is logged in (TESTING)
                    if (System.currentTimeMillis() > galaxy.nextTurnDate) {
                        StringBuffer loggedInUsers = new StringBuffer();
                        for (User u : galaxy.getLoggedInUsers()) {
                            loggedInUsers.append(u.getUsername()).append(", ");
                        }

                        long time = TurnExecutor.executeTurn(galaxy);
                        LOG.log(Level.INFO, "Turn {0} executed in {1} ms",
                                new Object[] { galaxy.getCurrentTurn(), time });
                        LOG.log(Level.INFO, "Logged in users: " + loggedInUsers.toString());
                        LOG.log(Level.INFO,
                                "====================================================================================");

                        if (galaxy.getCurrentTurn() % saveInterval == 0) {
                            saveGalaxy();
                        }

                        galaxy.lastTurnDate = System.currentTimeMillis();
                        galaxy.nextTurnDate = galaxy.lastTurnDate + galaxy.turnSpeed;
                    }

                } catch (InterruptedException e) {
                    LOG.log(Level.SEVERE, "Error in main server loop, interrupted", e);
                }
            }
        }
    });
    timerThread.start();

    // ACCEPT CONNECTIONS AND DELEGATE TO CLIENT SESSIONS
    while (true) {
        Socket clientConnection;
        try {
            clientConnection = server.accept();
            ClientSession c = new ClientSession(clientConnection, galaxy);
            Thread t = new Thread(c);
            t.start();
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, "IO Exception while trying to handle incoming client connection", ex);
        }
    }
}

From source file:de.tilman.synctool.SyncTool.java

/**
 * @param args//from www  .j a  va  2s.c  o  m
 */
public static void main(String[] args) {

    BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%d{ISO8601} - %m%n")));
    log.info("Starting SyncTool version 1.43");

    JSAP jsap = new JSAP();

    try {
        UnflaggedOption sourceOption = new UnflaggedOption("source path").setStringParser(JSAP.STRING_PARSER)
                .setRequired(true);
        sourceOption.setHelp("the source path");
        jsap.registerParameter(sourceOption);

        UnflaggedOption destinationOption = new UnflaggedOption("destination path")
                .setStringParser(JSAP.STRING_PARSER).setRequired(true);
        destinationOption.setHelp("the destination path");
        jsap.registerParameter(destinationOption);

        FlaggedOption dbFileOption = new FlaggedOption("database file").setStringParser(JSAP.STRING_PARSER)
                .setLongFlag("dbfile").setShortFlag('f').setDefault("synctool");
        dbFileOption.setHelp("the path to the database file to use");
        jsap.registerParameter(dbFileOption);

        FlaggedOption logfileOption = new FlaggedOption("logfile").setStringParser(JSAP.STRING_PARSER)
                .setLongFlag("logfile").setShortFlag('l');
        logfileOption.setHelp("the path for a logfile to write");
        jsap.registerParameter(logfileOption);

        FlaggedOption smtpUser = new FlaggedOption("SMTP user").setStringParser(JSAP.STRING_PARSER)
                .setLongFlag("smtpuser").setShortFlag('t');
        smtpUser.setHelp("the SMTP user for e-mail reporting");
        jsap.registerParameter(smtpUser);

        FlaggedOption smtpPassword = new FlaggedOption("SMTP password").setStringParser(JSAP.STRING_PARSER)
                .setLongFlag("smtppassword").setShortFlag('w');
        smtpPassword.setHelp("the SMTP password used for sending the e-mail report");
        jsap.registerParameter(smtpPassword);

        FlaggedOption emailAddress = new FlaggedOption("e-mail address").setStringParser(JSAP.STRING_PARSER)
                .setLongFlag("email").setShortFlag('e');
        emailAddress.setHelp("send logging output as jabber message to the given address");
        jsap.registerParameter(emailAddress);

        FlaggedOption jabberAddress = new FlaggedOption("jabber address").setStringParser(JSAP.STRING_PARSER)
                .setLongFlag("jabber").setShortFlag('j');
        jabberAddress.setHelp("send logging output as jabber message to the given address");
        jsap.registerParameter(jabberAddress);

        FlaggedOption jabberServer = new FlaggedOption("jabber server").setStringParser(JSAP.STRING_PARSER)
                .setLongFlag("server").setShortFlag('r');
        jabberServer.setHelp("the jabber server to connect to");
        jsap.registerParameter(jabberServer);

        FlaggedOption jabberUser = new FlaggedOption("jabber user").setStringParser(JSAP.STRING_PARSER)
                .setLongFlag("user").setShortFlag('u');
        jabberUser.setHelp("the jabber user name used for logging in to the server");
        jsap.registerParameter(jabberUser);

        FlaggedOption jabberPassword = new FlaggedOption("jabber password").setStringParser(JSAP.STRING_PARSER)
                .setLongFlag("password").setShortFlag('p');
        jabberPassword.setHelp("the jabber password used for logging in to the server");
        jsap.registerParameter(jabberPassword);

        FlaggedOption ignoredFile = new FlaggedOption("ignore file").setStringParser(JSAP.STRING_PARSER)
                .setLongFlag("ignore").setShortFlag('g').setAllowMultipleDeclarations(true);
        jabberPassword.setHelp("path to a file that should be ignored during synchronization");
        jsap.registerParameter(ignoredFile);

        Switch dryRunSwitch = new Switch("dry-run").setLongFlag("dry-run").setShortFlag('d');
        dryRunSwitch.setHelp("perform a trial run with no changes made");
        jsap.registerParameter(dryRunSwitch);

        Switch hashingSwitch = new Switch("hashing").setLongFlag("hashing").setShortFlag('h');
        hashingSwitch.setHelp("generate MD5 file hashes for exact comparison");
        jsap.registerParameter(hashingSwitch);

        Switch rollingSwitch = new Switch("rolling-logfile").setLongFlag("rolling-logfile").setShortFlag('o');
        rollingSwitch.setHelp("generate a rolling logfile with a maximum size of 10 MB");
        jsap.registerParameter(rollingSwitch);

        Switch ignoreDirAttribsSwitch = new Switch("ignore directory attributes")
                .setLongFlag("ignore-directory-attributes").setShortFlag('i');
        ignoreDirAttribsSwitch.setHelp("do not copy attributes for directories");
        jsap.registerParameter(ignoreDirAttribsSwitch);

        Switch silentSwitch = new Switch("silent").setLongFlag("silent").setShortFlag('s');
        silentSwitch.setHelp("do not print \"Entering directory\" and \"No operation\" messages");
        jsap.registerParameter(silentSwitch);

        FlaggedOption checkFileExists = new FlaggedOption("checkfile").setStringParser(JSAP.STRING_PARSER)
                .setLongFlag("check-file-exists");
        checkFileExists.setHelp("perform synchronization only if the given file exists");
        jsap.registerParameter(checkFileExists);

        Switch debugSwitch = new Switch("debug").setLongFlag("debug");
        debugSwitch.setHelp("print debug messages");
        jsap.registerParameter(debugSwitch);

        Switch helpSwitch = new Switch("help").setLongFlag("help").setShortFlag('?');
        helpSwitch.setHelp("print help and exit");
        jsap.registerParameter(helpSwitch);

    } catch (JSAPException e) {
        log.fatal(e.getMessage());
        System.exit(-1002);
    }

    JSAPResult config = jsap.parse(args);

    if (!config.success() || config.getBoolean("help")) {
        for (java.util.Iterator errs = config.getErrorMessageIterator(); errs.hasNext();) {
            log.error("Error: " + errs.next());
        }

        log.error("Usage: java -jar synctool.jar " + jsap.getUsage() + "\n\n" + jsap.getHelp());
        System.exit(-1003);
    }

    if (config.getBoolean("debug")) {
        log.setLevel(Level.DEBUG);
    } else {
        log.setLevel(Level.INFO);
    }
    log.info("Log level set to " + log.getLevel());

    if (config.getString("logfile") != null) {
        try {
            if (config.getBoolean("rolling-logfile")) {
                BasicConfigurator.configure(new RollingFileAppender(new PatternLayout("%d{ISO8601} - %m%n"),
                        config.getString("logfile")));
                log.info("Logging to rolling logfile " + config.getString("logfile"));
            } else {
                BasicConfigurator.configure(
                        new FileAppender(new PatternLayout("%d{ISO8601} - %m%n"), config.getString("logfile")));
                log.info("Logging to " + config.getString("logfile"));
            }
        } catch (IOException ioe) {
            log.fatal(ioe.getMessage(), ioe);
            System.exit(-1004);
        }
    }

    if (config.getString("SMTP user") != null) {
        BasicConfigurator.configure(new EmailCollector(200, config.getString("SMTP user"),
                config.getString("SMTP password"), config.getString("e-mail address"), "SyncTool Report"));
        log.info("Prepared e-mail report for " + config.getString("e-mail address"));

    }

    if (config.getString("jabber address") != null) {
        try {
            BasicConfigurator.configure(
                    new JabberAppender(config.getString("jabber address"), config.getString("jabber server"),
                            config.getString("jabber user"), config.getString("jabber password")));
        } catch (XMPPException xe) {
            log.fatal(xe.getMessage(), xe);
            System.exit(-1005);
        }
        log.info("Logging to " + config.getString("jabber address"));
    }

    if (config.getString("checkfile") != null) {
        if (new File(config.getString("checkfile")).exists() == false) {
            log.error(
                    "The file " + config.getString("checkfile") + " does not exist. Stopping synchronization.");
            System.exit(-1006);
        }
    }

    SyncTool syncTool = new SyncTool(config);
    syncTool.sync(config.getString("source path"), config.getString("destination path"));

    // shutting down the logger will trigger the generation of the e-mail report
    LogManager.shutdown();
}