Example usage for java.util Map get

List of usage examples for java.util Map get

Introduction

In this page you can find the example usage for java.util Map get.

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:de.citec.sc.matoll.process.Matoll_CreateMax.java

public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException,
        InstantiationException, IllegalAccessException, ClassNotFoundException, Exception {

    String directory;/*  ww  w. j  a va  2  s  .  c  o  m*/
    String gold_standard_lexicon;
    String output_lexicon;
    String configFile;
    Language language;
    String output;

    Stopwords stopwords = new Stopwords();

    HashMap<String, Double> maxima;
    maxima = new HashMap<String, Double>();

    if (args.length < 3) {
        System.out.print("Usage: Matoll --mode=train/test <DIRECTORY> <CONFIG>\n");
        return;

    }

    //      Classifier classifier;

    directory = args[1];
    configFile = args[2];

    final Config config = new Config();

    config.loadFromFile(configFile);

    gold_standard_lexicon = config.getGoldStandardLexicon();

    String model_file = config.getModel();

    output_lexicon = config.getOutputLexicon();
    output = config.getOutput();

    language = config.getLanguage();

    LexiconLoader loader = new LexiconLoader();
    Lexicon gold = loader.loadFromFile(gold_standard_lexicon);

    Set<String> uris = new HashSet<>();
    //        Map<Integer,String> sentence_list = new HashMap<>();
    Map<Integer, Set<Integer>> mapping_words_sentences = new HashMap<>();

    //consider only properties
    for (LexicalEntry entry : gold.getEntries()) {
        try {
            for (Sense sense : entry.getSenseBehaviours().keySet()) {
                String tmp_uri = sense.getReference().getURI().replace("http://dbpedia.org/ontology/", "");
                if (!Character.isUpperCase(tmp_uri.charAt(0))) {
                    uris.add(sense.getReference().getURI());
                }
            }
        } catch (Exception e) {
        }
        ;
    }

    ModelPreprocessor preprocessor = new ModelPreprocessor(language);
    preprocessor.setCoreferenceResolution(false);
    Set<String> dep = new HashSet<>();
    dep.add("prep");
    dep.add("appos");
    dep.add("nn");
    dep.add("dobj");
    dep.add("pobj");
    dep.add("num");
    preprocessor.setDEP(dep);

    List<File> list_files = new ArrayList<>();

    if (config.getFiles().isEmpty()) {
        File folder = new File(directory);
        File[] files = folder.listFiles();
        for (File file : files) {
            if (file.toString().contains(".ttl"))
                list_files.add(file);
        }
    } else {
        list_files.addAll(config.getFiles());
    }
    System.out.println(list_files.size());

    int sentence_counter = 0;
    Map<String, Set<Integer>> bag_words_uri = new HashMap<>();
    Map<String, Integer> mapping_word_id = new HashMap<>();
    for (File file : list_files) {
        Model model = RDFDataMgr.loadModel(file.toString());
        for (Model sentence : getSentences(model)) {
            String reference = getReference(sentence);
            reference = reference.replace("http://dbpedia/", "http://dbpedia.org/");
            if (uris.contains(reference)) {
                sentence_counter += 1;
                Set<Integer> words_ids = getBagOfWords(sentence, stopwords, mapping_word_id);
                //TODO: add sentence preprocessing
                String obj = getObject(sentence);
                String subj = getSubject(sentence);
                preprocessor.preprocess(sentence, subj, obj, language);
                //TODO: also return marker if object or subject of property (in SPARQL this has to be optional of course)
                String parsed_sentence = getParsedSentence(sentence);
                try (FileWriter fw = new FileWriter("mapping_sentences_to_ids_goldstandard.tsv", true);
                        BufferedWriter bw = new BufferedWriter(fw);
                        PrintWriter out = new PrintWriter(bw)) {
                    out.println(sentence_counter + "\t" + parsed_sentence);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                for (Integer word_id : words_ids) {
                    if (mapping_words_sentences.containsKey(word_id)) {
                        Set<Integer> tmp_set = mapping_words_sentences.get(word_id);
                        tmp_set.add(sentence_counter);
                        mapping_words_sentences.put(word_id, tmp_set);

                    } else {
                        Set<Integer> tmp_set = new HashSet<>();
                        tmp_set.add(sentence_counter);
                        mapping_words_sentences.put(word_id, tmp_set);
                    }

                }
                if (bag_words_uri.containsKey(reference)) {
                    Set<Integer> tmp = bag_words_uri.get(reference);
                    for (Integer w : words_ids) {
                        tmp.add(w);

                    }
                    bag_words_uri.put(reference, tmp);
                } else {
                    Set<Integer> tmp = new HashSet<>();
                    for (Integer w : words_ids) {
                        tmp.add(w);
                    }
                    bag_words_uri.put(reference, tmp);
                }
            }

        }
        model.close();

    }

    PrintWriter writer = new PrintWriter("bag_of_words_only_goldstandard.tsv");
    StringBuilder string_builder = new StringBuilder();
    for (String r : bag_words_uri.keySet()) {
        string_builder.append(r);
        for (Integer i : bag_words_uri.get(r)) {
            string_builder.append("\t");
            string_builder.append(i);
        }
        string_builder.append("\n");
    }
    writer.write(string_builder.toString());
    writer.close();

    writer = new PrintWriter("mapping_words_to_sentenceids_goldstandard.tsv");
    string_builder = new StringBuilder();
    for (Integer w : mapping_words_sentences.keySet()) {
        string_builder.append(w);
        for (int i : mapping_words_sentences.get(w)) {
            string_builder.append("\t");
            string_builder.append(i);
        }
        string_builder.append("\n");
    }
    writer.write(string_builder.toString());
    writer.close();

}

From source file:edu.msu.cme.rdp.alignment.errorcheck.CompareErrorType.java

public static void main(String[] args) throws IOException {
    Options options = new Options();
    options.addOption("s", "stem", true, "Output stem (default <query_nucl.fasta>)");

    final SeqReader queryReader;
    final List<Sequence> refSeqList;
    final PrintStream alignOutStream;
    final CompareErrorType errorProcessor;
    Sequence seq;//from w w  w  .  ja v a2 s. c om
    Map<String, PAObject> matchMap = new HashMap();

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

        String stem;

        args = line.getArgs();
        if (args.length != 2 && args.length != 3) {
            throw new Exception("Unexpected number of arguments");
        }

        File refFile = new File(args[0]);
        File queryFile = new File(args[1]);

        if (line.hasOption("stem")) {
            stem = line.getOptionValue("stem");
        } else {
            stem = queryFile.getName();
        }

        File alignOutFile = new File(stem + "_alignments.txt");
        File mismatchOutFile = new File(stem + "_mismatches.txt");
        File indelOutFile = new File(stem + "_indels.txt");
        File qualOutFile = null;

        refSeqList = SequenceReader.readFully(refFile);
        if (args.length == 3) {
            queryReader = new QSeqReader(queryFile, new File(args[2]));
        } else {
            queryReader = new SequenceReader(queryFile);
        }

        seq = queryReader.readNextSequence();
        if (seq instanceof QSequence) {
            qualOutFile = new File(stem + "_qual.txt");
        }

        errorProcessor = new CompareErrorType(mismatchOutFile, indelOutFile, qualOutFile);
        alignOutStream = new PrintStream(alignOutFile);

        System.err.println("Starting CompareErrorType");
        System.err.println("*  Time:              " + new Date());
        System.err.println("*  Reference File:    " + refFile);
        System.err.println("*  Query File:        " + queryFile);
        if (args.length == 3) {
            System.err.println("*  Qual File:         " + args[2]);
        }
        System.err.println("*  Query format:      " + queryReader.getFormat());
        System.err.println("*  Alignment Output:  " + alignOutFile);
        System.err.println("*  Mismatches Output: " + mismatchOutFile);
        System.err.println("*  Alignment Output:  " + indelOutFile);
        if (qualOutFile != null) {
            System.err.println("*  Quality Output:    " + qualOutFile);
        }

    } catch (Exception e) {
        new HelpFormatter().printHelp(
                "CompareErrorType [options] <ref_nucl> (<query_nucl> | <query_nucl.fasta> <query_nucl.qual>)",
                options);
        System.err.println("ERROR: " + e.getMessage());
        throw new RuntimeException(e);
        //System.exit(1);
        //return;
    }

    //ScoringMatrix scoringMatrix = ScoringMatrix.getDefaultNuclMatrix();
    // use a simple scoring function, match score 0, mismatch -1, gap opening -1, gap extension -1.
    ScoringMatrix scoringMatrix = new ScoringMatrix(
            ScoringMatrix.class.getResourceAsStream("/data/simple_scoringmatrix.txt"), -1, -1);

    do {
        try {
            PairwiseAlignment bestResult = null;
            Sequence bestSeq = null;
            boolean bestReversed = false;
            String querySeqStr = seq.getSeqString().toLowerCase();
            String reversedQuery = IUBUtilities.reverseComplement(querySeqStr);
            PAObject bestMatch = null;

            //checking if sequence has been seen before
            if (matchMap.containsKey(seq.getSeqString())) {
                bestMatch = matchMap.get(seq.getSeqString());
            } else {
                for (Sequence refSeq : refSeqList) {
                    String refSeqStr = refSeq.getSeqString().toLowerCase();
                    PairwiseAlignment result = PairwiseAligner.align(refSeqStr, querySeqStr, scoringMatrix,
                            AlignmentMode.global);
                    PairwiseAlignment reversedResult = PairwiseAligner.align(refSeqStr,
                            IUBUtilities.reverseComplement(querySeqStr), scoringMatrix, AlignmentMode.global);

                    PairwiseAlignment currBest = (result.getScore() > reversedResult.getScore()) ? result
                            : reversedResult;

                    if (bestResult == null || currBest.getScore() > bestResult.getScore()) {
                        bestResult = currBest;
                        bestSeq = refSeq;
                        if (currBest == reversedResult) {
                            bestReversed = true;
                        } else {
                            bestReversed = false;
                        }

                    }

                    //Since this is a new sequence, make a new PAObject to put into the map to compare against later
                    bestMatch = new PAObject(bestResult, bestReversed, bestSeq);
                    matchMap.put(seq.getSeqString(), bestMatch);
                }
            }
            int refStart = bestMatch.getPA().getStarti();
            int refEnd = bestMatch.getPA().getEndi();
            bestSeq = bestMatch.getRefSeq();
            bestReversed = bestMatch.getReversed();
            bestResult = bestMatch.getPA();

            //output information
            alignOutStream.println(">\t" + seq.getSeqName() + "\t" + bestSeq.getSeqName() + "\t"
                    + seq.getSeqString().length() + "\t" + refStart + "\t" + refEnd + "\t"
                    + bestResult.getScore() + "\t" + ((bestReversed) ? "\treversed" : ""));
            alignOutStream.println(bestResult.getAlignedSeqj() + "\n");
            alignOutStream.println(bestResult.getAlignedSeqi() + "\n");

            //seqi is reference seq, seqj is the refseq
            errorProcessor.processSequence(seq, bestResult.getAlignedSeqj(), bestSeq.getSeqName(),
                    bestResult.getAlignedSeqi(), refStart, bestReversed);

        } catch (Exception e) {
            throw new RuntimeException("Failed while processing seq " + seq.getSeqName(), e);
        }
    } while ((seq = queryReader.readNextSequence()) != null);
    queryReader.close();
    alignOutStream.close();
    errorProcessor.close();
}

From source file:org.ptm.translater.App.java

public static void main(String... args) {
    GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
    ctx.load("file:src/main/resources/spring/datasource.xml");
    ctx.refresh();//ww  w  .  jav  a2 s  . c  om

    GenericXmlApplicationContext ctx2 = new GenericXmlApplicationContext();
    ctx2.load("file:src/main/resources/spring/datasource2.xml");
    ctx2.refresh();

    ArchiveDao archiveDao = ctx.getBean("archiveDao", ArchiveDao.class);
    List<Archive> archives = archiveDao.findAll();

    UserDao userDao = ctx2.getBean("userDao", UserDao.class);
    TagDao tagDao = ctx2.getBean("tagDao", TagDao.class);
    PhotoDao photoDao = ctx2.getBean("photoDao", PhotoDao.class);

    List<Tag> tagz = tagDao.findAll();
    Map<String, Long> hashTags = new HashMap<String, Long>();
    for (Tag tag : tagz)
        hashTags.put(tag.getName(), tag.getId());

    MongoCache cache = new MongoCache();
    Calendar calendar = Calendar.getInstance();

    Map<String, String> associates = new HashMap<String, String>();

    for (Archive archive : archives) {
        AppUser appUser = new AppUser();
        appUser.setName(archive.getName());
        appUser.setEmail(archive.getUid() + "@mail.th");
        appUser.setPassword("123456");

        Role role = new Role();
        role.setRoleId("ROLE_USER");
        appUser.setRole(role);

        userDao.save(appUser);
        System.out.println("\tCreate user " + appUser);

        for (Photo photo : archive.getPhotos()) {
            // ?  ??? 
            if (cache.contains(photo.getUid()))
                continue;

            System.out.println("\tNew photo");
            org.ptm.translater.ch2.domain.Photo photo2 = new org.ptm.translater.ch2.domain.Photo();
            photo2.setAppUser(appUser);
            photo2.setName(photo.getTitle());
            photo2.setLicense((byte) 7);
            photo2.setDescription(photo.getDescription());

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                calendar.setTime(sdf.parse(photo.getTaken()));

                if (calendar.get(Calendar.YEAR) != 0 && calendar.get(Calendar.YEAR) > 1998)
                    continue;
                photo2.setYear(calendar.get(Calendar.YEAR));
                photo2.setMonth(calendar.get(Calendar.MONTH) + 1);
                photo2.setDay(calendar.get(Calendar.DAY_OF_MONTH));
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            if (photo.getLongitude() != null && photo.getLongitude().length() > 0) {
                //                    String key = photo.getLongitude()+"#"+photo.getLatitude();
                photo2.setLatitude(photo.getLatitude());
                photo2.setLongitude(photo.getLongitude());
                //                    if (associates.containsKey(key)) {
                //                        photo2.setAddress(associates.get(key));
                //                    } else {
                //                        Geocoder geocoder = new Geocoder();
                //                        GeocoderRequestBuilder geocoderRequest = new GeocoderRequestBuilder();
                //                        GeocoderRequest request =
                //                            geocoderRequest.setLocation(new LatLng(photo.getLongitude(), photo.getLatitude())).getGeocoderRequest();
                //
                //                        GeocodeResponse response = geocoder.geocode(request);
                //                        if (response.getResults().size() > 0) {
                //                            photo2.setAddress(response.getResults().get(0).getFormattedAddress());
                //                        }
                //                        try { Thread.sleep(2000); } catch (InterruptedException ex) { ex.printStackTrace(); }
                //                    }
            }

            System.out.println("\tFind tags");
            Set<Tag> tags = new HashSet<Tag>();
            for (org.ptm.translater.ch1.domain.Tag tag : photo.getTags()) {
                Tag item = new Tag();
                item.setName(tag.getName());
                if (hashTags.containsKey(tag.getName())) {
                    item.setId(hashTags.get(tag.getName()));
                } else {
                    tagDao.save(item);
                    hashTags.put(item.getName(), item.getId());
                }
                System.out.println("\t\tinit tag " + tag.getName());
                tags.add(item);
            }
            photo2.setTags(tags);
            System.out.println("\tFind " + tags.size() + " tags");
            photoDao.save(photo2);
            System.out.println("\tSave photo");

            Imaginator img = new Imaginator();
            img.setFolder(photo2.getId().toString());
            img.setPath();

            for (PhotoSize ps : photo.getSizes()) {
                if (ps.getLabel().equals("Original")) {
                    img.setImage(ps.getSource());
                    break;
                }
            }
            img.generate();
            System.out.println("\tGenerate image of photo");
            img = null;
            cache.create(photo.getUid());
            cache.create(photo2);

            System.out.println("Generate: " + photo2);
        }
    }
}

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

public static void main(String[] args) {
    String fname = null;/*from  w w  w . j av a2s. co  m*/
    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);
    }
}

From source file:FaceRatios.java

@SuppressWarnings("serial")
public static void main(String[] args) {
    int r = FSDK.ActivateLibrary(FACE_SDK_LICENSE);
    if (r == FSDK.FSDKE_OK) {
        FSDK.Initialize();/*from   w  w  w. j  a v a  2 s.  c o  m*/
        FSDK.SetFaceDetectionParameters(true, true, 384);

        Map<String, Map<String, ArrayList<Double>>> faceProperties = new HashMap<>();

        for (String directory : new File(FACE_DIRECTORY).list()) {
            if (new File(FACE_DIRECTORY + directory).isDirectory()) {
                Map<String, ArrayList<Double>> properties = new HashMap<String, ArrayList<Double>>() {
                    {
                        for (String property : propertyNames)
                            put(property, new ArrayList<Double>());
                    }
                };

                File[] files = new File(FACE_DIRECTORY + directory).listFiles();
                System.out.println("Analyzing " + directory + " with " + files.length + " files\n");
                for (File file : files) {
                    if (file.isFile()) {
                        HImage imageHandle = new HImage();
                        FSDK.LoadImageFromFileW(imageHandle, file.getAbsolutePath());

                        FSDK.TFacePosition.ByReference facePosition = new FSDK.TFacePosition.ByReference();
                        if (FSDK.DetectFace(imageHandle, facePosition) == FSDK.FSDKE_OK) {
                            FSDK_Features.ByReference facialFeatures = new FSDK_Features.ByReference();
                            FSDK.DetectFacialFeaturesInRegion(imageHandle, (FSDK.TFacePosition) facePosition,
                                    facialFeatures);

                            Point[] featurePoints = new Point[FSDK.FSDK_FACIAL_FEATURE_COUNT];
                            for (int i = 0; i < FSDK.FSDK_FACIAL_FEATURE_COUNT; i++) {
                                featurePoints[i] = new Point(0, 0);
                                featurePoints[i].x = facialFeatures.features[i].x;
                                featurePoints[i].y = facialFeatures.features[i].y;
                            }

                            double eyeDistance = featureDistance(featurePoints, FeatureID.LEFT_EYE,
                                    FeatureID.RIGHT_EYE);
                            double rightEyeSize = featureDistance(featurePoints,
                                    FeatureID.RIGHT_EYE_INNER_CORNER, FeatureID.RIGHT_EYE_OUTER_CORNER);
                            double leftEyeSize = featureDistance(featurePoints, FeatureID.LEFT_EYE_INNER_CORNER,
                                    FeatureID.LEFT_EYE_OUTER_CORNER);
                            double averageEyeSize = (rightEyeSize + leftEyeSize) / 2;

                            double mouthLength = featureDistance(featurePoints, FeatureID.MOUTH_RIGHT_CORNER,
                                    FeatureID.MOUTH_LEFT_CORNER);
                            double mouthHeight = featureDistance(featurePoints, FeatureID.MOUTH_BOTTOM,
                                    FeatureID.MOUTH_TOP);
                            double noseHeight = featureDistance(featurePoints, FeatureID.NOSE_BOTTOM,
                                    FeatureID.NOSE_BRIDGE);
                            double chinHeight = featureDistance(featurePoints, FeatureID.CHIN_BOTTOM,
                                    FeatureID.MOUTH_BOTTOM);

                            double chinToBridgeHeight = featureDistance(featurePoints, FeatureID.CHIN_BOTTOM,
                                    FeatureID.NOSE_BRIDGE);

                            double faceContourLeft = (featurePoints[FeatureID.CHIN_BOTTOM.getIndex()].getY()
                                    - featurePoints[FeatureID.FACE_CONTOUR2.getIndex()].getY())
                                    / (featurePoints[FeatureID.CHIN_BOTTOM.getIndex()].getX()
                                            - featurePoints[FeatureID.FACE_CONTOUR2.getIndex()].getX());
                            double faceContourRight = (featurePoints[FeatureID.CHIN_BOTTOM.getIndex()].getY()
                                    - featurePoints[FeatureID.FACE_CONTOUR12.getIndex()].getY())
                                    / (featurePoints[FeatureID.CHIN_BOTTOM.getIndex()].getX()
                                            - featurePoints[FeatureID.FACE_CONTOUR12.getIndex()].getX());

                            double bridgeLeftEyeDistance = featureDistance(featurePoints,
                                    FeatureID.LEFT_EYE_INNER_CORNER, FeatureID.NOSE_BRIDGE);
                            double bridgeRightEyeDistance = featureDistance(featurePoints,
                                    FeatureID.RIGHT_EYE_INNER_CORNER, FeatureID.NOSE_BRIDGE);

                            properties.get("eyeSize/eyeDistance").add(averageEyeSize / eyeDistance);
                            properties.get("eyeSizeDisparity")
                                    .add(Math.abs(leftEyeSize - rightEyeSize) / averageEyeSize);
                            properties.get("bridgeToEyeDisparity")
                                    .add(Math.abs(bridgeLeftEyeDistance - bridgeRightEyeDistance)
                                            / ((bridgeLeftEyeDistance + bridgeRightEyeDistance) / 2));
                            properties.get("eyeDistance/mouthLength").add(eyeDistance / mouthLength);
                            properties.get("eyeDistance/noseHeight").add(eyeDistance / noseHeight);
                            properties.get("eyeSize/mouthLength").add(eyeDistance / mouthLength);
                            properties.get("eyeSize/noseHeight").add(eyeDistance / noseHeight);
                            properties.get("mouthLength/mouthHeight").add(mouthLength / mouthHeight);
                            properties.get("chinHeight/noseHeight").add(chinHeight / noseHeight);
                            properties.get("chinHeight/chinToBridgeHeight")
                                    .add(chinHeight / chinToBridgeHeight);
                            properties.get("noseHeight/chinToBridgeHeight")
                                    .add(noseHeight / chinToBridgeHeight);
                            properties.get("mouthHeight/chinToBridgeHeight")
                                    .add(mouthHeight / chinToBridgeHeight);
                            properties.get("faceCountourAngle")
                                    .add(Math.toDegrees(Math.atan((faceContourLeft - faceContourRight)
                                            / (1 + faceContourLeft * faceContourRight))));
                        }

                        FSDK.FreeImage(imageHandle);
                    }
                }

                System.out.format("%32s\t%8s\t%8s\t%3s%n", "Property", "", "", "c");
                System.out.println(new String(new char[76]).replace("\0", "-"));

                ArrayList<Entry<String, ArrayList<Double>>> propertyList = new ArrayList<>(
                        properties.entrySet());
                Collections.sort(propertyList, new Comparator<Entry<String, ArrayList<Double>>>() {
                    @Override
                    public int compare(Entry<String, ArrayList<Double>> arg0,
                            Entry<String, ArrayList<Double>> arg1) {
                        DescriptiveStatistics dStats0 = new DescriptiveStatistics(listToArray(arg0.getValue()));
                        DescriptiveStatistics dStats1 = new DescriptiveStatistics(listToArray(arg1.getValue()));
                        return new Double(dStats0.getStandardDeviation() / dStats0.getMean())
                                .compareTo(dStats1.getStandardDeviation() / dStats1.getMean());
                    }
                });

                for (Entry<String, ArrayList<Double>> property : propertyList) {
                    DescriptiveStatistics dStats = new DescriptiveStatistics(listToArray(property.getValue()));
                    System.out.format("%32s\t%4f\t%4f\t%3s%n", property.getKey(), dStats.getMean(),
                            dStats.getStandardDeviation(),
                            Math.round(dStats.getStandardDeviation() / dStats.getMean() * 100) + "%");
                }

                System.out.println("\n");
                faceProperties.put(directory, properties);
            }
        }

        for (String propertyName : propertyNames) {
            DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset();
            for (Entry<String, Map<String, ArrayList<Double>>> face : faceProperties.entrySet()) {
                dataset.add(face.getValue().get(propertyName), "Default Series", face.getKey());
            }

            PropertyBoxWhisker plot = new PropertyBoxWhisker(propertyName, dataset);
            plot.pack();
            plot.setVisible(true);
        }
    }
}

From source file:com.liferay.portal.tools.service.builder.ServiceBuilder.java

public static void main(String[] args) throws Exception {
    Map<String, String> arguments = ArgumentsUtil.parseArguments(args);

    String apiDirName = arguments.get("service.api.dir");
    boolean autoImportDefaultReferences = GetterUtil
            .getBoolean(arguments.get("service.auto.import.default.references"), true);
    boolean autoNamespaceTables = GetterUtil.getBoolean(arguments.get("service.auto.namespace.tables"));
    String beanLocatorUtil = arguments.get("service.bean.locator.util");
    long buildNumber = GetterUtil.getLong(arguments.get("service.build.number"), 1);
    boolean buildNumberIncrement = GetterUtil.getBoolean(arguments.get("service.build.number.increment"), true);
    String hbmFileName = arguments.get("service.hbm.file");
    String implDirName = arguments.get("service.impl.dir");
    String inputFileName = arguments.get("service.input.file");
    String[] modelHintsConfigs = StringUtil
            .split(GetterUtil.getString(arguments.get("service.model.hints.configs"),
                    StringUtil.merge(ServiceBuilderArgs.MODEL_HINTS_CONFIGS)));
    String modelHintsFileName = arguments.get("service.model.hints.file");
    boolean osgiModule = GetterUtil.getBoolean(arguments.get("service.osgi.module"));
    String pluginName = arguments.get("service.plugin.name");
    String propsUtil = arguments.get("service.props.util");
    String[] readOnlyPrefixes = StringUtil
            .split(GetterUtil.getString(arguments.get("service.read.only.prefixes"),
                    StringUtil.merge(ServiceBuilderArgs.READ_ONLY_PREFIXES)));
    String remotingFileName = arguments.get("service.remoting.file");
    String[] resourceActionsConfigs = StringUtil
            .split(GetterUtil.getString(arguments.get("service.resource.actions.configs"),
                    StringUtil.merge(ServiceBuilderArgs.RESOURCE_ACTION_CONFIGS)));
    String resourcesDirName = arguments.get("service.resources.dir");
    String springFileName = arguments.get("service.spring.file");
    String[] springNamespaces = StringUtil.split(arguments.get("service.spring.namespaces"));
    String sqlDirName = arguments.get("service.sql.dir");
    String sqlFileName = arguments.get("service.sql.file");
    String sqlIndexesFileName = arguments.get("service.sql.indexes.file");
    String sqlSequencesFileName = arguments.get("service.sql.sequences.file");
    String targetEntityName = arguments.get("service.target.entity.name");
    String testDirName = arguments.get("service.test.dir");

    Set<String> resourceActionModels = readResourceActionModels(implDirName, resourceActionsConfigs);

    ModelHintsUtil modelHintsUtil = new ModelHintsUtil();

    ModelHintsImpl modelHintsImpl = new ModelHintsImpl();

    modelHintsImpl.setModelHintsConfigs(modelHintsConfigs);

    modelHintsImpl.afterPropertiesSet();

    modelHintsUtil.setModelHints(modelHintsImpl);

    try {/*from   ww  w.  j  a  va2  s  .  co m*/
        ServiceBuilder serviceBuilder = new ServiceBuilder(apiDirName, autoImportDefaultReferences,
                autoNamespaceTables, beanLocatorUtil, buildNumber, buildNumberIncrement, hbmFileName,
                implDirName, inputFileName, modelHintsFileName, osgiModule, pluginName, propsUtil,
                readOnlyPrefixes, remotingFileName, resourceActionModels, resourcesDirName, springFileName,
                springNamespaces, sqlDirName, sqlFileName, sqlIndexesFileName, sqlSequencesFileName,
                targetEntityName, testDirName, true);

        String modifiedFileNames = StringUtil.merge(serviceBuilder.getModifiedFileNames());

        System.setProperty(ServiceBuilderArgs.OUTPUT_KEY_MODIFIED_FILES, modifiedFileNames);
    } catch (Throwable t) {
        String message = "Please set these arguments. Sample values are:\n" + "\n"
                + "\tservice.api.dir=${basedir}/../portal-service/src\n"
                + "\tservice.auto.import.default.references=true\n" + "\tservice.auto.namespace.tables=false\n"
                + "\tservice.bean.locator.util=com.liferay.portal.kernel.bean.PortalBeanLocatorUtil\n"
                + "\tservice.build.number=1\n" + "\tservice.build.number.increment=true\n"
                + "\tservice.hbm.file=${basedir}/src/META-INF/portal-hbm.xml\n"
                + "\tservice.impl.dir=${basedir}/src\n" + "\tservice.input.file=${service.file}\n"
                + "\tservice.model.hints.configs=" + StringUtil.merge(ServiceBuilderArgs.MODEL_HINTS_CONFIGS)
                + "\n" + "\tservice.model.hints.file=${basedir}/src/META-INF/portal-model-hints.xml\n"
                + "\tservice.osgi.module=false\n" + "\tservice.plugin.name=\n"
                + "\tservice.props.util=com.liferay.portal.util.PropsUtil\n" + "\tservice.read.only.prefixes="
                + StringUtil.merge(ServiceBuilderArgs.READ_ONLY_PREFIXES) + "\n"
                + "\tservice.remoting.file=${basedir}/../portal-web/docroot/WEB-INF/remoting-servlet.xml\n"
                + "\tservice.resource.actions.configs="
                + StringUtil.merge(ServiceBuilderArgs.RESOURCE_ACTION_CONFIGS) + "\n"
                + "\tservice.resources.dir=${basedir}/src\n"
                + "\tservice.spring.file=${basedir}/src/META-INF/portal-spring.xml\n"
                + "\tservice.spring.namespaces=beans\n" + "\tservice.sql.dir=${basedir}/../sql\n"
                + "\tservice.sql.file=portal-tables.sql\n" + "\tservice.sql.indexes.file=indexes.sql\n"
                + "\tservice.sql.sequences.file=sequences.sql\n"
                + "\tservice.target.entity.name=${service.target.entity.name}\n"
                + "\tservice.test.dir=${basedir}/test/integration\n" + "\n"
                + "You can also customize the generated code by overriding the default templates with these optional system properties:\n"
                + "\n" + "\t-Dservice.tpl.bad_alias_names=" + _TPL_ROOT + "bad_alias_names.txt\n"
                + "\t-Dservice.tpl.bad_column_names=" + _TPL_ROOT + "bad_column_names.txt\n"
                + "\t-Dservice.tpl.bad_json_types=" + _TPL_ROOT + "bad_json_types.txt\n"
                + "\t-Dservice.tpl.bad_table_names=" + _TPL_ROOT + "bad_table_names.txt\n"
                + "\t-Dservice.tpl.base_mode_impl=" + _TPL_ROOT + "base_mode_impl.ftl\n"
                + "\t-Dservice.tpl.blob_model=" + _TPL_ROOT + "blob_model.ftl\n"
                + "\t-Dservice.tpl.copyright.txt=copyright.txt\n" + "\t-Dservice.tpl.ejb_pk=" + _TPL_ROOT
                + "ejb_pk.ftl\n" + "\t-Dservice.tpl.exception=" + _TPL_ROOT + "exception.ftl\n"
                + "\t-Dservice.tpl.export_actionable_dynamic_query=" + _TPL_ROOT
                + "export_actionable_dynamic_query.ftl\n" + "\t-Dservice.tpl.extended_model=" + _TPL_ROOT
                + "extended_model.ftl\n" + "\t-Dservice.tpl.extended_model_base_impl=" + _TPL_ROOT
                + "extended_model_base_impl.ftl\n" + "\t-Dservice.tpl.extended_model_impl=" + _TPL_ROOT
                + "extended_model_impl.ftl\n" + "\t-Dservice.tpl.finder=" + _TPL_ROOT + "finder.ftl\n"
                + "\t-Dservice.tpl.finder_util=" + _TPL_ROOT + "finder_util.ftl\n" + "\t-Dservice.tpl.hbm_xml="
                + _TPL_ROOT + "hbm_xml.ftl\n" + "\t-Dservice.tpl.json_js=" + _TPL_ROOT + "json_js.ftl\n"
                + "\t-Dservice.tpl.json_js_method=" + _TPL_ROOT + "json_js_method.ftl\n"
                + "\t-Dservice.tpl.model=" + _TPL_ROOT + "model.ftl\n" + "\t-Dservice.tpl.model_cache="
                + _TPL_ROOT + "model_cache.ftl\n" + "\t-Dservice.tpl.model_hints_xml=" + _TPL_ROOT
                + "model_hints_xml.ftl\n" + "\t-Dservice.tpl.model_impl=" + _TPL_ROOT + "model_impl.ftl\n"
                + "\t-Dservice.tpl.model_soap=" + _TPL_ROOT + "model_soap.ftl\n"
                + "\t-Dservice.tpl.model_wrapper=" + _TPL_ROOT + "model_wrapper.ftl\n"
                + "\t-Dservice.tpl.persistence=" + _TPL_ROOT + "persistence.ftl\n"
                + "\t-Dservice.tpl.persistence_impl=" + _TPL_ROOT + "persistence_impl.ftl\n"
                + "\t-Dservice.tpl.persistence_util=" + _TPL_ROOT + "persistence_util.ftl\n"
                + "\t-Dservice.tpl.props=" + _TPL_ROOT + "props.ftl\n" + "\t-Dservice.tpl.remoting_xml="
                + _TPL_ROOT + "remoting_xml.ftl\n" + "\t-Dservice.tpl.service=" + _TPL_ROOT + "service.ftl\n"
                + "\t-Dservice.tpl.service_base_impl=" + _TPL_ROOT + "service_base_impl.ftl\n"
                + "\t-Dservice.tpl.service_clp=" + _TPL_ROOT + "service_clp.ftl\n"
                + "\t-Dservice.tpl.service_clp_invoker=" + _TPL_ROOT + "service_clp_invoker.ftl\n"
                + "\t-Dservice.tpl.service_clp_message_listener=" + _TPL_ROOT
                + "service_clp_message_listener.ftl\n" + "\t-Dservice.tpl.service_clp_serializer=" + _TPL_ROOT
                + "service_clp_serializer.ftl\n" + "\t-Dservice.tpl.service_http=" + _TPL_ROOT
                + "service_http.ftl\n" + "\t-Dservice.tpl.service_impl=" + _TPL_ROOT + "service_impl.ftl\n"
                + "\t-Dservice.tpl.service_props_util=" + _TPL_ROOT + "service_props_util.ftl\n"
                + "\t-Dservice.tpl.service_soap=" + _TPL_ROOT + "service_soap.ftl\n"
                + "\t-Dservice.tpl.service_util=" + _TPL_ROOT + "service_util.ftl\n"
                + "\t-Dservice.tpl.service_wrapper=" + _TPL_ROOT + "service_wrapper.ftl\n"
                + "\t-Dservice.tpl.spring_xml=" + _TPL_ROOT + "spring_xml.ftl\n"
                + "\t-Dservice.tpl.spring_xml_session=" + _TPL_ROOT + "spring_xml_session.ftl";

        if (t instanceof ServiceBuilderException) {
            ServiceBuilderException serviceBuilderException = (ServiceBuilderException) t;

            System.err.println(serviceBuilderException.getMessage());
        } else if (t instanceof Exception) {
            System.out.println(message);

            ArgumentsUtil.processMainException(arguments, (Exception) t);
        } else {
            t.printStackTrace();
        }
    }

    try {
        ClearThreadLocalUtil.clearThreadLocal();
    } catch (Throwable t) {
        t.printStackTrace();
    }

    Introspector.flushCaches();
}

From source file:com.moviejukebox.MovieJukebox.java

public static void main(String[] args) throws Throwable {
    JukeboxStatistics.setTimeStart(System.currentTimeMillis());

    // Create the log file name here, so we can change it later (because it's locked
    System.setProperty("file.name", LOG_FILENAME);
    PropertyConfigurator.configure("properties/log4j.properties");

    LOG.info("Yet Another Movie Jukebox {}", GitRepositoryState.getVersion());
    LOG.info("~~~ ~~~~~~~ ~~~~~ ~~~~~~~ {}", StringUtils.repeat("~", GitRepositoryState.getVersion().length()));
    LOG.info("https://github.com/YAMJ/yamj-v2");
    LOG.info("Copyright (c) 2004-2016 YAMJ Members");
    LOG.info("");
    LOG.info("This software is licensed under the GNU General Public License v3+");
    LOG.info("See this page: https://github.com/YAMJ/yamj-v2/wiki/License");
    LOG.info("");
    LOG.info(" Revision SHA: {} {}", GIT.getCommitId(), GIT.getDirty() ? "(Custom Build)" : "");
    LOG.info("  Commit Date: {}", GIT.getCommitTime());
    LOG.info("   Build Date: {}", GIT.getBuildTime());
    LOG.info("");
    LOG.info(" Java Version: {}", GitRepositoryState.getJavaVersion());
    LOG.info("");

    if (!SystemTools.validateInstallation()) {
        LOG.info("ABORTING.");
        return;/*from   w  w  w .  j av  a 2  s. com*/
    }

    String movieLibraryRoot = null;
    String jukeboxRoot = null;
    Map<String, String> cmdLineProps = new LinkedHashMap<>();

    try {
        for (int i = 0; i < args.length; i++) {
            String arg = args[i];
            if ("-v".equalsIgnoreCase(arg)) {
                // We've printed the version, so quit now
                return;
            } else if ("-t".equalsIgnoreCase(arg)) {
                String pin = args[++i];

                // load the apikeys.properties file
                if (!setPropertiesStreamName("./properties/apikeys.properties", Boolean.TRUE)) {
                    return;
                }

                // authorize to Trakt.TV
                TraktTV.getInstance().initialize().authorizeWithPin(pin);

                // We've authorized access to Trakt.TV, so quit now
                return;
            } else if ("-o".equalsIgnoreCase(arg)) {
                jukeboxRoot = args[++i];
                PropertiesUtil.setProperty("mjb.jukeboxRoot", jukeboxRoot);
            } else if ("-c".equalsIgnoreCase(arg)) {
                jukeboxClean = Boolean.TRUE;
                PropertiesUtil.setProperty("mjb.jukeboxClean", TRUE);
            } else if ("-k".equalsIgnoreCase(arg)) {
                setJukeboxPreserve(Boolean.TRUE);
            } else if ("-p".equalsIgnoreCase(arg)) {
                userPropertiesName = args[++i];
            } else if ("-i".equalsIgnoreCase(arg)) {
                skipIndexGeneration = Boolean.TRUE;
                PropertiesUtil.setProperty("mjb.skipIndexGeneration", TRUE);
            } else if ("-h".equalsIgnoreCase(arg)) {
                skipHtmlGeneration = Boolean.TRUE;
                PropertiesUtil.setProperty("mjb.skipHtmlGeneration", Boolean.TRUE);
            } else if ("-dump".equalsIgnoreCase(arg)) {
                dumpLibraryStructure = Boolean.TRUE;
            } else if ("-memory".equalsIgnoreCase(arg)) {
                showMemory = Boolean.TRUE;
                PropertiesUtil.setProperty("mjb.showMemory", Boolean.TRUE);
            } else if (arg.startsWith("-D")) {
                String propLine = arg.length() > 2 ? arg.substring(2) : args[++i];
                int propDiv = propLine.indexOf('=');
                if (-1 != propDiv) {
                    cmdLineProps.put(propLine.substring(0, propDiv), propLine.substring(propDiv + 1));
                }
            } else if (arg.startsWith("-")) {
                help();
                return;
            } else {
                movieLibraryRoot = args[i];
            }
        }
    } catch (Exception error) {
        LOG.error("Wrong arguments specified");
        help();
        return;
    }

    // Save the name of the properties file for use later
    setProperty("userPropertiesName", userPropertiesName);

    LOG.info("Processing started at {}", new Date());
    LOG.info("");

    // Load the moviejukebox-default.properties file
    if (!setPropertiesStreamName("./properties/moviejukebox-default.properties", Boolean.TRUE)) {
        return;
    }

    // Load the user properties file "moviejukebox.properties"
    // No need to abort if we don't find this file
    // Must be read before the skin, because this may contain an override skin
    setPropertiesStreamName(userPropertiesName, Boolean.FALSE);

    // Grab the skin from the command-line properties
    if (cmdLineProps.containsKey(SKIN_DIR)) {
        setProperty(SKIN_DIR, cmdLineProps.get(SKIN_DIR));
    }

    // Load the skin.properties file
    if (!setPropertiesStreamName(getProperty(SKIN_DIR, SKIN_DEFAULT) + "/skin.properties", Boolean.TRUE)) {
        return;
    }

    // Load the skin-user.properties file (ignore the error)
    setPropertiesStreamName(getProperty(SKIN_DIR, SKIN_DEFAULT) + "/skin-user.properties", Boolean.FALSE);

    // Load the overlay.properties file (ignore the error)
    String overlayRoot = getProperty("mjb.overlay.dir", Movie.UNKNOWN);
    overlayRoot = (PropertiesUtil.getBooleanProperty("mjb.overlay.skinroot", Boolean.TRUE)
            ? (getProperty(SKIN_DIR, SKIN_DEFAULT) + File.separator)
            : "") + (StringTools.isValidString(overlayRoot) ? (overlayRoot + File.separator) : "");
    setPropertiesStreamName(overlayRoot + "overlay.properties", Boolean.FALSE);

    // Load the apikeys.properties file
    if (!setPropertiesStreamName("./properties/apikeys.properties", Boolean.TRUE)) {
        return;
    }

    // This is needed to update the static reference for the API Keys in the pattern formatter
    // because the formatter is initialised before the properties files are read
    FilteringLayout.addApiKeys();

    // Load the rest of the command-line properties
    for (Map.Entry<String, String> propEntry : cmdLineProps.entrySet()) {
        setProperty(propEntry.getKey(), propEntry.getValue());
    }

    // Read the information about the skin
    SkinProperties.readSkinVersion();
    // Display the information about the skin
    SkinProperties.printSkinVersion();

    StringBuilder properties = new StringBuilder("{");
    for (Map.Entry<Object, Object> propEntry : PropertiesUtil.getEntrySet()) {
        properties.append(propEntry.getKey());
        properties.append("=");
        properties.append(propEntry.getValue());
        properties.append(",");
    }
    properties.replace(properties.length() - 1, properties.length(), "}");

    // Print out the properties to the log file.
    LOG.debug("Properties: {}", properties.toString());

    // Check for mjb.skipIndexGeneration and set as necessary
    // This duplicates the "-i" functionality, but allows you to have it in the property file
    skipIndexGeneration = PropertiesUtil.getBooleanProperty("mjb.skipIndexGeneration", Boolean.FALSE);

    if (PropertiesUtil.getBooleanProperty("mjb.people", Boolean.FALSE)) {
        peopleScan = Boolean.TRUE;
        peopleScrape = PropertiesUtil.getBooleanProperty("mjb.people.scrape", Boolean.TRUE);
        peopleMax = PropertiesUtil.getIntProperty("mjb.people.maxCount", 10);
        popularity = PropertiesUtil.getIntProperty("mjb.people.popularity", 5);

        // Issue 1947: Cast enhancement - option to save all related files to a specific folder
        peopleFolder = PropertiesUtil.getProperty("mjb.people.folder", "");
        if (isNotValidString(peopleFolder)) {
            peopleFolder = "";
        } else if (!peopleFolder.endsWith(File.separator)) {
            peopleFolder += File.separator;
        }
        StringTokenizer st = new StringTokenizer(
                PropertiesUtil.getProperty("photo.scanner.photoExtensions", "jpg,jpeg,gif,bmp,png"), ",;| ");
        while (st.hasMoreTokens()) {
            PHOTO_EXTENSIONS.add(st.nextToken());
        }
    }

    // Check for mjb.skipHtmlGeneration and set as necessary
    // This duplicates the "-h" functionality, but allows you to have it in the property file
    skipHtmlGeneration = PropertiesUtil.getBooleanProperty("mjb.skipHtmlGeneration", Boolean.FALSE);

    // Look for the parameter in the properties file if it's not been set on the command line
    // This way we don't overwrite the setting if it's not found and defaults to FALSE
    showMemory = PropertiesUtil.getBooleanProperty("mjb.showMemory", Boolean.FALSE);

    // This duplicates the "-c" functionality, but allows you to have it in the property file
    jukeboxClean = PropertiesUtil.getBooleanProperty("mjb.jukeboxClean", Boolean.FALSE);

    MovieFilenameScanner.setSkipKeywords(
            tokenizeToArray(getProperty("filename.scanner.skip.keywords", ""), ",;| "),
            PropertiesUtil.getBooleanProperty("filename.scanner.skip.caseSensitive", Boolean.TRUE));
    MovieFilenameScanner.setSkipRegexKeywords(
            tokenizeToArray(getProperty("filename.scanner.skip.keywords.regex", ""), ","),
            PropertiesUtil.getBooleanProperty("filename.scanner.skip.caseSensitive.regex", Boolean.TRUE));
    MovieFilenameScanner.setExtrasKeywords(
            tokenizeToArray(getProperty("filename.extras.keywords", "trailer,extra,bonus"), ",;| "));
    MovieFilenameScanner.setMovieVersionKeywords(tokenizeToArray(
            getProperty("filename.movie.versions.keywords", "remastered,directors cut,extended cut,final cut"),
            ",;|"));
    MovieFilenameScanner.setLanguageDetection(
            PropertiesUtil.getBooleanProperty("filename.scanner.language.detection", Boolean.TRUE));
    final KeywordMap languages = PropertiesUtil.getKeywordMap("filename.scanner.language.keywords", null);
    if (!languages.isEmpty()) {
        MovieFilenameScanner.clearLanguages();
        for (String lang : languages.getKeywords()) {
            String values = languages.get(lang);
            if (values != null) {
                MovieFilenameScanner.addLanguage(lang, values, values);
            } else {
                LOG.info("No values found for language code '{}'", lang);
            }
        }
    }
    final KeywordMap sourceKeywords = PropertiesUtil.getKeywordMap("filename.scanner.source.keywords",
            "HDTV,PDTV,DVDRip,DVDSCR,DSRip,CAM,R5,LINE,HD2DVD,DVD,DVD5,DVD9,HRHDTV,MVCD,VCD,TS,VHSRip,BluRay,HDDVD,D-THEATER,SDTV");
    MovieFilenameScanner.setSourceKeywords(sourceKeywords.getKeywords(), sourceKeywords);

    String temp = getProperty("sorting.strip.prefixes");
    if (temp != null) {
        StringTokenizer st = new StringTokenizer(temp, ",");
        while (st.hasMoreTokens()) {
            String token = st.nextToken().trim();
            if (token.startsWith("\"") && token.endsWith("\"")) {
                token = token.substring(1, token.length() - 1);
            }
            Movie.addSortIgnorePrefixes(token.toLowerCase());
        }
    }

    enableWatchScanner = PropertiesUtil.getBooleanProperty("watched.scanner.enable", Boolean.TRUE);
    enableWatchTraktTv = PropertiesUtil.getBooleanProperty("watched.trakttv.enable", Boolean.FALSE);
    enableCompleteMovies = PropertiesUtil.getBooleanProperty("complete.movies.enable", Boolean.TRUE);

    // Check to see if don't have a root, check the property file
    if (StringTools.isNotValidString(movieLibraryRoot)) {
        movieLibraryRoot = getProperty("mjb.libraryRoot");
        if (StringTools.isValidString(movieLibraryRoot)) {
            LOG.info("Got libraryRoot from properties file: {}", movieLibraryRoot);
        } else {
            LOG.error("No library root found!");
            help();
            return;
        }
    }

    if (jukeboxRoot == null) {
        jukeboxRoot = getProperty("mjb.jukeboxRoot");
        if (jukeboxRoot == null) {
            LOG.info("jukeboxRoot is null in properties file. Please fix this as it may cause errors.");
        } else {
            LOG.info("Got jukeboxRoot from properties file: {}", jukeboxRoot);
        }
    }

    File f = new File(movieLibraryRoot);
    if (f.exists() && f.isDirectory() && jukeboxRoot == null) {
        jukeboxRoot = movieLibraryRoot;
    }

    if (movieLibraryRoot == null) {
        help();
        return;
    }

    if (jukeboxRoot == null) {
        LOG.info("Wrong arguments specified: you must define the jukeboxRoot property (-o) !");
        help();
        return;
    }

    if (!f.exists()) {
        LOG.error("Directory or library configuration file '{}', not found.", movieLibraryRoot);
        return;
    }

    FileTools.initUnsafeChars();
    FileTools.initSubtitleExtensions();

    // make canonical names
    jukeboxRoot = FileTools.getCanonicalPath(jukeboxRoot);
    movieLibraryRoot = FileTools.getCanonicalPath(movieLibraryRoot);
    MovieJukebox ml = new MovieJukebox(movieLibraryRoot, jukeboxRoot);
    if (dumpLibraryStructure) {
        LOG.warn(
                "WARNING !!! A dump of your library directory structure will be generated for debug purpose. !!! Library won't be built or updated");
        ml.makeDumpStructure();
    } else {
        ml.generateLibrary();
    }

    // Now rename the log files
    renameLogFile();

    if (ScanningLimit.isLimitReached()) {
        LOG.warn("Scanning limit of {} was reached, please re-run to complete processing.",
                ScanningLimit.getLimit());
        System.exit(EXIT_SCAN_LIMIT);
    } else {
        System.exit(EXIT_NORMAL);
    }
}

From source file:at.ac.tuwien.inso.subcat.postprocessor.PostProcessor.java

public static void main(String[] args) {
    Map<String, PostProcessorTask> steps = new HashMap<String, PostProcessorTask>();
    PostProcessorTask _step = new ClassificationTask();
    steps.put(_step.getName(), _step);//from  w ww. ja v  a  2s  . c o m
    CommentAnalyserTask commentAnalysisStep = new CommentAnalyserTask();
    steps.put(commentAnalysisStep.getName(), commentAnalysisStep);
    AccountInterlinkingTask interlinkingTask = new AccountInterlinkingTask();
    steps.put(interlinkingTask.getName(), interlinkingTask);
    _step = new CommitBugInterlinkingTask();
    steps.put(_step.getName(), _step);

    Options options = new Options();
    options.addOption("h", "help", false, "Show this options");
    options.addOption("d", "db", true, "The database to process (required)");
    options.addOption("v", "verbose", false, "Show details");
    options.addOption("p", "project", true, "The project ID to process");
    options.addOption("P", "list-projects", false, "List all registered projects");
    options.addOption("S", "list-processor-steps", false, "List all registered processor steps");
    options.addOption("s", "processor-step", true, "A processor step name");
    options.addOption("c", "commit-dictionary", true,
            "Path to a classification dictionary for commit message classification");
    options.addOption("b", "bug-dictionary", true,
            "Path to a classification dictionary for bug classification");
    options.addOption("m", "smart-matching", true,
            "Smart user matching configuration. Syntax: <method>:<distance>");
    options.addOption("M", "list-matching-methods", false, "List smart matching methods");

    final Reporter reporter = new Reporter(true);
    reporter.startTimer();

    Settings settings = new Settings();
    ModelPool pool = null;

    boolean printTraces = false;
    CommandLineParser parser = new PosixParser();

    try {
        CommandLine cmd = parser.parse(options, args);
        printTraces = cmd.hasOption("verbose");

        if (cmd.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("postprocessor", options);
            return;
        }

        if (cmd.hasOption("list-processor-steps")) {
            for (String proj : steps.keySet()) {
                System.out.println("  " + proj);
            }
            return;
        }

        if (cmd.hasOption("list-matching-methods")) {
            for (String method : HashFunc.getHashFuncNames()) {
                System.out.println("  " + method);
            }
            return;
        }

        if (cmd.hasOption("db") == false) {
            reporter.error("post-processor", "Option --db is required");
            reporter.printSummary();
            return;
        }

        File dbf = new File(cmd.getOptionValue("db"));
        if (dbf.exists() == false || dbf.isFile() == false) {
            reporter.error("post-processor", "Invalid database file path");
            reporter.printSummary();
            return;
        }

        pool = new ModelPool(cmd.getOptionValue("db"), 2);

        if (cmd.hasOption("list-projects")) {
            Model model = pool.getModel();

            for (Project proj : model.getProjects()) {
                System.out.println("  " + proj.getId() + ": " + proj.getDate());
            }

            model.close();
            return;
        }

        Integer projId = null;
        if (cmd.hasOption("project") == false) {
            reporter.error("post-processor", "Option --project is required");
            reporter.printSummary();
            return;
        } else {
            try {
                projId = Integer.parseInt(cmd.getOptionValue("project"));
            } catch (NumberFormatException e) {
                reporter.error("post-processor", "Invalid project ID");
                reporter.printSummary();
                return;
            }
        }

        Model model = pool.getModel();
        Project project = model.getProject(projId);
        model.close();

        if (project == null) {
            reporter.error("post-processor", "Invalid project ID");
            reporter.printSummary();
            return;
        }

        if (cmd.hasOption("bug-dictionary")) {
            DictionaryParser dp = new DictionaryParser();

            for (String path : cmd.getOptionValues("bug-dictionary")) {
                try {
                    Dictionary dict = dp.parseFile(path);
                    settings.bugDictionaries.add(dict);
                } catch (FileNotFoundException e) {
                    reporter.error("post-processor", "File  not found: " + path + ": " + e.getMessage());
                    reporter.printSummary();
                    return;
                } catch (XmlReaderException e) {
                    reporter.error("post-processor", "XML Error: " + path + ": " + e.getMessage());
                    reporter.printSummary();
                    return;
                }
            }
        }

        if (cmd.hasOption("commit-dictionary")) {
            DictionaryParser dp = new DictionaryParser();

            for (String path : cmd.getOptionValues("commit-dictionary")) {
                try {
                    Dictionary dict = dp.parseFile(path);
                    settings.srcDictionaries.add(dict);
                } catch (FileNotFoundException e) {
                    reporter.error("post-processor", "File  not found: " + path + ": " + e.getMessage());
                    reporter.printSummary();
                    return;
                } catch (XmlReaderException e) {
                    reporter.error("post-processor", "XML Error: " + path + ": " + e.getMessage());
                    reporter.printSummary();
                    return;
                }
            }
        }

        if (cmd.hasOption("smart-matching")) {
            String str = cmd.getOptionValue("smart-matching");
            String[] parts = str.split(":");
            if (parts.length != 2) {
                reporter.error("post-processor", "Unexpected smart-matching format");
                reporter.printSummary();
                return;
            }

            HashFunc func = HashFunc.getHashFunc(parts[0]);
            if (func == null) {
                reporter.error("post-processor", "Unknown smart matching hash function");
                reporter.printSummary();
                return;
            }

            int dist = -1;
            try {
                dist = Integer.parseInt(parts[1]);
            } catch (NumberFormatException e) {
                dist = -1;
            }

            if (dist < 0) {
                reporter.error("post-processor", "Invalid smart matching edist distance");
                reporter.printSummary();
                return;
            }

            interlinkingTask.setDistance(dist);
            interlinkingTask.setHashFunc(func);
        }

        PostProcessor processor = new PostProcessor(project, pool, settings);
        if (cmd.hasOption("processor-step")) {
            for (String stepName : cmd.getOptionValues("processor-step")) {
                PostProcessorTask step = steps.get(stepName);
                if (step == null) {
                    reporter.error("post-processor", "Unknown processor step: '" + stepName + "'");
                    reporter.printSummary();
                    return;
                }

                processor.register(step);
            }
        } else {
            processor.register(steps.values());
        }

        if (printTraces == true) {
            model = pool.getModel();
            final Stats stats = model.getStats(project);
            model.close();

            processor.addListener(new PostProcessorListener() {
                private int commitCount = 0;
                private int bugCount = 0;

                @Override
                public void commit(PostProcessor proc) {
                    commitCount++;
                    reporter.note("post-processor", "status: Commit " + commitCount + "/" + stats.commitCount);
                }

                @Override
                public void bug(PostProcessor proc) {
                    bugCount++;
                    reporter.note("post-processor", "status: Bug " + bugCount + "/" + stats.bugCount);
                }
            });
        }

        processor.process();
    } catch (ParseException e) {
        reporter.error("post-processor", "Parsing failed: " + e.getMessage());
        if (printTraces == true) {
            e.printStackTrace();
        }
    } catch (ClassNotFoundException e) {
        reporter.error("post-processor", "Failed to create a database connection: " + e.getMessage());
        if (printTraces == true) {
            e.printStackTrace();
        }
    } catch (SQLException e) {
        reporter.error("post-processor", "Failed to create a database connection: " + e.getMessage());
        if (printTraces == true) {
            e.printStackTrace();
        }
    } catch (PostProcessorException e) {
        reporter.error("post-processor", "Post-Processor Error: " + e.getMessage());
        if (printTraces == true) {
            e.printStackTrace();
        }
    } finally {
        if (pool != null) {
            pool.close();
        }
    }

    reporter.printSummary(true);
}

From source file:Helper.java

public static <K, V> V get(Map<K, V> m, K key, V def) {
    V v = m.get(key);
    return (v != null) ? v : def;
}

From source file:HelloWorldBookmarks.java

private static void showBookmark(Map bookmark) {
    System.out.println(bookmark.get("Title"));
    ArrayList kids = (ArrayList) bookmark.get("Kids");
    if (kids == null)
        return;//from www  .j av a  2  s.  com
    for (Iterator i = kids.iterator(); i.hasNext();) {
        showBookmark((Map) i.next());
    }
}