Example usage for java.util Collections sort

List of usage examples for java.util Collections sort

Introduction

In this page you can find the example usage for java.util Collections sort.

Prototype

@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> void sort(List<T> list, Comparator<? super T> c) 

Source Link

Document

Sorts the specified list according to the order induced by the specified comparator.

Usage

From source file:edu.umd.cloud9.example.bigram.AnalyzeBigramRelativeFrequencyTuple.java

@SuppressWarnings({ "static-access" })
public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));

    CommandLine cmdline = null;//from w  w w  .j ava  2s . c  o  m
    CommandLineParser parser = new GnuParser();

    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(AnalyzeBigramRelativeFrequencyJson.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String inputPath = cmdline.getOptionValue(INPUT);
    System.out.println("input path: " + inputPath);

    List<PairOfWritables<Tuple, FloatWritable>> pairs = SequenceFileUtils.readDirectory(new Path(inputPath));

    List<PairOfWritables<Tuple, FloatWritable>> list1 = Lists.newArrayList();
    List<PairOfWritables<Tuple, FloatWritable>> list2 = Lists.newArrayList();

    for (PairOfWritables<Tuple, FloatWritable> p : pairs) {
        Tuple bigram = p.getLeftElement();

        if (bigram.get(0).equals("light")) {
            list1.add(p);
        }

        if (bigram.get(0).equals("contain")) {
            list2.add(p);
        }
    }

    Collections.sort(list1, new Comparator<PairOfWritables<Tuple, FloatWritable>>() {
        @SuppressWarnings("unchecked")
        public int compare(PairOfWritables<Tuple, FloatWritable> e1, PairOfWritables<Tuple, FloatWritable> e2) {
            if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) {
                return e1.getLeftElement().compareTo(e2.getLeftElement());
            }

            return e2.getRightElement().compareTo(e1.getRightElement());
        }
    });

    Iterator<PairOfWritables<Tuple, FloatWritable>> iter1 = Iterators.limit(list1.iterator(), 10);
    while (iter1.hasNext()) {
        PairOfWritables<Tuple, FloatWritable> p = iter1.next();
        Tuple bigram = p.getLeftElement();
        System.out.println(bigram + "\t" + p.getRightElement());
    }

    Collections.sort(list2, new Comparator<PairOfWritables<Tuple, FloatWritable>>() {
        @SuppressWarnings("unchecked")
        public int compare(PairOfWritables<Tuple, FloatWritable> e1, PairOfWritables<Tuple, FloatWritable> e2) {
            if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) {
                return e1.getLeftElement().compareTo(e2.getLeftElement());
            }

            return e2.getRightElement().compareTo(e1.getRightElement());
        }
    });

    Iterator<PairOfWritables<Tuple, FloatWritable>> iter2 = Iterators.limit(list2.iterator(), 10);
    while (iter2.hasNext()) {
        PairOfWritables<Tuple, FloatWritable> p = iter2.next();
        Tuple bigram = p.getLeftElement();
        System.out.println(bigram + "\t" + p.getRightElement());
    }
}

From source file:edu.umd.cloud9.example.bigram.AnalyzeBigramRelativeFrequency.java

@SuppressWarnings({ "static-access" })
public static void main(String[] args) {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));

    CommandLine cmdline = null;// w  ww . jav  a  2 s.  co m
    CommandLineParser parser = new GnuParser();

    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(AnalyzeBigramRelativeFrequency.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String inputPath = cmdline.getOptionValue(INPUT);
    System.out.println("input path: " + inputPath);

    List<PairOfWritables<PairOfStrings, FloatWritable>> pairs = SequenceFileUtils
            .readDirectory(new Path(inputPath));

    List<PairOfWritables<PairOfStrings, FloatWritable>> list1 = Lists.newArrayList();
    List<PairOfWritables<PairOfStrings, FloatWritable>> list2 = Lists.newArrayList();

    for (PairOfWritables<PairOfStrings, FloatWritable> p : pairs) {
        PairOfStrings bigram = p.getLeftElement();

        if (bigram.getLeftElement().equals("light")) {
            list1.add(p);
        }
        if (bigram.getLeftElement().equals("contain")) {
            list2.add(p);
        }
    }

    Collections.sort(list1, new Comparator<PairOfWritables<PairOfStrings, FloatWritable>>() {
        public int compare(PairOfWritables<PairOfStrings, FloatWritable> e1,
                PairOfWritables<PairOfStrings, FloatWritable> e2) {
            if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) {
                return e1.getLeftElement().compareTo(e2.getLeftElement());
            }

            return e2.getRightElement().compareTo(e1.getRightElement());
        }
    });

    Iterator<PairOfWritables<PairOfStrings, FloatWritable>> iter1 = Iterators.limit(list1.iterator(), 10);
    while (iter1.hasNext()) {
        PairOfWritables<PairOfStrings, FloatWritable> p = iter1.next();
        PairOfStrings bigram = p.getLeftElement();
        System.out.println(bigram + "\t" + p.getRightElement());
    }

    Collections.sort(list2, new Comparator<PairOfWritables<PairOfStrings, FloatWritable>>() {
        public int compare(PairOfWritables<PairOfStrings, FloatWritable> e1,
                PairOfWritables<PairOfStrings, FloatWritable> e2) {
            if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) {
                return e1.getLeftElement().compareTo(e2.getLeftElement());
            }

            return e2.getRightElement().compareTo(e1.getRightElement());
        }
    });

    Iterator<PairOfWritables<PairOfStrings, FloatWritable>> iter2 = Iterators.limit(list2.iterator(), 10);
    while (iter2.hasNext()) {
        PairOfWritables<PairOfStrings, FloatWritable> p = iter2.next();
        PairOfStrings bigram = p.getLeftElement();
        System.out.println(bigram + "\t" + p.getRightElement());
    }
}

From source file:edu.umd.cloud9.example.bigram.AnalyzeBigramRelativeFrequencyJson.java

@SuppressWarnings({ "static-access" })
public static void main(String[] args) {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));

    CommandLine cmdline = null;//from   w w w .  ja v a2 s  . com
    CommandLineParser parser = new GnuParser();

    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(AnalyzeBigramRelativeFrequencyJson.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String inputPath = cmdline.getOptionValue(INPUT);
    System.out.println("input path: " + inputPath);

    List<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> pairs = SequenceFileUtils
            .readDirectory(new Path(inputPath));

    List<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> list1 = Lists.newArrayList();
    List<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> list2 = Lists.newArrayList();

    for (PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> p : pairs) {
        BigramRelativeFrequencyJson.MyTuple bigram = p.getLeftElement();

        if (bigram.getJsonObject().get("Left").getAsString().equals("light")) {
            list1.add(p);
        }

        if (bigram.getJsonObject().get("Left").getAsString().equals("contain")) {
            list2.add(p);
        }
    }

    Collections.sort(list1,
            new Comparator<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>>() {
                public int compare(PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> e1,
                        PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> e2) {
                    if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) {
                        return e1.getLeftElement().compareTo(e2.getLeftElement());
                    }

                    return e2.getRightElement().compareTo(e1.getRightElement());
                }
            });

    Iterator<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> iter1 = Iterators
            .limit(list1.iterator(), 10);
    while (iter1.hasNext()) {
        PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> p = iter1.next();
        BigramRelativeFrequencyJson.MyTuple bigram = p.getLeftElement();
        System.out.println(bigram + "\t" + p.getRightElement());
    }

    Collections.sort(list2,
            new Comparator<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>>() {
                public int compare(PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> e1,
                        PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> e2) {
                    if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) {
                        return e1.getLeftElement().compareTo(e2.getLeftElement());
                    }

                    return e2.getRightElement().compareTo(e1.getRightElement());
                }
            });

    Iterator<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> iter2 = Iterators
            .limit(list2.iterator(), 10);
    while (iter2.hasNext()) {
        PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> p = iter2.next();
        BigramRelativeFrequencyJson.MyTuple bigram = p.getLeftElement();
        System.out.println(bigram + "\t" + p.getRightElement());
    }
}

From source file:com.datazuul.iiif.presentation.api.ManifestGenerator.java

public static void main(String[] args)
        throws ParseException, JsonProcessingException, IOException, URISyntaxException {
    Options options = new Options();
    options.addOption("d", true, "Absolute file path to the directory containing the image files.");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("d")) {
        String imageDirectoryPath = cmd.getOptionValue("d");
        Path imageDirectory = Paths.get(imageDirectoryPath);
        final List<Path> files = new ArrayList<>();
        try {//w w  w  .  j  av  a2  s. c om
            Files.walkFileTree(imageDirectory, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (!attrs.isDirectory()) {
                        // TODO there must be a more elegant solution for filtering jpeg files...
                        if (file.getFileName().toString().endsWith("jpg")) {
                            files.add(file);
                        }
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        Collections.sort(files, new Comparator() {
            @Override
            public int compare(Object fileOne, Object fileTwo) {
                String filename1 = ((Path) fileOne).getFileName().toString();
                String filename2 = ((Path) fileTwo).getFileName().toString();

                try {
                    // numerical sorting
                    Integer number1 = Integer.parseInt(filename1.substring(0, filename1.lastIndexOf(".")));
                    Integer number2 = Integer.parseInt(filename2.substring(0, filename2.lastIndexOf(".")));
                    return number1.compareTo(number2);
                } catch (NumberFormatException nfe) {
                    // alpha-numerical sorting
                    return filename1.compareToIgnoreCase(filename2);
                }
            }
        });

        generateManifest(imageDirectory.getFileName().toString(), files);
    } else {
        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("ManifestGenerator", options);
    }
}

From source file:at.tuwien.ifs.somtoolbox.apps.SOMToolboxMain.java

/**
 * Central Main for SOMToolbox./*from www  . j  a v a 2s.  c  o  m*/
 * 
 * @param args the command line args
 */
public static void main(String[] args) {
    int screenWidth = 80;
    try {
        screenWidth = Integer.parseInt(System.getenv("COLUMNS"));
    } catch (Exception e) {
        screenWidth = 80;
    }

    JSAP jsap = new JSAP();
    try {
        jsap.registerParameter(new UnflaggedOption("main", JSAP.STRING_PARSER, null, false, false));
        jsap.registerParameter(new Switch("gui", 'G', "gui"));
        jsap.registerParameter(new Switch("version", JSAP.NO_SHORTFLAG, "version"));
        jsap.registerParameter(new Switch("listmains", JSAP.NO_SHORTFLAG, "list-mains"));
        jsap.registerParameter(
                new FlaggedOption("help", JSAP.STRING_PARSER, null, false, JSAP.NO_SHORTFLAG, "help"));
    } catch (JSAPException e) {
        assert false;
    }
    JSAPResult result = jsap.parse(args);

    ArrayList<Class<? extends SOMToolboxApp>> runnables = SubClassFinder.findSubclassesOf(SOMToolboxApp.class,
            true);
    Collections.sort(runnables, SOMToolboxApp.TYPE_GROUPED_COMPARATOR);

    // args > 0
    boolean useGUI = result.getBoolean("gui", false);
    if (useGUI) {
        UiUtils.setSOMToolboxLookAndFeel();
    }

    if (result.getBoolean("listmains")) {
        if (useGUI) {
            showAvailableRunnables(runnables, args);
        } else {
            printAvailableRunnables(screenWidth, runnables);
        }
    } else if (result.getBoolean("version")) {
        if (result.userSpecified("main")) {
            printVersion(result.getString("main"));
        } else {
            printVersion("somtoolbox");
        }
    } else if (result.userSpecified("main")) {
        String mainClass = result.getString("main");
        String[] cleanArgs = Arrays.copyOfRange(args, 1, args.length);
        if (!invokeMainClass(runnables, mainClass, cleanArgs, useGUI)) {
            Logger.getLogger("at.tuwien.ifs.somtoolbox").severe("Runnable \"" + mainClass + "\" not found.");
            printAvailableRunnables(screenWidth, runnables);
        }
    } else if (result.contains("help")) {
        if (result.getString("help") != null) {
            invokeMainClass(runnables, result.getString("help"), new String[] { "--help" }, useGUI);
        } else {
            printHelp();
        }
    } else {
        if (useGUI) {
            showAvailableRunnables(runnables, args);
        } else {
            printAvailableRunnables(screenWidth, runnables);
        }

    }
}

From source file:de.tudarmstadt.ukp.argumentation.data.roomfordebate.DataFetcher.java

public static void main(String[] args) throws Exception {
    File crawledPagesFolder = new File(args[0]);
    if (!crawledPagesFolder.exists()) {
        crawledPagesFolder.mkdirs();/*from   www  .jav a 2  s . c o m*/
    }

    File outputFolder = new File(args[1]);
    if (!outputFolder.exists()) {
        outputFolder.mkdirs();
    }

    // read links from text file
    final String urlsResourceName = "roomfordebate-urls.txt";

    InputStream urlsStream = DataFetcher.class.getClassLoader().getResourceAsStream(urlsResourceName);

    if (urlsStream == null) {
        throw new IOException("Cannot find resource " + urlsResourceName + " on the classpath");
    }

    // read list of urls
    List<String> urls = new ArrayList<>();
    LineIterator iterator = IOUtils.lineIterator(urlsStream, "utf-8");
    while (iterator.hasNext()) {
        // ignore commented url (line starts with #)
        String line = iterator.nextLine();
        if (!line.startsWith("#") && !line.trim().isEmpty()) {
            urls.add(line.trim());
        }
    }

    // download all
    crawlPages(urls, crawledPagesFolder);

    List<File> files = new ArrayList<>(FileUtils.listFiles(crawledPagesFolder, null, false));
    Collections.sort(files, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });

    int idCounter = 0;

    for (File file : files) {
        NYTimesCommentsScraper commentsScraper = new NYTimesCommentsScraper();
        NYTimesArticleExtractor extractor = new NYTimesArticleExtractor();

        String html = FileUtils.readFileToString(file, "utf-8");

        idCounter++;
        File outputFileArticle = new File(outputFolder, String.format("Cx%03d.txt", idCounter));
        File outputFileComments = new File(outputFolder, String.format("Dx%03d.txt", idCounter));

        try {
            List<Comment> comments = commentsScraper.extractComments(html);
            Article article = extractor.extractArticle(html);

            saveArticleToText(article, outputFileArticle);
            System.out.println("Saved to " + outputFileArticle);

            saveCommentsToText(comments, outputFileComments, article);
            System.out.println("Saved to " + outputFileComments);
        } catch (IOException ex) {
            System.err.println(file.getName() + "\n" + ex.getMessage());
        }
    }
}

From source file:org.jasig.portlet.maps.tools.MapDataTransformer.java

/**
 * @param args/* ww w . j  a va 2 s . c om*/
 */
public static void main(String[] args) {

    // translate the KML file to the map portlet's native data format
    File kml = new File("map-data.xml");
    File xslt = new File("google-earth.xsl");

    try {
        TransformerFactory transFact = javax.xml.transform.TransformerFactory.newInstance();
        Transformer trans = transFact.newTransformer(new StreamSource(xslt));
        trans.transform(new StreamSource(kml), new StreamResult(System.out));
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    } catch (TransformerException e) {
        e.printStackTrace();
    }

    // deserialize the map data from XML
    MapData data = null;
    try {
        JAXBContext jc = JAXBContext.newInstance(MapData.class);
        Unmarshaller u = jc.createUnmarshaller();
        data = (MapData) u.unmarshal(new FileInputStream(new File("map-data-transformed.xml")));
    } catch (JAXBException e1) {
        e1.printStackTrace();
        return;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return;
    }

    // ensure each location has a unique, non-null abbreviation
    setAbbreviations(data);

    // update each location with an address
    //        setAddresses(data);

    // sort locations by name
    Collections.sort(data.getLocations(), new ByNameLocationComparator());

    // serialize new map data out to a file into JSON format
    try {
        mapper.defaultPrettyPrintingWriter().writeValue(new File("map.json"), data);
    } catch (JsonGenerationException e) {
        System.out.println("Error generating JSON data for map");
        e.printStackTrace();
    } catch (JsonMappingException e) {
        System.out.println("Error generating JSON data for map");
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("Error writing JSON data to map file");
        e.printStackTrace();
    }

}

From source file:NaturalOrderComparator.java

public static void main(String[] args) {
    String[] strings = new String[] { "1-2", "1-02", "1-20", "10-20", "fred", "jane", "pic01", "pic2", "pic02",
            "pic02a", "pic3", "pic4", "pic 4 else", "pic 5", "pic05", "pic 5", "pic 5 something", "pic 6",
            "pic   7", "pic100", "pic100a", "pic120", "pic121", "pic02000", "tom", "x2-g8", "x2-y7", "x2-y08",
            "x8-y8" };

    List orig = Arrays.asList(strings);

    System.out.println("Original: " + orig);

    List scrambled = Arrays.asList(strings);
    Collections.shuffle(scrambled);

    System.out.println("Scrambled: " + scrambled);

    Collections.sort(scrambled, new NaturalOrderComparator());

    System.out.println("Sorted: " + scrambled);
}

From source file:mmllabvsdextractfeature.MMllabVSDExtractFeature.java

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

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

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

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

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

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

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

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

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

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

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

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

        // Zip Whole Folder

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

    }

}

From source file:guardar.en.base.de.datos.MainServidor.java

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

    Mongo mongo = new Mongo("localhost", 27017);

    // nombre de la base de datos
    DB database = mongo.getDB("paginas");
    // coleccion de la db
    DBCollection collection = database.getCollection("indice");
    DBCollection collection_textos = database.getCollection("tabla");
    ArrayList<String> lista_textos = new ArrayList();

    try {/*ww w  .  j a  v  a2s .c  o  m*/
        ServerSocket servidor = new ServerSocket(4545); // Crear un servidor en pausa hasta que un cliente llegue.
        while (true) {
            String aux = new String();
            lista_textos.clear();
            Socket clienteNuevo = servidor.accept();// Si llega se acepta.
            // Queda en pausa otra vez hasta que un objeto llegue.
            ObjectInputStream entrada = new ObjectInputStream(clienteNuevo.getInputStream());

            JSONObject request = (JSONObject) entrada.readObject();
            String b = (String) request.get("id");
            //hacer una query a la base de datos con la palabra que se quiere obtener

            BasicDBObject query = new BasicDBObject("palabra", b);
            DBCursor cursor = collection.find(query);
            ArrayList<DocumentosDB> lista_doc = new ArrayList<>();
            // de la query tomo el campo documentos y los agrego a una lista
            try {
                while (cursor.hasNext()) {
                    //System.out.println(cursor.next());
                    BasicDBList campo_documentos = (BasicDBList) cursor.next().get("documentos");
                    // en el for voy tomando uno por uno los elementos en el campo documentos
                    for (Iterator<Object> it = campo_documentos.iterator(); it.hasNext();) {
                        BasicDBObject dbo = (BasicDBObject) it.next();
                        //DOC tiene id y frecuencia
                        DocumentosDB doc = new DocumentosDB();
                        doc.makefn2(dbo);
                        //int id = (int)doc.getId_documento();
                        //int f = (int)doc.getFrecuencia();

                        lista_doc.add(doc);

                        //*******************************************

                        //********************************************

                        //QUERY A LA COLECCION DE TEXTOS
                        /* BasicDBObject query_textos = new BasicDBObject("id", doc.getId_documento());//query
                         DBCursor cursor_textos = collection_textos.find(query_textos);
                         try {
                        while (cursor_textos.hasNext()) {
                                    
                                    
                            DBObject obj = cursor_textos.next();
                                
                            String titulo = (String) obj.get("titulo");
                            titulo = titulo + "\n\n";
                            String texto = (String) obj.get("texto");
                                
                            String texto_final = titulo + texto;
                            aux = texto_final;
                            lista_textos.add(texto_final);
                        }
                         } finally {
                        cursor_textos.close();
                         }*/
                        //System.out.println(doc.getId_documento());
                        //System.out.println(doc.getFrecuencia());

                    } // end for

                } //end while query

            } finally {
                cursor.close();
            }

            // ordeno la lista de menor a mayor
            Collections.sort(lista_doc, new Comparator<DocumentosDB>() {

                @Override
                public int compare(DocumentosDB o1, DocumentosDB o2) {
                    //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                    return o1.getFrecuencia().compareTo(o2.getFrecuencia());
                }
            });
            int tam = lista_doc.size() - 1;
            for (int j = tam; j >= 0; j--) {

                BasicDBObject query_textos = new BasicDBObject("id",
                        (int) lista_doc.get(j).getId_documento().intValue());//query
                DBCursor cursor_textos = collection_textos.find(query_textos);// lo busco
                try {
                    while (cursor_textos.hasNext()) {

                        DBObject obj = cursor_textos.next();
                        String titulo = "*******************************";
                        titulo += (String) obj.get("titulo");
                        int f = (int) lista_doc.get(j).getFrecuencia().intValue();
                        String strinf = Integer.toString(f);
                        titulo += "******************************* frecuencia:" + strinf;
                        titulo = titulo + "\n\n";

                        String texto = (String) obj.get("texto");

                        String texto_final = titulo + texto + "\n\n";
                        aux = aux + texto_final;
                        //lista_textos.add(texto_final);
                    }
                } finally {
                    cursor_textos.close();
                }

            }

            //actualizar el cache
            try {
                Socket cliente_cache = new Socket("localhost", 4500); // nos conectamos con el servidor
                ObjectOutputStream mensaje_cache = new ObjectOutputStream(cliente_cache.getOutputStream()); // get al output del servidor, que es cliente : socket del cliente q se conecto al server
                JSONObject actualizacion_cache = new JSONObject();
                actualizacion_cache.put("actualizacion", 1);
                actualizacion_cache.put("busqueda", b);
                actualizacion_cache.put("respuesta", aux);
                mensaje_cache.writeObject(actualizacion_cache); // envio el msj al servidor
            } catch (Exception ex) {

            }

            //RESPONDER DESDE EL SERVIDORIndex al FRONT
            ObjectOutputStream resp = new ObjectOutputStream(clienteNuevo.getOutputStream());// obtengo el output del cliente para mandarle un msj
            resp.writeObject(aux);
            System.out.println("msj enviado desde el servidor");

        }
    } catch (IOException ex) {
        Logger.getLogger(MainServidor.class.getName()).log(Level.SEVERE, null, ex);
    }

}