Example usage for java.util ArrayList size

List of usage examples for java.util ArrayList size

Introduction

In this page you can find the example usage for java.util ArrayList size.

Prototype

int size

To view the source code for java.util ArrayList size.

Click Source Link

Document

The size of the ArrayList (the number of elements it contains).

Usage

From source file:POP3Mail.java

public static void main(String[] args) {
    try {//from ww w .j a  v a  2 s  .c om
        LogManager.getLogManager().readConfiguration(new FileInputStream("logging.properties"));
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    String server = null;
    String username = null;
    String password = null;
    if (new File("mail.properties").exists()) {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(new File("mail.properties")));
            server = properties.getProperty("server");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            ArrayList<String> list = new ArrayList<String>(
                    Arrays.asList(new String[] { server, username, password }));
            list.addAll(Arrays.asList(args));
            args = list.toArray(new String[list.size()]);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    if (args.length < 3) {
        System.err
                .println("Usage: POP3Mail <pop3 server hostname> <username> <password> [TLS [true=implicit]]");
        System.exit(1);
    }

    server = args[0];
    username = args[1];
    password = args[2];
    String proto = null;
    int messageid = -1;
    boolean implicit = false;
    for (int i = 3; i < args.length; ++i) {
        if (args[i].equals("-m")) {
            i += 1;
            messageid = Integer.parseInt(args[i]);
        }
    }

    // String proto = args.length > 3 ? args[3] : null;
    // boolean implicit = args.length > 4 ? Boolean.parseBoolean(args[4])
    // : false;

    POP3Client pop3;

    if (proto != null) {
        System.out.println("Using secure protocol: " + proto);
        pop3 = new POP3SClient(proto, implicit);
    } else {
        pop3 = new POP3Client();
    }
    pop3.setDefaultPort(110);
    System.out.println("Connecting to server " + server + " on " + pop3.getDefaultPort());

    // We want to timeout if a response takes longer than 60 seconds
    pop3.setDefaultTimeout(60000);
    // suppress login details
    pop3.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    try {
        pop3.connect(server);
    } catch (IOException e) {
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    try {
        if (!pop3.login(username, password)) {
            System.err.println("Could not login to server.  Check password.");
            pop3.disconnect();
            System.exit(1);
        }
        PrintWriter printWriter = new PrintWriter(new FileWriter("messages.csv"), true);
        POP3MessageInfo[] messages = null;
        POP3MessageInfo[] identifiers = null;
        if (messageid == -1) {
            messages = pop3.listMessages();
            identifiers = pop3.listUniqueIdentifiers();
        } else {
            messages = new POP3MessageInfo[] { pop3.listMessage(messageid) };
        }
        if (messages == null) {
            System.err.println("Could not retrieve message list.");
            pop3.disconnect();
            return;
        } else if (messages.length == 0) {
            System.out.println("No messages");
            pop3.logout();
            pop3.disconnect();
            return;
        }
        new File("../json").mkdirs();
        int count = 0;
        for (POP3MessageInfo msginfo : messages) {
            if (msginfo.number != identifiers[count].number) {
                throw new RuntimeException();
            }
            msginfo.identifier = identifiers[count].identifier;
            BufferedReader reader = (BufferedReader) pop3.retrieveMessageTop(msginfo.number, 0);
            ++count;
            if (count % 100 == 0) {
                logger.finest(String.format("%d %s", msginfo.number, msginfo.identifier));
            }
            System.out.println(String.format("%d %s", msginfo.number, msginfo.identifier));
            if (reader == null) {
                System.err.println("Could not retrieve message header.");
                pop3.disconnect();
                System.exit(1);
            }
            if (printMessageInfo(reader, msginfo.number, printWriter)) {
            }
        }
        printWriter.close();
        pop3.logout();
        pop3.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
}

From source file:at.tuwien.ifs.somtoolbox.apps.helper.VectorFileSubsetGenerator.java

public static void main(String[] args) throws IOException, SOMToolboxException {
    // register and parse all options
    JSAPResult config = OptionFactory.parseResults(args, OPTIONS);

    String inputFileName = AbstractOptionFactory.getFilePath(config, "input");
    String classInformationFileName = AbstractOptionFactory.getFilePath(config, "classInformationFile");
    String outputFileName = AbstractOptionFactory.getFilePath(config, "output");

    String[] keepClasses = config.getStringArray("classList");

    boolean skipInstanceNames = false;// config.getBoolean("skipInstanceNames");
    boolean skipInputsWithoutClass = false;// config.getBoolean("skipInputsWithoutClass");
    boolean tabSeparatedClassFile = false;// config.getBoolean("tabSeparatedClassFile");

    String inputFormat = config.getString("inputFormat");
    if (inputFormat == null) {
        inputFormat = InputDataFactory.detectInputFormatFromExtension(inputFileName, "input");
    }// ww w . ja  v  a  2  s.  c  om
    String outputFormat = config.getString("outputFormat");
    if (outputFormat == null) {
        outputFormat = InputDataFactory.detectInputFormatFromExtension(outputFileName, "output");
    }

    InputData data = InputDataFactory.open(inputFormat, inputFileName);
    if (classInformationFileName != null) {
        SOMLibClassInformation classInfo = new SOMLibClassInformation(classInformationFileName);
        data.setClassInfo(classInfo);
    }
    if (data.classInformation() == null) {
        throw new SOMToolboxException("Need to provide a class information file.");
    }

    Logger.getLogger("at.tuwien.ifs.somtoolbox")
            .info("Retaining elements of classes: " + Arrays.toString(keepClasses));

    ArrayList<InputDatum> subData = new ArrayList<InputDatum>();
    for (int i = 0; i < data.numVectors(); i++) {
        InputDatum datum = data.getInputDatum(i);
        String className = data.classInformation().getClassName(datum.getLabel());
        System.out.println(datum.getLabel() + "=>" + className);
        if (ArrayUtils.contains(keepClasses, className)) {
            subData.add(datum);
        }
    }

    InputData subset = new SOMLibSparseInputData(subData.toArray(new InputDatum[subData.size()]),
            data.classInformation());
    InputDataWriter.write(outputFileName, subset, outputFormat, tabSeparatedClassFile, skipInstanceNames,
            skipInputsWithoutClass);
}

From source file:com.ericsson.eiffel.remrem.semantics.clone.PrepareLocalEiffelSchemas.java

public static void main(String[] args) throws IOException {
    final PrepareLocalEiffelSchemas prepareLocalSchema = new PrepareLocalEiffelSchemas();
    final Proxy proxy = prepareLocalSchema.getProxy(httpProxyUrl, httpProxyPort, httpProxyUsername,
            httpProxyPassword);/*from  www  .  j a va 2  s .co m*/
    if (proxy != null) {
        prepareLocalSchema.setProxy(proxy);
    }
    final String eiffelRepoUrl = args[0];
    final String eiffelRepoBranch = args[1];
    final String operationRepoUrl = args[2];
    final String operationRepoBranch = args[3];

    final File localEiffelRepoPath = new File(
            System.getProperty(EiffelConstants.USER_HOME) + File.separator + EiffelConstants.EIFFEL);
    final File localOperationsRepoPath = new File(System.getProperty(EiffelConstants.USER_HOME) + File.separator
            + EiffelConstants.OPERATIONS_REPO_NAME);

    // Clone Eiffel Repo from GitHub 
    prepareLocalSchema.cloneEiffelRepo(eiffelRepoUrl, eiffelRepoBranch, localEiffelRepoPath);

    //Clone Eiffel operations Repo from GitHub 
    prepareLocalSchema.cloneEiffelRepo(operationRepoUrl, operationRepoBranch, localOperationsRepoPath);

    //Copy operations repo Schemas to location where Eiffel repo schemas available
    prepareLocalSchema.copyOperationSchemas(localOperationsRepoPath.getAbsolutePath(),
            localEiffelRepoPath.getAbsolutePath());

    // Read and Load JsonSchemas from Cloned Directory 
    final LocalRepo localRepo = new LocalRepo(localEiffelRepoPath);
    localRepo.readSchemas();

    final ArrayList<String> jsonEventNames = localRepo.getJsonEventNames();
    final ArrayList<File> jsonEventSchemas = localRepo.getJsonEventSchemas();

    // Schema changes 
    final SchemaFile schemaFile = new SchemaFile();

    // Iterate the Each jsonSchema file to Add and Modify the necessary properties 
    if (jsonEventNames != null && jsonEventSchemas != null) {
        for (int i = 0; i < jsonEventNames.size(); i++) {
            schemaFile.modify(jsonEventSchemas.get(i), jsonEventNames.get(i));
        }
    }

}

From source file:edu.cmu.lti.oaqa.annographix.apps.SolrQueryApp.java

public static void main(String[] args) {
    Options options = new Options();

    options.addOption("u", null, true, "Solr URI");
    options.addOption("q", null, true, "Query");
    options.addOption("n", null, true, "Max # of results");
    options.addOption("o", null, true, "An optional TREC-style output file");
    options.addOption("w", null, false, "Do a warm-up query call, before each query");

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    BufferedWriter trecOutFile = null;

    try {/*from  ww w .j a v  a 2s  .  co m*/
        CommandLine cmd = parser.parse(options, args);
        String queryFile = null, solrURI = null;

        if (cmd.hasOption("u")) {
            solrURI = cmd.getOptionValue("u");
        } else {
            Usage("Specify Solr URI");
        }

        SolrServerWrapper solr = new SolrServerWrapper(solrURI);

        if (cmd.hasOption("q")) {
            queryFile = cmd.getOptionValue("q");
        } else {
            Usage("Specify Query file");
        }

        int numRet = 100;

        if (cmd.hasOption("n")) {
            numRet = Integer.parseInt(cmd.getOptionValue("n"));
        }

        if (cmd.hasOption("o")) {
            trecOutFile = new BufferedWriter(new FileWriter(new File(cmd.getOptionValue("o"))));
        }

        List<String> fieldList = new ArrayList<String>();
        fieldList.add(UtilConst.ID_FIELD);
        fieldList.add(UtilConst.SCORE_FIELD);

        double totalTime = 0;
        double retQty = 0;

        ArrayList<Double> queryTimes = new ArrayList<Double>();

        boolean bDoWarmUp = cmd.hasOption("w");

        if (bDoWarmUp) {
            System.out.println("Using a warmup step!");
        }

        int queryQty = 0;
        for (String t : FileUtils.readLines(new File(queryFile))) {
            t = t.trim();
            if (t.isEmpty())
                continue;
            int ind = t.indexOf('|');
            if (ind < 0)
                throw new Exception("Wrong format, line: '" + t + "'");
            String qID = t.substring(0, ind);
            String q = t.substring(ind + 1);

            SolrDocumentList res = null;

            if (bDoWarmUp) {
                res = solr.runQuery(q, fieldList, numRet);
            }

            Long tm1 = System.currentTimeMillis();
            res = solr.runQuery(q, fieldList, numRet);
            Long tm2 = System.currentTimeMillis();
            retQty += res.getNumFound();
            System.out.println(qID + " Obtained: " + res.getNumFound() + " entries in " + (tm2 - tm1) + " ms");
            double delta = (tm2 - tm1);
            totalTime += delta;
            queryTimes.add(delta);
            ++queryQty;

            if (trecOutFile != null) {

                ArrayList<SolrRes> resArr = new ArrayList<SolrRes>();
                for (SolrDocument doc : res) {
                    String id = (String) doc.getFieldValue(UtilConst.ID_FIELD);
                    float score = (Float) doc.getFieldValue(UtilConst.SCORE_FIELD);
                    resArr.add(new SolrRes(id, "", score));
                }
                SolrRes[] results = resArr.toArray(new SolrRes[resArr.size()]);
                Arrays.sort(results);

                SolrEvalUtils.saveTrecResults(qID, results, trecOutFile, TREC_RUN, results.length);
            }
        }
        double devTime = 0, meanTime = totalTime / queryQty;
        for (int i = 0; i < queryQty; ++i) {
            double d = queryTimes.get(i) - meanTime;
            devTime += d * d;
        }
        devTime = Math.sqrt(devTime / (queryQty - 1));
        System.out.println(String.format("Query time, mean/standard dev: %.2f/%.2f (ms)", meanTime, devTime));
        System.out.println(String.format("Avg # of docs returned: %.2f", retQty / queryQty));

        solr.close();
        trecOutFile.close();
    } catch (ParseException e) {
        Usage("Cannot parse arguments");
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }

}

From source file:edu.oregonstate.eecs.mcplan.ml.LinearDiscriminantAnalysis.java

public static void main(final String[] args) throws FileNotFoundException {
    final File root = new File("test/LinearDiscriminantAnalysis");
    root.mkdirs();//from   w ww.ja  va2 s.c o m
    final int seed = 42;
    final int N = 30;
    final double shrinkage = 1e-6;

    final RandomGenerator rng = new MersenneTwister(seed);
    final Pair<ArrayList<double[]>, int[]> dataset = Datasets.twoVerticalGaussian2D(rng, N);
    final ArrayList<double[]> data = dataset.first;
    final int[] label = dataset.second;
    final int Nlabels = 2;
    final int[] shuffle_idx = Fn.linspace(0, Nlabels * N);
    Fn.shuffle(rng, shuffle_idx);
    final ArrayList<double[]> shuffled = new ArrayList<double[]>();
    final int[] shuffled_label = new int[label.length];
    for (int i = 0; i < data.size(); ++i) {
        shuffled.add(Fn.copy(data.get(shuffle_idx[i])));
        shuffled_label[i] = label[shuffle_idx[i]];
    }

    final Csv.Writer data_writer = new Csv.Writer(new PrintStream(new File(root, "data.csv")));
    for (final double[] v : data) {
        for (int i = 0; i < v.length; ++i) {
            data_writer.cell(v[i]);
        }
        data_writer.newline();
    }
    data_writer.close();

    System.out.println("[Training]");
    //      final KernelPrincipalComponentsAnalysis<RealVector> kpca
    //         = new KernelPrincipalComponentsAnalysis<RealVector>( shuffled, new RadialBasisFunctionKernel( 0.5 ), 1e-6 );
    final LinearDiscriminantAnalysis lda = new LinearDiscriminantAnalysis(shuffled, shuffled_label, Nlabels,
            shrinkage);
    System.out.println("[Finished]");
    for (final RealVector ev : lda.eigenvectors) {
        System.out.println(ev);
    }

    System.out.println("Transformed data:");
    final LinearDiscriminantAnalysis.Transformer transformer = lda.makeTransformer();
    final Csv.Writer transformed_writer = new Csv.Writer(new PrintStream(new File(root, "transformed.csv")));
    for (final double[] u : data) {
        final RealVector uvec = new ArrayRealVector(u);
        System.out.println(uvec);
        final RealVector v = transformer.transform(uvec);
        System.out.println("-> " + v);
        for (int i = 0; i < v.getDimension(); ++i) {
            transformed_writer.cell(v.getEntry(i));
        }
        transformed_writer.newline();
    }
    transformed_writer.close();
}

From source file:com.waitwha.nessus.server.Server.java

/**
 * @param args//from w w w  .  j  a va 2s  .  c o  m
 */
public static void main(String[] args) {
    String username = System.getProperty("user.name");
    String password = "";
    String url = "https://localhost:8834";
    String uuid = "";
    String output = "";

    for (int i = 0; i < args.length; i++) {
        if (args[i].equals("-h")) {
            url = args[(i + 1)];
            i++;
        } else if (args[i].equals("-p")) {
            password = args[(i + 1)];
            i++;
        } else if (args[i].equals("-u")) {
            username = args[(i + 1)];
            i++;
        } else if (args[i].equals("-d")) {
            uuid = args[(i + 1)];
            i++;
        } else if (args[i].equals("-o")) {
            output = args[(i + 1)];
            i++;
        }
    }

    if (uuid.length() > 0 && output.length() == 0)
        output = System.getProperty("user.dir") + File.pathSeparator + uuid + ".nessus";

    Server server = new Server(url);
    if (server.login(username, password)) {
        System.out.println(String.format("Successfully logged in as '%s'.", username));

        if (uuid.length() == 0) {
            System.out.println("Reports: ");
            ArrayList<Report> reports = server.getReports();
            for (Report report : reports)
                System.out.println(String.format(">> %s (%s)", report.getName(), report.getUuid()));

            if (reports.size() > 0) {
                System.out.println();
                System.out.println("Note: Use -d <uuid> to download a report.");
            }

        } else {
            System.out.print("Downloading report " + uuid + " -> " + output + " ...");
            try {
                server.downloadReport(uuid, output);
                System.out.println("done.");

            } catch (ParserConfigurationException | SAXException e) {
            }
        }

        server.logout();
    }
}

From source file:edu.oregonstate.eecs.mcplan.domains.toy.RallyWorld.java

public static void main(final String[] argv) throws NumberFormatException, IOException {
    final RandomGenerator rng = new MersenneTwister(42);
    final double dmg_slow = 0.1;
    final double dmg_fast = 0.9;
    final double pfault = 1.0;
    final int Nfaults = 2;
    final double pbreak = 1.0;
    final int W = 5;
    final int Nreckless = 3;

    final Parameters params = new Parameters(rng, dmg_slow, dmg_fast, pfault, Nfaults, pbreak, W, Nreckless);
    final Actions actions = new Actions(params);
    final FsssModel model = new FsssModel(params);
    State s = model.initialState();

    while (!s.isTerminal()) {
        System.out.println(s);/*from   w w w .j  av  a2s .  c  o m*/
        System.out.println("R(s): " + model.reward(s));
        actions.setState(s, 0);
        final ArrayList<Action> action_list = Fn.takeAll(actions);
        for (int i = 0; i < action_list.size(); ++i) {
            System.out.println(i + ": " + action_list.get(i));
        }
        System.out.print(">>> ");
        final BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
        final int choice = Integer.parseInt(cin.readLine());
        final Action a = action_list.get(choice);
        System.out.println("R(s, a): " + model.reward(s, a));
        s = model.sampleTransition(s, a);
    }
}

From source file:mmllabvsdextractfeature.MMllabVSDExtractFeature.java

/**
 * @param args the command line arguments
 *//* ww  w.j av a  2 s.c o  m*/
public static void main(String[] args) throws IOException {
    // TODO code application logic here
    MMllabVSDExtractFeature hello = new MMllabVSDExtractFeature();
    FileStructer metdata = new FileStructer();
    //Utility utilityClassIni = new Utility();
    FrameStructer frameStructer = new FrameStructer();

    /*
    Flow :
            
    1. Read  metdata file
    2. Untar folder:
        -1 Shot content 25 frame
        -1 folder 50 shot
    Process with 1 shot:
        - Resize All image 1 shot --> delete orginal.
        - Extract feature 25 frame
        - Pooling Max and aveg.
        - Delete Image, feature
        - zip file Feature 
    3. Delete File.
                
    */

    // Load metadata File
    String dir = "/media/data1";
    String metadataFileDir = "/media/data1/metdata/devel2011-new.lst";
    ArrayList<FileStructer> listFileFromMetadata = metdata.readMetadata(metadataFileDir);

    //        String test = utilityClass.readTextFile("C:\\Users\\tiendv\\Downloads\\VSD_devel2011_1.shot_1.RKF_1.Frame_1.txt");
    //        ArrayList <String> testFeatureSave = utilityClass.SplitUsingTokenizerWithLineArrayList(test, " ");
    //        utilityClass.writeToFile("C:\\Users\\tiendv\\Downloads\\VSD_devel2011_1.shot_1.txt", testFeatureSave);
    //        System.out.println(test);

    for (int i = 0; i < listFileFromMetadata.size(); i++) {

        Utility utilityClass = new Utility();
        //Un zip file
        String folderName = listFileFromMetadata.get(i).getWholeFolderName();
        String nameZipFile = dir + "/" + folderName + "/" + listFileFromMetadata.get(i).getNameZipFileName()
                + ".tar";
        nameZipFile = nameZipFile.replaceAll("\\s", "");
        String outPutFolder = dir + "/" + folderName + "/" + listFileFromMetadata.get(i).getNameZipFileName();
        outPutFolder = outPutFolder.replaceAll("\\s", "");
        utilityClass.unTarFolder(UNTARSHFILE, nameZipFile, outPutFolder + "_");

        // Resize all image in folder has been unzip
        utilityClass.createFolder(CREADFOLDER, outPutFolder);
        utilityClass.resizeWholeFolder(outPutFolder + "_", outPutFolder, resizeWidth, resizeHeight);
        utilityClass.deleteWholeFolder(DELETEFOLDER, outPutFolder + "_");
        // Read all file from Folder has been unzip

        ArrayList<FrameStructer> allFrameInZipFolder = new ArrayList<>();
        allFrameInZipFolder = frameStructer.getListFileInZipFolder(outPutFolder);
        System.out.println(allFrameInZipFolder.size());
        // sort with shot ID
        Collections.sort(allFrameInZipFolder, FrameStructer.frameIDNo);

        // Loop with 1 shot
        int indexFrame = 0;
        for (int n = 0; n < allFrameInZipFolder.size() / 25; n++) {
            // Process with 1 
            ArrayList<String> nameAllFrameOneShot = new ArrayList<>();
            String shotAndFolderName = new String();
            for (; indexFrame < Math.min((n + 1) * 25, allFrameInZipFolder.size()); indexFrame++) {
                String imageForExtract = outPutFolder + "/" + allFrameInZipFolder.get(indexFrame).toFullName()
                        + ".jpg";
                shotAndFolderName = allFrameInZipFolder.get(indexFrame).shotName();
                String resultNameAfterExtract = outPutFolder + "/"
                        + allFrameInZipFolder.get(indexFrame).toFullName() + ".txt";
                nameAllFrameOneShot.add(resultNameAfterExtract);
                // extract and Delete image file --> ouput image'feature
                utilityClass.excuteFeatureExtractionAnImage(EXTRACTFEATUREANDDELETESOURCEIMAGESHFILE, "0",
                        CUDAOVERFEATPATH, imageForExtract, resultNameAfterExtract);
            }
            // Pooling 

            //                    DenseMatrix64F resultMaTrixFeatureOneShot = utilityClass.buidEJMLMatrixFeatureOneShot(nameAllFrameOneShot);
            //                    utilityClass.savePoolingFeatureOneShotWithEJMLFromMatrix(resultMaTrixFeatureOneShot,outPutFolder,shotAndFolderName);

            utilityClass.buidPoolingFileWithOutMatrixFeatureOneShot(nameAllFrameOneShot, outPutFolder,
                    shotAndFolderName);
            // Save A file 

            for (int frameCount = 0; frameCount < nameAllFrameOneShot.size(); frameCount++) { // Delete feature extract file
                utilityClass.deletefile(DELETEFILE, nameAllFrameOneShot.get(frameCount));
            }
            // Release one shot data
            nameAllFrameOneShot.clear();
            System.out.print("The end of one's shot" + "\n" + n);
        }
        // Delete zip file
        utilityClass.deletefile(DELETEFILE, nameZipFile);

        // Zip Whole Folder

        /**
         * Extract 1 shot
         * Resize 25 frame with the same shotid --> delete orgra.
         * Extract 25 frame --> feature file --->delete 
         * 
         */

    }

}

From source file:net.sf.tweety.cli.plugins.CliMain.java

public static void main(String[] args) {

    // check, if first call parameter is for the helptext
    if (args.length == 0) {
        System.out.println("Welcome to the Tweety command line interface.");
        System.out.println("Obtain help with command --help");
        System.exit(0);//from   w  ww  . j  ava 2  s . c  o  m
    } else if ((args.length == 1 && args[0].equals("--help"))) {
        printHelpText();
        System.exit(0);
    } else if (args.length == 1 && !args[0].contains("--help")) {
        System.out.println("No valid input, call with --help for helptext");
        System.exit(0);
    }

    // create new plugin manager
    PluginManager pm = PluginManagerFactory.createPluginManager();
    // create plugin manager util
    PluginManagerUtil pmu = new PluginManagerUtil(pm);

    // System.out.println(pmu.getPlugins());

    // collected parameter
    ArrayList<ArrayList<String>> collectedparams = new ArrayList<ArrayList<String>>();

    // list of available plugins
    Map<String, String> availablePlugins = new HashMap<String, String>();

    // try to configure CLI
    try {
        availablePlugins = configCLI();
    } catch (ConfigurationException e) {
        System.out.println("Something went wrong with your Configuration: ");
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        System.out.println("No such configuration file: ");
        e.printStackTrace();
    }

    // handle all input parameter
    for (int i = 0; i < args.length; i++) {
        // The called plugin
        if (args[i].equals(ARG__CALLED_PLUGIN) || args[i].equals(ARG__CALLED_PLUGIN_SHORT)) {
            String calledPlugin = "";
            while ((i + 1) < args.length && !args[i + 1].startsWith("-")) {
                calledPlugin += args[++i];
            }
            plugin = calledPlugin;
        }

        // the input files
        else if (args[i].equals(ARG__INPUT_FILES) || args[i].equals(ARG__INPUT_FILES_SHORT)) {
            ArrayList<String> inFiles = new ArrayList<String>();
            while ((i + 1) < args.length && !args[i + 1].startsWith("-")) {
                inFiles.add(args[++i]);
            }

            String[] files = new String[inFiles.size()];
            inFiles.toArray(files);

            File[] inf = new File[inFiles.size()];

            for (int k = 0; k < inf.length; k++) {
                inf[k] = new File(files[k]).getAbsoluteFile();
            }

            inputFiles = inf;
        }

        // output file
        else if (args[i].equals(ARG__OUTPUT_FILE) || args[i].equals(ARG__OUTPUT_FILE_SHORT)) {
            // outputFile not used!
            outputFile = args[++i];
        }

        // collecting given command parameters
        else if (args[i].startsWith("-")) {
            ArrayList<String> temp = new ArrayList<String>();
            temp.add(args[i]);
            while ((i + 1) < args.length && !args[i + 1].startsWith("-")) {
                temp.add(args[++i]);

            }
            collectedparams.add(temp);
        } // else if (args[i].equals(ARG__DEBUG_FLAG)
          // ||args[i].equals(ARG__DEBUG_FLAG_SHORT)){
          // debug = true;
          // }
    }

    // check whether the called plugin is present
    boolean pluginPresent = false;
    for (TweetyPlugin tp : pmu.getPlugins(TweetyPlugin.class)) {
        if (tp.getCommand().equalsIgnoreCase(plugin)) {
            pluginPresent = true;
            System.out.println("Called plugin present");
        }
    }
    // TODO: move loading into own method
    // trying to load plugin if not present
    // old method for loading plugins
    if (!pluginPresent) {
        System.out.print("Trying to find plugin...");
        if (availablePlugins.containsKey(plugin)) {
            pm.addPluginsFrom(new File(availablePlugins.get(plugin)).toURI());
            System.out.print("success.\n");
        } else {
            System.out.print("no such plugin available.\n");
        }
    }

    // Test: print all plugins
    // System.out.println("Plugin loaded due to call parameter: " +
    // pm.getPlugin(TweetyPlugin.class, new
    // OptionCapabilities("Tweety Plugin", plugin) ));
    // System.out.println("Print all plugins: " + pmu.getPlugins());
    // System.out.println("Given plugin call parameter: " + plugin);

    // each plugin MUST implement the capabilites "Tweety Plugin" and the
    // variable "call parameter" to select called plugin from plugin pool
    TweetyPlugin tp = pm.getPlugin(TweetyPlugin.class, new OptionCapabilities("Tweety Plugin", plugin));

    // for (TweetyPlugin tp : pmu.getPlugins(TweetyPlugin.class)) {
    if (tp.getCommand().equalsIgnoreCase(plugin)) {
        System.out.println("Valid plugin found.");
        // each input parameter is checked against the called plugin
        // whether it is valid
        ArrayList<CommandParameter> ip = new ArrayList<CommandParameter>();

        System.out.print("Trying to instantiate parameters...");
        try {
            ip.addAll(instantiateParameters(tp, collectedparams));
            System.out.print("done.\n");
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        PluginOutput out = new PluginOutput();

        System.out.println("Execute Plugin...");
        out = tp.execute(inputFiles, ip.toArray(new CommandParameter[ip.size()]));

        if (outputFile != null) {

            try {
                FileWriter fw = new FileWriter(outputFile);
                fw.write(out.getOutput());
                fw.close();
                System.out.println("Output written to file: " + outputFile);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } else {
            System.out.println("No output file given, writing to console...");
            System.out.println("Output: \n" + out.getOutput());
        }
    } else {
        System.out.println("Faulty parameters. Please check input.");

    }

}

From source file:gash.router.app.DemoApp.java

/**
 * sample application (client) use of our messaging service
 *
 * @param args//from ww  w . j av a  2s . c  o m
 */
public static void main(String[] args) {
    if (args.length == 0) {
        System.out.println("usage:  <ip address> <port no>");
        System.exit(1);
    }
    String ipAddress = args[0];
    int port = Integer.parseInt(args[1]);
    Scanner s = new Scanner(System.in);
    boolean isExit = false;
    try {
        MessageClient mc = new MessageClient(ipAddress, port);
        DemoApp da = new DemoApp(mc);
        int choice = 0;

        while (true) {
            System.out.println(
                    "Enter your option \n1. WRITE a file. \n2. READ a file. \n3. Update a File. \n4. Delete a File\n 5 Ping(Global)\n 6 Exit");
            choice = s.nextInt();
            switch (choice) {
            case 1: {
                System.out.println("Enter the full pathname of the file to be written ");
                String currFileName = s.next();
                File file = new File(currFileName);
                if (file.exists()) {
                    ArrayList<ByteString> chunkedFile = da.divideFileChunks(file);
                    String name = file.getName();
                    int i = 0;
                    String requestId = SupportMessageGenerator.generateRequestID();
                    for (ByteString string : chunkedFile) {
                        mc.saveFile(name, string, chunkedFile.size(), i++, requestId);
                    }
                } else {
                    throw new FileNotFoundException("File does not exist in this path ");
                }
            }
                break;
            case 2: {
                System.out.println("Enter the file name to be read : ");
                String currFileName = s.next();
                da.sendReadTasks(currFileName);
                //Thread.sleep(1000 * 100);
            }
                break;
            case 3: {
                System.out.println("Enter the full pathname of the file to be updated");
                String currFileName = s.next();
                File file = new File(currFileName);
                if (file.exists()) {
                    ArrayList<ByteString> chunkedFile = da.divideFileChunks(file);
                    String name = file.getName();
                    int i = 0;
                    String requestId = SupportMessageGenerator.generateRequestID();
                    for (ByteString string : chunkedFile) {
                        mc.updateFile(name, string, chunkedFile.size(), i++, requestId);
                    }
                    //Thread.sleep(10 * 1000);
                } else {
                    throw new FileNotFoundException("File does not exist in this path ");
                }
            }
                break;

            case 4:
                System.out.println("Enter the file name to be deleted : ");
                String currFileName = s.next();
                mc.deleteFile(currFileName);
                //Thread.sleep(1000 * 100);
                break;
            case 5:
                da.ping(1);
                break;
            case 6:
                isExit = true;
                break;
            default:
                break;
            }
            if (isExit)
                break;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        CommConnection.getInstance().release();
        if (s != null)
            s.close();
    }
}