Example usage for java.util List isEmpty

List of usage examples for java.util List isEmpty

Introduction

In this page you can find the example usage for java.util List isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this list contains no elements.

Usage

From source file:SyntaxColoring.java

public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);

    final StyledText styledText = new StyledText(shell, SWT.V_SCROLL | SWT.BORDER);

    final String PUNCTUATION = "(){}";
    styledText.addExtendedModifyListener(new ExtendedModifyListener() {
        public void modifyText(ExtendedModifyEvent event) {
            int end = event.start + event.length - 1;

            if (event.start <= end) {
                String text = styledText.getText(event.start, end);
                java.util.List ranges = new java.util.ArrayList();

                for (int i = 0, n = text.length(); i < n; i++) {
                    if (PUNCTUATION.indexOf(text.charAt(i)) > -1) {
                        ranges.add(new StyleRange(event.start + i, 1, display.getSystemColor(SWT.COLOR_BLUE),
                                null, SWT.BOLD));
                    }//from  w ww  . j a  va2 s  .  c  o m
                }
                if (!ranges.isEmpty()) {
                    styledText.replaceStyleRanges(event.start, event.length,
                            (StyleRange[]) ranges.toArray(new StyleRange[0]));
                }
            }
        }
    });

    styledText.setBounds(10, 10, 500, 100);
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    display.dispose();
}

From source file:kindleclippings.word.QuizletSync.java

public static void main(String[] args) throws IOException, JSONException, URISyntaxException,
        InterruptedException, BackingStoreException, BadLocationException {

    JFileChooser fc = new JFileChooser();
    fc.setFileFilter(new FileNameExtensionFilter("Word documents", "doc", "rtf", "txt"));
    fc.setMultiSelectionEnabled(true);//from   ww  w.ja  v  a 2  s  .  c o  m
    int result = fc.showOpenDialog(null);
    if (result != JFileChooser.APPROVE_OPTION) {
        return;
    }
    File[] clf = fc.getSelectedFiles();
    if (clf == null || clf.length == 0)
        return;

    ProgressMonitor progress = new ProgressMonitor(null, "QuizletSync", "loading notes files", 0, 100);
    progress.setMillisToPopup(0);
    progress.setMillisToDecideToPopup(0);
    progress.setProgress(0);
    try {

        progress.setNote("checking Quizlet account");
        progress.setProgress(5);

        Preferences prefs = kindleclippings.quizlet.QuizletSync.getPrefs();

        QuizletAPI api = new QuizletAPI(prefs.get("access_token", null));

        Collection<TermSet> sets = null;
        try {
            progress.setNote("checking Quizlet library");
            progress.setProgress(10);
            sets = api.getSets(prefs.get("user_id", null));
        } catch (IOException e) {
            if (e.toString().contains("401")) {
                // Not Authorized => Token has been revoked
                kindleclippings.quizlet.QuizletSync.clearPrefs();
                prefs = kindleclippings.quizlet.QuizletSync.getPrefs();
                api = new QuizletAPI(prefs.get("access_token", null));
                sets = api.getSets(prefs.get("user_id", null));
            } else {
                throw e;
            }
        }

        progress.setProgress(15);
        progress.setMaximum(15 + clf.length * 10);
        progress.setNote("uploading new notes");

        int pro = 15;

        int addedSets = 0;
        int updatedTerms = 0;
        int updatedSets = 0;

        for (File f : clf) {
            progress.setProgress(pro);
            List<Clipping> clippings = readClippingsFile(f);

            if (clippings == null) {
                pro += 10;
                continue;
            }

            if (clippings.isEmpty()) {
                pro += 10;
                continue;
            }

            if (clippings.size() < 2) {
                pro += 10;
                continue;
            }

            String book = clippings.get(0).getBook();
            progress.setNote(book);

            TermSet termSet = null;
            String x = book.toLowerCase().replaceAll("\\W", "");

            for (TermSet t : sets) {
                if (t.getTitle().toLowerCase().replaceAll("\\W", "").equals(x)) {
                    termSet = t;
                    break;
                }
            }

            if (termSet == null) {

                addSet(api, book, clippings);
                addedSets++;
                pro += 10;
                continue;
            }

            // compare against existing terms
            boolean hasUpdated = false;
            for (Clipping cl : clippings) {
                if (!kindleclippings.quizlet.QuizletSync.checkExistingTerm(cl, termSet)) {
                    kindleclippings.quizlet.QuizletSync.addTerm(api, termSet, cl);
                    updatedTerms++;
                    hasUpdated = true;
                }
            }

            pro += 10;

            if (hasUpdated)
                updatedSets++;

        }

        if (updatedTerms == 0 && addedSets == 0) {
            JOptionPane.showMessageDialog(null, "Done.\nNo new data was uploaded", "QuizletSync",
                    JOptionPane.OK_OPTION);
        } else {
            if (addedSets > 0) {
                JOptionPane.showMessageDialog(null,
                        String.format("Done.\nCreated %d new sets and added %d cards to %d existing sets",
                                addedSets, updatedSets, updatedTerms),
                        "QuizletSync", JOptionPane.OK_OPTION);
            } else {
                JOptionPane.showMessageDialog(null,
                        String.format("Done.\nAdded %d cards to %d existing sets", updatedTerms, updatedSets),
                        "QuizletSync", JOptionPane.OK_OPTION);
            }
        }
    } finally {
        progress.close();
    }

    System.exit(0);
}

From source file:com.puppycrawl.tools.checkstyle.Main.java

/**
 * Loops over the files specified checking them for errors. The exit code
 * is the number of errors found in all the files.
 * @param args the command line arguments.
 * @throws FileNotFoundException if there is a problem with files access
 **//* w  ww .jav a2  s. c o m*/
public static void main(String... args) throws FileNotFoundException {
    int errorCounter = 0;
    boolean cliViolations = false;
    // provide proper exit code based on results.
    final int exitWithCliViolation = -1;
    int exitStatus = 0;

    try {
        //parse CLI arguments
        final CommandLine commandLine = parseCli(args);

        // show version and exit if it is requested
        if (commandLine.hasOption(OPTION_V_NAME)) {
            System.out.println("Checkstyle version: " + Main.class.getPackage().getImplementationVersion());
            exitStatus = 0;
        } else {
            // return error if something is wrong in arguments
            final List<String> messages = validateCli(commandLine);
            cliViolations = !messages.isEmpty();
            if (cliViolations) {
                exitStatus = exitWithCliViolation;
                errorCounter = 1;
                for (String message : messages) {
                    System.out.println(message);
                }
            } else {
                // create config helper object
                final CliOptions config = convertCliToPojo(commandLine);
                // run Checker
                errorCounter = runCheckstyle(config);
                exitStatus = errorCounter;
            }
        }
    } catch (ParseException pex) {
        // something wrong with arguments - print error and manual
        cliViolations = true;
        exitStatus = exitWithCliViolation;
        errorCounter = 1;
        System.out.println(pex.getMessage());
        printUsage();
    } catch (CheckstyleException e) {
        exitStatus = EXIT_WITH_CHECKSTYLE_EXCEPTION_CODE;
        errorCounter = 1;
        printMessageAndCause(e);
    } finally {
        // return exit code base on validation of Checker
        if (errorCounter != 0 && !cliViolations) {
            System.out.println(String.format("Checkstyle ends with %d errors.", errorCounter));
        }
        if (exitStatus != 0) {
            System.exit(exitStatus);
        }
    }
}

From source file:com.cyclopsgroup.waterview.jelly.JellyRunner.java

/**
 * Main entry to run a script//  www . ja v  a 2 s  .  c o m
 * 
 * @param args Script paths
 * @throws Exception Throw it out
 */
public static final void main(String[] args) throws Exception {
    List scripts = new ArrayList();
    for (int i = 0; i < args.length; i++) {
        String path = args[i];
        File file = new File(path);
        if (file.isFile()) {
            scripts.add(file.toURL());
        } else {
            Enumeration enu = JellyRunner.class.getClassLoader().getResources(path);
            CollectionUtils.addAll(scripts, enu);
        }
    }
    if (scripts.isEmpty()) {
        System.out.println("No script to run, return!");
        return;
    }

    String basedir = new File("").getAbsolutePath();
    Properties initProperties = new Properties(System.getProperties());
    initProperties.setProperty("basedir", basedir);
    initProperties.setProperty("plexus.home", basedir);

    WaterviewPlexusContainer container = new WaterviewPlexusContainer();
    for (Iterator j = initProperties.keySet().iterator(); j.hasNext();) {
        String initPropertyName = (String) j.next();
        container.addContextValue(initPropertyName, initProperties.get(initPropertyName));
    }

    container.addContextValue(Waterview.INIT_PROPERTIES, initProperties);
    container.initialize();
    container.start();

    JellyEngine je = (JellyEngine) container.lookup(JellyEngine.ROLE);
    JellyContext jc = new JellyContext(je.getGlobalContext());

    for (Iterator i = scripts.iterator(); i.hasNext();) {
        URL script = (URL) i.next();
        System.out.print("Running script " + script);
        jc.runScript(script, XMLOutput.createDummyXMLOutput());
        System.out.println("... Done!");
    }
    container.dispose();
}

From source file:com.netflix.genie.client.sample.ClusterServiceSampleClient.java

/**
 * Main for running client code./*w w w  . j  a  v a 2  s  . c om*/
 *
 * @param args program arguments
 * @throws Exception On issue.
 */
public static void main(final String[] args) throws Exception {
    // Initialize Eureka, if it is being used
    // LOG.info("Initializing Eureka");
    // ClusterServiceClient.initEureka("test");
    LOG.info("Initializing list of Genie servers");
    ConfigurationManager.getConfigInstance().setProperty("genie2Client.ribbon.listOfServers", "localhost:7001");

    LOG.info("Initializing ApplicationServiceClient");
    final ApplicationServiceClient appClient = ApplicationServiceClient.getInstance();

    final Application app1 = appClient.createApplication(
            ApplicationServiceSampleClient.getSampleApplication(ApplicationServiceSampleClient.ID));
    LOG.info("Created application:");
    LOG.info(app1.toString());

    final Application app2 = appClient.createApplication(
            ApplicationServiceSampleClient.getSampleApplication(ApplicationServiceSampleClient.ID + "2"));
    LOG.info("Created application:");
    LOG.info(app2.toString());

    LOG.info("Initializing CommandServiceClient");
    final CommandServiceClient commandClient = CommandServiceClient.getInstance();

    LOG.info("Creating command pig13_mr2");
    final Command command1 = commandClient
            .createCommand(CommandServiceSampleClient.createSampleCommand(CommandServiceSampleClient.ID));

    commandClient.setApplicationForCommand(command1.getId(), app1);

    LOG.info("Created command:");
    LOG.info(command1.toString());
    final List<Command> commands = new ArrayList<>();
    commands.add(command1);

    LOG.info("Initializing ClusterConfigServiceClient");
    final ClusterServiceClient clusterClient = ClusterServiceClient.getInstance();

    LOG.info("Creating new cluster configuration");
    final Cluster cluster1 = clusterClient.createCluster(createSampleCluster(ID));
    clusterClient.addCommandsToCluster(cluster1.getId(), commands);

    LOG.info("Cluster config created with id: " + cluster1.getId());
    LOG.info(cluster1.toString());

    LOG.info("Getting cluster config by id");
    final Cluster cluster2 = clusterClient.getCluster(cluster1.getId());
    LOG.info(cluster2.toString());

    LOG.info("Getting clusterConfigs using specified filter criteria");
    final Multimap<String, String> params = ArrayListMultimap.create();
    params.put("name", NAME);
    params.put("adHoc", "false");
    params.put("test", "true");
    params.put("limit", "3");
    final List<Cluster> clusters = clusterClient.getClusters(params);
    if (clusters != null && !clusters.isEmpty()) {
        for (final Cluster cluster : clusters) {
            LOG.info(cluster.toString());
        }
    } else {
        LOG.info("No clusters found for parameters");
    }

    LOG.info("Configurations for cluster with id " + cluster1.getId());
    final Set<String> configs = clusterClient.getConfigsForCluster(cluster1.getId());
    for (final String config : configs) {
        LOG.info("Config = " + config);
    }

    LOG.info("Adding configurations to cluster with id " + cluster1.getId());
    final Set<String> newConfigs = new HashSet<>();
    newConfigs.add("someNewConfigFile");
    newConfigs.add("someOtherNewConfigFile");
    final Set<String> configs2 = clusterClient.addConfigsToCluster(cluster1.getId(), newConfigs);
    for (final String config : configs2) {
        LOG.info("Config = " + config);
    }

    LOG.info("Updating set of configuration files associated with id " + cluster1.getId());
    //This should remove the original config leaving only the two in this set
    final Set<String> configs3 = clusterClient.updateConfigsForCluster(cluster1.getId(), newConfigs);
    for (final String config : configs3) {
        LOG.info("Config = " + config);
    }

    /**************** Begin tests for tag Api's *********************/
    LOG.info("Get tags for cluster with id " + cluster1.getId());
    final Set<String> tags = cluster1.getTags();
    for (final String tag : tags) {
        LOG.info("Tag = " + tag);
    }

    LOG.info("Adding tags to cluster with id " + cluster1.getId());
    final Set<String> newTags = new HashSet<>();
    newTags.add("tag1");
    newTags.add("tag2");
    final Set<String> tags2 = clusterClient.addTagsToCluster(cluster1.getId(), newTags);
    for (final String tag : tags2) {
        LOG.info("Tag = " + tag);
    }

    LOG.info("Updating set of tags associated with id " + cluster1.getId());
    //This should remove the original config leaving only the two in this set
    final Set<String> tags3 = clusterClient.updateTagsForCluster(cluster1.getId(), newTags);
    for (final String tag : tags3) {
        LOG.info("Tag = " + tag);
    }

    LOG.info("Deleting one tag from the cluster with id " + cluster1.getId());
    //This should remove the "tag3" from the tags
    final Set<String> tags5 = clusterClient.removeTagForCluster(cluster1.getId(), "tag1");
    for (final String tag : tags5) {
        //Shouldn't print anything
        LOG.info("Tag = " + tag);
    }

    LOG.info("Deleting all the tags from the cluster with id " + cluster1.getId());
    //This should remove the original config leaving only the two in this set
    final Set<String> tags4 = clusterClient.removeAllTagsForCluster(cluster1.getId());
    for (final String tag : tags4) {
        //Shouldn't print anything
        LOG.info("Config = " + tag);
    }
    /********************** End tests for tag Api's **********************/

    LOG.info("Commands for cluster with id " + cluster1.getId());
    final List<Command> commands1 = clusterClient.getCommandsForCluster(cluster1.getId());
    for (final Command command : commands1) {
        LOG.info("Command = " + command);
    }

    LOG.info("Adding commands to cluster with id " + cluster1.getId());
    final List<Command> newCmds = new ArrayList<>();
    newCmds.add(commandClient.createCommand(CommandServiceSampleClient.createSampleCommand(ID + "something")));
    newCmds.add(commandClient.createCommand(CommandServiceSampleClient.createSampleCommand(null)));

    final List<Command> commands2 = clusterClient.addCommandsToCluster(cluster1.getId(), newCmds);
    for (final Command command : commands2) {
        LOG.info("Command = " + command);
    }

    LOG.info("Updating set of commands files associated with id " + cluster1.getId());
    //This should remove the original config leaving only the two in this set
    final List<Command> commands3 = clusterClient.updateCommandsForCluster(cluster1.getId(), newCmds);
    for (final Command command : commands3) {
        LOG.info("Command = " + command);
    }

    LOG.info("Deleting the command from the cluster with id " + ID + "something");
    final Set<Command> commands4 = clusterClient.removeCommandForCluster(cluster1.getId(), ID + "something");
    for (final Command command : commands4) {
        LOG.info("Command = " + command);
    }

    LOG.info("Deleting all the commands from the command with id " + command1.getId());
    final List<Command> commands5 = clusterClient.removeAllCommandsForCluster(cluster1.getId());
    for (final Command command : commands5) {
        //Shouldn't print anything
        LOG.info("Command = " + command);
    }

    LOG.info("Updating existing cluster config");
    cluster2.setStatus(ClusterStatus.TERMINATED);
    final Cluster cluster3 = clusterClient.updateCluster(cluster2.getId(), cluster2);
    LOG.info("Cluster updated:");
    LOG.info(cluster3.toString());

    LOG.info("Deleting cluster config using id");
    final Cluster cluster4 = clusterClient.deleteCluster(cluster1.getId());
    LOG.info("Deleted cluster config with id: " + cluster1.getId());
    LOG.info(cluster4.toString());

    LOG.info("Deleting command config using id");
    final Command command5 = commandClient.deleteCommand(command1.getId());
    LOG.info("Deleted command config with id: " + command1.getId());
    LOG.info(command5.toString());

    LOG.info("Deleting commands in newCmd");
    for (final Command cmd : newCmds) {
        commandClient.deleteCommand(cmd.getId());
    }

    LOG.info("Deleting application config using id");
    final Application app3 = appClient.deleteApplication(app1.getId());
    LOG.info("Deleted application config with id: " + app1.getId());
    LOG.info(app3.toString());

    LOG.info("Deleting application config using id");
    final Application app4 = appClient.deleteApplication(app2.getId());
    LOG.info("Deleted application config with id: " + app2.getId());
    LOG.info(app4.toString());
    LOG.info("Done");
}

From source file:com.cyclopsgroup.waterview.jelly.JellyScriptsRunner.java

/**
 * Main entry to run a script/*from   w w  w.  jav a  2s  .c  o  m*/
 *
 * @param args Script paths
 * @throws Exception Throw it out
 */
public static final void main(String[] args) throws Exception {
    List scripts = new ArrayList();
    for (int i = 0; i < args.length; i++) {
        String path = args[i];
        File file = new File(path);
        if (file.isFile()) {
            scripts.add(file.toURL());
        } else {
            Enumeration enu = JellyScriptsRunner.class.getClassLoader().getResources(path);
            CollectionUtils.addAll(scripts, enu);
        }
    }
    if (scripts.isEmpty()) {
        System.out.println("No script to run, return!");
        return;
    }

    String basedir = new File("").getAbsolutePath();
    Properties initProperties = new Properties(System.getProperties());
    initProperties.setProperty("basedir", basedir);
    initProperties.setProperty("plexus.home", basedir);

    WaterviewPlexusContainer container = new WaterviewPlexusContainer();
    for (Iterator j = initProperties.keySet().iterator(); j.hasNext();) {
        String initPropertyName = (String) j.next();
        container.addContextValue(initPropertyName, initProperties.get(initPropertyName));
    }

    container.addContextValue(Waterview.INIT_PROPERTIES, initProperties);
    container.initialize();
    container.start();

    JellyEngine je = (JellyEngine) container.lookup(JellyEngine.ROLE);
    JellyContext jc = new JellyContext(je.getGlobalContext());
    XMLOutput output = XMLOutput.createXMLOutput(System.out);
    for (Iterator i = scripts.iterator(); i.hasNext();) {
        URL script = (URL) i.next();
        System.out.print("Running script " + script);
        ExtendedProperties ep = new ExtendedProperties();
        ep.putAll(initProperties);
        ep.load(script.openStream());
        for (Iterator j = ep.getKeys("script"); j.hasNext();) {
            String name = (String) j.next();
            if (name.endsWith(".file")) {
                File file = new File(ep.getString(name));
                if (file.exists()) {
                    System.out.println("Runner jelly file " + file);
                    jc.runScript(file, output);
                }
            } else if (name.endsWith(".resource")) {
                Enumeration k = JellyScriptsRunner.class.getClassLoader().getResources(ep.getString(name));
                while (j != null && k.hasMoreElements()) {
                    URL s = (URL) k.nextElement();
                    System.out.println("Running jelly script " + s);
                    jc.runScript(s, output);
                }
            }
        }
        //jc.runScript( script, XMLOutput.createDummyXMLOutput() );
        System.out.println("... Done!");
    }
    container.dispose();
}

From source file:act.installer.reachablesexplorer.WikiWebServicesExporter.java

public static void main(String[] args) throws Exception {
    CLIUtil cliUtil = new CLIUtil(WikiWebServicesExporter.class, HELP_MESSAGE, OPTION_BUILDERS);
    CommandLine cl = cliUtil.parseCommandLine(args);

    String host = cl.getOptionValue(OPTION_INPUT_DB_HOST, DEFAULT_HOST);
    Integer port = Integer.parseInt(cl.getOptionValue(OPTION_INPUT_DB_PORT, DEFAULT_PORT));
    String dbName = cl.getOptionValue(OPTION_INPUT_DB, DEFAULT_DB);
    String collection = cl.getOptionValue(OPTION_INPUT_DB_COLLECTION, DEFAULT_COLLECTION);
    String sequenceCollection = cl.getOptionValue(OPTION_INPUT_SEQUENCE_COLLECTION,
            DEFAULT_SEQUENCES_COLLECTION);

    LOGGER.info("Attempting to connect to DB %s:%d/%s, collection %s", host, port, dbName, collection);
    Loader loader = new Loader(host, port, UNUSED_SOURCE_DB, dbName, collection, sequenceCollection,
            DEFAULT_RENDERING_CACHE);//from  w  w w  . ja  v  a  2 s  .c  o  m

    JacksonDBCollection<Reachable, String> reachables = loader.getJacksonReachablesCollection();

    LOGGER.info("Connected to DB, reading reachables");

    List<Long> exportIds = !cl.hasOption(OPTION_EXPORT_SOME) ? Collections.emptyList()
            : Arrays.stream(cl.getOptionValues(OPTION_EXPORT_SOME)).map(Long::valueOf)
                    .collect(Collectors.toList());

    TSVWriter<String, String> tsvWriter = new TSVWriter<>(HEADER);
    tsvWriter.open(new File(cl.getOptionValue(OPTION_OUTPUT_FILE)));
    try {
        DBCursor<Reachable> cursor = exportIds.isEmpty() ? reachables.find()
                : reachables.find(DBQuery.in("_id", exportIds));
        int written = 0;
        while (cursor.hasNext()) {
            final Reachable r = cursor.next();

            Map<String, String> row = new HashMap<String, String>() {
                {
                    put("inchi", r.getInchi());
                    put("inchi_key", r.getInchiKey());
                    put("display_name", r.getPageName());
                    put("image_name", r.getStructureFilename());
                }
            };
            tsvWriter.append(row);
            tsvWriter.flush();
            written++;
        }
        LOGGER.info("Wrote %d reachables to output TSV", written);
    } finally {
        tsvWriter.close();
    }
}

From source file:com.sojw.TableNamesFinderExecutor.java

/**
 * @param args/*from  ww w  . j  av  a 2 s . c  o m*/
 */
public static void main(String[] args) throws Exception {
    List<CSVRecord> fileContentList = null;
    try {
        fileContentList = getCSVFileContents(FILE_ROOT_DIR + SOURCE_FILE_NAME);
    } catch (IOException e) {
        System.out.println("  .");
        System.exit(-1);
    }

    if (fileContentList == null || fileContentList.isEmpty()) {
        System.out.println("  .");
        System.exit(1);
    }

    //  
    final Set<String> iterMapKeys = iterMap.keySet();
    for (final String mapkey : iterMapKeys) {
        final List<String> iterList = iterMap.get(mapkey);
        for (final String tableName : iterList) {
            final List<String> resultList = extractTableNameByRegex(tableName, fileContentList);
            final String outputFileName = FILE_ROOT_DIR
                    + String.format(OUTPUT_FILE_NAME_FORMAT, mapkey, tableName);

            FileUtils.deleteQuietly(new File(outputFileName));
            FileUtils.writeLines(new File(outputFileName), resultList, false);
        }
    }

    // Zql
    //      final Set<String> iterMapKeys = iterMap.keySet();
    //      for (String mapkey : iterMapKeys) {
    //         final List<String> iterList = iterMap.get(mapkey);
    //         for (final String tableName : iterList) {
    //            extractTableNameByZql(fileContentList);
    //         }
    //      }

}

From source file:simauthenticator.SimAuthenticator.java

/**
 * @param args the command line arguments
 *///w w  w . j  av a2 s .  co m
public static void main(String[] args) throws Exception {

    cliOpts = new Options();
    cliOpts.addOption("U", "url", true, "Connection URL");
    cliOpts.addOption("u", "user", true, "User name");
    cliOpts.addOption("p", "password", true, "User password");
    cliOpts.addOption("d", "domain", true, "Domain name");
    cliOpts.addOption("v", "verbose", false, "Verbose output");
    cliOpts.addOption("k", "keystore", true, "KeyStore path");
    cliOpts.addOption("K", "keystorepass", true, "KeyStore password");
    cliOpts.addOption("h", "help", false, "Print help info");

    CommandLineParser clip = new GnuParser();
    cmd = clip.parse(cliOpts, args);

    if (cmd.hasOption("help")) {
        help();
        return;
    } else {
        boolean valid = init(args);
        if (!valid) {
            return;
        }
    }

    HttpClientContext clientContext = HttpClientContext.create();

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    char[] keystorePassword = passwk.toCharArray();
    FileInputStream kfis = null;
    try {
        kfis = new FileInputStream(keyStorePath);
        ks.load(kfis, keystorePassword);
    } finally {
        if (kfis != null) {
            kfis.close();
        }
    }

    SSLContext sslContext = SSLContexts.custom().useSSL().loadTrustMaterial(ks).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setSslcontext(sslContext)
            .setSSLSocketFactory(sslsf).setUserAgent(userAgent);
    ;

    cookieStore = new BasicCookieStore();
    /* BasicClientCookie cookie = new BasicClientCookie("SIM authenticator", "Utility for getting event details");
     cookie.setVersion(0);
     cookie.setDomain(".astelit.ukr");
     cookie.setPath("/");
     cookieStore.addCookie(cookie);*/

    CloseableHttpClient client = httpClientBuilder.build();

    try {

        NTCredentials creds = new NTCredentials(usern, passwu, InetAddress.getLocalHost().getHostName(),
                domain);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, creds);
        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);
        context.setCookieStore(cookieStore);
        HttpGet httpget = new HttpGet(eventUrl);
        if (verbose) {
            System.out.println("executing request " + httpget.getRequestLine());
        }
        HttpResponse response = client.execute(httpget, context);
        HttpEntity entity = response.getEntity();

        HttpPost httppost = new HttpPost(eventUrl);
        List<Cookie> cookies = cookieStore.getCookies();

        if (verbose) {
            System.out.println("----------------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.print("Initial set of cookies: ");
            if (cookies.isEmpty()) {
                System.out.println("none");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        }

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("usernameInput", usern));
        nvps.add(new BasicNameValuePair("passwordInput", passwu));
        nvps.add(new BasicNameValuePair("domainInput", domain));
        //nvps.add(new BasicNameValuePair("j_username", domain + "\\" + usern));
        //nvps.add(new BasicNameValuePair("j_password", ipAddr + ";" + passwu));
        if (entity != null && verbose) {
            System.out.println("Responce content length: " + entity.getContentLength());

        }

        //System.out.println(EntityUtils.toString(entity));

        httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        HttpResponse afterPostResponse = client.execute(httppost, context);
        HttpEntity afterPostEntity = afterPostResponse.getEntity();
        cookies = cookieStore.getCookies();
        if (entity != null && verbose) {
            System.out.println("----------------------------------------------");
            System.out.println(afterPostResponse.getStatusLine());
            System.out.println("Responce content length: " + afterPostEntity.getContentLength());
            System.out.print("After POST set of cookies: ");
            if (cookies.isEmpty()) {
                System.out.println("none");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        }

        System.out.println(EntityUtils.toString(afterPostEntity));
        EntityUtils.consume(entity);
        EntityUtils.consume(afterPostEntity);

    } finally {

        client.getConnectionManager().shutdown();
    }

}

From source file:br.usp.poli.lta.cereda.spa2run.Main.java

public static void main(String[] args) {

    Utils.printBanner();//  w  w  w .  j a  va 2 s  .  c om
    CommandLineParser parser = new DefaultParser();

    try {
        CommandLine line = parser.parse(Utils.getOptions(), args);
        List<Spec> specs = Utils.fromFilesToSpecs(line.getArgs());
        List<Metric> metrics = Utils.fromFilesToMetrics(line);
        Utils.setMetrics(metrics);
        Utils.resetCalculations();
        AdaptiveAutomaton automaton = Utils.getAutomatonFromSpecs(specs);

        System.out.println("SPA generated successfully:");
        System.out.println("- " + specs.size() + " submachine(s) found.");
        if (!Utils.detectEpsilon(automaton)) {
            System.out.println("- No empty transitions.");
        }
        if (!metrics.isEmpty()) {
            System.out.println("- " + metrics.size() + " metric(s) found.");
        }

        System.out.println("\nStarting shell, please wait...\n" + "(press CTRL+C or type `:quit'\n"
                + "to exit the application)\n");

        String query = "";
        Scanner scanner = new Scanner(System.in);
        String prompt = "[%d] query> ";
        String result = "[%d] result> ";
        int counter = 1;
        do {

            try {
                String term = String.format(prompt, counter);
                System.out.print(term);
                query = scanner.nextLine().trim();
                if (!query.equals(":quit")) {
                    boolean accept = automaton.recognize(Utils.toSymbols(query));
                    String type = automaton.getRecognitionPaths().size() == 1 ? " (deterministic)"
                            : " (nondeterministic)";
                    System.out.println(String.format(result, counter) + accept + type);

                    if (!metrics.isEmpty()) {
                        System.out.println(StringUtils.repeat(" ", String.format("[%d] ", counter).length())
                                + Utils.prettyPrintMetrics());
                    }

                    System.out.println();

                }
            } catch (Exception exception) {
                System.out.println();
                Utils.printException(exception);
                System.out.println();
            }

            counter++;
            Utils.resetCalculations();

        } while (!query.equals(":quit"));
        System.out.println("That's all folks!");

    } catch (ParseException nothandled) {
        Utils.printHelp();
    } catch (Exception exception) {
        Utils.printException(exception);
    }
}