Example usage for java.util Arrays sort

List of usage examples for java.util Arrays sort

Introduction

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

Prototype

public static <T> void sort(T[] a, Comparator<? super T> c) 

Source Link

Document

Sorts the specified array of objects according to the order induced by the specified comparator.

Usage

From source file:net.myrrix.batch.common.iterator.sequencefile.SequenceFileDirIterator.java

/**
 * Constructor that uses either {@link FileSystem#listStatus(Path)} or
 * {@link FileSystem#globStatus(Path)} to obtain list of files to iterate over
 * (depending on pathType parameter).//from w w  w  . ja v  a2s .co m
 */
public SequenceFileDirIterator(Path path, PathType pathType, PathFilter filter, Comparator<FileStatus> ordering,
        final boolean reuseKeyValueInstances, final Configuration conf) throws IOException {

    FileStatus[] statuses;
    FileSystem fs = path.getFileSystem(conf);
    if (filter == null) {
        statuses = pathType == PathType.GLOB ? fs.globStatus(path) : fs.listStatus(path);
    } else {
        statuses = pathType == PathType.GLOB ? fs.globStatus(path, filter) : fs.listStatus(path, filter);
    }

    if (statuses == null) {
        statuses = NO_STATUSES;
    } else {
        if (ordering == null) {
            // If order does not matter, use a random order
            Collections.shuffle(Arrays.asList(statuses));
        } else {
            Arrays.sort(statuses, ordering);
        }
    }

    closer = Closer.create();

    Iterator<Iterator<Pair<K, V>>> fsIterators = Iterators.transform(Iterators.forArray(statuses),
            new Function<FileStatus, Iterator<Pair<K, V>>>() {
                @Override
                public Iterator<Pair<K, V>> apply(FileStatus from) {
                    try {
                        SequenceFileIterator<K, V> iterator = new SequenceFileIterator<K, V>(from.getPath(),
                                reuseKeyValueInstances, conf);
                        closer.register(iterator);
                        return iterator;
                    } catch (IOException ioe) {
                        throw new IllegalStateException(from.getPath().toString(), ioe);
                    }
                }
            });

    delegate = Iterators.concat(fsIterators);
}

From source file:cc.pinel.mangue.storage.MangaStorage.java

public void addManga(Manga manga) throws IOException {
    JSONObject json = null;/*from www .java  2s .  c om*/

    try {
        json = readJSON();
    } catch (Exception e) {
        // ignored
    }
    if (json == null)
        json = new JSONObject();

    JSONArray jsonMangas = (JSONArray) json.get("mangas");
    if (jsonMangas == null) {
        jsonMangas = new JSONArray();
        json.put("mangas", jsonMangas);
    }

    JSONObject jsonManga = findManga(jsonMangas, manga.getId());
    if (jsonManga == null) {
        jsonManga = new JSONObject();
        jsonManga.put("id", manga.getId());
        jsonManga.put("name", manga.getName());
        jsonManga.put("path", manga.getPath());

        jsonMangas.add(jsonManga);

        Object[] sortedArray = jsonMangas.toArray();
        Arrays.sort(sortedArray, new Comparator() {
            public int compare(Object o1, Object o2) {
                JSONObject manga1 = (JSONObject) o1;
                JSONObject manga2 = (JSONObject) o2;
                return manga1.get("name").toString().compareTo(manga2.get("name").toString());
            }
        });

        JSONArray sortedJSONArray = new JSONArray();
        for (int i = 0; i < sortedArray.length; i++)
            sortedJSONArray.add(sortedArray[i]);
        json.put("mangas", sortedJSONArray);

        writeJSON(json);
    }
}

From source file:net.sf.jvifm.control.ListFileCommand.java

@SuppressWarnings("unchecked")
public void execute() throws Exception {

    if (pwd == null)
        return;/*from   w ww.j  a  va 2s .  com*/
    if (pwd.length() == 2 && pwd.endsWith(":")) {
        pwd = pwd + File.separator;
    }
    File currentDir = new File(pwd);

    String[] filters = cmdLine.getArgs();
    OrFileFilter orFileFilter = new OrFileFilter();

    if (filters == null || filters.length < 1) {
        orFileFilter.addFileFilter(new WildcardFileFilter("*"));
    } else {
        for (int i = 0; i < filters.length; i++) {
            orFileFilter.addFileFilter(new WildcardFileFilter(filters[i]));
        }
    }

    if (cmdLine.hasOption("R")) {
        // FileFinder finder = new FileFinder();
        // subFiles = finder.find(currentDir, orFileFilter);
    } else {
        subFiles = currentDir.listFiles((FilenameFilter) orFileFilter);
    }

    if (cmdLine.hasOption("r")) {
        if (cmdLine.hasOption("t")) {
            Arrays.sort(subFiles, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
        } else if (cmdLine.hasOption("S")) {
            Arrays.sort(subFiles, SizeFileComparator.SIZE_REVERSE);
        } else if (cmdLine.hasOption("X")) {
            Arrays.sort(subFiles, ExtensionFileComparator.EXTENSION_REVERSE);
        } else {
            Arrays.sort(subFiles, FileComprator.getFileComprator("name", true));
        }
    } else {
        if (cmdLine.hasOption("t")) {
            Arrays.sort(subFiles, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
        } else if (cmdLine.hasOption("S")) {
            Arrays.sort(subFiles, SizeFileComparator.SIZE_COMPARATOR);
        } else if (cmdLine.hasOption("X")) {
            Arrays.sort(subFiles, ExtensionFileComparator.EXTENSION_COMPARATOR);
        } else {
            Arrays.sort(subFiles, FileComprator.getFileComprator("name", false));
        }
    }

    listSubFileInPanel(subFiles);

}

From source file:ar.com.tadp.xml.rinzo.core.contentassist.processors.CompositeXMLContentAssistProcessor.java

public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
    this.viewer = viewer;
    ICompletionProposal result[] = null;
    Collection<ICompletionProposal> resultList = new ArrayList<ICompletionProposal>();
    XMLNode currentNode = this.editor.getModel().getTree().getActiveNode(documentOffset);

    //TODO MAKE THIS METHOD TO CALL this.computeCompletionProposal SO EACH PROCESSOR COULD GIVE PROPOSALS FOR AN EMPTY FILE LIKE FILE TEMPLATES
    if (currentNode == null) {
        return new ICompletionProposal[0];
    }/* ww w .  ja v a 2 s.co m*/

    if (currentNode.offset == documentOffset) {
        currentNode = this.editor.getModel().getTree().getPreviousNode(documentOffset);
    }

    this.computeCompletionProposal(resultList, documentOffset, currentNode);
    result = (ICompletionProposal[]) resultList.toArray(new ICompletionProposal[resultList.size()]);

    Arrays.sort(result, XMLCompletionProposalComparator.getInstance());

    return result;
}

From source file:com.sinosoft.one.mvc.web.impl.module.ControllerRef.java

private void init() {
    List<MethodRef> actions = new LinkedList<MethodRef>();
    Class<?> clz = controllerClass;
    ///*from  ww  w .  j av  a  2s . c  o  m*/
    List<Method> pastMethods = new LinkedList<Method>();
    while (true) {
        Method[] declaredMethods = clz.getDeclaredMethods();

        //class?ReqMethodvalue??ReqMethod?methodName
        //sort?,???????0?0+1??,??????
        Arrays.sort(declaredMethods, new Comparator<Method>() {
            public int compare(Method o1, Method o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        //?ReqMethod?ReqMethod.value?
        Map<ReqMethod, Method> checkReqMethod = new HashMap<ReqMethod, Method>();

        for (Method method : declaredMethods) {
            if (quicklyPass(pastMethods, method, controllerClass)) {
                continue;
            }

            Map<ReqMethod, String[]> shotcutMappings = collectsShotcutMappings(method);
            if (shotcutMappings.size() == 0) {
                if (ignoresCommonMethod(method)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("ignores common methods of controller " + controllerClass.getName() + "#"
                                + method.getName());
                    }
                } else {
                    // TODO: ?0.91.0?201007??
                    if ("get".equals(method.getName()) || "index".equals(method.getName())) {
                        // ??get/index@Get?@Get??
                        throw new IllegalArgumentException(
                                "please add @Get to " + controllerClass.getName() + "#" + method.getName());
                    }
                    if ("post".equals(method.getName()) || "delete".equals(method.getName())
                            || "put".equals(method.getName())) {
                        // ??post/delete/put@Get/@Delete/@Put?@Get??
                        throw new IllegalArgumentException(
                                "please add @" + StringUtils.capitalize(method.getName()) + " to "
                                        + controllerClass.getName() + "#" + method.getName());
                    }
                    shotcutMappings = new HashMap<ReqMethod, String[]>();
                    shotcutMappings.put(ReqMethod.GET, new String[] { "/" + method.getName() });
                    shotcutMappings.put(ReqMethod.POST, new String[] { "/" + method.getName() });
                }
            }
            if (shotcutMappings.size() > 0) {
                MethodRef methodRef = new MethodRef();
                for (Map.Entry<ReqMethod, String[]> entry : shotcutMappings.entrySet()) {

                    //?ReqMethod?ReqMethod.value?
                    if (entry.getValue().length == 1 && entry.getValue()[0].equals("")) {
                        if (checkReqMethod.get(entry.getKey()) == null) {
                            checkReqMethod.put(entry.getKey(), method);
                        } else {
                            entry.setValue(new String[] { "/" + method.getName() });
                        }
                    }

                    if (logger.isDebugEnabled()) {
                        logger.debug("[MethodPath] create:" + entry.getKey() + "="
                                + Arrays.toString(entry.getValue()));
                    }
                    methodRef.addMapping(entry.getKey(), entry.getValue());
                }
                methodRef.setMethod(method);
                actions.add(methodRef);
            }
        }
        for (int i = 0; i < declaredMethods.length; i++) {
            pastMethods.add(declaredMethods[i]);
        }
        clz = clz.getSuperclass();
        if (clz == null || clz.getAnnotation(AsSuperController.class) == null) {
            break;
        }
    }
    this.actions = actions;
}

From source file:ddf.mime.mapper.MimeTypeToTransformerMapperImpl.java

@Override
public <T> List<T> findMatches(Class<T> clazz, MimeType userMimeType) {
    BundleContext bundleContext = getContext();
    ServiceReference[] refs = null;/*from  w  w  w. j av a2  s .  co m*/
    List<T> list = new ArrayList<T>();

    if (bundleContext == null) {
        LOGGER.debug("Cannot find matches, bundle context is null.");
        return list;
    }
    if (clazz == null) {
        LOGGER.warn("Cannot find matches, service argument is null.");
        throw new IllegalArgumentException("Invalid argument supplied, null service argument");
    }

    /*
     * Extract the services using the bundle context.
     */
    try {
        refs = bundleContext.getServiceReferences(clazz.getName(), null);
    } catch (InvalidSyntaxException e) {
        LOGGER.warn("Invalid filter syntax ", e);
        throw new IllegalArgumentException("Invalid syntax supplied: " + userMimeType.toString());
    }

    // If no InputTransformers found, return empty list
    if (refs == null) {
        LOGGER.debug("No {} services found - return empty list", clazz.getName());
        return list;
    }

    /*
     * Sort the list of service references based in it's Comparable interface.
     */
    Arrays.sort(refs, Collections.reverseOrder());

    /*
     * If the mime type is null return the whole list of service references
     */
    if (userMimeType == null) {
        if (refs.length > 0) {
            for (ServiceReference ref : refs) {
                Object service = (bundleContext.getService(ref));
                T typedService = clazz.cast(service);
                list.add(typedService);
            }
        }
        return list;
    }

    String userIdValue = userMimeType.getParameter(MimeTypeToTransformerMapper.ID_KEY);
    List<T> strictlyMatching = new ArrayList<T>();

    for (ServiceReference ref : refs) {

        List<String> mimeTypesServicePropertyList = getServiceMimeTypesList(ref);

        String serviceId = getServiceId(ref);

        for (String mimeTypeRawEntry : mimeTypesServicePropertyList) {

            MimeType mimeTypeEntry = constructMimeType(mimeTypeRawEntry);

            if (mimeTypeEntry != null
                    && StringUtils.equals(mimeTypeEntry.getBaseType(), userMimeType.getBaseType())
                    && (userIdValue == null || StringUtils.equals(userIdValue, serviceId))) {

                try {
                    Object service = bundleContext.getService(ref);
                    T typedService = clazz.cast(service);
                    strictlyMatching.add(typedService);
                    break; // found exact mimetype, no need to continue within
                    // the same service

                } catch (ClassCastException cce) {
                    LOGGER.debug("Caught illegal cast to transformer type. ", cce);
                }
            }
        }
    }

    return strictlyMatching;
}

From source file:com.baasbox.service.dbmanager.DbManagerService.java

public static List<String> getExports() {
    java.io.File dir = new java.io.File(backupDir);
    if (!dir.exists()) {
        dir.mkdirs();/*from  w  ww  .  ja v a 2  s. co m*/
    }
    Collection<java.io.File> files = FileUtils.listFiles(dir, new String[] { "zip" }, false);
    File[] fileArr = files.toArray(new File[files.size()]);

    Arrays.sort(fileArr, LastModifiedFileComparator.LASTMODIFIED_REVERSE);

    List<String> fileNames = new ArrayList<String>();
    for (java.io.File file : fileArr) {
        fileNames.add(file.getName());
    }
    return fileNames;
}

From source file:com.logsniffer.model.file.RollingLogsSource.java

protected Log[] getPastLogs(final String liveLog) throws IOException {
    final File dir = new File(FilenameUtils.getFullPathNoEndSeparator(liveLog));
    final String pastPattern = FilenameUtils.getName(liveLog) + getPastLogsSuffixPattern();
    final FileFilter fileFilter = new WildcardFileFilter(pastPattern);
    final File[] files = dir.listFiles(fileFilter);
    final FileLog[] logs = new FileLog[files.length];
    Arrays.sort(files, getPastLogsType().getPastComparator());
    int i = 0;/*from  www .j  ava  2s  .  c  om*/
    for (final File file : files) {
        // TODO Decouple direct file log association
        logs[i++] = new FileLog(file);
    }
    logger.debug("Found {} past logs for {} with pattern {}", logs.length, liveLog, pastPattern);
    return logs;
}

From source file:org.carewebframework.api.spring.ResourceCache.java

/**
 * Use application context to enumerate resources. This call is thread safe.
 * /*from   w  w  w.  j  a  va  2s .com*/
 * @param pattern Pattern to be used to lookup resources.
 * @param ctx Resource cache-aware application context to be used to lookup resources.
 * @return An array of matching resources, sorted alphabetically by file name.
 * @throws IOException IO exception.
 */
private synchronized Resource[] internalGet(String pattern, IResourceCacheAware ctx) throws IOException {
    Resource[] resources = get(pattern);

    if (resources != null) {
        return resources;
    }

    resources = ctx.getResourcesForCache(pattern);

    if (resources == null) {
        resources = new Resource[0];
    } else {
        Arrays.sort(resources, resourceComparator);
    }

    put(pattern, resources);
    return resources;
}

From source file:com.greenpepper.repository.FileSystemRepository.java

private void navigateInto(File directory, Hashtable<String, Vector<?>> pageBranch) throws IOException {
    File[] files = directory.listFiles(NOT_HIDDEN);
    if (files != null) {
        Arrays.sort(files, PathFileComparator.PATH_COMPARATOR);
        for (File file : files) {
            if (file.isDirectory() || isSupported(file)) {
                generateDocumentNode(file, pageBranch);
            }// w  w w .j  a  va  2s.c  om
        }
    }
}