Example usage for java.util Collections shuffle

List of usage examples for java.util Collections shuffle

Introduction

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

Prototype

public static void shuffle(List<?> list) 

Source Link

Document

Randomly permutes the specified list using a default source of randomness.

Usage

From source file:com.netflix.simianarmy.basic.chaos.BasicChaosInstanceSelector.java

private Collection<String> selectNInstances(Collection<String> instances, int n, String selected) {
    logger().info("Randomly selecting {} from {} instances, excluding {}",
            new Object[] { n, instances.size(), selected });
    List<String> copy = Lists.newArrayList();
    for (String instance : instances) {
        if (!instance.equals(selected)) {
            copy.add(instance);/*  w  ww  .ja  v  a 2 s . c om*/
        }
    }
    if (n >= copy.size()) {
        return copy;
    }
    Collections.shuffle(copy);
    return copy.subList(0, n);
}

From source file:com.pinterest.teletraan.worker.HotfixStateTransitioner.java

void processBatch() throws Exception {
    // Get all current deploys, randomly pick one to work on
    List<String> hotfixIds = hotfixDAO.getOngoingHotfixIds();
    if (hotfixIds.isEmpty()) {
        LOG.info("HotfixStateTransitioner did not find any active hotfix, exiting.");
        return;/*w w w  . j  av a2 s . c  o m*/
    }
    Collections.shuffle(hotfixIds);
    for (String hotfixId : hotfixIds) {
        HotfixBean hotBean = hotfixDAO.getByHotfixId(hotfixId);
        try {
            LOG.info("HotfixStateTransitioner chooses hotfix {} to work on.", hotfixId);
            transitionHotfixState(hotBean);
        } catch (Throwable t) {
            // Catch all throwable so that subsequent job not suppressed, also long error in DB
            LOG.error("HotfixStateTransitioner failed to process {} " + hotfixId, t);
        }
    }
}

From source file:org.berlin.crawl.bom.StartURLSeedReader.java

public void launch() {
    final ApplicationContext ctx = new ClassPathXmlApplicationContext(
            "/org/berlin/batch/batch-databot-context.xml");
    final BotCrawlerDAO dao = new BotCrawlerDAO();
    final SessionFactory sf = (SessionFactory) ctx.getBean("sessionFactory");
    final Session session = sf.openSession();
    final List<BotSeed> seeds = dao.findSeedRequests(session);
    int numberOfSeeds = 0;

    // Randomize the seed list //      
    Collections.shuffle(seeds);
    for (final BotSeed seed : seeds) {
        if ("Y".equalsIgnoreCase(seed.getEnabled())) {
            numberOfSeeds++;/*from  ww w.j a v a 2  s  .  co  m*/
            if (this.activeThreads.size() < maxActiveThreads) {
                logger.info("At Start URL Seeder, seeding / num=" + numberOfSeeds + " / " + seed.getId()
                        + " sz=" + this.activeThreads.size());
                // Only launch so many threads               
                final BotTrueCrawler crawl = new BotTrueCrawler(this, ctx, seed.toLink());
                crawl.launch();
                // Slight delay after producing the links for processing //
                try {
                    Thread.sleep(BotTrueCrawler.DELAY_FROM_PRODUCER + (4 * 1000));
                } catch (final InterruptedException e) {
                    e.printStackTrace();
                } /// End of try catch //
            } else {
                // Wait for the threads to finish, using join
                for (final Thread wt : this.activeThreads) {
                    try {
                        logger.info("At Start URL Seeder, waiting on seeds to complete");
                        wt.join();
                    } catch (final InterruptedException e) {
                        e.printStackTrace();
                    }
                } // End of the for //
                  // If we reached this point, remove all the threads , they finished processing
                if (this.activeThreads.size() > 0) {
                    this.activeThreads.clear();
                }
            } // End of the if - else //            
            logger.info("!/=! At END OF seed launching, seeding / num=" + numberOfSeeds + " / " + seed.getId());
        } // End of the if //
    } // End of the for //

    // Wait for the threads to finish, using join
    for (final Thread wt : this.activeThreads) {
        try {
            logger.info("At Start URL Seeder, waiting on seeds to complete [f66x0");
            wt.join();
        } catch (final InterruptedException e) {
            e.printStackTrace();
        }
    } // End of the for //

    logger.info("!/=! At END OF seed seeding, launch complete");
    if (session != null) {
        // May not need to close the session
        session.close();
    } // End of the if //
}

From source file:com.jonschang.ai.ga.SpringGeneticAlgFactory.java

@Override
public G newGene() throws GeneticAlgException {
    Collections.shuffle(genes);
    return newGene(genes.get(0));
}

From source file:czlab.xlib.CU.java

/**
 * Shuffle characters in this string.//from   w ww  .  ja v  a 2  s. c  om
 *
 * @param s
 * @return
 */
public static String shuffle(String s) {
    List<Character> lst = new ArrayList<>();
    char[] cs = s.toCharArray();
    for (int n = 0; n < cs.length; ++n) {
        lst.add(cs[n]);
    }
    Collections.shuffle(lst);
    for (int n = 0; n < lst.size(); ++n) {
        cs[n] = lst.get(n).charValue();
    }
    return new String(cs);
}

From source file:com.music.scheduled.PieceDigestSendingJob.java

@Scheduled(cron = "0 0 9 ? * 1,4")
@Transactional(readOnly = true)/* ww  w  . j a va2s  . c  om*/
public void sendPieceDigestEmails() {
    logger.info("Sending email digests started");
    DateTime now = new DateTime();
    DateTime minusTwoDays = now.minusDays(2);
    List<Piece> pieces = pieceDao.getPiecesInRange(minusTwoDays, now);
    Collections.shuffle(pieces);
    final List<Piece> includedPieces = new ArrayList<>(pieces.subList(0, Math.min(pieces.size(), 3)));
    if (includedPieces.isEmpty()) {
        return;
    }
    // for now - using the same data for all users. TODO send personalized selection
    final EmailDetails baseDetails = new EmailDetails();
    baseDetails.setMessageTemplate("digest.vm");
    baseDetails.setSubject("Computoser-generated tracks digest for you");
    Map<String, Object> model = Maps.newHashMap();
    baseDetails.setMessageTemplateModel(model);
    baseDetails.setFrom(from);
    baseDetails.setHtml(true);
    userDao.performBatched(User.class, 100, new PageableOperation<User>() {
        @Override
        public void execute() {
            for (User user : getData()) {
                if (user.isReceiveDailyDigest() && StringUtils.isNotBlank(user.getEmail())) {
                    EmailDetails email = SerializationUtils.clone(baseDetails);
                    email.setTo(user.getEmail());
                    email.setCurrentUser(user);
                    String hmac = SecurityUtils.hmac(user.getEmail(), hmacKey);
                    email.getMessageTemplateModel().put("pieces", includedPieces);
                    email.getMessageTemplateModel().put("hmac", hmac);
                    // needed due to SES restrictions
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        throw new IllegalStateException(e);
                    }
                    emailService.send(email);
                }
            }
        }
    });
}

From source file:dk.statsbiblioteket.alto.AnagramHashingTest.java

public void disabledTestGenerateSampleWords() throws IOException {
    final int CHUNK = 100;

    List<String> words = new ArrayList<String>(100000);
    AnagramHashing te = new AnagramHashing();
    List<File> altos = new ArrayList<File>();
    te.getALTOs(altos, getInputFolder());
    for (File alto : altos) {
        log.debug("Processing ALTO " + alto);
        for (String ts : te.splitAndPrune(te.getStrings(alto))) {
            words.add(ts);/*www  .j  av  a 2s . c o  m*/
        }
    }
    Collections.shuffle(words);

    int pos = 0;
    StringBuilder sb = new StringBuilder();
    while (pos < words.size()) {
        sb.setLength(0);
        sb.append("<String CONTENT=\"");
        int end = Math.min(words.size(), pos + CHUNK);
        for (int i = pos; i < end; i++) {
            if (i > pos) {
                sb.append(' ');
            }
            sb.append(words.get(i).replace("&", "&amp;").replace("'", "&apos;").replace("\"", "&quot;")
                    .replace("<", "&lt;").replace(">", "&gt;"));
        }
        sb.append("\"/>");
        System.out.println(sb.toString());
        pos = end;
    }
}

From source file:com.facebook.hiveio.options.NamespaceOptions.java

/**
 * Read metastore information from file path
 *
 * @return HostPort of metastore/* w  w  w.j a v  a2 s .  co m*/
 * @throws IOException
 */
public HostPort readMetastoreInfo() throws IOException {
    if (path == null) {
        LOG.error("Cluster file not given");
        new Help().run();
        return null;
    }
    ObjectMapper objectMapper = new ObjectMapper();
    File file = new File(path);
    NamespaceData clustersData = objectMapper.readValue(file, NamespaceData.class);
    List<HostPort> hostAndPorts = clustersData.data.get(name);
    if (hostAndPorts == null) {
        LOG.error("Cluster {} not found in data file {}", name, path);
        return null;
    }
    Collections.shuffle(hostAndPorts);
    return hostAndPorts.get(0);
}

From source file:com.example.bidisha.ace.ClueScan.java

/***
 * @mitra00/*from  w ww. ja va2 s  . c  o m*/
 * function to generate the random clues
 * @param //savedInstanceState
 */
void gen_clues() {
    /**
     * @mitra00
     * creatiing the random clues array
     */
    ArrayList<Integer> list = new ArrayList<Integer>();
    for (int ii = 0; ii < 19; ii++) {
        list.add(new Integer(ii));
    }
    Collections.shuffle(list);
    for (int ii = 0; ii < 10; ii++) {
        //System.out.println(list.get(i));
        rando[ii] = clues[list.get(ii)];
        //Toast.makeText(ClueScan.this,rando[ii],Toast.LENGTH_LONG).show();

    }
    //first clue same for all
    rando[0] = "This app was recently inaugurated by Mysore MLA";
}

From source file:com.pinterest.teletraan.worker.AutoPromoter.java

void processBatch() throws Exception {
    // Get all auto_promote enabled & normal state envs, randomly pick one to work on
    List<String> envIds = promoteDAO.getAutoPromoteEnvIds();
    if (envIds.isEmpty()) {
        LOG.debug("AutoPromoter did not find any valid env to work on, exiting.");
        return;/*from  w w w. j  a  v a 2 s.  c o  m*/
    }
    Collections.shuffle(envIds);
    for (String envId : envIds) {
        try {
            LOG.debug("AutoPromoter chooses env {} to work on.", envId);
            processOnce(envId);
        } catch (Throwable t) {
            // Catch all throwable so that subsequent job not suppressed
            LOG.error("AutoPromoter failed to process {}", envId, t);
        }
    }
}