Example usage for java.util.concurrent ThreadLocalRandom current

List of usage examples for java.util.concurrent ThreadLocalRandom current

Introduction

In this page you can find the example usage for java.util.concurrent ThreadLocalRandom current.

Prototype

public static ThreadLocalRandom current() 

Source Link

Document

Returns the current thread's ThreadLocalRandom .

Usage

From source file:com.sk89q.craftbook.sponge.mechanics.HeadDrops.java

@Listener
public void onItemDrops(DropItemEvent.Destruct event, @First Entity spawnCause) {
    EntityDamageSource damageSource = event.getCause().first(EntityDamageSource.class).orElse(null);
    Entity killer = null;/*from   ww w . j a v  a2 s. co m*/

    if (damageSource != null) {
        killer = damageSource.getSource();
        if (killer instanceof Subject && !killPermission.hasPermission((Subject) killer)) {
            return;
        }
    }

    if (playerKillsOnly.getValue() && !(killer instanceof Player)) {
        return;
    }

    double chance = Math.min(1, dropRate.getValue());

    if (killer != null && killer instanceof Player) {
        int level = ((Player) killer).getItemInHand(HandTypes.MAIN_HAND)
                .filter(item -> item.get(Keys.ITEM_ENCHANTMENTS).isPresent())
                .map(item -> item.get(Keys.ITEM_ENCHANTMENTS).get().stream()
                        .filter(enchant -> enchant.getType().equals(EnchantmentTypes.LOOTING)).findFirst())
                .filter(Optional::isPresent).map(enchant -> enchant.get().getLevel()).orElse(0);
        chance = Math.min(1, chance + (lootingRateModifier.getValue() * level));
    }

    if (ThreadLocalRandom.current().nextDouble() > chance) {
        return;
    }

    GameProfile profile = null;
    if (spawnCause instanceof Player) {
        profile = ((Player) spawnCause).getProfile();
    }

    getStackForEntity(spawnCause.getType(), profile).ifPresent(itemStack -> {
        Vector3d location = spawnCause.getLocation().getPosition();
        Item item = (Item) spawnCause.getWorld().createEntity(EntityTypes.ITEM, location);
        item.offer(Keys.REPRESENTED_ITEM, itemStack.createSnapshot());
        spawnCause.getWorld().spawnEntity(item);
    });
}

From source file:org.neo4j.io.pagecache.impl.SingleFilePageSwapperTest.java

@Test
public void mustHandleMischiefInPositionedVectoredRead() throws Exception {
    int bytesTotal = 512;
    int bytesPerPage = 32;
    int pageCount = bytesTotal / bytesPerPage;
    byte[] data = new byte[bytesTotal];
    ThreadLocalRandom.current().nextBytes(data);

    PageSwapperFactory factory = swapperFactory();
    factory.setFileSystemAbstraction(getFs());
    File file = getFile();//from w  ww.  j  ava 2s . co  m
    PageSwapper swapper = createSwapper(factory, file, bytesTotal, NO_CALLBACK, true);
    try {
        swapper.write(0, new ByteBufferPage(wrap(data)));
    } finally {
        swapper.close();
    }

    RandomAdversary adversary = new RandomAdversary(0.5, 0.0, 0.0);
    factory.setFileSystemAbstraction(new AdversarialFileSystemAbstraction(adversary, getFs()));
    swapper = createSwapper(factory, file, bytesPerPage, NO_CALLBACK, false);

    ByteBufferPage[] pages = new ByteBufferPage[pageCount];
    for (int i = 0; i < pageCount; i++) {
        pages[i] = createPage(bytesPerPage);
    }

    byte[] temp = new byte[bytesPerPage];
    try {
        for (int i = 0; i < 10_000; i++) {
            for (ByteBufferPage page : pages) {
                clear(page);
            }
            assertThat(swapper.read(0, pages, 0, pages.length), is((long) bytesTotal));
            for (int j = 0; j < pageCount; j++) {
                System.arraycopy(data, j * bytesPerPage, temp, 0, bytesPerPage);
                assertThat(array(pages[j].buffer), is(temp));
            }
        }
    } finally {
        swapper.close();
    }
}

From source file:com.spotify.helios.testing.TemporaryJobBuilder.java

private String randomVersion() {
    return toHexString(ThreadLocalRandom.current().nextInt());
}

From source file:com.itdhq.contentLoader.ContentLoaderComponent.java

private long genLongProperty(PropertyDefinition def) {
    return ThreadLocalRandom.current().nextLong();
}

From source file:uk.dsxt.voting.tests.TestDataGenerator.java

private void saveData(ClientFullInfo[] clients, Participant[] participants, String name, Voting voting,
        int holdersCount, int vmCount, int minutes, boolean generateVotes, boolean generateDisconnect,
        int disconnectNodes) throws Exception {
    //saving info to appropriate files
    final String dirPath = "/src/main/resources/scenarios";
    FileUtils.writeStringToFile(//from w ww.j a v a 2  s  .co  m
            new File(String.format("%s/%s/%s/participants.json", BaseTestsLauncher.MODULE_NAME, dirPath, name)),
            mapper.writeValueAsString(participants));
    Iso20022Serializer serializer = new Iso20022Serializer();
    FileUtils.writeStringToFile(
            new File(String.format("%s/%s/%s/voting.xml", BaseTestsLauncher.MODULE_NAME, dirPath, name)),
            serializer.serialize(voting));
    StringBuilder vmConfig = new StringBuilder();
    int countByVM = (holdersCount + vmCount - 1) / vmCount;
    int totalCount = 0;
    for (int i = 0; i < vmCount; i++) {
        int count = Math.min(holdersCount - totalCount, countByVM);
        vmConfig.append(String.format("%s=%s%n", i, count));
        totalCount += count;
    }
    FileUtils.writeStringToFile(
            new File(String.format("%s/%s/%s/vm.txt", BaseTestsLauncher.MODULE_NAME, dirPath, name)),
            vmConfig.toString());

    //aggregating data from all files and save it to one file
    if (generateDisconnect)
        ThreadLocalRandom.current().ints(1, holdersCount - 1).distinct().limit(disconnectNodes)
                .forEach(i -> clients[i].setWalletOffShedule(generateWalletoffShedule(minutes)));
    StringBuilder nodesConfig = new StringBuilder();
    for (int i = 0; i < holdersCount; i++) {
        ClientFullInfo client = clients[i];
        List<ClientCredentials> credentials = client.getClients().stream()
                .map(child -> new ClientCredentials(Integer.toString(child.getId()),
                        Integer.toString(child.getId())))
                .collect(Collectors.toList());
        FileUtils.writeStringToFile(new File(String.format("%s/%s/%s/%s/credentials.json",
                BaseTestsLauncher.MODULE_NAME, dirPath, name, client.getId())),
                mapper.writeValueAsString(credentials));
        List<Client> clientsJson = client.getClients().stream()
                .map(child -> new Client(Integer.toString(child.getId()), child.getPacketSizeBySecurity(),
                        child.getRole()))
                .collect(Collectors.toList());
        FileUtils.writeStringToFile(
                new File(String.format("%s/%s/%s/%s/clients.json", BaseTestsLauncher.MODULE_NAME, dirPath, name,
                        client.getId())),
                mapper.writeValueAsString(new ClientsOnTime[] {
                        new ClientsOnTime(-20000, clientsJson.toArray(new Client[clientsJson.size()])) }));
        String messages = client.getClients().stream().filter(child -> child.getVote() != null)
                .map(child -> String.format("%s:%s", randomInt(30, minutes * 60), child.getVote().toString()))
                .reduce("", (s1, s2) -> s1 + "\n" + s2);
        FileUtils.writeStringToFile(new File(String.format("%s/%s/%s/%s/messages.txt",
                BaseTestsLauncher.MODULE_NAME, dirPath, name, client.getId())), generateVotes ? messages : "");
        FileUtils
                .writeStringToFile(
                        new File(String.format("%s/%s/%s/%s/walletoff_schedule.txt",
                                BaseTestsLauncher.MODULE_NAME, dirPath, name, client.getId())),
                        client.getWalletOffShedule());

        nodesConfig.append(i);
        nodesConfig.append("=");
        nodesConfig.append(mapper.writeValueAsString(new NodeInfo(
                client.getId() == 0 ? MASTER_PASSWORD : (client.isVictim() ? "victim_password" : ""),
                client.getId(), Math.max(0, client.getHolderId()), client.getPrivateKey(),
                !client.isHonest() ? "client_password" : null)));
        nodesConfig.append("\n");
    }
    FileUtils.writeStringToFile(
            new File(String.format("%s/%s/%s/voting.txt", BaseTestsLauncher.MODULE_NAME, dirPath, name)),
            nodesConfig.toString());
}

From source file:com.itdhq.contentLoader.ContentLoaderComponent.java

private int genIntProperty(PropertyDefinition def, int max) {
    return ThreadLocalRandom.current().nextInt(max);
}

From source file:com.itdhq.contentLoader.ContentLoaderComponent.java

private Date genDateTimeProperty(PropertyDefinition def, int max) {
    //long t2 = t1 + 2 * 60 * 1000 + r.nextInt(60 * 1000) + 1;
    return new Date(System.currentTimeMillis() + ThreadLocalRandom.current().nextInt());
    //DateTime d2 = new DateTime(t2);

}

From source file:com.itdhq.contentLoader.ContentLoaderComponent.java

private String genTextProperty(PropertyDefinition def) {
    if (def.getConstraints().isEmpty()) {
        return genPlainText(ThreadLocalRandom.current().nextInt(5, 100));
    } else {//from www  .  j  ava2 s  .co  m
        if (def.getConstraints().get(0).getConstraint().getType() == ListOfValuesConstraint.CONSTRAINT_TYPE) {
            List<String> list = ((ListOfValuesConstraint) def.getConstraints().get(0).getConstraint())
                    .getAllowedValues();
            return list.get(ThreadLocalRandom.current().nextInt(list.size()));
        }
    }
    return genPlainText(ThreadLocalRandom.current().nextInt(5, 100));
}

From source file:org.jahia.utils.maven.plugin.contentgenerator.bo.PageBO.java

private Element getPersonalizedElement(Element element) {

    Random random = ThreadLocalRandom.current();

    Element personalizationElement = new Element("experience-" + element.getName());
    personalizationElement.setAttribute("primaryType", "wemnt:personalizedContent", ContentGeneratorCst.NS_JCR);
    personalizationElement.setAttribute("active", "true", ContentGeneratorCst.NS_WEM);
    personalizationElement.setAttribute("personalizationStrategy", "priority", ContentGeneratorCst.NS_WEM);
    String[] segments = ContentGeneratorCst.SEGMENTS[random.nextInt(ContentGeneratorCst.SEGMENTS.length)];
    int nbPersonalizationVariants = minPersonalizationVariants
            + random.nextInt(maxPersonalizationVariants - minPersonalizationVariants + 1);
    if (nbPersonalizationVariants > segments.length) {
        nbPersonalizationVariants = segments.length;
    }//  w  ww. jav  a 2  s . c o m
    for (int i = 0; i < nbPersonalizationVariants; i++) {

        Element variantElement = (Element) element.clone();
        variantElement.setName(variantElement.getName() + "-" + (i + 1));

        Attribute mixinTypesAttribute = variantElement.getAttribute("mixinTypes", ContentGeneratorCst.NS_JCR);
        String mixinTypes;
        if (mixinTypesAttribute == null) {
            mixinTypes = StringUtils.EMPTY;
        } else {
            mixinTypes = mixinTypesAttribute.getValue() + " ";
        }
        variantElement.setAttribute("mixinTypes", mixinTypes + "wemmix:editItem", ContentGeneratorCst.NS_JCR);

        String jsonFilter = "{\"parameterValues\":{\"subConditions\":[{\"type\":\"profileSegmentCondition\",\"parameterValues\":{\"segments\":[\""
                + segments[i] + "\"]}}],\"operator\":\"and\"},\"type\":\"booleanCondition\"}";
        variantElement.setAttribute("jsonFilter", jsonFilter, ContentGeneratorCst.NS_WEM);
        personalizationElement.addContent(variantElement);
    }

    return personalizationElement;
}

From source file:org.neo4j.io.pagecache.impl.SingleFilePageSwapperTest.java

@Test
public void mustHandleMischiefInPositionedVectoredWrite() throws Exception {
    int bytesTotal = 512;
    int bytesPerPage = 32;
    int pageCount = bytesTotal / bytesPerPage;
    byte[] data = new byte[bytesTotal];
    ThreadLocalRandom.current().nextBytes(data);
    ByteBufferPage zeroPage = createPage(bytesPerPage);
    clear(zeroPage);//w w w  . j ava2 s.c o m

    File file = getFile();
    PageSwapperFactory factory = swapperFactory();
    RandomAdversary adversary = new RandomAdversary(0.5, 0.0, 0.0);
    factory.setFileSystemAbstraction(new AdversarialFileSystemAbstraction(adversary, getFs()));
    PageSwapper swapper = createSwapper(factory, file, bytesPerPage, NO_CALLBACK, true);

    ByteBufferPage[] writePages = new ByteBufferPage[pageCount];
    ByteBufferPage[] readPages = new ByteBufferPage[pageCount];
    ByteBufferPage[] zeroPages = new ByteBufferPage[pageCount];
    for (int i = 0; i < pageCount; i++) {
        writePages[i] = createPage(bytesPerPage);
        writePages[i].putBytes(data, 0, i * bytesPerPage, bytesPerPage);
        readPages[i] = createPage(bytesPerPage);
        zeroPages[i] = zeroPage;
    }

    try {
        for (int i = 0; i < 10_000; i++) {
            adversary.setProbabilityFactor(0);
            swapper.write(0, zeroPages, 0, pageCount);
            adversary.setProbabilityFactor(1);
            swapper.write(0, writePages, 0, pageCount);
            for (ByteBufferPage readPage : readPages) {
                clear(readPage);
            }
            adversary.setProbabilityFactor(0);
            assertThat(swapper.read(0, readPages, 0, pageCount), is((long) bytesTotal));
            for (int j = 0; j < pageCount; j++) {
                assertThat(array(readPages[j].buffer), is(array(writePages[j].buffer)));
            }
        }
    } finally {
        swapper.close();
    }
}