Example usage for java.util Collections reverse

List of usage examples for java.util Collections reverse

Introduction

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

Prototype

@SuppressWarnings({ "rawtypes", "unchecked" })
public static void reverse(List<?> list) 

Source Link

Document

Reverses the order of the elements in the specified list.

This method runs in linear time.

Usage

From source file:com.hp.alm.ali.idea.ui.MultipleItemsDialog.java

public MultipleItemsDialog(Project project, String title, final MultipleItemsDialogModel<K, E> model) {
    super(project, title, true);

    this.model = model;

    mySelectionModel = new MySelectionModel();
    myListSelectionListener = new MyListSelectionListener();

    tooMany = new JLabel("Too many results, narrow your search");
    tooMany.setBorder(BorderFactory.createEtchedBorder());
    tooMany.setVisible(false);/* w ww . jav  a 2 s . c o  m*/
    selected = new JLabel("Showing currently selected items");
    selected.setVisible(false);
    toggleSelected = new JToggleButton();
    toggleSelected.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            model.setShowingSelected(toggleSelected.isSelected());
            if (!model.isShowingSelected() && !model.getSelectedFields().isEmpty()) {
                updateSelectionFromModel();
            } else if (model.isShowingSelected()) {
                header.getFilterEditor(1).setContent("");
            }
        }
    });
    updateSelected();

    table = new JBTable() {
        @Override
        public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) {
            int column = convertColumnIndexToModel(columnIndex);
            mySelectionModel.setFirstColumnEvent(column == 0);
            super.changeSelection(rowIndex, columnIndex, toggle, extend);
        }
    };
    table.setRowSelectionAllowed(true);
    table.setColumnSelectionAllowed(false);
    table.setAutoCreateColumnsFromModel(false);
    table.setModel(model);
    final MyTableRowSorter sorter = new MyTableRowSorter(model);
    table.setRowSorter(sorter);
    table.setDefaultRenderer(Boolean.class, new MyRenderer());
    table.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
    table.setSelectionModel(mySelectionModel);

    sorter.setIgnoreAddRowSorterListener(true); // prevent auto-selection (functionality not accessible via proper API)
    header = new TableFilterHeader(table);
    sorter.setIgnoreAddRowSorterListener(false);

    sorter.setSortKeys(Arrays.asList(new RowSorter.SortKey(1, SortOrder.ASCENDING)));
    JPanel panel = new JPanel(new BorderLayout());
    JPanel toolbar = new JPanel(new BorderLayout());
    toolbar.setBorder(BorderFactory.createEtchedBorder());
    panel.add(toolbar, BorderLayout.NORTH);
    toolbar.add(toggleSelected, BorderLayout.EAST);

    if (model.isMultiple()) {
        table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        table.getColumnModel().addColumn(createColumn(0, model, 45, 45));
        header.getFilterEditor(0).setEditable(false);
        header.getFilterEditor(0).setUserInteractionEnabled(false);

        final LinkListener selectUnselect = new LinkListener() {
            public void linkSelected(LinkLabel aSource, Object aLinkData) {
                if (model.isShowingSelected()) {
                    if (!Boolean.TRUE.equals(aLinkData)) {
                        List<Integer> ixs = new ArrayList<Integer>();
                        for (int i = 0; i < sorter.getViewRowCount(); i++) {
                            ixs.add(sorter.convertRowIndexToModel(i));
                        }
                        // make sure indexes are not affected by removal by starting from the last
                        Collections.sort(ixs);
                        Collections.reverse(ixs);
                        for (int ix : ixs) {
                            model.setValueAt(aLinkData, ix, 0);
                        }
                    }
                } else {
                    if (Boolean.TRUE.equals(aLinkData)) {
                        mySelectionModel.doAddSelectionInterval(0, table.getRowCount() - 1);
                    } else {
                        mySelectionModel.removeSelectionInterval(0, table.getRowCount() - 1);
                    }
                }
            }
        };

        JPanel left = new JPanel(new FlowLayout(FlowLayout.LEFT));
        left.add(new LinkLabel("Select All", IconLoader.getIcon("/actions/selectall.png"), selectUnselect,
                true));
        left.add(new LinkLabel("Unselect All", IconLoader.getIcon("/actions/unselectall.png"), selectUnselect,
                false));
        toolbar.add(left, BorderLayout.WEST);
    } else {
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }
    table.getColumnModel().addColumn(createColumn(1, model, 450, null));
    table.getSelectionModel().addListSelectionListener(myListSelectionListener);

    model.addTableModelListener(new TableModelListener() {
        @Override
        public void tableChanged(TableModelEvent e) {
            selected.setVisible(model.isShowingSelected());
            tooMany.setVisible(model.hasMore() && !model.isShowingSelected());
            updateSelected();
        }
    });

    JPanel contentPanel = new JPanel(new BorderLayout());
    contentPanel.add(selected, BorderLayout.NORTH);
    contentPanel.add(new JBScrollPane(table), BorderLayout.CENTER);
    contentPanel.add(tooMany, BorderLayout.SOUTH);
    panel.add(contentPanel, BorderLayout.CENTER);
    JPanel buttons = new JPanel();
    okButton = new JButton("OK");
    okButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            ok = true;
            close(true);
        }
    });
    buttons.add(okButton);
    JButton cancel = new JButton("Cancel");
    cancel.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            close(false);
        }
    });
    buttons.add(cancel);
    panel.add(buttons, BorderLayout.SOUTH);
    getContentPane().add(panel, BorderLayout.CENTER);

    pack();
    setResizable(false);
    centerOnOwner();

    requestPropertyFilterFocus(header);

    load(true, null);
}

From source file:org.zaproxy.zap.extension.multiFuzz.impl.http.HttpFuzzResultDialog.java

@Override
public JXTreeTable getTable() {
    if (table == null) {
        if (model == null) {
            model = new HttpFuzzTableModel();
        }/*from  w w w .  ja  v a  2  s.  c o  m*/
        table = new JXTreeTable(model);
        table.setDoubleBuffered(true);
        table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        table.setName("HttpFuzzResultTable");
        table.setFont(new java.awt.Font("Default", java.awt.Font.PLAIN, 12));
        table.setDefaultRenderer(Pair.class, new IconTableCellRenderer());

        int[] widths = { 10, 25, 550, 30, 85, 55, 40, 70 };
        for (int i = 0, count = widths.length; i < count; i++) {
            TableColumn column = table.getColumnModel().getColumn(i);
            column.setPreferredWidth(widths[i]);
        }
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mousePressed(java.awt.event.MouseEvent e) {
                showPopupMenuIfTriggered(e);
            }

            @Override
            public void mouseReleased(java.awt.event.MouseEvent e) {
                showPopupMenuIfTriggered(e);
            }

            private void showPopupMenuIfTriggered(java.awt.event.MouseEvent e) {
                if (e.isPopupTrigger()) {
                    if (e.isPopupTrigger()) {
                        // Select list item on right click
                        JTable table = (JTable) e.getSource();
                        int row = table.rowAtPoint(e.getPoint());

                        if (!table.isRowSelected(row)) {
                            table.changeSelection(row, 0, false, false);
                        }
                        View.getSingleton().getPopupMenu().show(e.getComponent(), e.getX(), e.getY());
                    }
                }
            }

        });
        table.getSelectionModel().addListSelectionListener(new javax.swing.event.ListSelectionListener() {

            @Override
            public void valueChanged(javax.swing.event.ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    if (table.getSelectedRowCount() == 0) {
                        return;
                    }
                    final int row = table.getSelectedRow();
                    if (getEntry(row) instanceof HttpFuzzRequestRecord) {
                        final HistoryReference historyReference = ((HttpFuzzRequestRecord) getEntry(row))
                                .getHistory();
                        try {
                            getMessageInspection().setMessage(historyReference.getHttpMessage());
                        } catch (HttpMalformedHeaderException | SQLException ex) {
                            logger.error(ex.getMessage(), ex);
                        }
                    }
                    updateValues();
                    redrawDiagrams();
                }
            }
        });
    }
    table.getTableHeader().addMouseListener(new MouseListener() {
        int sortedOn = -1;

        @Override
        public void mouseReleased(MouseEvent arg0) {
        }

        @Override
        public void mousePressed(MouseEvent arg0) {
        }

        @Override
        public void mouseExited(MouseEvent arg0) {
        }

        @Override
        public void mouseEntered(MouseEvent arg0) {
        }

        @Override
        public void mouseClicked(MouseEvent e) {
            int index = table.columnAtPoint(e.getPoint());
            List<HttpFuzzRecord> list = model.getEntries();
            if (list.size() == 0) {
                return;
            }
            HttpFuzzRecordComparator comp = new HttpFuzzRecordComparator();
            comp.setFeature(index);
            if (index == sortedOn) {
                Collections.sort(list, comp);
                Collections.reverse(list);
                sortedOn = -1;
            } else {
                Collections.sort(list, comp);
                sortedOn = index;
            }
            table.updateUI();
        }
    });
    table.setRootVisible(false);
    table.setVisible(true);
    return table;
}

From source file:fi.vm.sade.organisaatio.resource.OrganisaatioResourceImpl.java

@Override
public String parentoids(String oid) throws Exception {
    Preconditions.checkNotNull(oid);//from   w  w w . j a  va 2 s .  c o  m
    // find parents
    final List<String> parentOidList = organisaatioSearchService.findParentOids(oid);
    Collections.reverse(parentOidList);

    // NOTE - this assumes everything is under one "root", ie. "OPH"
    if (!parentOidList.contains(rootOrganisaatioOid)) {
        parentOidList.add(0, rootOrganisaatioOid); // add root organisaatio if needed
    }
    if (!parentOidList.contains(oid)) {
        parentOidList.add(oid); // add self if needed
    }
    return Joiner.on(OID_SEPARATOR).join(parentOidList);
}

From source file:com.netflix.curator.x.discovery.TestServiceCache.java

@Test
public void testUpdate() throws Exception {
    List<Closeable> closeables = Lists.newArrayList();
    TestingServer server = new TestingServer();
    closeables.add(server);//  w  w w. j ava2 s .co m
    try {
        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                new RetryOneTime(1));
        closeables.add(client);
        client.start();

        ServiceInstance<String> instance = ServiceInstance.<String>builder().payload("thing").name("test")
                .port(10064).build();
        ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/test")
                .client(client).thisInstance(instance).build();
        closeables.add(discovery);
        discovery.start();

        final CountDownLatch latch = new CountDownLatch(1);
        ServiceCache<String> cache = discovery.serviceCacheBuilder().name("test").build();
        closeables.add(cache);
        ServiceCacheListener listener = new ServiceCacheListener() {
            @Override
            public void cacheChanged() {
                latch.countDown();
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }
        };
        cache.addListener(listener);
        cache.start();

        instance = ServiceInstance.<String>builder().payload("changed").name("test").port(10064)
                .id(instance.getId()).build();
        discovery.updateService(instance);

        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));

        Assert.assertEquals(cache.getInstances().size(), 1);
        Assert.assertEquals(cache.getInstances().get(0).getPayload(), instance.getPayload());
    } finally {
        Collections.reverse(closeables);
        for (Closeable c : closeables) {
            IOUtils.closeQuietly(c);
        }
    }
}

From source file:com.liato.bankdroid.banking.banks.SEBKortBase.java

@Override
public void update() throws BankException, LoginException, BankChoiceException {
    super.update();
    if (username == null || password == null || username.length() == 0 || password.length() == 0) {
        throw new LoginException(res.getText(R.string.invalid_username_password).toString());
    }//from w w w. j a v a2 s.  c o  m
    urlopen = login();
    Matcher matcher;
    try {
        if (!String.format("https://application.sebkort.com/nis/%s/main.do", provider_part)
                .equals(urlopen.getCurrentURI())) {
            response = urlopen
                    .open(String.format("https://application.sebkort.com/nis/%s/main.do", provider_part));
        }
        matcher = reAccounts.matcher(response);
        /*
         * Capture groups:
         * GROUP                EXAMPLE DATA
         * 1: amount            10 579,43
         * 
         */
        if (matcher.find()) {
            Account account = new Account("Kpgrns", Helpers.parseBalance(matcher.group(1)), "3");
            account.setType(Account.OTHER);
            account.setAliasfor("1");
            accounts.add(account);
        }
        if (matcher.find()) {
            Account account = new Account("Saldo", Helpers.parseBalance(matcher.group(1)), "2");
            account.setType(Account.OTHER);
            account.setAliasfor("1");
            accounts.add(account);
        }
        if (matcher.find()) {
            Account account = new Account("Disponibelt belopp", Helpers.parseBalance(matcher.group(1)), "1");
            account.setType(Account.CCARD);
            accounts.add(account);
            balance = balance.add(Helpers.parseBalance(matcher.group(1)));
        }
        Collections.reverse(accounts);
        if (accounts.isEmpty()) {
            throw new BankException(res.getText(R.string.no_accounts_found).toString());
        }
    } catch (ClientProtocolException e) {
        throw new BankException(e.getMessage());
    } catch (IOException e) {
        throw new BankException(e.getMessage());
    } finally {
        super.updateComplete();
    }
}

From source file:com.jvoid.products.product.service.CategoryProductsMasterService.java

public String getPath(int id) {

    String path = "";
    //System.out.println("PID(getPath):"+id);
    ArrayList<Integer> parentIdList = new ArrayList<>();
    Categories cat = this.categoriesService.getCategoriesById(id);
    parentIdList.add(id);//from   w w w  .j av  a 2  s .c  o  m
    int parentId = id;
    while ((parentId = getParentId(parentId)) > 0) {
        if (parentId > 0)
            parentIdList.add(parentId);
    }
    Collections.reverse(parentIdList);
    for (int i = 0; i < parentIdList.size(); i++) {
        path = path + parentIdList.get(i).intValue() + "/";
    }

    return path;
}

From source file:de.tudarmstadt.ukp.dkpro.lexsemresource.graph.EntityGraphJUNG.java

/**
 * This algorithm measures the importance of a node in terms of the fraction
 * of time spent at that node relative to all other nodes.
 *
 * @return A list of nodes with their PageRank rankings in descending order.
 *///ww w .j  a v  a2s.  c  o m
@Override
public List<String> getPageRank() {

    logger.info("Getting PageRank...");
    PageRank<Entity, EntityGraphEdge> ranker = new PageRank<Entity, EntityGraphEdge>(directedGraph, 0.15);
    logger.info("Ranker was created.");
    logger.info("Evaluating...");
    ranker.evaluate();

    logger.info("Got PageRank.");
    Collection<Entity> vertices = directedGraph.getVertices();
    List<String> rankingList = new ArrayList<String>();
    Format formatter = new Format("%7.6f");

    for (Entity vertex : vertices) {
        rankingList.add(formatter.format(ranker.getVertexScore(vertex)) + " " + vertex);
        // logger.info("PageRanking for " + vertex.getVertexEntity() + " : "
        // + ranker.getRankScore(vertex));
    }

    Collections.sort(rankingList);
    Collections.reverse(rankingList);
    // logger.info("Sorted PageRankings: " + rankingList);
    // ranker.printRankings(false, true);

    return rankingList;
}

From source file:com.clustercontrol.plugin.HinemosPluginService.java

/**
 * HinemosPlugin????.//from   w w  w  .jav  a2s. c  o  m
 * 
 * <p>
 * {@link com.clustercontrol.plugin.HinemosPluginService.activate()}?????????
 * ??deactivate???
 * </p>
 */
public synchronized void deactivate() {
    List<HinemosPlugin> pluginDeactivationOrder = new ArrayList<HinemosPlugin>(pluginActivatationOrder);
    Collections.reverse(pluginDeactivationOrder);

    for (HinemosPlugin plugin : pluginDeactivationOrder) {
        try {
            log.info("deactivating plugin - " + plugin.getClass().getName());
            pluginStatusMap.put(plugin.getClass().getName(), PluginStatus.DEACTIVATED);
            plugin.deactivate();
        } catch (Throwable t) {
            log.warn("plugin deactivation failure.", t);
        }
    }
}

From source file:com.inform.jamps.solver.gurobi.GurobiExecutionResult.java

private void determineSolutions(final GRBModel nativeModel) throws GRBException {
    final int solutionCount = nativeModel.get(IntAttr.SolCount);
    final boolean isOptimal = (nativeModel.get(IntAttr.Status) == Status.OPTIMAL);
    final boolean isMip = (nativeModel.get(IntAttr.IsMIP) == 1);

    final double bestBound = (isMip ? nativeModel.get(DoubleAttr.ObjBound)
            : nativeModel.get(DoubleAttr.ObjVal));

    final List<GurobiVariable> variables = program.getVariables();

    for (int i = 0; i < solutionCount; i++) {
        nativeModel.getEnv().set(IntParam.SolutionNumber, i);

        final GurobiSolution solution = new GurobiSolution(program, i == 0 && isOptimal);
        solution.setBestObjectiveBound(bestBound);

        for (final GurobiVariable var : variables) {
            final GRBVar nativeVariable = var.getNativeVariable();
            final double value = (isMip ? nativeVariable.get(DoubleAttr.Xn) : nativeVariable.get(DoubleAttr.X));

            // Storing value 0.0 is not necessary due to it is the default value
            if (Precision.equals(Math.abs(value), DEFAULT_SOLUTION_VAR_VALUE)) {
                continue;
            }//www.  j a v  a2  s.c  o  m

            solution.setVariableValue(var, value);
        }

        solutions.add(solution);
    }

    Collections.sort(solutions);
    if (program.determineProgramObjectiveSense() == ObjectiveSense.MAXIMIZE) {
        Collections.reverse(solutions);
    }
}

From source file:net.sourceforge.jaulp.lang.ObjectUtilsTest.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test(enabled = false)//  w w  w  . ja  va2s. c om
public void testCompareTo() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    List<Person> persons = new ArrayList<>();
    Person obelix = new Person();
    obelix.setGender(Gender.MALE);
    obelix.setName("obelix");

    Person asterix = new Person();
    asterix.setGender(Gender.MALE);
    asterix.setName("asterix");

    Person miraculix = new Person();
    miraculix.setGender(Gender.MALE);
    miraculix.setName("miraculix");

    int i = ObjectUtils.compareTo(asterix, obelix, "name");

    System.out.println(i);

    persons.add(obelix);
    persons.add(asterix);
    persons.add(miraculix);
    System.out.println("Unsorted Persons:");
    System.out.println(persons.toString());
    Comparator defaultComparator = new BeanComparator("name");
    Collections.sort(persons, defaultComparator);
    System.out.println("Sorted Persons by name:");
    System.out.println(persons.toString());
    Collections.reverse(persons);
    System.out.println("Sorted Persons by name reversed:");
    System.out.println(persons.toString());
}