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:dpfmanager.shell.interfaces.gui.component.report.ReportsModel.java

public void readReports() {
    int start = getData().size() - 1;
    if (start < 0) {
        start = 0;//from  ww w  .  j  a  v  a 2 s.  c  om
    }
    int count = reports_loaded;

    ObservableList<ReportRow> rows = FXCollections.observableArrayList(new ArrayList<>());
    String baseDir = ReportGenerator.getReportsFolder();
    File reportsDir = new File(baseDir);
    if (reportsDir.exists()) {
        String[] directories = reportsDir.list((current, name) -> new File(current, name).isDirectory());
        Arrays.sort(directories, Collections.reverseOrder());
        int index = 0;
        for (int i = 0; i < directories.length; i++) {
            String reportDay = directories[i];
            File reportsDay = new File(baseDir + "/" + reportDay);
            String[] directories2 = reportsDay.list((current, name) -> new File(current, name).isDirectory());

            // Convert to ints for ordering
            Integer[] int_directories = new Integer[directories2.length];
            for (int j = 0; j < directories2.length; j++) {
                try {
                    int_directories[j] = Integer.parseInt(directories2[j]);
                } catch (Exception ex) {
                    context.send(BasicConfig.MODULE_MESSAGE, new LogMessage(getClass(), Level.DEBUG,
                            bundle.getString("incorrectReport") + ": " + directories2[j]));
                    int_directories[j] = -1;
                }
            }
            Arrays.sort(int_directories, Collections.reverseOrder());

            if (index + directories2.length >= start) {
                String[] available_formats = { "html", "xml", "json", "pdf" };
                for (int j = 0; j < int_directories.length; j++) {
                    if (int_directories[j] < 0)
                        continue;
                    String reportDir = String.valueOf(int_directories[j]);
                    if (index >= start && index < start + count) {
                        ReportRow rr = null;
                        File reportXml = new File(baseDir + "/" + reportDay + "/" + reportDir + "/summary.xml");
                        File reportJson = new File(
                                baseDir + "/" + reportDay + "/" + reportDir + "/summary.json");
                        File reportHtml = new File(
                                baseDir + "/" + reportDay + "/" + reportDir + "/report.html");
                        File reportPdf = new File(baseDir + "/" + reportDay + "/" + reportDir + "/report.pdf");

                        if (reportXml.exists() && reportXml.length() > 0) {
                            rr = ReportRow.createRowFromXml(reportDay, reportXml, getBundle());
                        }
                        if (rr == null && reportJson.exists() && reportJson.length() > 0) {
                            rr = ReportRow.createRowFromJson(reportDay, reportJson, getBundle());
                        }
                        if (rr == null && reportHtml.exists() && reportHtml.length() > 0) {
                            rr = ReportRow.createRowFromHtml(reportDay, reportHtml, getBundle());
                        }
                        if (rr == null && reportPdf.exists() && reportPdf.length() > 0) {
                            rr = ReportRow.createRowFromPdf(reportDay, reportPdf, getBundle());
                        }

                        if (rr != null) {
                            // Add formats
                            for (String format : available_formats) {
                                File report;
                                if (format == "json" || format == "xml") {
                                    report = new File(
                                            baseDir + "/" + reportDay + "/" + reportDir + "/summary." + format);
                                } else {
                                    report = new File(
                                            baseDir + "/" + reportDay + "/" + reportDir + "/report." + format);
                                }
                                if (report.exists() && report.length() > 0) {
                                    rr.addFormat(format, report.getPath());
                                }
                            }
                            // Add mets
                            File folder = new File(baseDir + "/" + reportDay + "/" + reportDir + "/");
                            if (folder.exists() && folder.isDirectory()) {
                                String[] filter = { "mets.xml" };
                                Collection<File> childs = FileUtils.listFiles(folder, filter, false);
                                if (childs.size() > 0) {
                                    rr.addFormat("mets", folder.getPath());
                                }
                            }
                            rows.add(rr);
                            index++;
                        }

                        // Check if all done
                        if (i == directories.length - 1 && j == directories2.length - 1) {
                            all_reports_loaded = true;
                        }
                    } else {
                        index++;
                    }
                }

            } else {
                index += directories2.length;
            }
        }
    }
    data.addAll(rows);
}

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 www  . j  a  v  a2 s .c om
 */
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:com.ricemap.spateDB.core.PrismNN.java

public static <S1 extends Shape, S2 extends Shape> int SpatialJoin_planeSweep(final S1[] R, final S2[] S,
        ResultCollector2<S1, S2> output) {
    int count = 0;

    final Comparator<Shape> comparator = new Comparator<Shape>() {
        @Override//from   w  w  w .  j  a  va  2s. c  om
        public int compare(Shape o1, Shape o2) {
            return o1.getMBR().x1 < o2.getMBR().x1 ? -1 : 1;
        }
    };

    LOG.info("Joining " + R.length + " with " + S.length);
    Arrays.sort(R, comparator);
    Arrays.sort(S, comparator);

    int i = 0, j = 0;

    while (i < R.length && j < S.length) {
        S1 r;
        S2 s;
        if (comparator.compare(R[i], S[j]) < 0) {
            r = R[i];
            int jj = j;

            while ((jj < S.length) && ((s = S[jj]).getMBR().x1 <= r.getMBR().x2)) {
                if (r.isIntersected(s)) {
                    if (output != null)
                        output.collect(r, s);
                    count++;
                }
                jj++;
            }
            i++;
        } else {
            s = S[j];
            int ii = i;

            while ((ii < R.length) && ((r = R[ii]).getMBR().x1 <= s.getMBR().x2)) {
                if (r.isIntersected(s)) {
                    if (output != null)
                        output.collect(r, s);
                    count++;
                }
                ii++;
            }
            j++;
        }
    }
    LOG.info("Finished plane sweep and found " + count + " pairs");
    return count;
}

From source file:ie.programmer.catcher.browser.FileBrowserEngine.FileBrowserEngine.java

/**
 * Loads the specified folder.//from w  w w.  j  a v a2 s.c  o m
 *
 * @param directory The file object to points to the directory to load.
 * @return An {@link AdapterData} object that holds the data of the specified directory.
 */
public AdapterData loadDir(File directory) {
    mCurrentDir = directory;
    //Init the directory's data arrays.
    ArrayList<String> namesList = new ArrayList<String>();
    ArrayList<String> pathsList = new ArrayList<String>();
    ArrayList<Integer> typesList = new ArrayList<Integer>();
    ArrayList<String> sizesList = new ArrayList<String>();
    //Grab a list of all files/subdirs within the specified directory.
    File[] files = directory.listFiles();
    if (files != null) {
        //Sort the files/subdirs by name.
        Arrays.sort(files, NameFileComparator.NAME_INSENSITIVE_COMPARATOR);
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if ((!file.isHidden() || mFileBrowserView.shouldShowHiddenFiles()) && file.canRead()) {
                if (file.isDirectory() && mFileBrowserView.shouldShowFolders()) {

                    /*
                     * Starting with Android 4.2, /storage/emulated/legacy/...
                    * is a symlink that points to the actual directory where
                    * the user's files are stored. We need to detect the
                    * actual directory's file path here.
                    */
                    String filePath;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
                        filePath = getRealFilePath(file.getAbsolutePath());
                    else
                        filePath = file.getAbsolutePath();
                    pathsList.add(filePath);
                    namesList.add(file.getName());
                    File[] listOfFiles = file.listFiles();
                    if (listOfFiles != null) {
                        typesList.add(FOLDER);
                        if (listOfFiles.length == 1) {
                            sizesList.add("" + listOfFiles.length + " item");
                        } else {
                            sizesList.add("" + listOfFiles.length + " items");
                        }
                    } else {
                        typesList.add(FOLDER);
                        sizesList.add("Unknown items");
                    }
                } else {
                    try {
                        String path = file.getCanonicalPath();
                        if (isFilteredFile(path)) {
                            continue;
                        }
                        pathsList.add(path);
                    } catch (Exception e) {
                        Log.e("File Error", e.getMessage());
                        continue;
                    }
                    namesList.add(file.getName());
                    String fileName = "";
                    try {
                        fileName = file.getCanonicalPath();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    //Add the file element to typesList based on the file type.
                    if (getFileExtension(fileName).equalsIgnoreCase("mp3")
                            || getFileExtension(fileName).equalsIgnoreCase("3gp")
                            || getFileExtension(fileName).equalsIgnoreCase("mp4")
                            || getFileExtension(fileName).equalsIgnoreCase("m4a")
                            || getFileExtension(fileName).equalsIgnoreCase("aac")
                            || getFileExtension(fileName).equalsIgnoreCase("ts")
                            || getFileExtension(fileName).equalsIgnoreCase("flac")
                            || getFileExtension(fileName).equalsIgnoreCase("mid")
                            || getFileExtension(fileName).equalsIgnoreCase("xmf")
                            || getFileExtension(fileName).equalsIgnoreCase("mxmf")
                            || getFileExtension(fileName).equalsIgnoreCase("midi")
                            || getFileExtension(fileName).equalsIgnoreCase("rtttl")
                            || getFileExtension(fileName).equalsIgnoreCase("rtx")
                            || getFileExtension(fileName).equalsIgnoreCase("ota")
                            || getFileExtension(fileName).equalsIgnoreCase("imy")
                            || getFileExtension(fileName).equalsIgnoreCase("ogg")
                            || getFileExtension(fileName).equalsIgnoreCase("mkv")
                            || getFileExtension(fileName).equalsIgnoreCase("wav")) {
                        //The file is an audio file.
                        typesList.add(FILE_AUDIO);
                        sizesList.add("" + getFormattedFileSize(file.length()));
                    } else if (getFileExtension(fileName).equalsIgnoreCase("jpg")
                            || getFileExtension(fileName).equalsIgnoreCase("gif")
                            || getFileExtension(fileName).equalsIgnoreCase("png")
                            || getFileExtension(fileName).equalsIgnoreCase("bmp")
                            || getFileExtension(fileName).equalsIgnoreCase("webp")) {
                        //The file is a picture file.
                        typesList.add(FILE_PICTURE);
                        sizesList.add("" + getFormattedFileSize(file.length()));
                    } else if (getFileExtension(fileName).equalsIgnoreCase("3gp")
                            || getFileExtension(fileName).equalsIgnoreCase("mp4")
                            || getFileExtension(fileName).equalsIgnoreCase("3gp")
                            || getFileExtension(fileName).equalsIgnoreCase("ts")
                            || getFileExtension(fileName).equalsIgnoreCase("webm")
                            || getFileExtension(fileName).equalsIgnoreCase("mkv")) {
                        //The file is a video file.
                        typesList.add(FILE_VIDEO);
                        sizesList.add("" + getFormattedFileSize(file.length()));
                    } else {
                        //We don't have an icon for this file type so give it the generic file flag.
                        typesList.add(FILE_GENERIC);
                        sizesList.add("" + getFormattedFileSize(file.length()));
                    }
                }
            }
        }
    }
    return new AdapterData(namesList, typesList, pathsList, sizesList);
}

From source file:com.mac.holdempoker.app.impl.util.HandMatrix.java

public HandRank getHand() throws InvalidHandException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException {
    if (hasValidHand()) {
        Method[] methods = this.getClass().getDeclaredMethods();
        Arrays.sort(methods, new MethodNameComparator());
        for (Method method : methods) {
            method.setAccessible(true);/*  w w w  .jav a  2  s  .  c o  m*/
            String methodName = method.getName();
            //                System.out.println(methodName);
            Matcher m = METHOD_PATTERN.matcher(methodName);
            if (m.matches()) {
                Object[] args = null;
                Object obj = method.invoke(this, args);
                if (Objects.nonNull(obj)) {
                    HandRank hr = (HandRank) obj;
                    if (Objects.nonNull(hr)) {
                        method.setAccessible(false);
                        return hr;
                    }
                }
            }
            method.setAccessible(false);
        }
    }
    throw new InvalidHandException();
}

From source file:com.juliazozulia.wordusage.Utils.Frequency.java

public String[] getItems() {

    String[] str = freqTable.keySet().toArray(new String[getUniqueCount()]);
    Arrays.sort(str, new Comparator<String>() {
        public int compare(String o1, String o2) {
            return getCount(o2).compareTo(getCount(o1));
        }//  w w w .  j  a v a 2s.  c o m
    });
    return str;
}

From source file:CrossRef.java

/**
 * Print the fields and methods of one class.
 *///w w w .j a  va2s .co m
protected void doClass(Class c) {
    int i, mods;
    startClass(c);
    try {
        Field[] fields = c.getDeclaredFields();
        Arrays.sort(fields, new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Field) o1).getName().compareTo(((Field) o2).getName());
            }
        });
        for (i = 0; i < fields.length; i++) {
            Field field = (Field) fields[i];
            if (!Modifier.isPrivate(field.getModifiers()))
                putField(field, c);
            // else System.err.println("private field ignored: " + field);
        }

        Method methods[] = c.getDeclaredMethods();
        // Arrays.sort(methods);
        for (i = 0; i < methods.length; i++) {
            if (!Modifier.isPrivate(methods[i].getModifiers()))
                putMethod(methods[i], c);
            // else System.err.println("pvt: " + methods[i]);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    endClass();
}

From source file:com.unister.semweb.drums.TestUtils.java

public static DummyKVStorable[] generateTestdata(int numberToGenerate) {
    DummyKVStorable[] result = new DummyKVStorable[numberToGenerate];
    for (int i = 0; i < numberToGenerate; i++) {
        DummyKVStorable oneEntry = TestUtils.createDummyData(Bytes.toBytes(i + 1l), i + 1000, i - 0.05);
        result[i] = oneEntry;//from w ww . j  a va  2s .co  m
    }

    Arrays.sort(result, new AbstractKVStorableComparator());
    return result;
}

From source file:RectListManager.java

/**
 * Construct a <tt>RectListManager</tt> from a Collection of Rectangles
 * @param rects Collection that must only contain rectangles.
 *///  w w  w.ja v a 2s  .c  o  m
public RectListManager(Collection rects) {
    this.rects = new Rectangle[rects.size()];
    Iterator i = rects.iterator();
    int j = 0;
    while (i.hasNext()) // todo can be replaced by rects.toArray()
        this.rects[j++] = (Rectangle) i.next();
    this.size = this.rects.length;

    Arrays.sort(this.rects, comparator);
}

From source file:com.laxser.blitz.lama.provider.jdbc.JdbcDataAccessProvider.java

/**
 * findPlugin<br>//from  ww  w. j ava  2 s  . c om
 * 
 * @return
 * 
 * @author tai.wang@opi-corp.com May 26, 2010 - 4:30:09 PM
 */
protected JdbcWrapper[] findJdbcWrappers() {
    // JdbcWrapperscoreprototype
    @SuppressWarnings("unchecked")
    Collection<JdbcWrapper> jdbcWrappers = this.applicationContext.getBeansOfType(JdbcWrapper.class).values();
    JdbcWrapper[] arrayJdbcWrappers = jdbcWrappers.toArray(new JdbcWrapper[0]);
    for (JdbcWrapper jdbcWrapper : arrayJdbcWrappers) {
        Assert.isNull(jdbcWrapper.getJdbc());// jdbc should be null here
    }
    Arrays.sort(arrayJdbcWrappers, new Comparator<JdbcWrapper>() {

        @Override
        public int compare(JdbcWrapper thees, JdbcWrapper that) {
            Order thessOrder = thees.getClass().getAnnotation(Order.class);
            Order thatOrder = that.getClass().getAnnotation(Order.class);
            int thessValue = thessOrder == null ? 0 : thessOrder.value();
            int thatValue = thatOrder == null ? 0 : thatOrder.value();
            return thessValue - thatValue;
        }

    });
    return arrayJdbcWrappers;
}