Example usage for java.util Collections rotate

List of usage examples for java.util Collections rotate

Introduction

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

Prototype

public static void rotate(List<?> list, int distance) 

Source Link

Document

Rotates the elements in the specified list by the specified distance.

Usage

From source file:com.lithium.flow.jetty.JettyClient.java

@Override
@Nonnull//from ww w.  j a va  2 s  . c  o  m
public Session makeObject() throws IOException {
    List<String> urls = HostUtils.expand(config.getList("url", Splitter.on(' ')));
    Collections.rotate(urls, pos.decrementAndGet() % urls.size());
    for (String url : urls) {
        log.debug("connecting: {}", url);
        try {
            return client.connect(this, new URI(url), new ClientUpgradeRequest()).get();
        } catch (Exception e) {
            log.warn("failed to connect to url: {}", url, e);
        }
    }
    throw new IOException("unable to connect to any url: " + urls);
}

From source file:com.mac.holdempoker.app.impl.SimplePlayOrder.java

@Override
public void order(List<Player> players) {
    resetPointers();/*from ww  w .java 2  s.  c o  m*/
    clear();
    if (isFirstOrder) {
        orderPlayers(players);
    } else {
        Collections.rotate(orderedPlayers, 1);
    }
    //head to head, dealer must be small blind
    if (orderedPlayers.size() == 2) {
        orderedPlayers.get(getPlayerOrder()).addStatus(Status.BUTTON);
        orderedPlayers.get(getPlayerOrder()).addStatus(Status.BIG_BLIND);
        orderedPlayers.get(getPlayerOrder()).addStatus(Status.SMALL_BLIND);
        getPlayerOrder();
    } else {
        orderedPlayers.get(getPlayerOrder()).addStatus(Status.BUTTON);
        orderedPlayers.get(getPlayerOrder()).addStatus(Status.SMALL_BLIND);
        orderedPlayers.get(getPlayerOrder()).addStatus(Status.BIG_BLIND);
    }
}

From source file:br.com.diegosilva.jsfcomponents.util.Utils.java

/**
 * Moves the element at <tt>oldPosition</tt> to <tt>newPosition</tt>.
 * <p>/*  ww w  . ja  v  a2  s . c  o  m*/
 * Correctly handles forward and backward shifting of previous or subsequent
 * elements.
 * 
 * @param list
 *            the list that is affected
 * @param oldPosition
 *            the position of the element to move
 * @param newPosition
 *            the new position of the element
 */
public static void shiftListElement(List list, int oldPosition, int newPosition) {
    if (oldPosition > newPosition) {
        Collections.rotate(list.subList(newPosition, oldPosition + 1), +1);
    } else if (oldPosition < newPosition) {
        Collections.rotate(list.subList(oldPosition, newPosition + 1), -1);
    }
}

From source file:com.haulmont.cuba.web.gui.components.WebCalendar.java

@Override
public Map<DayOfWeek, String> getDayNames() {
    List<String> days = Arrays.asList(component.getDayNamesShort().clone());

    int shift = Math.abs(component.getFirstDayOfWeek() - java.util.Calendar.MONDAY) + 1;
    Collections.rotate(days, -shift);

    return days.stream().collect(Collectors.toMap((String d) -> DayOfWeek.of(days.indexOf(d) + 1), d -> d));
}

From source file:com.haulmont.cuba.web.gui.components.WebCalendar.java

@Override
public void setDayNames(Map<DayOfWeek, String> dayNames) {
    Preconditions.checkNotNullArgument(dayNames);

    if (!CollectionUtils.isEqualCollection(Arrays.asList(DayOfWeek.values()), dayNames.keySet())) {
        throw new IllegalArgumentException("Day names map doesn't contain all required values");
    }//from  ww w. j a  v a2s  . c o m

    List<String> daysList = Arrays.stream(DayOfWeek.values()).map(dayNames::get).collect(Collectors.toList());

    int shift = Math.abs(component.getFirstDayOfWeek() - java.util.Calendar.MONDAY) + 1;
    Collections.rotate(daysList, shift);

    String[] days = new String[7];
    component.setDayNamesShort(daysList.toArray(days));
}

From source file:org.elasticsearch.client.RestClient.java

/**
 * Returns an {@link Iterable} of hosts to be used for a request call.
 * Ideally, the first host is retrieved from the iterable and used successfully for the request.
 * Otherwise, after each failure the next host has to be retrieved from the iterator so that the request can be retried until
 * there are no more hosts available to retry against. The maximum total of attempts is equal to the number of hosts in the iterable.
 * The iterator returned will never be empty. In case there are no healthy hosts available, or dead ones to be be retried,
 * one dead host gets returned so that it can be retried.
 *///w ww . java2 s  .  c  om
private HostTuple<Iterator<HttpHost>> nextHost() {
    final HostTuple<Set<HttpHost>> hostTuple = this.hostTuple;
    Collection<HttpHost> nextHosts = Collections.emptySet();
    do {
        Set<HttpHost> filteredHosts = new HashSet<>(hostTuple.hosts);
        for (Map.Entry<HttpHost, DeadHostState> entry : blacklist.entrySet()) {
            if (System.nanoTime() - entry.getValue().getDeadUntilNanos() < 0) {
                filteredHosts.remove(entry.getKey());
            }
        }
        if (filteredHosts.isEmpty()) {
            //last resort: if there are no good host to use, return a single dead one, the one that's closest to being retried
            List<Map.Entry<HttpHost, DeadHostState>> sortedHosts = new ArrayList<>(blacklist.entrySet());
            if (sortedHosts.size() > 0) {
                Collections.sort(sortedHosts, new Comparator<Map.Entry<HttpHost, DeadHostState>>() {
                    @Override
                    public int compare(Map.Entry<HttpHost, DeadHostState> o1,
                            Map.Entry<HttpHost, DeadHostState> o2) {
                        return Long.compare(o1.getValue().getDeadUntilNanos(),
                                o2.getValue().getDeadUntilNanos());
                    }
                });
                HttpHost deadHost = sortedHosts.get(0).getKey();
                logger.trace("resurrecting host [" + deadHost + "]");
                nextHosts = Collections.singleton(deadHost);
            }
        } else {
            List<HttpHost> rotatedHosts = new ArrayList<>(filteredHosts);
            Collections.rotate(rotatedHosts, rotatedHosts.size() - lastHostIndex.getAndIncrement());
            nextHosts = rotatedHosts;
        }
    } while (nextHosts.isEmpty());
    return new HostTuple<>(nextHosts.iterator(), hostTuple.authCache);
}

From source file:org.apache.hadoop.raid.TestDirectoryBlockFixer.java

/**
 * Create a file with three stripes, corrupt a block each in two stripes,
 * and wait for the the file to be fixed.
 *///from   w w w .ja  v a2  s  .  c om
private void implDirBlockFix(boolean local, boolean hasStripeInfo, boolean corruptStripe) throws Exception {
    LOG.info("Test testDirBlockFix started. local:" + local + " hasStripeInfo:" + hasStripeInfo
            + " corruptStripe:" + corruptStripe);
    int stripeLength = 3;
    mySetup(stripeLength);
    long[] crcs = new long[3];
    int[] seeds = new int[3];
    Path dirPath = new Path("/user/dhruba/raidtestrs");
    Path[] files = TestRaidDfs.createTestFiles(dirPath, fileSizes, blockSizes, crcs, seeds, fileSys, (short) 1);
    Path destPath = new Path("/destraidrs/user/dhruba");
    LOG.info("Test testDirBlockFix created test files");
    Configuration localConf = this.getRaidNodeConfig(conf, local);
    // Not allow multiple running jobs
    localConf.setLong("raid.blockfix.maxpendingjobs", 1L);

    try {
        cnode = RaidNode.createRaidNode(null, localConf);
        TestRaidDfs.waitForDirRaided(LOG, fileSys, dirPath, destPath);
        cnode.stop();
        cnode.join();

        DistributedFileSystem dfs = (DistributedFileSystem) fileSys;
        String[] corruptFiles = DFSUtil.getCorruptFiles(dfs);
        assertEquals("no corrupt files expected", 0, corruptFiles.length);
        assertEquals("filesFixed() should return 0 before fixing files", 0,
                cnode.blockIntegrityMonitor.getNumFilesFixed());
        if (!hasStripeInfo) {
            // clear out all stripes
            LocalStripeStore lss = new LocalStripeStore();
            lss.initialize(localConf, false, dfs);
            lss.clear();
        }
        if (corruptStripe) {
            LocalStripeStore lss = new LocalStripeStore();
            lss.initialize(localConf, false, dfs);
            Set<List<Block>> corruptCandidates = new HashSet<List<Block>>(lss.stripeSet.keySet());
            for (List<Block> lb : corruptCandidates) {
                for (Codec codec : Codec.getCodecs()) {
                    StripeInfo si = lss.getStripe(codec, lb.get(0));
                    if (si == null) {
                        continue;
                    }
                    String oldSi = si.toString();
                    Collections.rotate(si.parityBlocks, 1);
                    Collections.rotate(si.srcBlocks, 1);
                    lss.putStripe(codec, si.parityBlocks, si.srcBlocks);
                    String newSi = lss.getStripe(codec, lb.get(0)).toString();
                    LOG.info("Corrupt the stripe info old : " + oldSi + " new : " + newSi);
                }
            }
        }

        this.corruptFiles(dirPath, crcs, rsCorruptFileIdx1, dfs, files, rsNumCorruptBlocksInFiles1);
        cnode = RaidNode.createRaidNode(null, localConf);
        long start = System.currentTimeMillis();
        while (cnode.blockIntegrityMonitor.getNumFilesFixed() < 3
                && cnode.blockIntegrityMonitor.getNumFileFixFailures() < 3
                && System.currentTimeMillis() - start < 120000) {
            LOG.info("Test testDirBlockFix waiting for files to be fixed.");
            Thread.sleep(1000);
        }
        long totalCorruptBlocks = getTotal(rsNumCorruptBlocksInFiles1);
        if (hasStripeInfo) {
            if (!corruptStripe) {
                TestBlockFixer.verifyMetrics(fileSys, cnode, local, 3L, totalCorruptBlocks);

                dfs = getDFS(conf, dfs);
                for (int i = 0; i < fileSizes.length; i++) {
                    assertTrue("file " + files[i] + " not fixed",
                            TestRaidDfs.validateFile(dfs, files[i], fileSizes[i], crcs[i]));
                }
            } else {
                TestBlockFixer.verifyMetrics(fileSys, cnode, local, 0L, 0L);
                assertTrue("should fail to fix more than 3 files",
                        cnode.blockIntegrityMonitor.getNumFileFixFailures() >= 3L);
                TestBlockFixer.verifyMetrics(fileSys, cnode, LOGTYPES.OFFLINE_RECONSTRUCTION_FILE,
                        LOGRESULTS.FAILURE, 3L, true);
                // Will throw stripe mismatch exception for the first blocks of 3 files
                TestBlockFixer.verifyMetrics(fileSys, cnode,
                        LOGTYPES.OFFLINE_RECONSTRUCTION_STRIPE_VERIFICATION, LOGRESULTS.FAILURE, 3L, true);
            }
        } else {
            TestBlockFixer.verifyMetrics(fileSys, cnode, local, 0L, 0L);
            assertTrue("should fail to fix more than 3 files",
                    cnode.blockIntegrityMonitor.getNumFileFixFailures() >= 3L);
            TestBlockFixer.verifyMetrics(fileSys, cnode, LOGTYPES.OFFLINE_RECONSTRUCTION_GET_STRIPE,
                    LOGRESULTS.FAILURE, totalCorruptBlocks, true);
            TestBlockFixer.verifyMetrics(fileSys, cnode, LOGTYPES.OFFLINE_RECONSTRUCTION_FILE,
                    LOGRESULTS.FAILURE, 3L, true);
        }
    } catch (Exception e) {
        LOG.info("Test testDirBlockFix Exception " + e, e);
        throw e;
    } finally {
        myTearDown();
    }
    LOG.info("Test testDirBlockFix completed.");
}

From source file:org.broadinstitute.gatk.tools.walkers.genotyper.afcalc.AFCalculationUnitTest.java

@DataProvider(name = "GLsWithNonInformative")
public Object[][] makeGLsWithNonInformative() {
    List<Object[]> tests = new ArrayList<Object[]>();

    final List<NonInformativeData> nonInformativeTests = new LinkedList<NonInformativeData>();
    nonInformativeTests.add(new NonInformativeData(Arrays.asList(AB1), NON_INFORMATIVE1, 1));
    nonInformativeTests.add(new NonInformativeData(Arrays.asList(AB2), NON_INFORMATIVE2, 2));
    nonInformativeTests.add(new NonInformativeData(Arrays.asList(AB2, BC2), NON_INFORMATIVE2, 2));

    for (final int nNonInformative : Arrays.asList(1, 10, 100)) {
        for (final NonInformativeData testData : nonInformativeTests) {
            final List<Genotype> samples = new ArrayList<Genotype>();
            samples.addAll(testData.called);
            samples.addAll(Collections.nCopies(nNonInformative, testData.nonInformative));

            final int nSamples = samples.size();
            List<AFCalculator> calcs = createAFCalculators(Arrays.asList(AFCalculatorImplementation.values()),
                    MAX_ALT_ALLELES, PLOIDY);

            final double[] priors = MathUtils.normalizeFromLog10(new double[2 * nSamples + 1], true); // flat priors

            for (AFCalculator model : calcs) {
                if (testData.nAltAlleles > 1 && model instanceof OriginalDiploidExactAFCalculator)
                    continue;

                final GetGLsTest onlyInformative = new GetGLsTest(model, testData.nAltAlleles, testData.called,
                        priors, "flat");

                for (int rotation = 0; rotation < nSamples; rotation++) {
                    Collections.rotate(samples, 1);
                    final GetGLsTest withNonInformative = new GetGLsTest(model, testData.nAltAlleles, samples,
                            priors, "flat");
                    tests.add(new Object[] { onlyInformative, withNonInformative });
                }// w  w w  . j  av a 2s.c  o m
            }
        }
    }

    return tests.toArray(new Object[][] {});
}

From source file:org.broadinstitute.gatk.tools.walkers.genotyper.afcalc.AFCalcUnitTest.java

@DataProvider(name = "GLsWithNonInformative")
public Object[][] makeGLsWithNonInformative() {
    List<Object[]> tests = new ArrayList<Object[]>();

    final List<NonInformativeData> nonInformativeTests = new LinkedList<NonInformativeData>();
    nonInformativeTests.add(new NonInformativeData(Arrays.asList(AB1), NON_INFORMATIVE1, 1));
    nonInformativeTests.add(new NonInformativeData(Arrays.asList(AB2), NON_INFORMATIVE2, 2));
    nonInformativeTests.add(new NonInformativeData(Arrays.asList(AB2, BC2), NON_INFORMATIVE2, 2));

    for (final int nNonInformative : Arrays.asList(1, 10, 100)) {
        for (final NonInformativeData testData : nonInformativeTests) {
            final List<Genotype> samples = new ArrayList<Genotype>();
            samples.addAll(testData.called);
            samples.addAll(Collections.nCopies(nNonInformative, testData.nonInformative));

            final int nSamples = samples.size();
            List<AFCalc> calcs = AFCalcFactory.createAFCalcs(Arrays.asList(AFCalcFactory.Calculation.values()),
                    4, 2, 2);//from  www. ja v a2  s  .  c  o m

            final double[] priors = MathUtils.normalizeFromLog10(new double[2 * nSamples + 1], true); // flat priors

            for (AFCalc model : calcs) {
                if (testData.nAltAlleles > 1 && model instanceof OriginalDiploidExactAFCalc)
                    continue;

                final GetGLsTest onlyInformative = new GetGLsTest(model, testData.nAltAlleles, testData.called,
                        priors, "flat");

                for (int rotation = 0; rotation < nSamples; rotation++) {
                    Collections.rotate(samples, 1);
                    final GetGLsTest withNonInformative = new GetGLsTest(model, testData.nAltAlleles, samples,
                            priors, "flat");
                    tests.add(new Object[] { onlyInformative, withNonInformative });
                }
            }
        }
    }

    return tests.toArray(new Object[][] {});
}

From source file:org.jivesoftware.openfire.clearspace.ClearspaceManager.java

/**
 * Sends an IQ packet to the Clearspace external component and returns the IQ packet
 * returned by CS or <tt>null</tt> if no answer was received before the specified
 * timeout./*  w  w  w . jav  a 2 s .  c om*/
 *
 * @param packet IQ packet to send.
 * @param timeout milliseconds to wait before timing out.
 * @return IQ packet returned by Clearspace responsing the packet we sent.
 */
public IQ query(final IQ packet, int timeout) {
    // Complain if FROM is empty
    if (packet.getFrom() == null) {
        throw new IllegalStateException("IQ packets with no FROM cannot be sent to Clearspace");
    }
    // If CS is not connected then return null
    if (clearspaces.isEmpty()) {
        return null;
    }
    // Set the target address to the IQ packet. Roate list so we distribute load
    String component;
    synchronized (clearspaces) {
        component = clearspaces.get(0);
        Collections.rotate(clearspaces, 1);
    }
    packet.setTo(component);
    final LinkedBlockingQueue<IQ> answer = new LinkedBlockingQueue<IQ>(8);
    final IQRouter router = XMPPServer.getInstance().getIQRouter();
    router.addIQResultListener(packet.getID(), new IQResultListener() {
        public void receivedAnswer(IQ packet) {
            answer.offer(packet);
        }

        public void answerTimeout(String packetId) {
            Log.warn("No answer from Clearspace was received for IQ stanza: " + packet);
        }
    });
    XMPPServer.getInstance().getIQRouter().route(packet);
    IQ reply = null;
    try {
        reply = answer.poll(timeout, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        // Ignore
    }
    return reply;
}