Example usage for java.util Comparator Comparator

List of usage examples for java.util Comparator Comparator

Introduction

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

Prototype

Comparator

Source Link

Usage

From source file:io.sugo.grok.api.Discovery.java

/**
 * Sort by regex complexity./*from   w  w w  .  j av  a 2 s.c  o  m*/
 *
 * @param groks Map of the pattern name and grok instance
 * @return the map sorted by grok pattern complexity
 */
private Map<String, Grok> sort(Map<String, Grok> groks) {

    List<Grok> groky = new ArrayList<Grok>(groks.values());
    Map<String, Grok> mGrok = new LinkedHashMap<String, Grok>();
    Collections.sort(groky, new Comparator<Grok>() {

        public int compare(Grok g1, Grok g2) {
            return (this.complexity(g1.getNamedRegex()) < this.complexity(g2.getNamedRegex())) ? 1 : 0;
        }

        private int complexity(String expandedPattern) {
            int score = 0;
            score += expandedPattern.split("\\Q" + "|" + "\\E", -1).length - 1;
            score += expandedPattern.length();
            return score;
        }
    });

    for (Grok g : groky) {
        mGrok.put(g.getSaved_pattern(), g);
    }
    return mGrok;

}

From source file:info.magnolia.cms.beans.config.Bootstrapper.java

/**
 * Repositories appears to be empty and the <code>"magnolia.bootstrap.dir</code> directory is configured in
 * web.xml. Loops over all the repositories and try to load any xml file found in a subdirectory with the same name
 * of the repository. For example the <code>config</code> repository will be initialized using all the
 * <code>*.xml</code> files found in <code>"magnolia.bootstrap.dir</code><strong>/config</strong> directory.
 * @param bootdirs bootstrap dir/*from   ww  w. j  a v a 2s. com*/
 */
protected static void bootstrapRepositories(String[] bootdirs) {

    if (log.isInfoEnabled()) {
        log.info("-----------------------------------------------------------------"); //$NON-NLS-1$
        log.info("Trying to initialize repositories from:");
        for (int i = 0; i < bootdirs.length; i++) {
            log.info(bootdirs[i]);
        }
        log.info("-----------------------------------------------------------------"); //$NON-NLS-1$
    }

    MgnlContext.setInstance(MgnlContext.getSystemContext());

    Iterator repositoryNames = ContentRepository.getAllRepositoryNames();
    while (repositoryNames.hasNext()) {
        String repository = (String) repositoryNames.next();

        Set xmlfileset = new TreeSet(new Comparator() {

            // remove file with the same name in different dirs
            public int compare(Object file1obj, Object file2obj) {
                File file1 = (File) file1obj;
                File file2 = (File) file2obj;
                String fn1 = file1.getParentFile().getName() + '/' + file1.getName();
                String fn2 = file2.getParentFile().getName() + '/' + file2.getName();
                return fn1.compareTo(fn2);
            }
        });

        for (int j = 0; j < bootdirs.length; j++) {
            String bootdir = bootdirs[j];
            File xmldir = new File(bootdir, repository);
            if (!xmldir.exists() || !xmldir.isDirectory()) {
                continue;
            }

            File[] files = xmldir.listFiles(new FilenameFilter() {

                public boolean accept(File dir, String name) {
                    return name.endsWith(DataTransporter.XML) || name.endsWith(DataTransporter.ZIP)
                            || name.endsWith(DataTransporter.GZ); //$NON-NLS-1$
                }
            });

            xmlfileset.addAll(Arrays.asList(files));

        }

        if (xmlfileset.isEmpty()) {
            log.info("No bootstrap files found in directory [{}], skipping...", repository); //$NON-NLS-1$
            continue;
        }

        log.info("Trying to import content from {} files into repository [{}]", //$NON-NLS-1$
                Integer.toString(xmlfileset.size()), repository);

        File[] files = (File[]) xmlfileset.toArray(new File[xmlfileset.size()]);
        Arrays.sort(files, new Comparator() {

            public int compare(Object file1, Object file2) {
                String name1 = StringUtils.substringBeforeLast(((File) file1).getName(), "."); //$NON-NLS-1$
                String name2 = StringUtils.substringBeforeLast(((File) file2).getName(), "."); //$NON-NLS-1$
                // a simple way to detect nested nodes
                return name1.length() - name2.length();
            }
        });

        try {
            for (int k = 0; k < files.length; k++) {

                File xmlfile = files[k];
                DataTransporter.executeBootstrapImport(xmlfile, repository);
            }

        } catch (IOException ioe) {
            log.error(ioe.getMessage(), ioe);
        } catch (OutOfMemoryError e) {
            int maxMem = (int) (Runtime.getRuntime().maxMemory() / 1024 / 1024);
            int needed = Math.max(256, maxMem + 128);
            log.error("Unable to complete bootstrapping: out of memory.\n" //$NON-NLS-1$
                    + "{} MB were not enough, try to increase the amount of memory available by adding the -Xmx{}m parameter to the server startup script.\n" //$NON-NLS-1$
                    + "You will need to completely remove the magnolia webapp before trying again", //$NON-NLS-1$
                    Integer.toString(maxMem), Integer.toString(needed));
            break;
        }

        log.info("Repository [{}] has been initialized.", repository); //$NON-NLS-1$

    }
}

From source file:org.lieuofs.extraction.etatpays.ExtractionGeTaX.java

public void extraire() throws IOException {
    EtatCritere critere = new EtatCritere();
    Calendar cal = Calendar.getInstance();
    cal.set(2012, Calendar.DECEMBER, 31);
    critere.setReconnuSuisseALaDate(cal.getTime());
    Set<IEtat> etats = gestionnaire.rechercher(critere);
    List<IEtat> listeEtat = new ArrayList<IEtat>(etats);
    Collections.sort(listeEtat, new Comparator<IEtat>() {
        @Override//from  ww w  .  j a va2 s.c o m
        public int compare(IEtat o1, IEtat o2) {
            return o1.getNumeroOFS() - o2.getNumeroOFS();
        }
    });
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
            new FileOutputStream(new File("ExtractionEtatGETaX2012.csv")), Charset.forName("ISO8859-1")));

    for (IEtat etat : listeEtat) {
        writer.write(String.valueOf(etat.getNumeroOFS()));
        writer.write(";");
        writer.write(etat.getFormeCourte("fr"));
        writer.newLine();
    }
    writer.close();
}

From source file:net.chrissearle.flickrvote.web.admin.PhotographerDataAction.java

public void prepare() throws Exception {
    List<PhotographerItem> photographerList = photographyService.getPhotographers();

    photographers = new ArrayList<Photographer>(photographerList.size());

    for (PhotographerItem photographer : photographerList) {
        photographers.add(new DisplayPhotographer(photographer));
    }/*from   w  ww  . ja  va2 s . co m*/

    Collections.sort(photographers, new Comparator<Photographer>() {
        public int compare(Photographer o1, Photographer o2) {
            return o1.getPhotographerName().compareTo(o2.getPhotographerName());
        }
    });
}

From source file:$.DemoApplicationServiceImpl.java

@Override
    public List<DemoApplication> getAllApplications() {
        List<DemoApplication> result = new ArrayList<DemoApplication>(demoApplicationRepository.findAll());
        Collections.sort(result, new Comparator<DemoApplication>() {

            @Override//  ww  w  .  j  av a2 s.c  om
            public int compare(DemoApplication o1, DemoApplication o2) {
                int result = o1.getAppGroup().compareTo(o2.getAppGroup());
                return result != 0 ? result : o1.getAppId().compareToIgnoreCase(o2.getAppId());
            }
        });
        return result;
    }

From source file:com.logsniffer.util.grok.GrokAppConfig.java

@Bean
public GroksRegistry groksRegistry() throws IOException, GrokException {
    GroksRegistry registry = new GroksRegistry();
    PathMatchingResourcePatternResolver pathMatcher = new PathMatchingResourcePatternResolver();
    Resource[] classPathPatterns = pathMatcher.getResources("classpath*:/grok-patterns/*");
    Arrays.sort(classPathPatterns, new Comparator<Resource>() {
        @Override/* w  w w .  j a  v  a  2 s. co  m*/
        public int compare(final Resource o1, final Resource o2) {
            return o1.getFilename().compareTo(o2.getFilename());
        }
    });
    LinkedHashMap<String, String[]> grokBlocks = new LinkedHashMap<String, String[]>();
    for (Resource r : classPathPatterns) {
        grokBlocks.put(r.getFilename(), IOUtils.readLines(r.getInputStream()).toArray(new String[0]));
    }
    registry.registerPatternBlocks(grokBlocks);
    return registry;
}

From source file:com.chinamobile.bcbsp.fault.browse.SortList.java

/**
 * sort the given list according the value returned by the method;
 * and the sort//from   w  w  w  .j av  a2  s .c  o  m
 * determinate the correct order or reverted order
 * @param list
 *        list to sort.
 * @param method
 *        given method to get the value to compare.
 * @param sort
 *        decide the correct order or reverted order
 */
public void Sort(List<E> list, final String method, final String sort) {
    Collections.sort(list, new Comparator<E>() {
        @Override
        @SuppressWarnings("unchecked")
        public int compare(Object a, Object b) {
            int ret = 0;
            try {
                Object[] objs = null;
                Method m1 = ((E) a).getClass().getMethod(method, (Class<?>[]) objs);
                Method m2 = ((E) b).getClass().getMethod(method, (Class<?>[]) objs);
                if (sort != null && "desc".equals(sort)) {
                    ret = m2.invoke(((E) b), objs).toString().compareTo(m1.invoke(((E) a), objs).toString());
                } else {
                    ret = m1.invoke(((E) a), objs).toString().compareTo(m2.invoke(((E) b), objs).toString());
                }
            } catch (NoSuchMethodException ne) {
                LOG.error("[Sort]", ne);
                throw new RuntimeException("[Sort]", ne);
            } catch (IllegalAccessException ie) {
                throw new RuntimeException("[Sort]", ie);
            } catch (InvocationTargetException it) {
                throw new RuntimeException("[Sort]", it);
            }
            return ret;
        }
    });
}

From source file:net.chrissearle.flickrvote.web.HallOfFameAction.java

public void prepare() throws Exception {
    Set<ImageItem> images = winnerService.getGoldWinners();

    displayImages = new ArrayList<DisplayImage>(images.size());

    for (ImageItem image : images) {
        displayImages.add(new DisplayImage(image));
    }/*from  w  w  w.  j a v  a 2s  . co m*/

    Collections.sort(displayImages, new Comparator<DisplayImage>() {

        public int compare(DisplayImage o1, DisplayImage o2) {
            return o2.getChallengeTag().compareTo(o1.getChallengeTag());
        }
    });
}

From source file:alluxio.cli.fs.command.WithWildCardPathCommand.java

private static Comparator<AlluxioURI> createAlluxioURIComparator() {
    return new Comparator<AlluxioURI>() {
        @Override/*  w w w .ja v  a  2s.co m*/
        public int compare(AlluxioURI tUri1, AlluxioURI tUri2) {
            // ascending order
            return tUri1.getPath().compareTo(tUri2.getPath());
        }
    };
}

From source file:com.vrem.wifianalyzer.settings.CountryPreferenceTest.java

@Before
public void setUp() {
    MainActivity mainActivity = RobolectricUtil.INSTANCE.getActivity();
    fixture = new CountryPreference(mainActivity, Robolectric.buildAttributeSet().build());

    countries = WiFiChannelCountry.getAll();
    Collections.sort(countries, new Comparator<WiFiChannelCountry>() {
        @Override// w w w  .j  a  v a2s .  c om
        public int compare(WiFiChannelCountry lhs, WiFiChannelCountry rhs) {
            return new CompareToBuilder().append(lhs.getCountryName(), rhs.getCountryName())
                    .append(lhs.getCountryCode(), rhs.getCountryCode()).toComparison();
        }
    });
}