Example usage for java.lang String contains

List of usage examples for java.lang String contains

Introduction

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

Prototype

public boolean contains(CharSequence s) 

Source Link

Document

Returns true if and only if this string contains the specified sequence of char values.

Usage

From source file:CalcoloRitardiLotti.java

public static void main(String[] args) {
    String id_ref = "cbededce-269f-48d2-8c25-2359bf246f42";
    String requestString = "http://dati.openexpo2015.it/catalog/api/action/datastore_search?resource_id="
            + id_ref;/*from ww w.  ja va 2s .co  m*/
    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(requestString);
    try {

        HttpResponse response = client.execute(request);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String result = "";
        String resline = "";
        Calendar c = Calendar.getInstance();
        Date current = Date.valueOf(
                c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH));
        while ((resline = rd.readLine()) != null)
            result += resline;

        //System.out.println(jsonObject.toString());
        if (result != null) {
            JSONObject jsonObject = new JSONObject(result);
            JSONObject resultJson = (JSONObject) jsonObject.get("result");
            JSONArray records = (JSONArray) resultJson.get("records");
            Date temp1, temp2;
            //System.out.printf(records.toString());
            long diffInizioFineLavori;
            long ritardo;
            long den = (24 * 60 * 60 * 1000);
            JSONObject temp;

            DefaultCategoryDataset cdata = new DefaultCategoryDataset();
            String partialQuery;
            DefaultPieDataset data = new DefaultPieDataset();

            String totalQuery = "";
            int countSospesi = 0;
            int countConclusi = 0;
            int countVerifica = 0;
            int countInCorso = 0;
            int countCollaudo = 0;
            String stato;
            for (int i = 0; i < records.length(); i++) {
                temp = (JSONObject) records.get(i);
                temp1 = Date.valueOf((temp.getString("Data Consegna Lavori")).substring(0, 10));
                temp2 = Date.valueOf((temp.getString("Data Fine lavori")).substring(0, 10));
                diffInizioFineLavori = (long) (temp2.getTime() - temp1.getTime()) / den;
                stato = temp.getString("STATO");
                if (stato.equals("Concluso"))
                    countConclusi++;
                else if (stato.equals("In corso"))
                    countInCorso++;
                else if (stato.contains("Verifiche"))
                    countVerifica++;
                else if (stato.contains("Collaudo sospeso") || stato.contains("sospeso"))
                    countSospesi++;
                else
                    countCollaudo++;

                if (!temp.getString("STATO").equals("Concluso") && temp2.getTime() < current.getTime())
                    ritardo = (long) (current.getTime() - temp2.getTime()) / den;
                else
                    ritardo = 0;

                cdata.setValue(ritardo, String.valueOf(i + 1), String.valueOf(i + 1));
                System.out.println(
                        "Opera: " + temp.getString("Oggetto del lotto") + " | id: " + temp.getInt("_id"));
                System.out.println("Data consegna lavoro: " + temp.getString("Data Consegna Lavori")
                        + " | Data fine lavoro: " + temp.getString("Data Fine lavori"));
                System.out.println("STATO: " + temp.getString("STATO"));
                System.out.println("Differenza in giorni: " + diffInizioFineLavori
                        + " | Numero giorni contrattuali: " + temp.getString("numero di giorni contrattuali"));
                System.out.println("Ritardo accumulato: " + ritardo);

                System.out.println("----------------------------------");

                partialQuery = "\nid: " + temp.getInt("_id") + "\nOpera:" + temp.getString("Oggetto del lotto")
                        + "\n" + "Data consegna lavoro: " + temp.getString("Data Consegna Lavori")
                        + "Data fine lavoro: " + temp.getString("Data Fine lavori") + "\n" + "STATO: "
                        + temp.getString("STATO") + "\n" + "Differenza in giorni: " + diffInizioFineLavori
                        + " - Numero giorni contrattuali: " + temp.getString("numero di giorni contrattuali")
                        + "\n" + "Ritardo accumulato: " + ritardo + "\n"
                        + "----------------------------------\n";
                totalQuery = totalQuery + partialQuery;

            }

            JFreeChart chart1 = ChartFactory.createBarChart3D("RITARDI AL " + current, "Id lotto",
                    "ritardo(in giorni)", cdata);
            ChartRenderingInfo info = null;
            ChartUtilities.saveChartAsPNG(
                    new File(System.getProperty("user.dir") + "/istogramma" + current + ".png"), chart1, 1500,
                    1500, info, true, 10);
            FileUtils.writeStringToFile(new File(current + "_1.txt"), totalQuery);

            data.setValue("Conclusi: " + countConclusi, countConclusi);
            data.setValue("Sospeso: " + countSospesi, countSospesi);
            data.setValue("In Corso: " + countInCorso, countInCorso);
            data.setValue("Verifica: " + countVerifica, countVerifica);
            data.setValue("Collaudo: " + countCollaudo, countCollaudo);
            JFreeChart chart2 = ChartFactory.createPieChart3D("Statistiche del " + current, data, true, true,
                    true);
            ChartUtilities.saveChartAsPNG(new File(System.getProperty("user.dir") + "/pie" + current + ".png"),
                    chart2, 800, 450);

        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:GGbot.pkg0.Mainclass.java

public static void main(String[] args)
        throws InterruptedException, TwitterException, DbxException, IOException, Exception {

    String input = "";

    System.out.println("Welcomet to GGbot\nFor more information please take a look at the Read Me\n");

    System.out.println("- Twitter: PlayerName   (flex, returns the latest tweets from a player)\n"
            + "- Facebook: PlayerName  (flex, returns all the information available about a player)\n"
            + "- Note to self: Input   (notflex, create a new text document with your input, and put it in a drop box)\n"
            + "- Translate: Input      (notflex, detects the language of your input and translate it to english)\n"
            + "- Wiki                  (flex, returns the definition of league of legends from wikipedia\n"
            + "- !Players:             (returns the list of the players available in the library (only players from the teams: Cloud9, CLG, and TSM are available at the moment))\n"
            + "- !dropbox:             (returns the link to the dropbox)\n\n" + "Start to chat now!\n");
    while (!input.contains("bye")) {
        System.out.print("<User>");
        Scanner scanner = new Scanner(System.in);
        input = scanner.nextLine();/*  www.  j  av a  2  s.  com*/

        String output = bot.Bot(input.toLowerCase().trim());
        System.out.println("<GGbot>" + WordUtils.wrap(output, 75));
    }

}

From source file:com.linkedin.cubert.io.rubix.RubixFile.java

public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException,
        ParseException, InstantiationException, IllegalAccessException {
    final int VERBOSE_NUM_ROWS = 4;

    Options options = new Options();

    options.addOption("h", "help", false, "shows this message");
    options.addOption("v", "verbose", false, "print summary and first few rows of each block");
    options.addOption("m", "metadata", false, "show the metadata");
    options.addOption("d", "dump", false,
            "dump the contents of the rubix file. Use -f for specifying format, and -o for specifying "
                    + "output location");
    options.addOption("f", "format", true, "the data format for dumping data (AVRO or TEXT). Default: TEXT");
    options.addOption("e", "extract", true,
            "Extract one or more rubix blocks starting from the given blockId. Use -e blockId,numBlocks "
                    + "for specifying the blocks to be extracted. Use -o for specifying output location");
    options.addOption("o", true, "Store the output at the specified location");

    CommandLineParser parser = new BasicParser();

    // parse the command line arguments
    CommandLine line = parser.parse(options, args);

    // show the help message
    if (line.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(/*from   w w  w. jav a2s  .  c om*/
                "RubixFile <rubix file or dir> [options]\nIf no options are provided, print a summary of the blocks.",
                options);
        return;
    }

    // validate provided options
    if (line.hasOption("d") && line.hasOption("e")) {
        System.err.println("Cannot dump (-d) and extract (-e) at the same time!");
        return;
    }

    // obtain the list of rubix files
    String[] files = line.getArgs();
    if (files == null || files.length == 0) {
        System.err.println("Rubix file not specified");
        return;
    }

    Configuration conf = new JobConf();
    FileSystem fs = FileSystem.get(conf);

    Path path = new Path(files[0]);
    FileStatus[] allFiles;

    FileStatus status = fs.getFileStatus(path);
    if (status.isDir()) {
        allFiles = RubixFile.getRubixFiles(path, fs);
    } else {
        allFiles = new FileStatus[] { status };
    }

    // walk over all files and extract the trailer section
    List<RubixFile<Tuple, Object>> rfiles = new ArrayList<RubixFile<Tuple, Object>>();

    for (FileStatus s : allFiles) {
        Path p = s.getPath();

        RubixFile<Tuple, Object> rfile = new RubixFile<Tuple, Object>(conf, p);

        // if printing meta data information.. exit after first file (since all files
        // have the same meta data)
        if (line.hasOption("m")) {
            rfile.getKeyData();

            System.out.println(new ObjectMapper().writer().writeValueAsString(rfile.metadataJson));
            break;
        }

        rfiles.add(rfile);
    }

    // dump the data
    if (line.hasOption("d")) {
        String format = line.getOptionValue("f");
        if (format == null)
            format = "TEXT";

        format = format.trim().toUpperCase();

        if (format.equals("AVRO")) {
            // dumpAvro(rfiles, line.getOptionValue("o"));
            throw new UnsupportedOperationException(
                    "Dumping to avro is not currently supporting. Please write a Cubert (map-only) script to store data in avro format");
        } else if (format.equals("TEXT")) {
            if (line.hasOption("o")) {
                System.err.println("Dumping TEXT format data *into a file* is not currently supported");
                return;
            }
            dumpText(rfiles, line.getOptionValue("o"), Integer.MAX_VALUE);
        } else {
            System.err.println("Invalid format [" + format + "] for dumping. Please use AVRO or TEXT");
            return;
        }
    }
    // extract arguments: -e blockId,numBlocks(contiguous) -o ouputLocation
    else if (line.hasOption("e")) {
        String extractArguments = line.getOptionValue("e");
        String outputLocation;
        if (line.hasOption("o")) {
            outputLocation = line.getOptionValue("o");
        } else {
            System.err.println("Need to specify the location to store the output");
            return;
        }
        long blockId;
        int numBlocks = 1;
        if (extractArguments.contains(",")) {
            String[] splitExtractArgs = extractArguments.split(",");
            blockId = Long.parseLong(splitExtractArgs[0]);
            numBlocks = Integer.parseInt(splitExtractArgs[1]);
        } else {
            blockId = Long.parseLong(extractArguments);
        }

        extract(rfiles, blockId, numBlocks, outputLocation);
    } else
    // print summary
    {
        dumpText(rfiles, null, line.hasOption("v") ? VERBOSE_NUM_ROWS : 0);
    }
}

From source file:com.act.lcms.db.analysis.StandardIonAnalysis.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());//from w w w  . j ava2 s  .c  o m
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        return;
    }

    File lcmsDir = new File(cl.getOptionValue(OPTION_DIRECTORY));
    if (!lcmsDir.isDirectory()) {
        System.err.format("File at %s is not a directory\n", lcmsDir.getAbsolutePath());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    try (DB db = DB.openDBFromCLI(cl)) {
        ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir);
        StandardIonAnalysis analysis = new StandardIonAnalysis();
        HashMap<Integer, Plate> plateCache = new HashMap<>();

        String plateBarcode = cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE);
        String inputChemicals = cl.getOptionValue(OPTION_STANDARD_CHEMICAL);
        String medium = cl.getOptionValue(OPTION_MEDIUM);

        // If standard chemical is specified, do standard LCMS ion selection analysis
        if (inputChemicals != null && !inputChemicals.equals("")) {
            String[] chemicals;
            if (!inputChemicals.contains(",")) {
                chemicals = new String[1];
                chemicals[0] = inputChemicals;
            } else {
                chemicals = inputChemicals.split(",");
            }

            String outAnalysis = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + "." + CSV_FORMAT;
            String plottingDirectory = cl.getOptionValue(OPTION_PLOTTING_DIR);
            String[] headerStrings = { "Molecule", "Plate Bar Code", "LCMS Detection Results" };
            CSVPrinter printer = new CSVPrinter(new FileWriter(outAnalysis),
                    CSVFormat.DEFAULT.withHeader(headerStrings));

            for (String inputChemical : chemicals) {
                List<StandardWell> standardWells;

                Plate queryPlate = Plate.getPlateByBarcode(db,
                        cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE));
                if (plateBarcode != null && medium != null) {
                    standardWells = analysis.getStandardWellsForChemicalInSpecificPlateAndMedium(db,
                            inputChemical, queryPlate.getId(), medium);
                } else if (plateBarcode != null) {
                    standardWells = analysis.getStandardWellsForChemicalInSpecificPlate(db, inputChemical,
                            queryPlate.getId());
                } else {
                    standardWells = analysis.getStandardWellsForChemical(db, inputChemical);
                }

                if (standardWells.size() == 0) {
                    throw new RuntimeException("Found no LCMS wells for " + inputChemical);
                }

                // Sort in descending order of media where MeOH and Water related media are promoted to the top and
                // anything derived from yeast media are demoted.
                Collections.sort(standardWells, new Comparator<StandardWell>() {
                    @Override
                    public int compare(StandardWell o1, StandardWell o2) {
                        if (StandardWell.doesMediaContainYeastExtract(o1.getMedia())
                                && !StandardWell.doesMediaContainYeastExtract(o2.getMedia())) {
                            return 1;
                        } else {
                            return 0;
                        }
                    }
                });

                Map<StandardWell, StandardIonResult> wellToIonRanking = StandardIonAnalysis
                        .getBestMetlinIonsForChemical(inputChemical, lcmsDir, db, standardWells,
                                plottingDirectory);

                if (wellToIonRanking.size() != standardWells.size()
                        && !cl.hasOption(OPTION_OVERRIDE_NO_SCAN_FILE_FOUND)) {
                    throw new Exception("Could not find a scan file associated with one of the standard wells");
                }

                for (StandardWell well : wellToIonRanking.keySet()) {
                    LinkedHashMap<String, XZ> snrResults = wellToIonRanking.get(well).getAnalysisResults();

                    String snrRankingResults = "";
                    int numResultsToShow = 0;

                    Plate plateForWellToAnalyze = Plate.getPlateById(db, well.getPlateId());

                    for (Map.Entry<String, XZ> ionToSnrAndTime : snrResults.entrySet()) {
                        if (numResultsToShow > 3) {
                            break;
                        }

                        String ion = ionToSnrAndTime.getKey();
                        XZ snrAndTime = ionToSnrAndTime.getValue();

                        snrRankingResults += String.format(ion + " (%.2f SNR at %.2fs); ",
                                snrAndTime.getIntensity(), snrAndTime.getTime());
                        numResultsToShow++;
                    }

                    String[] resultSet = { inputChemical,
                            plateForWellToAnalyze.getBarcode() + " " + well.getCoordinatesString() + " "
                                    + well.getMedia() + " " + well.getConcentration(),
                            snrRankingResults };

                    printer.printRecord(resultSet);
                }
            }

            try {
                printer.flush();
                printer.close();
            } catch (IOException e) {
                System.err.println("Error while flushing/closing csv writer.");
                e.printStackTrace();
            }
        } else {
            // Get the set of chemicals that includes the construct and all it's intermediates
            Pair<ConstructEntry, List<ChemicalAssociatedWithPathway>> constructAndPathwayChems = analysis
                    .getChemicalsForConstruct(db, cl.getOptionValue(OPTION_CONSTRUCT));
            System.out.format("Construct: %s\n", constructAndPathwayChems.getLeft().getCompositionId());

            for (ChemicalAssociatedWithPathway pathwayChem : constructAndPathwayChems.getRight()) {
                System.out.format("  Pathway chem %s\n", pathwayChem.getChemical());

                // Get all the standard wells for the pathway chemicals. These wells contain only the
                // the chemical added with controlled solutions (ie no organism or other chemicals in the
                // solution)

                List<StandardWell> standardWells;

                if (plateBarcode != null) {
                    Plate queryPlate = Plate.getPlateByBarcode(db,
                            cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE));
                    standardWells = analysis.getStandardWellsForChemicalInSpecificPlate(db,
                            pathwayChem.getChemical(), queryPlate.getId());
                } else {
                    standardWells = analysis.getStandardWellsForChemical(db, pathwayChem.getChemical());
                }

                for (StandardWell wellToAnalyze : standardWells) {
                    List<StandardWell> negativeControls = analysis.getViableNegativeControlsForStandardWell(db,
                            wellToAnalyze);
                    Map<StandardWell, List<ScanFile>> allViableScanFiles = analysis
                            .getViableScanFilesForStandardWells(db, wellToAnalyze, negativeControls);

                    List<String> primaryStandardScanFileNames = new ArrayList<>();
                    for (ScanFile scanFile : allViableScanFiles.get(wellToAnalyze)) {
                        primaryStandardScanFileNames.add(scanFile.getFilename());
                    }
                    Plate plate = plateCache.get(wellToAnalyze.getPlateId());
                    if (plate == null) {
                        plate = Plate.getPlateById(db, wellToAnalyze.getPlateId());
                        plateCache.put(plate.getId(), plate);
                    }

                    System.out.format("    Standard well: %s @ %s, '%s'%s%s\n", plate.getBarcode(),
                            wellToAnalyze.getCoordinatesString(), wellToAnalyze.getChemical(),
                            wellToAnalyze.getMedia() == null ? ""
                                    : String.format(" in %s", wellToAnalyze.getMedia()),
                            wellToAnalyze.getConcentration() == null ? ""
                                    : String.format(" @ %s", wellToAnalyze.getConcentration()));
                    System.out.format("      Scan files: %s\n",
                            StringUtils.join(primaryStandardScanFileNames, ", "));

                    for (StandardWell negCtrlWell : negativeControls) {
                        plate = plateCache.get(negCtrlWell.getPlateId());
                        if (plate == null) {
                            plate = Plate.getPlateById(db, negCtrlWell.getPlateId());
                            plateCache.put(plate.getId(), plate);
                        }
                        List<String> negativeControlScanFileNames = new ArrayList<>();
                        for (ScanFile scanFile : allViableScanFiles.get(negCtrlWell)) {
                            negativeControlScanFileNames.add(scanFile.getFilename());
                        }

                        System.out.format("      Viable negative: %s @ %s, '%s'%s%s\n", plate.getBarcode(),
                                negCtrlWell.getCoordinatesString(), negCtrlWell.getChemical(),
                                negCtrlWell.getMedia() == null ? ""
                                        : String.format(" in %s", negCtrlWell.getMedia()),
                                negCtrlWell.getConcentration() == null ? ""
                                        : String.format(" @ %s", negCtrlWell.getConcentration()));
                        System.out.format("        Scan files: %s\n",
                                StringUtils.join(negativeControlScanFileNames, ", "));
                        // TODO: do something useful with the standard wells and their scan files, and then stop all the printing.
                    }
                }
            }
        }
    }
}

From source file:org.eclipse.lyo.client.oslc.samples.RRCFormSample.java

/**
 * Login to the RRC server and perform some OSLC actions
 * @param args/*  www .  j a va  2 s.c  om*/
 * @throws ParseException 
 */
public static void main(String[] args) throws ParseException {

    Options options = new Options();

    options.addOption("url", true, "url");
    options.addOption("user", true, "user ID");
    options.addOption("password", true, "password");
    options.addOption("project", true, "project area");

    CommandLineParser cliParser = new GnuParser();

    //Parse the command line
    CommandLine cmd = cliParser.parse(options, args);

    if (!validateOptions(cmd)) {
        logger.severe(
                "Syntax:  java <class_name> -url https://<server>:port/<context>/ -user <user> -password <password> -project \"<project_area>\"");
        logger.severe(
                "Example: java RRCFormSample -url https://exmple.com:9443/rm -user ADMIN -password ADMIN -project \"JKE Banking (Requirements Management)\"");
        return;
    }

    String webContextUrl = cmd.getOptionValue("url");
    String user = cmd.getOptionValue("user");
    String passwd = cmd.getOptionValue("password");
    String projectArea = cmd.getOptionValue("project");

    try {

        //STEP 1: Initialize a Jazz rootservices helper and indicate we're looking for the RequirementManagement catalog
        JazzRootServicesHelper helper = new JazzRootServicesHelper(webContextUrl, OSLCConstants.OSLC_RM_V2);

        //STEP 2: Create a new Form Auth client with the supplied user/password
        //RRC is a fronting server, so need to use the initForm() signature which allows passing of an authentication URL.
        //For RRC, use the JTS for the authorization URL

        //This is a bit of a hack for readability.  It is assuming RRC is at context /rm.  Could use a regex or UriBuilder instead.
        String authUrl = webContextUrl.replaceFirst("/rm", "/jts");
        JazzFormAuthClient client = helper.initFormClient(user, passwd, authUrl);

        //STEP 3: Login in to Jazz Server
        if (client.formLogin() == HttpStatus.SC_OK) {

            //STEP 4: Get the URL of the OSLC ChangeManagement catalog
            String catalogUrl = helper.getCatalogUrl();

            //STEP 5: Find the OSLC Service Provider for the project area we want to work with
            String serviceProviderUrl = client.lookupServiceProviderUrl(catalogUrl, projectArea);

            //STEP 6: Get the Query Capabilities URL so that we can run some OSLC queries
            String queryCapability = client.lookupQueryCapability(serviceProviderUrl, OSLCConstants.OSLC_RM_V2,
                    OSLCConstants.RM_REQUIREMENT_TYPE);
            //STEP 7: Create base requirements
            //Get the Creation Factory URL for change requests so that we can create one
            Requirement requirement = new Requirement();
            String requirementFactory = client.lookupCreationFactory(serviceProviderUrl,
                    OSLCConstants.OSLC_RM_V2, requirement.getRdfTypes()[0].toString());

            //Get Feature Requirement Type URL
            ResourceShape featureInstanceShape = RmUtil.lookupRequirementsInstanceShapes(serviceProviderUrl,
                    OSLCConstants.OSLC_RM_V2, requirement.getRdfTypes()[0].toString(), client, "Feature");

            URI rootFolder = null;
            //Get Collection Type URL
            RequirementCollection collection = new RequirementCollection();
            ResourceShape collectionInstanceShape = RmUtil.lookupRequirementsInstanceShapes(serviceProviderUrl,
                    OSLCConstants.OSLC_RM_V2, collection.getRdfTypes()[0].toString(), client,
                    "Personal Collection");

            String req01URL = null;
            String req02URL = null;
            String req03URL = null;
            String req04URL = null;
            String reqcoll01URL = null;

            String primaryText = null;
            if ((featureInstanceShape != null) && (requirementFactory != null)) {

                // Create REQ01
                requirement.setInstanceShape(featureInstanceShape.getAbout());
                requirement.setTitle("Req01");

                // Decorate the PrimaryText
                primaryText = "My Primary Text";
                org.w3c.dom.Element obj = RmUtil.convertStringToHTML(primaryText);
                requirement.getExtendedProperties().put(RmConstants.PROPERTY_PRIMARY_TEXT, obj);

                requirement.setDescription("Created By EclipseLyo");
                requirement.addImplementedBy(new Link(new URI("http://google.com"), "Link in REQ01"));
                //Create the change request
                ClientResponse creationResponse = client.createResource(requirementFactory, requirement,
                        OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML);
                req01URL = creationResponse.getHeaders().getFirst(HttpHeaders.LOCATION);
                creationResponse.consumeContent();

                // Create REQ02   
                requirement = new Requirement();
                requirement.setInstanceShape(featureInstanceShape.getAbout());
                requirement.setTitle("Req02");
                requirement.setDescription("Created By EclipseLyo");
                requirement.addValidatedBy(new Link(new URI("http://bancomer.com"), "Link in REQ02"));
                //Create the change request
                creationResponse = client.createResource(requirementFactory, requirement,
                        OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML);

                req02URL = creationResponse.getHeaders().getFirst(HttpHeaders.LOCATION);
                creationResponse.consumeContent();

                // Create REQ03   
                requirement = new Requirement();
                requirement.setInstanceShape(featureInstanceShape.getAbout());
                requirement.setTitle("Req03");
                requirement.setDescription("Created By EclipseLyo");
                requirement.addValidatedBy(new Link(new URI("http://outlook.com"), "Link in REQ03"));
                //Create the change request
                creationResponse = client.createResource(requirementFactory, requirement,
                        OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML);
                req03URL = creationResponse.getHeaders().getFirst(HttpHeaders.LOCATION);
                creationResponse.consumeContent();

                // Create REQ04   
                requirement = new Requirement();
                requirement.setInstanceShape(featureInstanceShape.getAbout());
                requirement.setTitle("Req04");
                requirement.setDescription("Created By EclipseLyo");

                //Create the Requirement
                creationResponse = client.createResource(requirementFactory, requirement,
                        OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML);
                req04URL = creationResponse.getHeaders().getFirst(HttpHeaders.LOCATION);
                creationResponse.consumeContent();

                // Now create a collection 
                // Create REQ04   
                collection = new RequirementCollection();

                collection.addUses(new URI(req03URL));
                collection.addUses(new URI(req04URL));

                collection.setInstanceShape(collectionInstanceShape.getAbout());
                collection.setTitle("Collection01");
                collection.setDescription("Created By EclipseLyo");
                //Create the change request
                creationResponse = client.createResource(requirementFactory, collection,
                        OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML);
                reqcoll01URL = creationResponse.getHeaders().getFirst(HttpHeaders.LOCATION);
                creationResponse.consumeContent();

            }

            // Check that everything was properly created
            if (req01URL == null || req02URL == null || req03URL == null || req04URL == null
                    || reqcoll01URL == null) {
                throw new Exception("Failed to create an artifact");
            }

            // GET the root folder based on First requirement created
            ClientResponse getResponse = client.getResource(req01URL, OslcMediaType.APPLICATION_RDF_XML);
            requirement = getResponse.getEntity(Requirement.class);
            String etag1 = getResponse.getHeaders().getFirst(OSLCConstants.ETAG);
            // May not be needed getResponse.consumeContent();
            //Save the URI of the root folder in order to used it easily 
            rootFolder = (URI) requirement.getExtendedProperties().get(RmConstants.PROPERTY_PARENT_FOLDER);

            String changedPrimaryText = (String) requirement.getExtendedProperties()
                    .get(RmConstants.PROPERTY_PRIMARY_TEXT);
            if (changedPrimaryText == null) {
                // Check with the workaround
                changedPrimaryText = (String) requirement.getExtendedProperties()
                        .get(PROPERTY_PRIMARY_TEXT_WORKAROUND);
            }

            if ((changedPrimaryText != null) && (!changedPrimaryText.contains(primaryText))) {
                logger.log(Level.SEVERE, "Error getting primary Text");
            }

            //QUERIES
            // SCENARIO 01  Do a query for type= Requirements
            OslcQueryParameters queryParams = new OslcQueryParameters();
            queryParams.setPrefix("rdf=<http://www.w3.org/1999/02/22-rdf-syntax-ns#>");
            queryParams.setWhere("rdf:type=<http://open-services.net/ns/rm#Requirement>");
            OslcQuery query = new OslcQuery(client, queryCapability, 10, queryParams);
            OslcQueryResult result = query.submit();
            boolean processAsJavaObjects = false;
            int resultsSize = result.getMembersUrls().length;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for SCENARIO 01 = " + resultsSize + "\n");

            // SCENARIO 02    Do a query for type= Requirements and for it folder container = rootFolder
            queryParams = new OslcQueryParameters();
            queryParams.setPrefix(
                    "nav=<http://com.ibm.rdm/navigation#>,rdf=<http://www.w3.org/1999/02/22-rdf-syntax-ns#>");
            queryParams.setWhere("rdf:type=<http://open-services.net/ns/rm#Requirement> and nav:parent=<"
                    + rootFolder + ">");
            query = new OslcQuery(client, queryCapability, 10, queryParams);
            result = query.submit();
            processAsJavaObjects = false;
            resultsSize = result.getMembersUrls().length;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for SCENARIO 02 = " + resultsSize + "\n");

            // SCENARIO 03   Do a query for title
            queryParams = new OslcQueryParameters();
            queryParams.setPrefix("dcterms=<http://purl.org/dc/terms/>");
            queryParams.setWhere("dcterms:title=\"Req04\"");
            query = new OslcQuery(client, queryCapability, 10, queryParams);
            result = query.submit();
            resultsSize = result.getMembersUrls().length;
            processAsJavaObjects = false;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for SCENARIO 03 = " + resultsSize + "\n");

            // SCENARIO 04   Do a query for the link that is implemented
            queryParams = new OslcQueryParameters();
            queryParams.setPrefix("oslc_rm=<http://open-services.net/ns/rm#>");
            queryParams.setWhere("oslc_rm:implementedBy=<http://google.com>");
            query = new OslcQuery(client, queryCapability, 10, queryParams);
            result = query.submit();
            resultsSize = result.getMembersUrls().length;
            processAsJavaObjects = false;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for SCENARIO 04 = " + resultsSize + "\n");

            // SCENARIO 05   Do a query for the links that is validated 
            queryParams = new OslcQueryParameters();
            queryParams.setPrefix("oslc_rm=<http://open-services.net/ns/rm#>");
            queryParams.setWhere("oslc_rm:validatedBy in [<http://bancomer.com>,<http://outlook.com>]");
            query = new OslcQuery(client, queryCapability, 10, queryParams);
            result = query.submit();
            resultsSize = result.getMembersUrls().length;
            processAsJavaObjects = false;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for SCENARIO 05 = " + resultsSize + "\n");

            // SCENARIO 06 Do a query for it container folder and for the link that is implemented
            queryParams = new OslcQueryParameters();
            queryParams.setPrefix(
                    "nav=<http://com.ibm.rdm/navigation#>,oslc_rm=<http://open-services.net/ns/rm#>");
            queryParams
                    .setWhere("nav:parent=<" + rootFolder + "> and oslc_rm:validatedBy=<http://bancomer.com>");
            query = new OslcQuery(client, queryCapability, 10, queryParams);
            result = query.submit();
            resultsSize = result.getMembersUrls().length;
            processAsJavaObjects = false;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for SCENARIO 06 = " + resultsSize + "\n");

            // GET resources from req03 in order edit its values
            getResponse = client.getResource(req03URL, OslcMediaType.APPLICATION_RDF_XML);
            requirement = getResponse.getEntity(Requirement.class);
            // Get the eTAG, we need it to update
            String etag = getResponse.getHeaders().getFirst(OSLCConstants.ETAG);
            getResponse.consumeContent();
            requirement.setTitle("My new Title");
            requirement.addImplementedBy(
                    new Link(new URI("http://google.com"), "Link created by an Eclipse Lyo user"));

            // Update the requirement with the proper etag 
            ClientResponse updateResponse = client.updateResource(req03URL, requirement,
                    OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML, etag);

            updateResponse.consumeContent();

            /*Do a query in order to see if the requirement have changed*/
            // SCENARIO 07 Do a query for the new title just changed
            queryParams = new OslcQueryParameters();
            queryParams.setPrefix("dcterms=<http://purl.org/dc/terms/>");
            queryParams.setWhere("dcterms:title=\"My new Title\"");
            query = new OslcQuery(client, queryCapability, 10, queryParams);
            result = query.submit();
            resultsSize = result.getMembersUrls().length;
            processAsJavaObjects = false;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for SCENARIO 07 = " + resultsSize + "\n");

            // SCENARIO 08   Do a query for implementedBy links
            queryParams = new OslcQueryParameters();
            queryParams.setPrefix("oslc_rm=<http://open-services.net/ns/rm#>");
            queryParams.setWhere("oslc_rm:implementedBy=<http://google.com>");
            query = new OslcQuery(client, queryCapability, 10, queryParams);
            result = query.submit();
            resultsSize = result.getMembersUrls().length;
            processAsJavaObjects = false;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for SCENARIO 08 = " + resultsSize + "\n");

        }
    } catch (RootServicesException re) {
        logger.log(Level.SEVERE,
                "Unable to access the Jazz rootservices document at: " + webContextUrl + "/rootservices", re);
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }

}

From source file:com.jlgranda.fede.ejb.mail.reader.FacturaElectronicaMailReader.java

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

    FacturaElectronicaMailReader famr = new FacturaElectronicaMailReader();
    String server = "jlgranda.com";
    String username = "1104499049@jlgranda.com";
    String password = "FKR5oznrtVwnEirkrbl4rmeba0mFCmYh";

    String proto = "TLS";
    IMAPClient client = new IMAPClient(server, username, password);
    String contentType = null;// w ww  .  j av  a  2s.  c  o m
    StringReader reader = null;
    Address[] fromAddress = null;
    String messageContent = "";
    String attachFiles = "";
    org.apache.james.mime4j.dom.Multipart multiPart = null;
    MimeBodyPart part = null;
    int i = 0;
    String partContentType = null;
    String partName = null;
    String from = "";
    String subject = "";
    String sentDate = "";
    int contadorFacturasLeidas = 0;
    List<FacturaReader> result = new ArrayList<>(); //Guardar enlaces a factura si es el caso

    boolean facturaEncontrada = false;
    int index = 0;
    int numberOfParts = 0;
    String[] token = null;
    MessageBuilder builder = new DefaultMessageBuilder();
    ByteArrayOutputStream os = null;
    EmailHelper emailHelper = new EmailHelper();
    for (Message message : client.getMessages("inbox", false)) {
        //System.out.println("Message #" + email.fullMail(message) + ":");

        //attachFiles = "";
        fromAddress = message.getFrom();
        from = fromAddress[0].toString();
        subject = message.getSubject();
        sentDate = message.getSentDate() != null ? message.getSentDate().toString() : "";
        if (subject.contains(
                "Fwd: Ghost - Doc. Electrnico: 2201201601180145025300120010320000336391234567819")) {
            System.out.println("--------------------------------------" + (index++)
                    + "-----------------------------------------");
            System.out.println("From: " + fromAddress);
            System.out.println("Subject: " + subject);
            try {
                org.apache.james.mime4j.dom.Message mime4jMessage = builder
                        .parseMessage(new ByteArrayInputStream(emailHelper.fullMail(message).getBytes()));
                result.addAll(famr.handleMessage(mime4jMessage));
            } catch (org.apache.james.mime4j.MimeIOException mioe) {
                mioe.printStackTrace();
            } catch (org.apache.james.mime4j.MimeException me) {
                me.printStackTrace();
            }
            System.out
                    .println("-------------------------------------------------------------------------------");
        }
    }
    System.err.println("Facturas encontradas>> " + result.size());
    client.close();

}

From source file:com.wittawat.wordseg.Main.java

public static void main(String[] args) throws Exception {
    Console con = System.console();
    if (con == null) {
        System.out.println("The system must support console to run the program.");
        System.exit(1);//from   ww  w.j  a va2 s. com
    }
    // Load model
    System.out.println("Loading model ...");
    Classifier model = Data.getDefaultModel();

    System.out.println("Finished loading model.");
    System.out.println(getAgreement());

    boolean isUseDict = true;

    // Dummy statement to eliminate all lazy loading
    System.out.println("\n" + new NukeTokenizer3(
            "?????",
            model, isUseDict).tokenize() + "\n");

    System.out.println(getHelp());

    final String SET_DICT_PAT_STR = "\\s*set\\s+dict\\s+(true|false)\\s*";
    final Pattern SET_DICT_PAT = Pattern.compile(SET_DICT_PAT_STR);
    while (true) {
        System.out.print(">> ");
        String line = con.readLine();
        if (line != null && !line.trim().equals("")) {

            line = line.trim();
            try {
                if (line.equals("h") || line.equals("help")) {
                    System.out.println(getHelp());
                } else if (line.equals("about")) {
                    System.out.println(getAbout());
                } else if (line.equals("agreement")) {
                    System.out.println(getAgreement());
                } else if (SET_DICT_PAT.matcher(line).find()) {
                    Matcher m = SET_DICT_PAT.matcher(line);
                    m.find();
                    String v = m.group(1);
                    isUseDict = v.equals("true");
                    System.out.println("Dictionary will " + (isUseDict ? "" : "not ") + "be used.");
                } else if (line.matches("q|quit|exit")) {
                    System.out.println("Bye");
                    System.exit(0);
                } else if (line.contains(":tokfile:")) {
                    String[] splits = line.split(":tokfile:");
                    String in = splits[0];
                    String out = splits[1];
                    String content = FileUtils.readFileToString(new File(in));
                    long start = new Date().getTime();

                    NukeTokenizer tokenizer = new NukeTokenizer3(content, model, isUseDict);

                    String tokenized = tokenizer.tokenize();
                    long end = new Date().getTime();
                    System.out.println("Time to tokenize: " + (end - start) + " ms.");
                    FileUtils.writeStringToFile(new File(out), tokenized);
                } else if (line.contains(":tokfile")) {
                    String[] splits = line.split(":tokfile");
                    String in = splits[0];

                    String content = FileUtils.readFileToString(new File(in));
                    long start = new Date().getTime();
                    NukeTokenizer tokenizer = new NukeTokenizer3(content, model, isUseDict);
                    String tokenized = tokenizer.tokenize();
                    long end = new Date().getTime();

                    System.out.println(tokenized);
                    System.out.println("Time to tokenize: " + (end - start) + " ms.");
                } else if (line.contains(":tok:")) {
                    String[] splits = line.split(":tok:");
                    String inText = splits[0];
                    String out = splits[1];

                    long start = new Date().getTime();
                    NukeTokenizer tokenizer = new NukeTokenizer3(inText, model, isUseDict);
                    String tokenized = tokenizer.tokenize();
                    long end = new Date().getTime();
                    System.out.println("Time to tokenize: " + (end - start) + " ms.");
                    FileUtils.writeStringToFile(new File(out), tokenized);
                } else if (line.contains(":tok")) {
                    String[] splits = line.split(":tok");
                    String inText = splits[0];

                    long start = new Date().getTime();
                    NukeTokenizer tokenizer = new NukeTokenizer3(inText, model, isUseDict);
                    String tokenized = tokenizer.tokenize();
                    long end = new Date().getTime();

                    System.out.println(tokenized);
                    System.out.println("Time to tokenize: " + (end - start) + " ms.");
                } else {
                    System.out.println("Unknown command");
                }
            } catch (Exception e) {
                System.out.println("Error. See the exception.");
                e.printStackTrace();
            }

        }
    }

}

From source file:com.genentech.chemistry.tool.align.SDFAlign.java

public static void main(String... args) {
    Options options = new Options();
    Option opt = new Option("in", true, "input sd file");
    opt.setRequired(true);// w  ww  .j  ava2  s .  c om
    options.addOption(opt);

    opt = new Option("out", true, "output file");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("method", true, "fss|sss|MCS|clique (default mcs).");
    options.addOption(opt);

    opt = new Option("ref", true,
            "reference molecule if not given first in file is used. If multiple ref molecules are read the min RMSD is reported");
    options.addOption(opt);

    opt = new Option("mirror", false, "If given and the molecule is not chiral, return best mirror image.");
    options.addOption(opt);

    opt = new Option("rmsdTag", true, "Tagname for output of rmsd, default: no output.");
    options.addOption(opt);

    opt = new Option("atomMatch", true,
            "Sequence of none|default|hcount|noAromatic specifing how atoms are matched cf. oe document.\n"
                    + "noAromatic can be used to make terminal atoms match aliphatic and aromatic atoms.\n"
                    + "Queryfeatures are considered only if default is used.");
    options.addOption(opt);

    opt = new Option("bondMatch", true,
            "Sequence of none|default specifing how bonds are matched cf. oe document.");
    options.addOption(opt);

    opt = new Option("keepCoreHydrogens", false,
            "If not specified the hydrigen atoms are removed from the core.");
    options.addOption(opt);

    opt = new Option("outputMol", true, "aligned|original (def: aligned) use original to just compute rmsd.");
    options.addOption(opt);

    opt = new Option("doNotOptimize", false,
            "If specified the RMSD is computed without moving optimizing the overlay.");
    options.addOption(opt);

    opt = new Option("quiet", false, "Reduced warining messages");
    options.addOption(opt);

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        exitWithHelp(e.getMessage(), options);
    }

    if (cmd.getArgs().length > 0)
        exitWithHelp("To many arguments", options);

    // do not check aromaticity on atoms so that a terminal atom matches aromatic and non aromatic atoms
    int atomExpr = OEExprOpts.DefaultAtoms;
    int bondExpr = OEExprOpts.DefaultBonds;

    String atomMatch = cmd.getOptionValue("atomMatch");
    if (atomMatch == null)
        atomMatch = "";
    atomMatch = '|' + atomMatch.toLowerCase() + '|';

    String bondMatch = cmd.getOptionValue("bondMatch");
    if (bondMatch == null)
        bondMatch = "";
    bondMatch = '|' + bondMatch.toLowerCase() + '|';

    String inFile = cmd.getOptionValue("in");
    String outFile = cmd.getOptionValue("out");
    String refFile = cmd.getOptionValue("ref");
    String method = cmd.getOptionValue("method");
    String rmsdTag = cmd.getOptionValue("rmsdTag");
    String oMol = cmd.getOptionValue("outputMol");
    boolean doMirror = cmd.hasOption("mirror");
    boolean doOptimize = !cmd.hasOption("doNotOptimize");
    boolean quiet = cmd.hasOption("quiet");

    OUTType outputMol = oMol == null ? OUTType.ALIGNED : OUTType.valueOf(oMol.toUpperCase());

    if (atomMatch.startsWith("|none"))
        atomExpr = 0;
    if (atomMatch.contains("|hcount|"))
        atomExpr |= OEExprOpts.HCount;
    if (atomMatch.contains("|noAromatic|"))
        atomExpr &= (~OEExprOpts.Aromaticity);

    if (bondMatch.startsWith("|none"))
        bondExpr = 0;

    ArrayList<OEMol> refmols = new ArrayList<OEMol>();
    if (refFile != null) {
        oemolistream reffs = new oemolistream(refFile);
        if (!is3DFormat(reffs.GetFormat()))
            oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates");
        reffs.SetFormat(OEFormat.MDL);

        int aromodel = OEIFlavor.Generic.OEAroModelOpenEye;
        int qflavor = reffs.GetFlavor(reffs.GetFormat());
        reffs.SetFlavor(reffs.GetFormat(), (qflavor | aromodel));

        OEMol rmol = new OEMol();
        while (oechem.OEReadMDLQueryFile(reffs, rmol)) {
            if (!cmd.hasOption("keepCoreHydrogens"))
                oechem.OESuppressHydrogens(rmol);
            refmols.add(rmol);
            rmol = new OEMol();
        }
        rmol.delete();

        if (refmols.size() == 0)
            throw new Error("reference file had no entries");

        reffs.close();
    }

    oemolistream fitfs = new oemolistream(inFile);
    if (!is3DFormat(fitfs.GetFormat()))
        oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates");

    oemolostream ofs = new oemolostream(outFile);
    if (!is3DFormat(ofs.GetFormat()))
        oechem.OEThrow.Fatal("Invalid output format: need 3D coordinates");

    AlignInterface aligner = null;
    OEGraphMol fitmol = new OEGraphMol();

    if (oechem.OEReadMolecule(fitfs, fitmol)) {
        if (refmols.size() == 0) {
            OEMol rmol = new OEMol(fitmol);
            if (!cmd.hasOption("keepCoreHydrogens"))
                oechem.OESuppressHydrogens(rmol);

            refmols.add(rmol);
        }

        if ("sss".equalsIgnoreCase(method)) {
            aligner = new SSSAlign(refmols, outputMol, rmsdTag, doOptimize, doMirror, atomExpr, bondExpr,
                    quiet);

        } else if ("clique".equalsIgnoreCase(method)) {
            aligner = new CliqueAlign(refmols, outputMol, rmsdTag, doOptimize, doMirror, atomExpr, bondExpr,
                    quiet);

        } else if ("fss".equalsIgnoreCase(method)) {
            if (cmd.hasOption("atomMatch") || cmd.hasOption("bondMatch"))
                exitWithHelp("method fss does not support '-atomMatch' or '-bondMatch'", options);
            aligner = new FSSAlign(refmols, outputMol, rmsdTag, doOptimize, doMirror);

        } else {
            aligner = new McsAlign(refmols, outputMol, rmsdTag, doOptimize, doMirror, atomExpr, bondExpr,
                    quiet);
        }

        do {
            aligner.align(fitmol);
            oechem.OEWriteMolecule(ofs, fitmol);
        } while (oechem.OEReadMolecule(fitfs, fitmol));

    }

    fitmol.delete();
    if (aligner != null)
        aligner.close();
    for (OEMolBase mol : refmols)
        mol.delete();
    fitfs.close();
    ofs.close();
}

From source file:gov.nasa.jpl.memex.pooledtimeseries.PoT.java

public static void main(String[] args) {
      System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
      Option fileOpt = OptionBuilder.withArgName("file").hasArg().withLongOpt("file")
              .withDescription("Path to a single file").create('f');

      Option dirOpt = OptionBuilder.withArgName("directory").hasArg().withLongOpt("dir")
              .withDescription("A directory with image files in it").create('d');

      Option helpOpt = OptionBuilder.withLongOpt("help").withDescription("Print this message.").create('h');

      Option pathFileOpt = OptionBuilder.withArgName("path file").hasArg().withLongOpt("pathfile")
              .withDescription(/*from   w w  w.j a va2  s .  c om*/
                      "A file containing full absolute paths to videos. Previous default was memex-index_temp.txt")
              .create('p');

      Option outputFileOpt = OptionBuilder.withArgName("output file").withLongOpt("outputfile").hasArg()
              .withDescription("File containing similarity results. Defaults to ./similarity.txt").create('o');

      Option jsonOutputFlag = OptionBuilder.withArgName("json output").withLongOpt("json")
              .withDescription("Set similarity output format to JSON. Defaults to .txt").create('j');

      Option similarityFromFeatureVectorsOpt = OptionBuilder
              .withArgName("similarity from FeatureVectors directory")
              .withLongOpt("similarityFromFeatureVectorsDirectory").hasArg()
              .withDescription("calculate similarity matrix from given directory of feature vectors").create('s');

      Options options = new Options();
      options.addOption(dirOpt);
      options.addOption(pathFileOpt);
      options.addOption(fileOpt);
      options.addOption(helpOpt);
      options.addOption(outputFileOpt);
      options.addOption(jsonOutputFlag);
      options.addOption(similarityFromFeatureVectorsOpt);

      // create the parser
      CommandLineParser parser = new GnuParser();

      try {
          // parse the command line arguments
          CommandLine line = parser.parse(options, args);
          String directoryPath = null;
          String pathFile = null;
          String singleFilePath = null;
          String similarityFromFeatureVectorsDirectory = null;
          ArrayList<Path> videoFiles = null;

          if (line.hasOption("dir")) {
              directoryPath = line.getOptionValue("dir");
          }

          if (line.hasOption("pathfile")) {
              pathFile = line.getOptionValue("pathfile");
          }

          if (line.hasOption("file")) {
              singleFilePath = line.getOptionValue("file");
          }

          if (line.hasOption("outputfile")) {
              outputFile = line.getOptionValue("outputfile");
          }

          if (line.hasOption("json")) {
              outputFormat = OUTPUT_FORMATS.JSON;
          }

          if (line.hasOption("similarityFromFeatureVectorsDirectory")) {
              similarityFromFeatureVectorsDirectory = line
                      .getOptionValue("similarityFromFeatureVectorsDirectory");
          }

          if (line.hasOption("help")
                  || (line.getOptions() == null || (line.getOptions() != null && line.getOptions().length == 0))
                  || (directoryPath != null && pathFile != null && !directoryPath.equals("")
                          && !pathFile.equals(""))) {
              HelpFormatter formatter = new HelpFormatter();
              formatter.printHelp("pooled_time_series", options);
              System.exit(1);
          }

          if (directoryPath != null) {
              File dir = new File(directoryPath);
              List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE,
                      TrueFileFilter.INSTANCE);
              videoFiles = new ArrayList<Path>(files.size());

              for (File file : files) {
                  String filePath = file.toString();

                  // When given a directory to load videos from we need to ensure that we
                  // don't try to load the of.txt and hog.txt intermediate result files
                  // that results from previous processing runs.
                  if (!filePath.contains(".txt")) {
                      videoFiles.add(file.toPath());
                  }
              }

              LOG.info("Added " + videoFiles.size() + " video files from " + directoryPath);

          }

          if (pathFile != null) {
              Path list_file = Paths.get(pathFile);
              videoFiles = loadFiles(list_file);
              LOG.info("Loaded " + videoFiles.size() + " video files from " + pathFile);
          }

          if (singleFilePath != null) {
              Path singleFile = Paths.get(singleFilePath);
              LOG.info("Loaded file: " + singleFile);
              videoFiles = new ArrayList<Path>(1);
              videoFiles.add(singleFile);
          }

          if (similarityFromFeatureVectorsDirectory != null) {
              File dir = new File(similarityFromFeatureVectorsDirectory);
              List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE,
                      TrueFileFilter.INSTANCE);
              videoFiles = new ArrayList<Path>(files.size());

              for (File file : files) {
                  String filePath = file.toString();

                  // We need to load only the *.of.txt and *.hog.txt values
                  if (filePath.endsWith(".of.txt")) {
                      videoFiles.add(file.toPath());
                  }

                  if (filePath.endsWith(".hog.txt")) {
                      videoFiles.add(file.toPath());
                  }
              }

              LOG.info("Added " + videoFiles.size() + " feature vectors from "
                      + similarityFromFeatureVectorsDirectory);
              evaluateSimilarity(videoFiles, 1);
          } else {
              evaluateSimilarity(videoFiles, 1);
          }
          LOG.info("done.");

      } catch (ParseException exp) {
          // oops, something went wrong
          System.err.println("Parsing failed.  Reason: " + exp.getMessage());
      }

  }

From source file:io.compgen.cgpipe.CGPipe.java

public static void main(String[] args) {
    String fname = null;//from   ww  w  .  j  a va  2s.  c  om
    String logFilename = null;
    String outputFilename = null;
    PrintStream outputStream = null;

    int verbosity = 0;
    boolean silent = false;
    boolean dryrun = false;
    boolean silenceStdErr = false;
    boolean showHelp = false;

    List<String> targets = new ArrayList<String>();
    Map<String, VarValue> confVals = new HashMap<String, VarValue>();

    String k = null;

    for (int i = 0; i < args.length; i++) {
        String arg = args[i];
        if (i == 0) {
            if (new File(arg).exists()) {
                fname = arg;
                silenceStdErr = true;
                continue;
            }
        } else if (args[i - 1].equals("-f")) {
            fname = arg;
            continue;
        } else if (args[i - 1].equals("-l")) {
            logFilename = arg;
            continue;
        } else if (args[i - 1].equals("-o")) {
            outputFilename = arg;
            continue;
        }

        if (arg.equals("-h") || arg.equals("-help") || arg.equals("--help")) {
            if (k != null) {
                if (k.contains("-")) {
                    k = k.replaceAll("-", "_");
                }
                confVals.put(k, VarBool.TRUE);
            }
            showHelp = true;
        } else if (arg.equals("-license")) {
            license();
            System.exit(1);
        } else if (arg.equals("-s")) {
            if (k != null) {
                if (k.contains("-")) {
                    k = k.replaceAll("-", "_");
                }
                confVals.put(k, VarBool.TRUE);
            }
            silent = true;
        } else if (arg.equals("-nolog")) {
            if (k != null) {
                if (k.contains("-")) {
                    k = k.replaceAll("-", "_");
                }
                confVals.put(k, VarBool.TRUE);
            }
            silenceStdErr = true;
        } else if (arg.equals("-v")) {
            if (k != null) {
                if (k.contains("-")) {
                    k = k.replaceAll("-", "_");
                }
                confVals.put(k, VarBool.TRUE);
            }
            verbosity++;
        } else if (arg.equals("-vv")) {
            if (k != null) {
                if (k.contains("-")) {
                    k = k.replaceAll("-", "_");
                }
                confVals.put(k, VarBool.TRUE);
            }
            verbosity += 2;
        } else if (arg.equals("-vvv")) {
            if (k != null) {
                if (k.contains("-")) {
                    k = k.replaceAll("-", "_");
                }
                confVals.put(k, VarBool.TRUE);
            }
            verbosity += 3;
        } else if (arg.equals("-dr")) {
            if (k != null) {
                if (k.contains("-")) {
                    k = k.replaceAll("-", "_");
                }
                confVals.put(k, VarBool.TRUE);
            }
            dryrun = true;
        } else if (arg.startsWith("--")) {
            if (k != null) {
                if (k.contains("-")) {
                    k = k.replaceAll("-", "_");
                }
                confVals.put(k, VarBool.TRUE);
            }
            k = arg.substring(2);
        } else if (k != null) {
            if (k.contains("-")) {
                k = k.replaceAll("-", "_");
            }
            if (confVals.containsKey(k)) {
                try {
                    VarValue val = confVals.get(k);
                    if (val.getClass().equals(VarList.class)) {
                        ((VarList) val).add(VarValue.parseStringRaw(arg));
                    } else {
                        VarList list = new VarList();
                        list.add(val);
                        list.add(VarValue.parseStringRaw(arg));
                        confVals.put(k, list);
                    }
                } catch (VarTypeException e) {
                    System.err.println("Error setting variable: " + k + " => " + arg);
                    System.exit(1);
                    ;
                }
            } else {
                confVals.put(k, VarValue.parseStringRaw(arg));
            }
            k = null;
        } else if (arg.charAt(0) != '-') {
            targets.add(arg);
        }
    }
    if (k != null) {
        if (k.contains("-")) {
            k = k.replaceAll("-", "_");
        }
        confVals.put(k, VarBool.TRUE);
    }

    confVals.put("cgpipe.loglevel", new VarInt(verbosity));

    if (fname == null) {
        usage();
        System.exit(1);
    }

    if (!showHelp) {
        switch (verbosity) {
        case 0:
            SimpleFileLoggerImpl.setLevel(Level.INFO);
            break;
        case 1:
            SimpleFileLoggerImpl.setLevel(Level.DEBUG);
            break;
        case 2:
            SimpleFileLoggerImpl.setLevel(Level.TRACE);
            break;
        case 3:
        default:
            SimpleFileLoggerImpl.setLevel(Level.ALL);
            break;
        }
    } else {
        SimpleFileLoggerImpl.setLevel(Level.FATAL);
    }

    SimpleFileLoggerImpl.setSilent(silenceStdErr || showHelp);

    Log log = LogFactory.getLog(CGPipe.class);
    log.info("Starting new run: " + fname);

    if (logFilename != null) {
        confVals.put("cgpipe.log", new VarString(logFilename));
    }

    if (System.getenv("CGPIPE_DRYRUN") != null && !System.getenv("CGPIPE_DRYRUN").equals("")) {
        dryrun = true;
    }

    JobRunner runner = null;
    try {
        // Load config values from global config. 
        RootContext root = new RootContext();
        loadInitFiles(root);

        // Load settings from environment variables.
        root.loadEnvironment();

        // Set cmd-line arguments
        if (silent) {
            root.setOutputStream(null);
        }

        if (outputFilename != null) {
            outputStream = new PrintStream(new FileOutputStream(outputFilename));
            root.setOutputStream(outputStream);
        }

        for (String k1 : confVals.keySet()) {
            log.info("config: " + k1 + " => " + confVals.get(k1).toString());
        }

        root.update(confVals);
        root.set("cgpipe.procs", new VarInt(Runtime.getRuntime().availableProcessors()));

        // update the URL Source loader configs
        SourceLoader.updateRemoteHandlers(root.cloneString("cgpipe.remote"));

        // Now check for help, only after we've setup the remote handlers...
        if (showHelp) {
            try {
                Parser.showHelp(fname);
                System.exit(0);
            } catch (IOException e) {
                System.err.println("Unable to find pipeline: " + fname);
                System.exit(1);
            }
        }

        // Set the global config values
        //         globalConfig.putAll(root.cloneValues());

        // Parse the AST and run it
        Parser.exec(fname, root);

        // Load the job runner *after* we execute the script to capture any config changes
        runner = JobRunner.load(root, dryrun);

        // find a build-target, and submit the job(s) to a runner
        if (targets.size() > 0) {
            for (String target : targets) {
                log.debug("building: " + target);

                BuildTarget initTarget = root.build(target);
                if (initTarget != null) {
                    runner.submitAll(initTarget, root);
                } else {
                    System.out.println("CGPIPE ERROR: Unable to find target: " + target);
                }
            }
        } else {
            BuildTarget initTarget = root.build();
            if (initTarget != null) {
                runner.submitAll(initTarget, root);
                // Leave this commented out - it should be allowed to run cgpipe scripts w/o a target defined (testing)
                //            } else {
                //               System.out.println("CGPIPE ERROR: Unable to find default target");
            }
        }
        runner.done();

        if (outputStream != null) {
            outputStream.close();
        }

    } catch (ASTParseException | ASTExecException | RunnerException | FileNotFoundException e) {
        if (outputStream != null) {
            outputStream.close();
        }
        if (runner != null) {
            runner.abort();
        }

        if (e.getClass().equals(ExitException.class)) {
            System.exit(((ExitException) e).getReturnCode());
        }

        System.out.println("CGPIPE ERROR " + e.getMessage());
        if (verbosity > 0) {
            e.printStackTrace();
        }
        System.exit(1);
    }
}