Example usage for java.lang String equalsIgnoreCase

List of usage examples for java.lang String equalsIgnoreCase

Introduction

In this page you can find the example usage for java.lang String equalsIgnoreCase.

Prototype

public boolean equalsIgnoreCase(String anotherString) 

Source Link

Document

Compares this String to another String , ignoring case considerations.

Usage

From source file:com.http.ClientConfiguration.java

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

    // Use custom message parser / writer to customize the way HTTP
    // messages are parsed from and written out to the data stream.
    HttpMessageParserFactory<HttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() {

        @Override//  w ww.j ava2s .  c o m
        public HttpMessageParser<HttpResponse> create(SessionInputBuffer buffer,
                MessageConstraints constraints) {
            LineParser lineParser = new BasicLineParser() {

                @Override
                public Header parseHeader(final CharArrayBuffer buffer) {
                    try {
                        return super.parseHeader(buffer);
                    } catch (ParseException ex) {
                        return new BasicHeader(buffer.toString(), null);
                    }
                }

            };
            return new DefaultHttpResponseParser(buffer, lineParser, DefaultHttpResponseFactory.INSTANCE,
                    constraints) {

                @Override
                protected boolean reject(final CharArrayBuffer line, int count) {
                    // try to ignore all garbage preceding a status line infinitely
                    return false;
                }

            };
        }

    };
    HttpMessageWriterFactory<HttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory();

    // Use a custom connection factory to customize the process of
    // initialization of outgoing HTTP connections. Beside standard connection
    // configuration parameters HTTP connection factory can define message
    // parser / writer routines to be employed by individual connections.
    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory(
            requestWriterFactory, responseParserFactory);

    // Client HTTP connection objects when fully initialized can be bound to
    // an arbitrary network socket. The process of network socket initialization,
    // its connection to a remote address and binding to a local one is controlled
    // by a connection socket factory.

    // SSL context for secure connections can be created either based on
    // system or application specific properties.
    SSLContext sslcontext = SSLContexts.createSystemDefault();
    // Use custom hostname verifier to customize SSL hostname verification.
    X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier();

    // Create a registry of custom connection socket factories for supported
    // protocol schemes.
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext, hostnameVerifier)).build();

    // Use custom DNS resolver to override the system DNS resolution.
    DnsResolver dnsResolver = new SystemDefaultDnsResolver() {

        @Override
        public InetAddress[] resolve(final String host) throws UnknownHostException {
            if (host.equalsIgnoreCase("myhost")) {
                return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
            } else {
                return super.resolve(host);
            }
        }

    };

    // Create a connection manager with custom configuration.
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry, connFactory, dnsResolver);

    // Create socket configuration
    SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
    // Configure the connection manager to use socket configuration either
    // by default or for a specific host.
    connManager.setDefaultSocketConfig(socketConfig);
    connManager.setSocketConfig(new HttpHost("somehost", 80), socketConfig);

    // Create message constraints
    MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200)
            .setMaxLineLength(2000).build();
    // Create connection configuration
    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
            .setMessageConstraints(messageConstraints).build();
    // Configure the connection manager to use connection configuration either
    // by default or for a specific host.
    connManager.setDefaultConnectionConfig(connectionConfig);
    connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT);

    // Configure total max or per route limits for persistent connections
    // that can be kept in the pool or leased by the connection manager.
    connManager.setMaxTotal(100);
    connManager.setDefaultMaxPerRoute(10);
    connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20);

    // Use custom cookie store if necessary.
    CookieStore cookieStore = new BasicCookieStore();
    // Use custom credentials provider if necessary.
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    // Create global request configuration
    RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH)
            .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();

    // Create an HttpClient with the given custom dependencies and configuration.
    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(connManager)
            .setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(credentialsProvider)
            .setProxy(new HttpHost("myproxy", 8080)).setDefaultRequestConfig(defaultRequestConfig).build();

    try {
        HttpGet httpget = new HttpGet("http://218.75.79.230:8085/");
        // Request configuration can be overridden at the request level.
        // They will take precedence over the one set at the client level.
        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).setSocketTimeout(5000)
                .setConnectTimeout(5000).setConnectionRequestTimeout(5000)
                .setProxy(new HttpHost("218.75.79.230", 8085)).build();
        httpget.setConfig(requestConfig);

        // Execution context can be customized locally.
        HttpClientContext context = HttpClientContext.create();
        // Contextual attributes set the local context level will take
        // precedence over those set at the client level.
        context.setCookieStore(cookieStore);
        context.setCredentialsProvider(credentialsProvider);

        System.out.println("executing request " + httpget.getURI());
        CloseableHttpResponse response = httpclient.execute(httpget, context);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            System.out.println("----------------------------------------");

            // Once the request has been executed the local context can
            // be used to examine updated state and various objects affected
            // by the request execution.

            // Last executed request
            context.getRequest();
            // Execution route
            context.getHttpRoute();
            // Target auth state
            context.getTargetAuthState();
            // Proxy auth state
            context.getTargetAuthState();
            // Cookie origin
            context.getCookieOrigin();
            // Cookie spec used
            context.getCookieSpec();
            // User security token
            context.getUserToken();

        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.httpcilient.example.ClientConfiguration.java

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

    // Use custom message parser / writer to customize the way HTTP
    // messages are parsed from and written out to the data stream.
    HttpMessageParserFactory<HttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() {

        @Override//from  w w  w . ja  v a2  s.  co  m
        public HttpMessageParser<HttpResponse> create(SessionInputBuffer buffer,
                MessageConstraints constraints) {
            LineParser lineParser = new BasicLineParser() {

                @Override
                public Header parseHeader(final CharArrayBuffer buffer) {
                    try {
                        return super.parseHeader(buffer);
                    } catch (ParseException ex) {
                        return new BasicHeader(buffer.toString(), null);
                    }
                }

            };
            return new DefaultHttpResponseParser(buffer, lineParser, DefaultHttpResponseFactory.INSTANCE,
                    constraints) {

                @Override
                protected boolean reject(final CharArrayBuffer line, int count) {
                    // try to ignore all garbage preceding a status line infinitely
                    return false;
                }

            };
        }

    };
    HttpMessageWriterFactory<HttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory();

    // Use a custom connection factory to customize the process of
    // initialization of outgoing HTTP connections. Beside standard connection
    // configuration parameters HTTP connection factory can define message
    // parser / writer routines to be employed by individual connections.
    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory(
            requestWriterFactory, responseParserFactory);

    // Client HTTP connection objects when fully initialized can be bound to
    // an arbitrary network socket. The process of network socket initialization,
    // its connection to a remote address and binding to a local one is controlled
    // by a connection socket factory.

    // SSL context for secure connections can be created either based on
    // system or application specific properties.
    SSLContext sslcontext = SSLContexts.createSystemDefault();
    // Use custom hostname verifier to customize SSL hostname verification.
    X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier();

    // Create a registry of custom connection socket factories for supported
    // protocol schemes.
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext, hostnameVerifier)).build();

    // Use custom DNS resolver to override the system DNS resolution.
    DnsResolver dnsResolver = new SystemDefaultDnsResolver() {

        @Override
        public InetAddress[] resolve(final String host) throws UnknownHostException {
            if (host.equalsIgnoreCase("myhost")) {
                return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
            } else {
                return super.resolve(host);
            }
        }

    };

    // Create a connection manager with custom configuration.
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry, connFactory, dnsResolver);

    // Create socket configuration
    SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
    // Configure the connection manager to use socket configuration either
    // by default or for a specific host.
    connManager.setDefaultSocketConfig(socketConfig);
    connManager.setSocketConfig(new HttpHost("somehost", 80), socketConfig);

    // Create message constraints
    MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200)
            .setMaxLineLength(2000).build();
    // Create connection configuration
    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
            .setMessageConstraints(messageConstraints).build();
    // Configure the connection manager to use connection configuration either
    // by default or for a specific host.
    connManager.setDefaultConnectionConfig(connectionConfig);
    connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT);

    // Configure total max or per route limits for persistent connections
    // that can be kept in the pool or leased by the connection manager.
    connManager.setMaxTotal(100);
    connManager.setDefaultMaxPerRoute(10);
    connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20);

    // Use custom cookie store if necessary.
    CookieStore cookieStore = new BasicCookieStore();
    // Use custom credentials provider if necessary.
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    // Create global request configuration
    RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH)
            .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();

    // Create an HttpClient with the given custom dependencies and configuration.
    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(connManager)
            .setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(credentialsProvider)
            //.setProxy(new HttpHost("myproxy", 8080))
            .setDefaultRequestConfig(defaultRequestConfig).build();

    try {
        HttpGet httpget = new HttpGet("http://www.apache.org/");
        // Request configuration can be overridden at the request level.
        // They will take precedence over the one set at the client level.
        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).setSocketTimeout(5000)
                .setConnectTimeout(5000).setConnectionRequestTimeout(5000)
                // .setProxy(new HttpHost("myotherproxy", 8080))
                .build();
        httpget.setConfig(requestConfig);

        // Execution context can be customized locally.
        HttpClientContext context = HttpClientContext.create();
        // Contextual attributes set the local context level will take
        // precedence over those set at the client level.
        context.setCookieStore(cookieStore);
        context.setCredentialsProvider(credentialsProvider);

        System.out.println("executing request " + httpget.getURI());
        CloseableHttpResponse response = httpclient.execute(httpget, context);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            System.out.println("----------------------------------------");

            // Once the request has been executed the local context can
            // be used to examine updated state and various objects affected
            // by the request execution.

            // Last executed request
            context.getRequest();
            // Execution route
            context.getHttpRoute();
            // Target auth state
            context.getTargetAuthState();
            // Proxy auth state
            context.getTargetAuthState();
            // Cookie origin
            context.getCookieOrigin();
            // Cookie spec used
            context.getCookieSpec();
            // User security token
            context.getUserToken();

        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:mamo.vanillaVotifier.VanillaVotifier.java

public static void main(String[] args) {
    String[] javaVersion = System.getProperty("java.version").split("\\.");
    if (!(javaVersion.length >= 1 && Integer.parseInt(javaVersion[0]) >= 1 && javaVersion.length >= 2
            && Integer.parseInt(javaVersion[1]) >= 6)) {
        System.out.println(("You need at least Java 1.6 to run this program! Current version: "
                + System.getProperty("java.version") + "."));
        return;// ww  w .  j av a2s . co m
    }

    VanillaVotifier votifier = new VanillaVotifier();
    for (String arg : args) {
        if (arg.equalsIgnoreCase("-report-exceptions")) {
            votifier.reportExceptions = true;
        } else if (arg.equalsIgnoreCase("-help")) {
            votifier.getLogger().printlnTranslation("s58");
            return;
        } else {
            votifier.getLogger().printlnTranslation("s55",
                    new AbstractMap.SimpleEntry<String, Object>("option", arg));
            return;
        }
    }
    votifier.getLogger().printlnTranslation("s42");
    if (!(loadConfig(votifier) && startServer(votifier))) {
        return;
    }
    Scanner in = new Scanner(System.in);

    while (true) {
        String command;
        try {
            command = in.nextLine();
        } catch (NoSuchElementException e) {
            // NoSuchElementException: Can only happen at unexpected program interruption (i. e. CTRL+C). Ignoring.
            continue;
        } catch (Exception e) {
            votifier.getLogger().printlnTranslation("s57",
                    new AbstractMap.SimpleEntry<String, Object>("exception", e));
            if (!stopServer(votifier)) {
                System.exit(0); // "return" somehow isn't enough.
            }
            return;
        }
        if (command.equalsIgnoreCase("stop") || command.toLowerCase().startsWith("stop ")) {
            if (command.split(" ").length == 1) {
                stopServer(votifier);
                break;
            } else {
                votifier.getLogger().printlnTranslation("s17");
            }
        } else if (command.equalsIgnoreCase("restart") || command.toLowerCase().startsWith("restart ")) {
            if (command.split(" ").length == 1) {
                Listener listener = new Listener() {
                    @Override
                    public void onEvent(Event event, VanillaVotifier votifier) {
                        if (event instanceof ServerStoppedEvent) {
                            if (loadConfig((VanillaVotifier) votifier)
                                    && startServer((VanillaVotifier) votifier)) {
                                votifier.getServer().getListeners().remove(this);
                            } else {
                                System.exit(0);
                            }
                        }
                    }
                };
                votifier.getServer().getListeners().add(listener);
                if (!stopServer(votifier)) { // Kill the process if the server doesn't stop
                    System.exit(0); // "return" somehow isn't enough.
                    return;
                }
            } else {
                votifier.getLogger().printlnTranslation("s56");
            }
        } else if (command.equalsIgnoreCase("gen-key-pair") || command.startsWith("gen-key-pair ")) {
            String[] commandArgs = command.split(" ");
            int keySize;
            if (commandArgs.length == 1) {
                keySize = 2048;
            } else if (commandArgs.length == 2) {
                try {
                    keySize = Integer.parseInt(commandArgs[1]);
                } catch (NumberFormatException e) {
                    votifier.getLogger().printlnTranslation("s19");
                    continue;
                }
                if (keySize < 512) {
                    votifier.getLogger().printlnTranslation("s51");
                    continue;
                }
                if (keySize > 16384) {
                    votifier.getLogger().printlnTranslation("s52");
                    continue;
                }
            } else {
                votifier.getLogger().printlnTranslation("s20");
                continue;
            }
            votifier.getLogger().printlnTranslation("s16");
            votifier.getConfig().genKeyPair(keySize);
            try {
                votifier.getConfig().save();
            } catch (Exception e) {
                votifier.getLogger().printlnTranslation("s21",
                        new AbstractMap.SimpleEntry<String, Object>("exception", e));
            }
            votifier.getLogger().printlnTranslation("s23");
        } else if (command.equalsIgnoreCase("test-vote") || command.toLowerCase().startsWith("test-vote ")) {
            String[] commandArgs = command.split(" ");
            if (commandArgs.length == 2) {
                try {
                    votifier.getTester().testVote(new Vote("TesterService", commandArgs[1],
                            votifier.getConfig().getInetSocketAddress().getAddress().getHostName()));
                } catch (Exception e) { // GeneralSecurityException, IOException
                    votifier.getLogger().printlnTranslation("s27",
                            new AbstractMap.SimpleEntry<String, Object>("exception", e));
                }
            } else {
                votifier.getLogger().printlnTranslation("s26");
            }
        } else if (command.equalsIgnoreCase("test-query") || command.toLowerCase().startsWith("test-query ")) {
            if (command.split(" ").length >= 2) {
                try {
                    votifier.getTester()
                            .testQuery(command.replaceFirst("test-query ", "").replaceAll("---", "\n"));
                } catch (Exception e) { // GeneralSecurityException, IOException
                    votifier.getLogger().printlnTranslation("s35",
                            new AbstractMap.SimpleEntry<String, Object>("exception", e));
                }
            } else {
                votifier.getLogger().printlnTranslation("s34");
            }
        } else if (command.equalsIgnoreCase("help") || command.toLowerCase().startsWith("help ")) {
            if (command.split(" ").length == 1) {
                votifier.getLogger().printlnTranslation("s31");
            } else {
                votifier.getLogger().printlnTranslation("s32");
            }
        } else if (command.equalsIgnoreCase("manual") || command.toLowerCase().startsWith("manual ")) {
            if (command.split(" ").length == 1) {
                votifier.getLogger().printlnTranslation("s36");
            } else {
                votifier.getLogger().printlnTranslation("s37");
            }
        } else if (command.equalsIgnoreCase("info") || command.toLowerCase().startsWith("info ")) {
            if (command.split(" ").length == 1) {
                votifier.getLogger().printlnTranslation("s40");
            } else {
                votifier.getLogger().printlnTranslation("s41");
            }
        } else if (command.equalsIgnoreCase("license") || command.toLowerCase().startsWith("license ")) {
            if (command.split(" ").length == 1) {
                votifier.getLogger().printlnTranslation("s43");
            } else {
                votifier.getLogger().printlnTranslation("s44");
            }
        } else {
            votifier.getLogger().printlnTranslation("s33");
        }
    }
}

From source file:org.key2gym.client.Main.java

/**
 * The main method which performs all the task described in the class
 * description./*from   ww w .j av  a2  s  .c  o  m*/
 * 
 * @param args an array of arguments
 */
public static void main(String[] args) {

    /*
     * Configures the logger using 'etc/logging.properties' or the default
     * logging properties file.
     */
    try (InputStream input = new FileInputStream(PATH_LOGGING_PROPERTIES)) {
        PropertyConfigurator.configure(input);
    } catch (IOException ex) {
        try (InputStream input = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream(RESOURCE_DEFAULT_LOGGING_PROPERTIES)) {
            PropertyConfigurator.configure(input);

            /*
             * Notify that the default logging properties file has been
             * used.
             */
            logger.info("Could not load the logging properties file");
        } catch (IOException ex2) {
            throw new RuntimeException("Failed to initialize logging system", ex2);
        }
    }

    logger.info("Starting...");

    /*
     * Loads the built-in default properties file.
     */
    try (InputStream input = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream(RESOURCE_DEFAULT_CLIENT_PROPERTIES)) {
        Properties defaultProperties = null;
        defaultProperties = new Properties();
        defaultProperties.load(input);
        properties.putAll(defaultProperties);
    } catch (IOException ex) {
        throw new RuntimeException("Failed to load the default client properties file", ex);
    }

    /*
     * Loads the local client properties file.
     */
    try (FileInputStream input = new FileInputStream(PATH_APPLICATION_PROPERTIES)) {
        Properties localProperties = null;
        localProperties = new Properties();
        localProperties.load(input);
        properties.putAll(localProperties);
    } catch (IOException ex) {
        if (logger.isEnabledFor(Level.DEBUG)) {
            logger.debug("Failed to load the client properties file", ex);
        } else {
            logger.info("Could not load the local client properties file");
        }

        /*
         * It's okay to start without the local properties file.
         */
    }

    logger.debug("Effective properties: " + properties);

    if (properties.containsKey(PROPERTY_LOCALE_COUNTRY) && properties.containsKey(PROPERTY_LOCALE_LANGUAGE)) {

        /*
         * Changes the application's locale.
         */
        Locale.setDefault(new Locale(properties.getProperty(PROPERTY_LOCALE_LANGUAGE),
                properties.getProperty(PROPERTY_LOCALE_COUNTRY)));

    } else {
        logger.debug("Using the default locale");
    }

    /*
     * Changes the application's L&F.
     */
    String ui = properties.getProperty(PROPERTY_UI);
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if (ui.equalsIgnoreCase(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
            | UnsupportedLookAndFeelException ex) {
        logger.error("Failed to change the L&F:", ex);
    }

    SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);

    // Loads the client application context
    context = new ClassPathXmlApplicationContext("META-INF/client.xml");

    logger.info("Started!");
    launchAndWaitMainFrame();
    logger.info("Shutting down!");

    context.close();
}

From source file:biospectra.BioSpectra.java

/**
 * @param args the command line arguments
 *///w  w w . ja  v a  2 s.c  om
public static void main(String[] args) throws Exception {
    if (args.length < 1) {
        printHelp();
        return;
    }

    String programMode = args[0];
    String[] programArgs = new String[args.length - 1];
    System.arraycopy(args, 1, programArgs, 0, args.length - 1);

    if (programMode.equalsIgnoreCase("i") || programMode.equalsIgnoreCase("index")) {
        System.out.println("Indexing...");
        CommandArgumentsParser<CommandArgumentIndex> parser = new CommandArgumentsParser<CommandArgumentIndex>();
        CommandArgumentIndex indexArg = new CommandArgumentIndex();
        if (!parser.parse(programArgs, indexArg)) {
            return;
        }

        index(indexArg);
    } else if (programMode.equalsIgnoreCase("lc") || programMode.equalsIgnoreCase("lclassify")) {
        System.out.println("Classifying (LOCAL mode)...");
        CommandArgumentsParser<CommandArgumentLocalClassifier> parser = new CommandArgumentsParser<CommandArgumentLocalClassifier>();
        CommandArgumentLocalClassifier classifierArg = new CommandArgumentLocalClassifier();
        if (!parser.parse(programArgs, classifierArg)) {
            return;
        }

        classifyLocal(classifierArg);
    } else if (programMode.equalsIgnoreCase("rc") || programMode.equalsIgnoreCase("rclassify")) {
        System.out.println("Classifying (REMOTE mode)...");
        CommandArgumentsParser<CommandArgumentClassifierClient> parser = new CommandArgumentsParser<CommandArgumentClassifierClient>();
        CommandArgumentClassifierClient clientArg = new CommandArgumentClassifierClient();
        if (!parser.parse(programArgs, clientArg)) {
            return;
        }

        classifyRemote(clientArg);
    } else if (programMode.equalsIgnoreCase("svr") || programMode.equalsIgnoreCase("server")) {
        System.out.println("Running a classification server...");
        CommandArgumentsParser<CommandArgumentServer> parser = new CommandArgumentsParser<CommandArgumentServer>();
        CommandArgumentServer serverArg = new CommandArgumentServer();
        if (!parser.parse(programArgs, serverArg)) {
            return;
        }

        runServer(serverArg);
    } else if (programMode.equalsIgnoreCase("simulate")) {
        System.out.println("Generating simulated reads...");
        simulateReads(programArgs);
    } else {
        printHelp();
    }
}

From source file:jackrabbit.app.App.java

public static void main(String[] args) {
    if (args.length == 0 || args.length == 1 && args[0].equals("-h")) {
        System.out.println("Usage: java -jar ackrabbit-migration-query-tool-" + VERSION
                + "-jar-with-dependencies.jar "
                + "--src src --src-conf conf [--src-repo-path path] [--src-user src_user] [--src-passwd src_pw] "
                + "[--dest-user dest_user] [--dest-passwd dest_pw] [--dest dest] [--dest-conf conf] [--dest-repo-path path] "
                + "[--cnd cnd] [--node-limit limit] " + "[--query-type type] [--query query]");
        System.out.println("\t --src source repository directory");
        System.out.println("\t --src-conf source repository configuration file");
        System.out.println("\t --src-repo-path path to source node to copy from; default is \"/\"");
        System.out.println("\t --src-user source repository login");
        System.out.println("\t --src-passwd source repository password");
        System.out.println("\t --dest destination repository directory");
        System.out.println("\t --dest-conf destination repository configuration file");
        System.out.println("\t --dest-repo-path path to destination node to copy to; default is \"/\"");
        System.out.println("\t --dest-user destination repository login");
        System.out.println("\t --dest-passwd destination repository password");
        System.out.println(/*from  ww  w  . ja v a  2  s  .c o m*/
                "\t --node-limit size to partition nodes with before copying. If it is not supplied, no partitioning is performed");
        System.out.println("\t --cnd common node type definition file");
        System.out.println(
                "\t --query query to run in src. If --query is specified, then --dest, --dest-conf, --dest-repo-path and --cnd will be ignored.");
        System.out.println("\t --query-type query type (sql, xpath, JCR-SQL2); default is JCR-SQL2");
        return;
    }
    for (int i = 0; i < args.length; i = i + 2) {
        if (args[i].equals("--src") && i + 1 < args.length) {
            srcRepoDir = args[i + 1];
        } else if (args[i].equals("--dest") && i + 1 < args.length) {
            destRepoDir = args[i + 1];
        } else if (args[i].equals("--src-conf") && i + 1 < args.length) {
            srcConf = args[i + 1];
        } else if (args[i].equals("--dest-conf") && i + 1 < args.length) {
            destConf = args[i + 1];
        } else if (args[i].equals("--src-repo-path") && i + 1 < args.length) {
            srcRepoPath = args[i + 1];
        } else if (args[i].equals("--dest-repo-path") && i + 1 < args.length) {
            destRepoPath = args[i + 1];
        } else if (args[i].equals("--src-user") && i + 1 < args.length) {
            srcUser = args[i + 1];
        } else if (args[i].equals("--src-passwd") && i + 1 < args.length) {
            srcPasswd = args[i + 1];
        } else if (args[i].equals("--dest-user") && i + 1 < args.length) {
            destUser = args[i + 1];
        } else if (args[i].equals("--dest-passwd") && i + 1 < args.length) {
            destPasswd = args[i + 1];
        } else if (args[i].equals("--node-limit") && i + 1 < args.length) {
            nodeLimit = Long.parseLong(args[i + 1]);
        } else if (args[i].equals("--cnd") && i + 1 < args.length) {
            cndPath = args[i + 1];
        } else if (args[i].equals("--query") && i + 1 < args.length) {
            query = args[i + 1];
        } else if (args[i].equals("--query-type") && i + 1 < args.length) {
            queryType = args[i + 1];
        }
    }
    boolean missingArgs = false;

    if (srcRepoDir.isEmpty()) {
        missingArgs = true;
        log.error("Please specify the --src option.");
    }
    if (destRepoDir.isEmpty() && !destConf.isEmpty()) {
        missingArgs = true;
        log.error("Please specify the --dest option.");
    }
    if (srcConf.isEmpty()) {
        missingArgs = true;
        log.error("Please specify the --src-conf option.");
    }
    if (destConf.isEmpty() && !destRepoDir.isEmpty()) {
        missingArgs = true;
        log.error("Please specify the --dest-conf option.");
    }

    if (missingArgs)
        return;

    SimpleCredentials credentials = new SimpleCredentials(srcUser, srcPasswd.toCharArray());
    SimpleCredentials destCredentials = new SimpleCredentials(destUser, destPasswd.toCharArray());

    JackrabbitRepository dest = null;
    RepositoryFactory destRf = null;
    RepositoryFactory srcRf = new RepositoryFactoryImpl(srcConf, srcRepoDir);
    if (!destConf.isEmpty()) {
        destRf = new RepositoryFactoryImpl(destConf, destRepoDir);
    }

    try {
        final JackrabbitRepository src = srcRf.getRepository();
        SessionFactory srcSf = new SessionFactoryImpl(src, credentials);
        final Session srcSession = srcSf.getSession();
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                srcSession.logout();
                src.shutdown();
            }
        });
        if (destConf.isEmpty()) {//query mode
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
            if (query.isEmpty()) {
                while (true) {
                    System.out.print(">");
                    String line = in.readLine();
                    if (line == null || line.isEmpty() || line.equalsIgnoreCase("quit")
                            || line.equalsIgnoreCase("exit")) {
                        break;
                    }
                    try {
                        runQuery(srcSession, line, queryType);
                    } catch (RepositoryException e) {
                        log.error(e.getMessage(), e);
                    }
                }
            } else {
                try {
                    runQuery(srcSession, query, queryType);
                } catch (RepositoryException e) {
                    log.error(e.getMessage(), e);
                }
            }
            return;
        }

        dest = destRf.getRepository();
        SessionFactory destSf = new SessionFactoryImpl(dest, destCredentials);
        Session destSession = destSf.getSession();

        try {
            RepositoryManager.registerCustomNodeTypes(destSession, cndPath);
            if (nodeLimit == 0)
                NodeCopier.copy(srcSession, destSession, srcRepoPath, destRepoPath, true);
            else
                NodeCopier.copy(srcSession, destSession, srcRepoPath, destRepoPath, nodeLimit, true);
            log.info("Copying " + srcSession.getWorkspace().getName() + " to "
                    + destSession.getWorkspace().getName() + " for " + srcRepoDir + " done.");
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } catch (PathNotFoundException e) {
            log.error(e.getMessage(), e);
        } catch (RepositoryException e) {
            log.error(e.getMessage(), e);
        }

        List<String> destWkspaces = RepositoryManager.getDestinationWorkspaces(srcSession, destSession);

        for (String workspace : destWkspaces) {
            Session wsSession = srcSf.getSession(workspace);
            Session wsDestSession = destSf.getSession(workspace);
            try {
                RepositoryManager.registerCustomNodeTypes(wsDestSession, cndPath);
                if (nodeLimit == 0)
                    NodeCopier.copy(wsSession, wsDestSession, srcRepoPath, destRepoPath, true);
                else {
                    NodeCopier.copy(wsSession, wsDestSession, srcRepoPath, destRepoPath, nodeLimit, true);
                }
                log.info("Copying " + wsSession.getWorkspace().getName() + " to "
                        + wsDestSession.getWorkspace().getName() + " for " + srcRepoDir + " done.");
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            } catch (ParseException e) {
                log.error(e.getMessage(), e);
            } catch (PathNotFoundException e) {
                log.error(e.getMessage(), e);
            } catch (RepositoryException e) {
                log.error(e.getMessage(), e);
            } finally {
                wsSession.logout();
                wsDestSession.logout();
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } catch (PathNotFoundException e) {
        log.error(e.getMessage(), e);
    } catch (RepositoryException e) {
        log.error(e.getMessage(), e);
    } finally {
        if (dest != null)
            dest.shutdown();
    }
}

From source file:com.artistech.tuio.mouse.ZeroMqMouse.java

/**
 * Main entry point for ZeroMQ integration.
 *
 * @param args//from   ww  w  .j a  va 2  s.c  o  m
 * @throws AWTException
 * @throws java.io.IOException
 */
public static void main(String[] args) throws AWTException, java.io.IOException {
    //read off the TUIO port from the command line
    String zeromq_port;

    Options options = new Options();
    options.addOption("z", "zeromq-port", true, "ZeroMQ Server:Port to subscribe to. (-z localhost:5565)");
    options.addOption("h", "help", false, "Show this message.");
    HelpFormatter formatter = new HelpFormatter();

    try {
        CommandLineParser parser = new org.apache.commons.cli.BasicParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("help")) {
            formatter.printHelp("tuio-mouse-driver", options);
            return;
        } else {
            if (cmd.hasOption("z") || cmd.hasOption("zeromq-port")) {
                zeromq_port = cmd.getOptionValue("z");
            } else {
                System.err.println("The zeromq-port value must be specified.");
                formatter.printHelp("tuio-mouse-driver", options);
                return;
            }
        }
    } catch (ParseException ex) {
        System.err.println("Error Processing Command Options:");
        formatter.printHelp("tuio-mouse-driver", options);
        return;
    }

    //load conversion services
    ServiceLoader<ProtoConverter> services = ServiceLoader.load(ProtoConverter.class);

    //create zeromq context
    ZMQ.Context context = ZMQ.context(1);

    // Connect our subscriber socket
    ZMQ.Socket subscriber = context.socket(ZMQ.SUB);
    subscriber.setIdentity(ZeroMqMouse.class.getName().getBytes());

    //this could change I guess so we can get different data subscrptions.
    subscriber.subscribe("TuioCursor".getBytes());
    //        subscriber.subscribe("TuioTime".getBytes());
    subscriber.connect("tcp://" + zeromq_port);

    System.out.println("Subscribed to " + zeromq_port + " for ZeroMQ messages.");

    // Get updates, expect random Ctrl-C death
    String msg = "";
    MouseDriver md = new MouseDriver();
    while (!msg.equalsIgnoreCase("END")) {
        boolean success = false;
        byte[] recv = subscriber.recv();

        com.google.protobuf.GeneratedMessage message = null;
        TuioPoint pt = null;
        String type = recv.length > 0 ? new String(recv) : "";
        recv = subscriber.recv();
        switch (type) {
        case "TuioCursor.PROTOBUF":
            try {
                //it is a cursor?
                message = com.artistech.protobuf.TuioProtos.Cursor.parseFrom(recv);
                success = true;
            } catch (Exception ex) {
            }
            break;
        case "TuioTime.PROTOBUF":
            //                    try {
            //                        //it is a cursor?
            //                        message = com.artistech.protobuf.TuioProtos.Time.parseFrom(recv);
            //                        success = true;
            //                    } catch (Exception ex) {
            //                    }
            break;
        case "TuioObject.PROTOBUF":
            try {
                //it is a cursor?
                message = com.artistech.protobuf.TuioProtos.Object.parseFrom(recv);
                success = true;
            } catch (Exception ex) {
            }
            break;
        case "TuioBlob.PROTOBUF":
            try {
                //it is a cursor?
                message = com.artistech.protobuf.TuioProtos.Blob.parseFrom(recv);
                success = true;
            } catch (Exception ex) {
            }
            break;
        case "TuioCursor.JSON":
            try {
                //it is a cursor?
                pt = mapper.readValue(recv, TUIO.TuioCursor.class);
                success = true;
            } catch (Exception ex) {
            }
            break;
        case "TuioTime.JSON":
            //                    try {
            //                        //it is a cursor?
            //                        pt = mapper.readValue(recv, TUIO.TuioTime.class);
            //                        success = true;
            //                    } catch (Exception ex) {
            //                    }
            break;
        case "TuioObject.JSON":
            try {
                //it is a cursor?
                pt = mapper.readValue(recv, TUIO.TuioObject.class);
                success = true;
            } catch (Exception ex) {
            }
            break;
        case "TuioBlob.JSON":
            try {
                //it is a cursor?
                pt = mapper.readValue(recv, TUIO.TuioBlob.class);
                success = true;
            } catch (Exception ex) {
            }
            break;
        case "TuioTime.OBJECT":
            break;
        case "TuioCursor.OBJECT":
        case "TuioObject.OBJECT":
        case "TuioBlob.OBJECT":
            try {
                //Try reading the data as a serialized Java object:
                try (ByteArrayInputStream bis = new ByteArrayInputStream(recv)) {
                    //Try reading the data as a serialized Java object:
                    ObjectInput in = new ObjectInputStream(bis);
                    Object o = in.readObject();
                    //if it is of type Point (Cursor, Object, Blob), process:
                    if (TuioPoint.class.isAssignableFrom(o.getClass())) {
                        pt = (TuioPoint) o;
                        process(pt, md);
                    }

                    success = true;
                }
            } catch (java.io.IOException | ClassNotFoundException ex) {
            } finally {
            }
            break;
        default:
            success = false;
            break;
        }

        if (message != null && success) {
            //ok, so we have a message that is not null, so it was protobuf:
            Object o = null;

            //look for a converter that will suppor this objec type and convert:
            for (ProtoConverter converter : services) {
                if (converter.supportsConversion(message)) {
                    o = converter.convertFromProtobuf(message);
                    break;
                }
            }

            //if the type is of type Point (Cursor, Blob, Object), process:
            if (o != null && TuioPoint.class.isAssignableFrom(o.getClass())) {
                pt = (TuioPoint) o;
            }
        }

        if (pt != null) {
            process(pt, md);
        }
    }
}

From source file:com.shoddytcg.server.GameServer.java

/**
 * If you don't know what this method does, you clearly don't know enough Java to be working on this.
 * @param args//  ww w  . j a va  2  s .c o m
 */
public static void main(String[] args) {
    /*
     * Pipe errors to a file
     */
    try {
        PrintStream p = new PrintStream(new File("./errors.txt"));
        System.setErr(p);
    } catch (Exception e) {
        e.printStackTrace();
    }

    /*
     * Server settings
     */
    Options options = new Options();
    options.addOption("s", "settings", true, "Can be low, medium, or high.");
    options.addOption("p", "players", true, "Sets the max number of players.");
    options.addOption("ng", "nogui", false, "Starts server in headless mode.");
    options.addOption("ar", "autorun", false, "Runs without asking a single question.");
    options.addOption("h", "help", false, "Shows this menu.");

    if (args.length > 0) {

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

            /*
             * The following sets the server's settings based on the
             * computing ability of the server specified by the server owner.
             */
            if (line.hasOption("settings")) {
                String settings = line.getOptionValue("settings");
                if (settings.equalsIgnoreCase("low")) {
                    m_movementThreads = 4;
                } else if (settings.equalsIgnoreCase("medium")) {
                    m_movementThreads = 8;
                } else if (settings.equalsIgnoreCase("high")) {
                    m_movementThreads = 12;
                } else {
                    System.err.println("Server requires a settings parameter");
                    HelpFormatter formatter = new HelpFormatter();
                    formatter.printHelp("java GameServer [param] <args>", options);
                    System.exit(0);
                }
            } else {
                System.err.println("Server requires a settings parameter");
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("java GameServer [param] <args>", options);
                System.exit(0);
            }

            if (line.hasOption("players")) {
                m_maxPlayers = Integer.parseInt(line.getOptionValue("players"));
                if (m_maxPlayers == 0 || m_maxPlayers == -1)
                    m_maxPlayers = 99999;
            } else {
                System.err.println("WARNING: No maximum player count provided. Will default to 500 players.");
                m_maxPlayers = 500;
            }

            if (line.hasOption("help")) {
                HelpFormatter formatter = new HelpFormatter();
                System.err.println("Server requires a settings parameter");
                formatter.printHelp("java GameServer [param] <args>", options);
            }

            /*
             * Create the server gui
             */
            @SuppressWarnings("unused")
            GameServer gs;
            if (line.hasOption("nogui")) {
                if (line.hasOption("autorun"))
                    gs = new GameServer(true);
                else
                    gs = new GameServer(false);
            } else {
                if (line.hasOption("autorun"))
                    System.out.println("autorun doesn't work with GUI");
                gs = new GameServer(false);
            }
        } catch (ParseException exp) {
            // oops, something went wrong
            System.err.println("Parsing failed.  Reason: " + exp.getMessage());
            // automatically generate the help statement
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java GameServer [param] <args>", options);
        }

    } else {
        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        System.err.println("Server requires a settings parameter");
        formatter.printHelp("java GameServer [param] <args>", options);
    }
}

From source file:edu.msu.cme.rdp.multicompare.Main.java

public static void main(String[] args) throws Exception {
    PrintStream hier_out = null;//  ww w . ja  va2 s .  c  om
    PrintWriter assign_out = new PrintWriter(new NullWriter());
    PrintStream bootstrap_out = null;
    File hier_out_filename = null;
    String propFile = null;
    File biomFile = null;
    File metadataFile = null;
    PrintWriter shortseq_out = null;
    List<MCSample> samples = new ArrayList();
    ClassificationResultFormatter.FORMAT format = ClassificationResultFormatter.FORMAT.allRank;
    float conf = CmdOptions.DEFAULT_CONF;
    String gene = null;
    int min_bootstrap_words = Classifier.MIN_BOOTSTRSP_WORDS;

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

        if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) {
            assign_out = new PrintWriter(line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT));
        } else {
            throw new IllegalArgumentException("Require the output file for classification assignment");
        }
        if (line.hasOption(CmdOptions.HIER_OUTFILE_SHORT_OPT)) {
            hier_out_filename = new File(line.getOptionValue(CmdOptions.HIER_OUTFILE_SHORT_OPT));
            hier_out = new PrintStream(hier_out_filename);
        }
        if (line.hasOption(CmdOptions.BIOMFILE_SHORT_OPT)) {
            biomFile = new File(line.getOptionValue(CmdOptions.BIOMFILE_SHORT_OPT));
        }
        if (line.hasOption(CmdOptions.METADATA_SHORT_OPT)) {
            metadataFile = new File(line.getOptionValue(CmdOptions.METADATA_SHORT_OPT));
        }

        if (line.hasOption(CmdOptions.TRAINPROPFILE_SHORT_OPT)) {
            if (gene != null) {
                throw new IllegalArgumentException(
                        "Already specified the gene from the default location. Can not specify train_propfile");
            } else {
                propFile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT);
            }
        }
        if (line.hasOption(CmdOptions.FORMAT_SHORT_OPT)) {
            String f = line.getOptionValue(CmdOptions.FORMAT_SHORT_OPT);
            if (f.equalsIgnoreCase("allrank")) {
                format = ClassificationResultFormatter.FORMAT.allRank;
            } else if (f.equalsIgnoreCase("fixrank")) {
                format = ClassificationResultFormatter.FORMAT.fixRank;
            } else if (f.equalsIgnoreCase("filterbyconf")) {
                format = ClassificationResultFormatter.FORMAT.filterbyconf;
            } else if (f.equalsIgnoreCase("db")) {
                format = ClassificationResultFormatter.FORMAT.dbformat;
            } else if (f.equalsIgnoreCase("biom")) {
                format = ClassificationResultFormatter.FORMAT.biom;
            } else {
                throw new IllegalArgumentException(
                        "Not an valid output format, only allrank, fixrank, biom, filterbyconf and db allowed");
            }
        }
        if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) {
            if (propFile != null) {
                throw new IllegalArgumentException(
                        "Already specified train_propfile. Can not specify gene any more");
            }
            gene = line.getOptionValue(CmdOptions.GENE_SHORT_OPT).toLowerCase();

            if (!gene.equals(ClassifierFactory.RRNA_16S_GENE) && !gene.equals(ClassifierFactory.FUNGALLSU_GENE)
                    && !gene.equals(ClassifierFactory.FUNGALITS_warcup_GENE)
                    && !gene.equals(ClassifierFactory.FUNGALITS_unite_GENE)) {
                throw new IllegalArgumentException(gene + " not found, choose from"
                        + ClassifierFactory.RRNA_16S_GENE + ", " + ClassifierFactory.FUNGALLSU_GENE + ", "
                        + ClassifierFactory.FUNGALITS_warcup_GENE + ", "
                        + ClassifierFactory.FUNGALITS_unite_GENE);
            }
        }
        if (line.hasOption(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT)) {
            min_bootstrap_words = Integer
                    .parseInt(line.getOptionValue(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT));
            if (min_bootstrap_words < Classifier.MIN_BOOTSTRSP_WORDS) {
                throw new IllegalArgumentException(CmdOptions.MIN_BOOTSTRAP_WORDS_LONG_OPT
                        + " must be at least " + Classifier.MIN_BOOTSTRSP_WORDS);
            }
        }
        if (line.hasOption(CmdOptions.BOOTSTRAP_SHORT_OPT)) {
            String confString = line.getOptionValue(CmdOptions.BOOTSTRAP_SHORT_OPT);
            try {
                conf = Float.valueOf(confString);
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("Confidence must be a decimal number");
            }

            if (conf < 0 || conf > 1) {
                throw new IllegalArgumentException("Confidence must be in the range [0,1]");
            }
        }
        if (line.hasOption(CmdOptions.SHORTSEQ_OUTFILE_SHORT_OPT)) {
            shortseq_out = new PrintWriter(line.getOptionValue(CmdOptions.SHORTSEQ_OUTFILE_SHORT_OPT));
        }
        if (line.hasOption(CmdOptions.BOOTSTRAP_OUTFILE_SHORT_OPT)) {
            bootstrap_out = new PrintStream(line.getOptionValue(CmdOptions.BOOTSTRAP_OUTFILE_SHORT_OPT));
        }

        if (format.equals(ClassificationResultFormatter.FORMAT.biom) && biomFile == null) {
            throw new IllegalArgumentException("biom format requires an input biom file");
        }
        if (biomFile != null) { // if input biom file provided, use biom format
            format = ClassificationResultFormatter.FORMAT.biom;
        }

        args = line.getArgs();
        for (String arg : args) {
            String[] inFileNames = arg.split(",");
            File inputFile = new File(inFileNames[0]);
            File idmappingFile = null;
            if (!inputFile.exists()) {
                throw new IllegalArgumentException("Failed to find input file \"" + inFileNames[0] + "\"");
            }
            if (inFileNames.length == 2) {
                idmappingFile = new File(inFileNames[1]);
                if (!idmappingFile.exists()) {
                    throw new IllegalArgumentException("Failed to find input file \"" + inFileNames[1] + "\"");
                }
            }

            MCSample nextSample = new MCSample(inputFile, idmappingFile);
            samples.add(nextSample);
        }
        if (propFile == null && gene == null) {
            gene = CmdOptions.DEFAULT_GENE;
        }
        if (samples.size() < 1) {
            throw new IllegalArgumentException("Require at least one sample files");
        }
    } catch (Exception e) {
        System.out.println("Command Error: " + e.getMessage());
        new HelpFormatter().printHelp(80, " [options] <samplefile>[,idmappingfile] ...", "", options, "");
        return;
    }

    MultiClassifier multiClassifier = new MultiClassifier(propFile, gene, biomFile, metadataFile);
    MultiClassifierResult result = multiClassifier.multiCompare(samples, conf, assign_out, format,
            min_bootstrap_words);
    assign_out.close();
    if (hier_out != null) {
        DefaultPrintVisitor printVisitor = new DefaultPrintVisitor(hier_out, samples);
        result.getRoot().topDownVisit(printVisitor);
        hier_out.close();
        if (multiClassifier.hasCopyNumber()) {
            // print copy number corrected counts
            File cn_corrected_s = new File(hier_out_filename.getParentFile(),
                    "cnadjusted_" + hier_out_filename.getName());
            PrintStream cn_corrected_hier_out = new PrintStream(cn_corrected_s);
            printVisitor = new DefaultPrintVisitor(cn_corrected_hier_out, samples, true);
            result.getRoot().topDownVisit(printVisitor);
            cn_corrected_hier_out.close();
        }
    }

    if (bootstrap_out != null) {
        for (MCSample sample : samples) {
            MCSamplePrintUtil.printBootstrapCountTable(bootstrap_out, sample);
        }
        bootstrap_out.close();
    }

    if (shortseq_out != null) {
        for (String id : result.getBadSequences()) {
            shortseq_out.write(id + "\n");
        }
        shortseq_out.close();
    }

}

From source file:ZipExploder.java

/**
 * Main command line entry point.//from   w w  w . j a  v a  2 s .  c  o  m
 * 
 * @param args
 */
public static void main(final String[] args) {
    if (args.length == 0) {
        printHelp();
        System.exit(0);
    }
    List zipNames = new ArrayList();
    List jarNames = new ArrayList();
    String destDir = null;
    boolean jarActive = false, zipActive = false, destDirActive = false;
    boolean verbose = 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;
                zipActive = false;
                destDirActive = false;
            } else if (arg.equalsIgnoreCase("zip")) {
                zipActive = true;
                jarActive = false;
                destDirActive = false;
            } else if (arg.equalsIgnoreCase("dir")) {
                jarActive = false;
                zipActive = false;
                destDirActive = true;
            } else if (arg.equalsIgnoreCase("verbose")) {
                verbose = true;
            } else {
                reportError("Invalid switch - " + arg);
            }
        } else {
            if (jarActive) {
                jarNames.add(arg);
            } else if (zipActive) {
                zipNames.add(arg);
            } else if (destDirActive) {
                if (destDir != null) {
                    reportError("duplicate argument - " + "-destDir");
                }
                destDir = arg;
            } else {
                reportError("Too many parameters - " + arg);
            }
        }
    }
    if (destDir == null || (zipNames.size() + jarNames.size()) == 0) {
        reportError("Missing parameters");
    }
    if (verbose) {
        System.out.println("Effective command: " + ZipExploder.class.getName() + " "
                + (jarNames.size() > 0 ? "-jars " + jarNames + " " : "")
                + (zipNames.size() > 0 ? "-zips " + zipNames + " " : "") + "-dir " + destDir);
    }
    try {
        ZipExploder ze = new ZipExploder(verbose);
        ze.process((String[]) zipNames.toArray(new String[zipNames.size()]),
                (String[]) jarNames.toArray(new String[jarNames.size()]), destDir);
    } catch (IOException ioe) {
        System.err.println("Exception - " + ioe.getMessage());
        ioe.printStackTrace(); // *** debug ***
        System.exit(2);
    }
}