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:glacierpipe.GlacierPipeMain.java

public static void main(String[] args) throws IOException, ParseException {
    CommandLineParser parser = new GnuParser();

    CommandLine cmd = parser.parse(OPTIONS, args);

    if (cmd.hasOption("help")) {
        try (PrintWriter writer = new PrintWriter(System.err)) {
            printHelp(writer);/*w w w .  j av  a 2  s.  co m*/
        }

        System.exit(0);
    } else if (cmd.hasOption("upload")) {

        // Turn the CommandLine into Properties
        Properties cliProperties = new Properties();
        for (Iterator<?> i = cmd.iterator(); i.hasNext();) {
            Option o = (Option) i.next();

            String opt = o.getLongOpt();
            opt = opt != null ? opt : o.getOpt();

            String value = o.getValue();
            value = value != null ? value : "";

            cliProperties.setProperty(opt, value);
        }

        // Build up a configuration
        ConfigBuilder configBuilder = new ConfigBuilder();

        // Archive name
        List<?> archiveList = cmd.getArgList();
        if (archiveList.size() > 1) {
            throw new ParseException("Too many arguments");
        } else if (archiveList.isEmpty()) {
            throw new ParseException("No archive name provided");
        }

        configBuilder.setArchive(archiveList.get(0).toString());

        // All other arguments on the command line
        configBuilder.setFromProperties(cliProperties);

        // Load any config from the properties file
        Properties fileProperties = new Properties();
        try (InputStream in = new FileInputStream(configBuilder.propertiesFile)) {
            fileProperties.load(in);
        } catch (IOException e) {
            System.err.printf("Warning: unable to read properties file %s; %s%n", configBuilder.propertiesFile,
                    e);
        }

        configBuilder.setFromProperties(fileProperties);

        // ...
        Config config = new Config(configBuilder);

        IOBuffer buffer = new MemoryIOBuffer(config.partSize);

        AmazonGlacierClient client = new AmazonGlacierClient(
                new BasicAWSCredentials(config.accessKey, config.secretKey));
        client.setEndpoint(config.endpoint);

        // Actual upload
        try (InputStream in = new BufferedInputStream(System.in, 4096);
                PrintWriter writer = new PrintWriter(System.err);
                ObservableProperties configMonitor = config.reloadProperties
                        ? new ObservableProperties(config.propertiesFile)
                        : null;
                ProxyingThrottlingStrategy throttlingStrategy = new ProxyingThrottlingStrategy(config);) {
            TerminalGlacierPipeObserver observer = new TerminalGlacierPipeObserver(writer);

            if (configMonitor != null) {
                configMonitor.registerObserver(throttlingStrategy);
            }

            GlacierPipe pipe = new GlacierPipe(buffer, observer, config.maxRetries, throttlingStrategy);
            pipe.pipe(client, config.vault, config.archive, in);
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }

        System.exit(0);
    } else {
        try (PrintWriter writer = new PrintWriter(System.err)) {
            writer.println("No action specified.");
            printHelp(writer);
        }

        System.exit(-1);
    }
}

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

/**
 * Main for running client code.//from   w  w  w.j  a  v  a 2 s. com
 *
 * @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");
    // ApplicationServiceClient.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(createSampleCommand(ID));
    commandClient.setApplicationForCommand(command1.getId(), app1);
    LOG.info("Created command:");
    LOG.info(command1.toString());

    LOG.info("Getting Commands using specified filter criteria name =  " + CMD_NAME);
    final Multimap<String, String> params = ArrayListMultimap.create();
    params.put("name", CMD_NAME);
    final List<Command> commands = commandClient.getCommands(params);
    if (commands.isEmpty()) {
        LOG.info("No commands found for specified criteria.");
    } else {
        LOG.info("Commands found:");
        for (final Command command : commands) {
            LOG.info(command.toString());
        }
    }

    LOG.info("Getting command config by id");
    final Command command3 = commandClient.getCommand(ID);
    LOG.info(command3.toString());

    LOG.info("Updating existing command config");
    command3.setStatus(CommandStatus.INACTIVE);
    final Command command4 = commandClient.updateCommand(ID, command3);
    LOG.info(command4.toString());

    LOG.info("Configurations for command with id " + command1.getId());
    final Set<String> configs = commandClient.getConfigsForCommand(command1.getId());
    for (final String config : configs) {
        LOG.info("Config = " + config);
    }

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

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

    LOG.info("Deleting all the configuration files from the command with id " + command1.getId());
    //This should remove the original config leaving only the two in this set
    final Set<String> configs4 = commandClient.removeAllConfigsForCommand(command1.getId());
    for (final String config : configs4) {
        //Shouldn't print anything
        LOG.info("Config = " + config);
    }

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

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

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

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

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

    LOG.info("Application for command with id " + command1.getId());
    final Application application = commandClient.getApplicationForCommand(command1.getId());
    LOG.info("Application = " + application);

    LOG.info("Removing Application for command with id " + command1.getId());
    final Application application2 = commandClient.removeApplicationForCommand(command1.getId());
    LOG.info("Application = " + application2);

    LOG.info("Getting all the clusters for command with id  " + command1.getId());
    final Set<Cluster> clusters = commandClient.getClustersForCommand(command1.getId());
    for (final Cluster cluster : clusters) {
        LOG.info("Cluster = " + cluster);
    }

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

    LOG.info("Deleting all applications");
    final List<Application> deletedApps = appClient.deleteAllApplications();
    LOG.info("Deleted all applications");
    LOG.info(deletedApps.toString());

    LOG.info("Done");
}

From source file:appmain.AppMain.java

public static void main(String[] args) {

    try {//from   w  w  w  . ja v a 2s  .c  o m
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        UIManager.put("OptionPane.yesButtonText", "Igen");
        UIManager.put("OptionPane.noButtonText", "Nem");
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    try {

        AppMain app = new AppMain();
        app.init();

        File importFolder = new File(DEFAULT_IMPORT_FOLDER);
        if (!importFolder.isDirectory() || !importFolder.exists()) {
            JOptionPane.showMessageDialog(null,
                    "Az IMPORT mappa nem elrhet!\n"
                            + "Ellenrizze az elrsi utat s a jogosultsgokat!\n" + "Mappa: "
                            + importFolder.getAbsolutePath(),
                    "Informci", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        File exportFolder = new File(DEFAULT_EXPORT_FOLDER);
        if (!exportFolder.isDirectory() || !exportFolder.exists()) {
            JOptionPane.showMessageDialog(null,
                    "Az EXPORT mappa nem elrhet!\n"
                            + "Ellenrizze az elrsi utat s a jogosultsgokat!\n" + "Mappa: "
                            + exportFolder.getAbsolutePath(),
                    "Informci", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        List<File> xmlFiles = app.getXMLFiles(importFolder);
        if (xmlFiles == null || xmlFiles.isEmpty()) {
            JOptionPane.showMessageDialog(null,
                    "Nincs beolvasand XML fjl!\n" + "Mappa: " + importFolder.getAbsolutePath(),
                    "Informci", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        StringBuilder fileList = new StringBuilder();
        xmlFiles.stream().forEach(xml -> fileList.append("\n").append(xml.getName()));
        int ret = JOptionPane.showConfirmDialog(null,
                "Beolvassra elksztett fjlok:\n" + fileList + "\n\nIndulhat a feldolgozs?",
                "Megtallt XML fjlok", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

        if (ret == JOptionPane.OK_OPTION) {
            String csvName = "tranzakcio_lista_" + df.format(new Date()) + "_" + System.currentTimeMillis()
                    + ".csv";
            File csv = new File(DEFAULT_EXPORT_FOLDER + "/" + csvName);
            app.writeCSV(csv, Arrays.asList(app.getHeaderLine()));
            xmlFiles.stream().forEach(xml -> {
                List<String> lines = app.readXMLData(xml);
                if (lines != null)
                    app.writeCSV(csv, lines);
            });
            if (csv.isFile() && csv.exists()) {
                JOptionPane.showMessageDialog(null,
                        "A CSV fjl sikeresen elllt!\n" + "Fjl: " + csv.getAbsolutePath(),
                        "Informci", JOptionPane.INFORMATION_MESSAGE);
                app.openFile(csv);
            }
        } else {
            JOptionPane.showMessageDialog(null, "Feldolgozs megszaktva!", "Informci",
                    JOptionPane.INFORMATION_MESSAGE);
        }

    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "Nem kezelt kivtel!\n" + ExceptionUtils.getStackTrace(ex), "Hiba",
                JOptionPane.ERROR_MESSAGE);
    }

}

From source file:ca.uqac.lif.bullwinkle.BullwinkleCli.java

/**
 * @param args/*from   ww  w.j ava 2  s.co  m*/
 */
public static void main(String[] args) {
    // Setup parameters
    int verbosity = 1;
    String output_format = "xml", grammar_filename = null, filename_to_parse = null;

    // Parse command line arguments
    Options options = setupOptions();
    CommandLine c_line = setupCommandLine(args, options);
    assert c_line != null;
    if (c_line.hasOption("verbosity")) {
        verbosity = Integer.parseInt(c_line.getOptionValue("verbosity"));
    }
    if (verbosity > 0) {
        showHeader();
    }
    if (c_line.hasOption("version")) {
        System.err.println("(C) 2014 Sylvain Hall et al., Universit du Qubec  Chicoutimi");
        System.err.println("This program comes with ABSOLUTELY NO WARRANTY.");
        System.err.println("This is a free software, and you are welcome to redistribute it");
        System.err.println("under certain conditions. See the file LICENSE-2.0 for details.\n");
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("h")) {
        showUsage(options);
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("f")) {
        output_format = c_line.getOptionValue("f");
    }
    // Get grammar file
    @SuppressWarnings("unchecked")
    List<String> remaining_args = c_line.getArgList();
    if (remaining_args.isEmpty()) {
        System.err.println("ERROR: no grammar file specified");
        System.exit(ERR_ARGUMENTS);
    }
    grammar_filename = remaining_args.get(0);
    // Get file to parse, if any
    if (remaining_args.size() >= 2) {
        filename_to_parse = remaining_args.get(1);
    }

    // Read grammar file
    BnfParser parser = null;
    try {
        parser = new BnfParser(new File(grammar_filename));
    } catch (InvalidGrammarException e) {
        System.err.println("ERROR: invalid grammar");
        System.exit(ERR_GRAMMAR);
    } catch (IOException e) {
        System.err.println("ERROR reading grammar " + grammar_filename);
        System.exit(ERR_IO);
    }
    assert parser != null;

    // Read input file
    BufferedReader bis = null;
    if (filename_to_parse == null) {
        // Read from stdin
        bis = new BufferedReader(new InputStreamReader(System.in));
    } else {
        // Read from file
        try {
            bis = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filename_to_parse))));
        } catch (FileNotFoundException e) {
            System.err.println("ERROR: file not found " + filename_to_parse);
            System.exit(ERR_IO);
        }
    }
    assert bis != null;
    String str;
    StringBuilder input_file = new StringBuilder();
    try {
        while ((str = bis.readLine()) != null) {
            input_file.append(str).append("\n");
        }
    } catch (IOException e) {
        System.err.println("ERROR reading input");
        System.exit(ERR_IO);
    }
    String file_contents = input_file.toString();

    // Parse contents of file
    ParseNode p_node = null;
    try {
        p_node = parser.parse(file_contents);
    } catch (ca.uqac.lif.bullwinkle.BnfParser.ParseException e) {
        System.err.println("ERROR parsing input\n");
        e.printStackTrace();
        System.exit(ERR_PARSE);
    }
    if (p_node == null) {
        System.err.println("ERROR parsing input\n");
        System.exit(ERR_PARSE);
    }
    assert p_node != null;

    // Output parse node to desired format
    PrintStream output = System.out;
    OutputFormatVisitor out_vis = null;
    if (output_format.compareToIgnoreCase("xml") == 0) {
        // Output to XML
        out_vis = new XmlVisitor();
    } else if (output_format.compareToIgnoreCase("dot") == 0) {
        // Output to DOT
        out_vis = new GraphvizVisitor();
    } else if (output_format.compareToIgnoreCase("txt") == 0) {
        // Output to indented plain text
        out_vis = new IndentedTextVisitor();
    } else if (output_format.compareToIgnoreCase("json") == 0) {
        // Output to JSON
    }
    if (out_vis == null) {
        System.err.println("ERROR: unknown output format " + output_format);
        System.exit(ERR_ARGUMENTS);
    }
    assert out_vis != null;
    p_node.prefixAccept(out_vis);
    output.print(out_vis.toOutputString());

    // Terminate without error
    System.exit(ERR_OK);
}

From source file:com.px100systems.data.utility.RestoreUtility.java

public static void main(String[] args) {
    if (args.length < 3) {
        System.err.println("Usage: java -cp ... com.px100systems.data.utility.RestoreUtility "
                + "<springXmlConfigFile> <persisterBeanName> <backupDirectory> [compare]");
        return;/* ww w .  j a  v a 2 s.  c om*/
    }

    FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext("file:" + args[0]);
    try {
        PersistenceProvider persister = ctx.getBean(args[1], PersistenceProvider.class);

        File directory = new File(args[2]);
        if (!directory.isDirectory()) {
            System.err.println(directory.getName() + " is not a directory");
            return;
        }

        List<File> files = new ArrayList<File>();
        //noinspection ConstantConditions
        for (File file : directory.listFiles())
            if (BackupFile.isBackup(file))
                files.add(file);

        if (files.isEmpty()) {
            System.err.println(directory.getName() + " directory has no backup files");
            return;
        }

        if (args.length == 4 && args[3].equalsIgnoreCase("compare")) {
            final Map<String, Map<Long, RawRecord>> units = new HashMap<String, Map<Long, RawRecord>>();

            for (String storage : persister.storage()) {
                System.out.println("Storage " + storage);
                persister.loadByStorage(storage, new PersistenceProvider.LoadCallback() {
                    @Override
                    public void process(RawRecord record) {
                        Map<Long, RawRecord> unitList = units.get(record.getUnitName());
                        if (unitList == null) {
                            unitList = new HashMap<Long, RawRecord>();
                            units.put(record.getUnitName(), unitList);
                        }
                        unitList.put(record.getId(), record);
                    }
                });

                for (final Map.Entry<String, Map<Long, RawRecord>> unit : units.entrySet()) {
                    BackupFile file = null;
                    for (int i = 0, n = files.size(); i < n; i++)
                        if (BackupFile.isBackup(files.get(i), unit.getKey())) {
                            file = new BackupFile(files.get(i));
                            files.remove(i);
                            break;
                        }

                    if (file == null)
                        throw new RuntimeException("Could not find backup file for unit " + unit.getKey());

                    final Long[] count = new Long[] { 0L };
                    file.read(new PersistenceProvider.LoadCallback() {
                        @Override
                        public void process(RawRecord record) {
                            RawRecord r = unit.getValue().get(record.getId());
                            if (r == null)
                                throw new RuntimeException("Could not find persisted record " + record.getId()
                                        + " for unit " + unit.getKey());
                            if (!r.equals(record))
                                throw new RuntimeException(
                                        "Record " + record.getId() + " mismatch for unit " + unit.getKey());
                            count[0] = count[0] + 1;
                        }
                    });

                    if (count[0] != unit.getValue().size())
                        throw new RuntimeException("Extra persisted records for unit " + unit.getKey());
                    System.out.println("   Unit " + unit.getKey() + ": OK");
                }

                units.clear();
            }

            if (!files.isEmpty()) {
                System.err.println("Extra backups: ");
                for (File file : files)
                    System.err.println("   " + file.getName());
            }
        } else {
            persister.init();
            for (File file : files) {
                InMemoryDatabase.readBackupFile(file, persister);
                System.out.println("Loaded " + file.getName());
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        ctx.close();
    }
}

From source file:org.n52.oss.testdata.sml.GeneratorClient.java

/**
 * @param args/*ww w .  ja v  a 2  s .  c o m*/
 */
public static void main(String[] args) {
    if (sending)
        log.info("Starting insertion of test sensors into " + sirURL);
    else
        log.warn("Starting generation of test sensors, NOT sending!");

    TestSensorFactory factory = new TestSensorFactory();

    // create sensors
    List<TestSensor> sensors = new ArrayList<TestSensor>();

    for (int i = 0; i < nSensorsToGenerate; i++) {
        TestSensor s = factory.createRandomTestSensor();
        sensors.add(s);
        log.info("Added new random sensor: " + s);
    }

    ArrayList<String> insertedSirIds = new ArrayList<String>();

    // insert sensors to service
    int startOfSubList = 0;
    int endOfSubList = nSensorsInOneInsertRequest;
    while (endOfSubList <= sensors.size() + nSensorsInOneInsertRequest) {
        List<TestSensor> currentSensors = sensors.subList(startOfSubList,
                Math.min(endOfSubList, sensors.size()));

        if (currentSensors.isEmpty())
            break;

        try {
            String[] insertedSirIDs = insertSensorsInSIR(currentSensors);
            if (insertedSirIDs == null) {
                log.error("Did not insert dummy sensors.");
            } else {
                insertedSirIds.addAll(Arrays.asList(insertedSirIDs));
            }
        } catch (HttpException e) {
            log.error("Error inserting sensors.", e);
        } catch (IOException e) {
            log.error("Error inserting sensors.", e);
        }

        startOfSubList = Math.min(endOfSubList, sensors.size());
        endOfSubList = endOfSubList + nSensorsInOneInsertRequest;

        if (sending) {
            try {
                if (log.isDebugEnabled())
                    log.debug("Sleeping for " + SLEEP_BETWEEN_REQUESTS + " msecs.");
                Thread.sleep(SLEEP_BETWEEN_REQUESTS);
            } catch (InterruptedException e) {
                log.error("Interrupted!", e);
            }
        }
    }

    log.info("Added sensors (ids in sir): " + Arrays.toString(insertedSirIds.toArray()));
}

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

/**
 * Main for running client code.//  w w  w  .j av  a 2 s .c o m
 *
 * @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");
    //        ApplicationServiceClient.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();

    LOG.info("Creating new application config");
    final Application app1 = appClient.createApplication(getSampleApplication(null));
    LOG.info("Application configuration created with id: " + app1.getId());
    LOG.info(app1.toString());

    LOG.info("Getting Applications using specified filter criteria name =  " + APP_NAME);
    final Multimap<String, String> params = ArrayListMultimap.create();
    params.put("name", APP_NAME);
    final List<Application> appResponses = appClient.getApplications(params);
    if (appResponses.isEmpty()) {
        LOG.info("No applications found for specified criteria.");
    } else {
        LOG.info("Applications found:");
        for (final Application appResponse : appResponses) {
            LOG.info(appResponse.toString());
        }
    }

    LOG.info("Getting application config by id");
    final Application app2 = appClient.getApplication(app1.getId());
    LOG.info(app2.toString());

    LOG.info("Updating existing application config");
    app2.setStatus(ApplicationStatus.INACTIVE);
    final Application app3 = appClient.updateApplication(app1.getId(), app2);
    LOG.info(app3.toString());

    LOG.info("Configurations for application with id " + app1.getId());
    final Set<String> configs = appClient.getConfigsForApplication(app1.getId());
    for (final String config : configs) {
        LOG.info("Config = " + config);
    }

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

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

    LOG.info("Deleting all the configuration files from the application with id " + app1.getId());
    //This should remove the original config leaving only the two in this set
    final Set<String> configs4 = appClient.removeAllConfigsForApplication(app1.getId());
    for (final String config : configs4) {
        //Shouldn't print anything
        LOG.info("Config = " + config);
    }

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

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

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

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

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

    LOG.info("Jars for application with id " + app1.getId());
    final Set<String> jars = appClient.getJarsForApplication(app1.getId());
    for (final String jar : jars) {
        LOG.info("jar = " + jar);
    }

    LOG.info("Adding jars to application with id " + app1.getId());
    final Set<String> newJars = new HashSet<>();
    newJars.add("someNewJarFile.jar");
    newJars.add("someOtherNewJarFile.jar");
    final Set<String> jars2 = appClient.addJarsToApplication(app1.getId(), newJars);
    for (final String jar : jars2) {
        LOG.info("jar = " + jar);
    }

    LOG.info("Updating set of jars associated with id " + app1.getId());
    //This should remove the original jar leaving only the two in this set
    final Set<String> jars3 = appClient.updateJarsForApplication(app1.getId(), newJars);
    for (final String jar : jars3) {
        LOG.info("jar = " + jar);
    }

    LOG.info("Deleting all the jars from the application with id " + app1.getId());
    //This should remove the original jar leaving only the two in this set
    final Set<String> jars4 = appClient.removeAllJarsForApplication(app1.getId());
    for (final String jar : jars4) {
        //Shouldn't print anything
        LOG.info("jar = " + jar);
    }

    LOG.info("Getting the commands associated with id " + app1.getId());
    final Set<Command> commands = appClient.getCommandsForApplication(app1.getId());
    for (final Command command : commands) {
        LOG.info("Command: " + command.toString());
    }

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

    LOG.info("Done");
}

From source file:com.auditbucket.client.Importer.java

public static void main(String args[]) {

    try {//from  ww  w.  j a va 2 s  .  co  m
        ArgumentParser parser = ArgumentParsers.newArgumentParser("ABImport").defaultHelp(true)
                .description("Import file formats to AuditBucket");

        parser.addArgument("-s", "--server").setDefault("http://localhost/ab-engine")
                .help("Host URL to send files to");

        parser.addArgument("-b", "--batch").setDefault(100).help("Default batch size");

        parser.addArgument("-x", "--xref").setDefault(false).help("Cross References Only");

        parser.addArgument("files").nargs("*").help(
                "Path and filename of Audit records to import in the format \"[/filepath/filename.ext],[com.import.YourClass],{skipCount}\"");

        Namespace ns = null;
        try {
            ns = parser.parseArgs(args);
        } catch (ArgumentParserException e) {
            parser.handleError(e);
            System.exit(1);
        }
        List<String> files = ns.getList("files");
        if (files.isEmpty()) {
            parser.handleError(new ArgumentParserException("No files to parse", parser));
            System.exit(1);
        }
        String b = ns.getString("batch");
        int batchSize = 100;
        if (b != null && !"".equals(b))
            batchSize = Integer.parseInt(b);

        StopWatch watch = new StopWatch();
        watch.start();
        logger.info("*** Starting {}", DateFormat.getDateTimeInstance().format(new Date()));
        long totalRows = 0;
        for (String file : files) {

            int skipCount = 0;
            List<String> items = Arrays.asList(file.split("\\s*,\\s*"));
            if (items.size() == 0)
                parser.handleError(new ArgumentParserException("No file arguments to process", parser));
            int item = 0;
            String fileName = null;
            String fileClass = null;
            for (String itemArg : items) {
                if (item == 0) {
                    fileName = itemArg;
                } else if (item == 1) {
                    fileClass = itemArg;
                } else if (item == 2)
                    skipCount = Integer.parseInt(itemArg);

                item++;
            }
            logger.debug("*** Calculated process args {}, {}, {}, {}", fileName, fileClass, batchSize,
                    skipCount);
            totalRows = totalRows + processFile(ns.get("server").toString(), fileName,
                    (fileClass != null ? Class.forName(fileClass) : null), batchSize, skipCount);
        }
        endProcess(watch, totalRows);

        logger.info("Finished at {}", DateFormat.getDateTimeInstance().format(new Date()));

    } catch (Exception e) {
        logger.error("Import error", e);
    }
}

From source file:com.gypsai.ClientFormLogin.java

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

    DefaultHttpClient httpclient = new DefaultHttpClient();
    httppostclient = new DefaultHttpClient();
    httppostclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    try {//  w w w .j av a  2s  .  c o  m

        String loginUrl = "http://www.cnsfk.com/member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes";
        //String loginUrl = "http://renren.com/PLogin.do";

        String testurl = "http://www.baidu.com";
        HttpGet httpget = new HttpGet(testurl);

        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        //System.out.println(istostring(entity.getContent()));

        System.out.println("Login form get: " + response.getStatusLine());
        EntityUtils.consume(entity);

        System.out.println("Initial set of cookies:");
        List<Cookie> cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                //     System.out.println("- " + cookies.get(i).toString());
            }
        }

        HttpPost httpost = new HttpPost(loginUrl);

        String password = MD5.MD5Encode("luom1ng");
        String redirectURL = "http://www.renren.com/home";
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("username", "gypsai@foxmail.com"));
        nvps.add(new BasicNameValuePair("password", password));
        // nvps.add(new BasicNameValuePair("origURL", redirectURL));  
        // nvps.add(new BasicNameValuePair("domain", "renren.com"));  
        //  nvps.add(new BasicNameValuePair("autoLogin", "true"));  
        //  nvps.add(new BasicNameValuePair("formName", ""));  
        //  nvps.add(new BasicNameValuePair("method", ""));  
        //  nvps.add(new BasicNameValuePair("submit", ""));  

        httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
        httpost.setHeader("User-Agent",
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.28 (KHTML, like Gecko) Chrome/26.0.1397.2 Safari/537.28");

        //posthttpclient
        //DefaultHttpClient httppostclient = new DefaultHttpClient();

        //postheader
        Header[] pm = httpost.getAllHeaders();
        for (Header header : pm) {
            System.out.println("%%%%->" + header.toString());
        }

        //
        response = httppostclient.execute(httpost);

        EntityUtils.consume(response.getEntity());

        doget();
        //
        //

        //httppostclient.getConnectionManager().shutdown();

        //cookie
        List<Cookie> cncookies = httppostclient.getCookieStore().getCookies();
        System.out.println("Post logon cookies:");

        if (cncookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cncookies.size(); i++) {
                System.out.println("- " + cncookies.get(i).getName().toString() + "   ---->"
                        + cncookies.get(i).getValue().toString());
            }
        }

        //
        submit();

        //httpheader
        entity = response.getEntity();
        Header[] m = response.getAllHeaders();
        for (Header header : m) {
            //System.out.println("+++->"+header.toString());
        }
        //System.out.println(response.getAllHeaders());
        System.out.println(entity.getContentEncoding());

        //statusline
        System.out.println("Login form get: " + response.getStatusLine());

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        //  httpclient.getConnectionManager().shutdown();
        //httppostclient.getConnectionManager().shutdown();
    }
}

From source file:com.linkedin.pinot.integration.tests.HybridClusterIntegrationTestCommandLineRunner.java

public static void main(String[] args) throws Exception {
    int numArgs = args.length;
    if (!((numArgs == 5) || (numArgs == 6 && args[0].equals("--llc")))) {
        printUsage();//from  ww  w.j a  va2s .  co m
    }

    CustomHybridClusterIntegrationTest._enabled = true;

    int argIdx = 0;
    if (args[0].equals("--llc")) {
        CustomHybridClusterIntegrationTest._useLlc = true;
        argIdx++;
    }

    CustomHybridClusterIntegrationTest._tableName = args[argIdx++];
    File schemaFile = new File(args[argIdx++]);
    Preconditions.checkState(schemaFile.isFile());
    CustomHybridClusterIntegrationTest._schemaFile = schemaFile;
    File dataDir = new File(args[argIdx++]);
    Preconditions.checkState(dataDir.isDirectory());
    CustomHybridClusterIntegrationTest._dataDir = dataDir;
    CustomHybridClusterIntegrationTest._invertedIndexColumns = Arrays.asList(args[argIdx++].split(","));
    CustomHybridClusterIntegrationTest._sortedColumn = args[argIdx];

    TestListenerAdapter testListenerAdapter = new TestListenerAdapter();
    TestNG testNG = new TestNG();
    testNG.setTestClasses(new Class[] { CustomHybridClusterIntegrationTest.class });
    testNG.addListener(testListenerAdapter);
    testNG.run();

    System.out.println(testListenerAdapter.toString());
    boolean success = true;
    List<ITestResult> skippedTests = testListenerAdapter.getSkippedTests();
    if (!skippedTests.isEmpty()) {
        System.out.println("Skipped tests: " + skippedTests);
        for (ITestResult skippedTest : skippedTests) {
            System.out.println(skippedTest.getName() + ": " + skippedTest.getThrowable());
        }
        success = false;
    }
    List<ITestResult> failedTests = testListenerAdapter.getFailedTests();
    if (!failedTests.isEmpty()) {
        System.err.println("Failed tests: " + failedTests);
        for (ITestResult failedTest : failedTests) {
            System.out.println(failedTest.getName() + ": " + failedTest.getThrowable());
        }
        success = false;
    }
    if (success) {
        System.exit(0);
    } else {
        System.exit(1);
    }
}