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:io.hops.hopsworks.api.jupyter.JupyterService.java

@POST
@Path("/start")
@Consumes(MediaType.APPLICATION_JSON)//w  w w  .  jav  a  2  s .  co  m
@Produces(MediaType.APPLICATION_JSON)
@AllowedProjectRoles({ AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST })
public Response startNotebookServer(JupyterSettings jupyterSettings, @Context SecurityContext sc,
        @Context HttpServletRequest req) throws ProjectException, HopsSecurityException, ServiceException {

    String hdfsUser = getHdfsUser(sc);
    String loggedinemail = sc.getUserPrincipal().getName();
    Users hopsworksUser = userFacade.findByEmail(loggedinemail);
    String realName = hopsworksUser.getFname() + " " + hopsworksUser.getLname();

    if (project.getPaymentType().equals(PaymentType.PREPAID)) {
        YarnProjectsQuota projectQuota = yarnProjectsQuotaFacade.findByProjectName(project.getName());
        if (projectQuota == null || projectQuota.getQuotaRemaining() < 0) {
            throw new ProjectException(RESTCodes.ProjectErrorCode.PROJECT_QUOTA_INSUFFICIENT, Level.FINE);
        }
    }

    boolean enabled = project.getConda();
    if (!enabled) {
        throw new ProjectException(RESTCodes.ProjectErrorCode.ANACONDA_NOT_ENABLED, Level.FINE);
    }

    JupyterProject jp = jupyterFacade.findByUser(hdfsUser);

    if (jp == null) {
        HdfsUsers user = hdfsUsersFacade.findByName(hdfsUser);

        String configSecret = DigestUtils.sha256Hex(Integer.toString(ThreadLocalRandom.current().nextInt()));
        JupyterDTO dto = null;
        DistributedFileSystemOps dfso = dfsService.getDfsOps();

        try {
            jupyterSettingsFacade.update(jupyterSettings);
            dto = jupyterProcessFacade.startServerAsJupyterUser(project, configSecret, hdfsUser, realName,
                    jupyterSettings);
            HopsUtils.materializeCertificatesForUserCustomDir(project.getName(), user.getUsername(),
                    settings.getHdfsTmpCertDir(), dfso, certificateMaterializer, settings,
                    dto.getCertificatesDir());
            // When Livy launches a job it will look in the standard directory for the certificates
            // We materialize them twice but most probably other operations will need them too, so it is OK
            // Remember to remove both when stopping Jupyter server or an exception is thrown
            certificateMaterializer.materializeCertificatesLocal(user.getUsername(), project.getName());
        } catch (IOException | ServiceException ex) {
            LOGGER.log(Level.SEVERE, null, ex);
            certificateMaterializer.removeCertificatesLocal(user.getUsername(), project.getName());
            if (dto != null) {
                HopsUtils.cleanupCertificatesForUserCustomDir(user.getUsername(), project.getName(),
                        settings.getHdfsTmpCertDir(), certificateMaterializer, dto.getCertificatesDir(),
                        settings);
            } else {
                throw new HopsSecurityException(RESTCodes.SecurityErrorCode.CERT_LOCATION_UNDEFINED,
                        Level.SEVERE);
            }
            throw new ServiceException(RESTCodes.ServiceErrorCode.JUPYTER_START_ERROR, Level.SEVERE,
                    ex.getMessage(), null, ex);
        } finally {
            if (dfso != null) {
                dfsService.closeDfsClient(dfso);
            }
        }

        String externalIp = Ip.getHost(req.getRequestURL().toString());

        jp = jupyterFacade.saveServer(externalIp, project, configSecret, dto.getPort(), user.getId(),
                dto.getToken(), dto.getPid());

        if (jp == null) {
            throw new ServiceException(RESTCodes.ServiceErrorCode.JUPYTER_SAVE_SETTINGS_ERROR, Level.SEVERE);
        }
    }
    return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(jp).build();
}

From source file:frequencyanalysis.FrequencyAnalysis.java

public static String runPlayFairDecryptor(String cipherText) throws Exception {
    String warAndPeaceString = getCleansedStringFromWarAndPeace();
    HashMap quadGramData = (HashMap) getQuadgramDataFromWarAndPeace(warAndPeaceString);

    String parentKey = generateRandom25LetterString();
    //String parentKey = "TUVJDCISYLOEMFNPWKQRGHAXB";

    String plainText = decipherPlayFairWithKey(parentKey, cipherText);
    float parentFitness = findFitnessOfString(quadGramData, plainText);

    outerloop: {/*from  www . ja v  a2s  . com*/
        for (int temp = 50; temp >= 0; temp--) {
            for (int count = 50000; count > 0; count--) {
                String childKey;

                if (parentFitness < -14000) {
                    childKey = modifyString(parentKey, 3);
                } else {
                    childKey = modifyString(parentKey, 1);
                }

                float childFitness = findFitnessOfString(quadGramData,
                        decipherPlayFairWithKey(childKey, cipherText));
                float dF = childFitness - parentFitness;

                System.out.println(
                        temp + " - " + count + ": " + parentFitness + "     " + childFitness + "       " + dF);

                if (dF > 0) {
                    parentKey = childKey;
                    parentFitness = childFitness;
                } else {
                    float randFloat = ThreadLocalRandom.current().nextFloat();

                    if (randFloat < Math.exp(dF / (temp))) {
                        parentKey = childKey;
                        parentFitness = childFitness;
                    }
                }

                //if(parentFitness >= -10000)
                // break outerloop;
            }
        }
    }

    // Generally a fitness of more than -300 is good as an end point
    return parentKey;
}

From source file:org.finra.herd.dao.impl.BusinessObjectDefinitionDaoImpl.java

@Override
public List<BusinessObjectDefinitionEntity> getPercentageOfAllBusinessObjectDefinitions(double percentage) {
    // Create the criteria builder and a tuple style criteria query.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Integer> criteria = builder.createQuery(Integer.class);

    // The criteria root is the business object definition.
    Root<BusinessObjectDefinitionEntity> businessObjectDefinitionEntityRoot = criteria
            .from(BusinessObjectDefinitionEntity.class);

    // Get the columns.
    Path<Integer> idColumn = businessObjectDefinitionEntityRoot.get(BusinessObjectDefinitionEntity_.id);

    criteria.select(idColumn);// w w w  . j a va2  s . com

    List<Integer> allBusinessObjectDefinitionIdsList = entityManager.createQuery(criteria).getResultList();
    List<Integer> percentageOfBusinessObjectDefinitionIdsList = new ArrayList<>();

    /*
    * Gets a percentage of all business object definition entities.
    * The percentage is randomly selected from all the business object definitions.
    *
    * For each business object id in the list of all business object definition ids, get a random double value between 0 and 1.
    * If that value is below the percentage double value, also a number between 0 and 1 (inclusive),
    * then add the business object id to the list of business object definition ids that will be used to return a random percentage
    * of business object definition entities retrieved from the database.
    */
    allBusinessObjectDefinitionIdsList.forEach(id -> {
        if (ThreadLocalRandom.current().nextDouble() < percentage) {
            percentageOfBusinessObjectDefinitionIdsList.add(id);
        }
    });

    return getAllBusinessObjectDefinitionsByIds(percentageOfBusinessObjectDefinitionIdsList);
}

From source file:org.apache.hadoop.hbase.master.cleaner.TestLogsCleaner.java

private void createFiles(FileSystem fs, Path parentDir, int numOfFiles) throws IOException {
    for (int i = 0; i < numOfFiles; i++) {
        // size of each file is 1M, 2M, or 3M
        int xMega = 1 + ThreadLocalRandom.current().nextInt(1, 4);
        try (FSDataOutputStream fsdos = fs.create(new Path(parentDir, "file-" + i))) {
            byte[] M = RandomUtils.nextBytes(Math.toIntExact(FileUtils.ONE_MB * xMega));
            fsdos.write(M);/*from  w w  w  . j  a  v  a  2 s .  c  om*/
        }
    }
}

From source file:ffx.algorithms.mc.RosenbluthChiAllMove.java

/**
 * So named, yet inadequate. Final stats on the ctrl vs bias algorithm for chis2,3 of LYS monomer are:
 *          calc "4.23846e+07 / 22422"  for the biased run
        calc "4.21623e+06 / 10000"  for the control run, where numerator = total timer; demon = accepted
 * Possible accelerations are predicated on the fact that the test above was performed using unbinned
 * ie fully-continuous rotamers and sampling was done with replacement. Rectifying either of these 
 * breaks balance, however, when used with MD...
 *///  ww w .  j  a v  a2  s . c o  m
private boolean engage_cheap() {
    report.append(String.format(" Rosenbluth CBMC Move: %4d  (%s)\n", moveNumber, target));

    AminoAcid3 name = AminoAcid3.valueOf(target.getName());
    double chi[] = RotamerLibrary.measureRotamer(target, false);
    HashMap<Integer, BackBondedList> map = createBackBondedMap(name);

    // For each chi, create a test set from Boltzmann distr on torsion energy (Ubond).
    // Select from among this set based on Boltzmann weight of REMAINING energy (Uext).
    // The Uext partition function of each test set (wn) becomes a factor of the overall Rosenbluth (Wn).
    // ^ NOPE. Instead, Rosenbluth is going to be calculated just once for the whole combined set of chis.
    List<Torsion> allTors = new ArrayList<>();
    for (int i = 0; i < chi.length; i++) {
        Torsion tors = map.get(i).torsion;
        allTors.add(tors);
    }
    TrialSet newTrialSet = cheapTorsionSet(allTors, testSetSize, "bkn");
    Wn = newTrialSet.sumExtBolt(); // yields uExt(1) + uExt(2) + ...
    if (Wn <= 0) {
        report.append("WARNING: Numerical instability in CMBC.");
        report.append("  Test set uExt values:  ");
        for (int i = 0; i < newTrialSet.uExt.length; i++) {
            report.append(String.format("%5.2f,  ", newTrialSet.uExt[i]));
        }
        report.append("  Discarding move.\n");
        target.revertState(origState);
        Wn = -1.0;
        Wo = 1000;
        logger.info(report.toString());
        return false;
    }

    // Choose a proposal move from amongst this trial set (bn).
    double rng = rand.nextDouble(Wn);
    double running = 0.0;
    for (int j = 0; j < newTrialSet.uExt.length; j++) {
        double uExtBolt = FastMath.exp(-beta * newTrialSet.uExt[j]);
        running += uExtBolt;
        if (rng < running) {
            proposedMove = newTrialSet.rotamer[j];
            proposedChis = newTrialSet.theta;
            double prob = uExtBolt / Wn * 100;
            if (printTestSets) {
                report.append(String.format("       Chose %d   %7.4f\t  %4.1f%%\n", j + 1, newTrialSet.uExt[j],
                        prob));
            }
            break;
        }
    }
    report.append(String.format("    Wn Total:  %g\n", Wn));

    // Reprise the above procedure for the old configuration.
    // The existing conformation forms first member of each test set (wo).
    double ouDep = 0.0;
    for (Torsion tors : allTors) {
        ouDep += tors.energy(false); // original-conf uDep
    }
    double ouExt = totalEnergy() - ouDep; // original-conf uExt
    double ouExtBolt = FastMath.exp(-beta * ouExt);
    if (printTestSets) {
        report.append(
                String.format("       %3s %d:  %9.5g  %9.5g  %9.5g\n", "bko", 0, ouDep, ouExt, ouExtBolt));
    }
    writeSnapshot("bko", true);
    TrialSet oldTrialSet = cheapTorsionSet(allTors, testSetSize - 1, "bko");
    Wo = ouExtBolt + oldTrialSet.sumExtBolt();

    report.append(String.format("    Wo Total:  %11.4g\n", Wo));
    report.append(String.format("    Wn/Wo:     %11.4g", Wn / Wo));

    RotamerLibrary.applyRotamer(target, proposedMove);
    proposedChis = RotamerLibrary.measureRotamer(target, false);
    finalEnergy = totalEnergy();
    if (finalEnergy < CATASTROPHE_THRESHOLD) {
        report.append("\nWARNING: Multipole catastrophe in CMBC.\n");
        report.append("  Discarding move.\n");
        target.revertState(origState);
        updateAll();
        Wn = -1.0;
        Wo = 1000;
        logger.info(report.toString());
        return false;
    }

    double criterion = Math.min(1, Wn / Wo);
    rng = ThreadLocalRandom.current().nextDouble();
    report.append(String.format("    rng:    %5.2f\n", rng));
    if (rng < criterion) {
        accepted = true;
        numAccepted++;
        updateAll();
        write();
        report.append(String.format(" Accepted! %5d    NewEnergy: %.4f    Chi:", numAccepted, finalEnergy));
        for (int k = 0; k < proposedChis.length; k++) {
            report.append(String.format(" %7.2f", proposedChis[k]));
        }
        report.append(String.format("\n"));
    } else {
        accepted = false;
        target.revertState(origState);
        updateAll();
        report.append(String.format(" Denied.   %5d    OldEnergy: %.4f    Chi:", numAccepted, origEnergy));
        for (int k = 0; k < chi.length; k++) {
            report.append(String.format(" %7.2f", chi[k]));
        }
        report.append(String.format("\n"));
    }

    endTime = System.nanoTime();
    double took = (endTime - startTime) * NS_TO_MS;
    if (logTimings) {
        report.append(String.format("   Timing (ms): %.2f", took));
    }
    logger.info(report.toString());
    return accepted;
}

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

@Test
public void mustHandleMischiefInPositionedWrite() throws Exception {
    int bytesTotal = 512;
    byte[] data = new byte[bytesTotal];
    ThreadLocalRandom.current().nextBytes(data);
    ByteBufferPage zeroPage = createPage(bytesTotal);
    clear(zeroPage);/*w w  w .  jav a2s.  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, bytesTotal, NO_CALLBACK, true);

    ByteBufferPage page = createPage(bytesTotal);

    try {
        for (int i = 0; i < 10_000; i++) {
            adversary.setProbabilityFactor(0);
            swapper.write(0, zeroPage);
            page.putBytes(data, 0, 0, data.length);
            adversary.setProbabilityFactor(1);
            assertThat(swapper.write(0, page), is((long) bytesTotal));
            clear(page);
            adversary.setProbabilityFactor(0);
            swapper.read(0, page);
            assertThat(array(page.buffer), is(data));
        }
    } finally {
        swapper.close();
    }
}

From source file:com.pushtechnology.consulting.SessionCreator.java

/**
 * Session churn.//from w  ww.  j a  v  a2  s .  c  o  m
 *
 * @param multiIpClientAddresses
 * @param sessionCreateRatePerSec
 * @param sessionDurationMs
 */
private void doStart(long sessionCreateRatePerSec, long sessionDurationSec) {

    LOG.trace("SessionCreator#doStart for '{}' sessions/second and '{}' sessionDurationMs",
            sessionCreateRatePerSec, sessionDurationSec);

    final long interval = 1000 / sessionCreateRatePerSec;
    long now = System.currentTimeMillis();

    do {
        try {
            startedSessions.incrementAndGet();
            Benchmarker.connectThreadPool.submit(new Runnable() {

                @Override
                public void run() {

                    LOG.trace("Adding session");
                    try {
                        /* ASYNC session creation */
                        sessionFactory.open(getConnectionString(),
                                new OpenChurningSessionCallback(sessionDurationSec));
                        LOG.trace("Done submitting session open");
                    } catch (Exception e) {
                        /* ASYNC session creation */
                        connectionFailures.incrementAndGet();
                        LOG.error("Exception caught trying to connect:", e);
                    }
                }

                private String getConnectionString() {
                    final ThreadLocalRandom rnd = ThreadLocalRandom.current();
                    return connectionStrings.get(rnd.nextInt(connectionStrings.size()));
                }
            });
        } catch (Exception e) {
            LOG.error("Exception caught when submitting session open ", e.getMessage());
            connectionFailures.incrementAndGet();
        }
        if (connectedSessions.get() >= sessionCreateRatePerSec * sessionDurationSec) {
            writeSteadyStateFlagFile();
        }

        now = now + interval;
        LockSupport.parkUntil(now);
    } while (true);
}

From source file:com.adaptris.core.PoolingWorkflow.java

private GenericObjectPool<Worker> createObjectPool() {
    GenericObjectPool<Worker> pool = new GenericObjectPool<>(new WorkerFactory());
    long lifetime = threadLifetimeMs();
    pool.setMaxTotal(poolSize());//  w  ww . jav  a2 s .c  o  m
    pool.setMinIdle(minIdle());
    pool.setMaxIdle(maxIdle());
    pool.setMaxWaitMillis(-1L);
    pool.setBlockWhenExhausted(true);
    pool.setSoftMinEvictableIdleTimeMillis(lifetime);
    pool.setTimeBetweenEvictionRunsMillis(lifetime + ThreadLocalRandom.current().nextLong(lifetime));
    return pool;
}

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

private void buildPageElement() {

    pageElement = new Element(getName());
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_JCR);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_NT);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_JNT);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_TEST);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_SV);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_JMIX);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_J);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_SV);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_REP);
    pageElement.addNamespaceDeclaration(ContentGeneratorCst.NS_WEM);

    pageElement.setAttribute("changefreq", "monthly");
    pageElement.setAttribute("templateName", pageTemplate, ContentGeneratorCst.NS_J);
    pageElement.setAttribute("primaryType", "jnt:page", ContentGeneratorCst.NS_JCR);
    pageElement.setAttribute("priority", "0.5");

    String mixinTypes = "jmix:sitemap";
    if (hasVanity) {
        mixinTypes = mixinTypes + " jmix:vanityUrlMapped";
    }//from  w  w  w .  ja  v  a  2 s .c o  m
    pageElement.setAttribute("mixinTypes", mixinTypes, ContentGeneratorCst.NS_JCR);

    if (idCategory != null) {
        pageElement.setAttribute("jcategorized", StringUtils.EMPTY, ContentGeneratorCst.NS_JMIX);
        pageElement.setAttribute("defaultCategory", "/sites/systemsite/categories/category" + idCategory,
                ContentGeneratorCst.NS_J);
    }

    if (idTag != null) {
        pageElement.setAttribute("tags", "/sites/" + siteKey + "/tags/tag" + idTag, ContentGeneratorCst.NS_J);
    }

    // articles
    for (Map.Entry<String, ArticleBO> entry : articles.entrySet()) {
        Element translationNode = new Element("translation_" + entry.getKey(), ContentGeneratorCst.NS_J);
        translationNode.setAttribute("language", entry.getKey(), ContentGeneratorCst.NS_JCR);
        translationNode.setAttribute("mixinTypes", "mix:title", ContentGeneratorCst.NS_JCR);
        translationNode.setAttribute("primaryType", "jnt:translation", ContentGeneratorCst.NS_JCR);
        translationNode.setAttribute("title", entry.getValue().getTitle(), ContentGeneratorCst.NS_JCR);

        if (StringUtils.isNotEmpty(description)) {
            translationNode.setAttribute("description", description, ContentGeneratorCst.NS_JCR);
        }
        pageElement.addContent(translationNode);
    }

    if (!acls.isEmpty()) {
        Element aclNode = new Element("acl", ContentGeneratorCst.NS_J);
        aclNode.setAttribute("inherit", "true", ContentGeneratorCst.NS_J);
        aclNode.setAttribute("primaryType", "jnt:acl", ContentGeneratorCst.NS_JCR);

        for (Map.Entry<String, List<String>> entry : acls.entrySet()) {
            String roles = "";
            for (String s : entry.getValue()) {
                roles += s + " ";
            }
            Element aceNode = new Element("GRANT_" + entry.getKey().replace(":", "_"));
            aceNode.setAttribute("aceType", "GRANT", ContentGeneratorCst.NS_J);
            aceNode.setAttribute("principal", entry.getKey(), ContentGeneratorCst.NS_J);
            aceNode.setAttribute("protected", "false", ContentGeneratorCst.NS_J);
            aceNode.setAttribute("roles", roles.trim(), ContentGeneratorCst.NS_J);
            aceNode.setAttribute("primaryType", "jnt:ace", ContentGeneratorCst.NS_JCR);

            aclNode.addContent(aceNode);
        }
        pageElement.addContent(aclNode);
    }

    // begin content list
    Element listNode = new Element("listA");
    listNode.setAttribute("primaryType", "jnt:contentList", ContentGeneratorCst.NS_JCR);

    LinkedList<Element> personalizableElements = new LinkedList<Element>();

    if (pageTemplate.equals(ContentGeneratorCst.PAGE_TPL_QALIST)) {

        List<String> languages = new ArrayList<String>();
        for (Map.Entry<String, ArticleBO> entry : articles.entrySet()) {
            languages.add(entry.getKey());
        }
        for (int i = 1; i <= ContentGeneratorCst.NB_NEWS_IN_QALIST; i++) {
            Element newsNode = new NewsBO(namePrefix + "-" + "news" + i, languages).getElement();
            listNode.addContent(newsNode);
            if (i <= ContentGeneratorCst.NB_NEWS_PER_PAGE_IN_QALIST) {
                // News are split to multiple pages by Jahia at runtime, so only personalize items present on the first page.
                personalizableElements.add(newsNode);
            }
        }
    } else if (pageTemplate.equals(ContentGeneratorCst.PAGE_TPL_DEFAULT)) {
        for (int i = 1; i <= numberBigText.intValue(); i++) {
            Element bigTextNode = new Element("bigText_" + i);
            bigTextNode.setAttribute("primaryType", "jnt:bigText", ContentGeneratorCst.NS_JCR);
            bigTextNode.setAttribute("mixinTypes", "jmix:renderable", ContentGeneratorCst.NS_JCR);
            for (Map.Entry<String, ArticleBO> entry : articles.entrySet()) {
                Element translationNode = new Element("translation_" + entry.getKey(),
                        ContentGeneratorCst.NS_J);
                translationNode.setAttribute("language", entry.getKey(), ContentGeneratorCst.NS_JCR);
                translationNode.setAttribute("primaryType", "jnt:translation", ContentGeneratorCst.NS_JCR);
                translationNode.setAttribute("text", entry.getValue().getContent());
                bigTextNode.addContent(translationNode);
            }
            listNode.addContent(bigTextNode);
            personalizableElements.add(bigTextNode);
        }
    }

    // for pages with external/internal file reference, we check the page name
    if (StringUtils.startsWith(namePrefix, ContentGeneratorCst.PAGE_TPL_QAEXTERNAL)) {
        for (int i = 0; i < externalFilePaths.size(); i++) {
            String externalFilePath = externalFilePaths.get(i);
            Element externalFileReference = new Element("external-file-reference-" + i);
            externalFileReference.setAttribute("node", "/mounts/" + ContentGeneratorCst.CMIS_MOUNT_POINT_NAME
                    + "/Sites/" + cmisSite + externalFilePath, ContentGeneratorCst.NS_J);
            externalFileReference.setAttribute("primaryType", "jnt:fileReference", ContentGeneratorCst.NS_JCR);
            listNode.addContent(externalFileReference);
            personalizableElements.add(externalFileReference);
        }
    }

    if (StringUtils.startsWith(namePrefix, ContentGeneratorCst.PAGE_TPL_QAINTERNAL) && fileName != null) {

        Element randomFileNode = new Element("rand-file");
        randomFileNode.setAttribute("primaryType", "jnt:fileReference", ContentGeneratorCst.NS_JCR);

        Element fileTranslationNode = new Element("translation_en", ContentGeneratorCst.NS_J);
        fileTranslationNode.setAttribute("language", "en", ContentGeneratorCst.NS_JCR);
        fileTranslationNode.setAttribute("primaryType", "jnt:translation", ContentGeneratorCst.NS_JCR);
        fileTranslationNode.setAttribute("title", "My file", ContentGeneratorCst.NS_JCR);

        randomFileNode.addContent(fileTranslationNode);

        Element publicationNode = new Element("publication");
        publicationNode.setAttribute("primaryType", "jnt:publication", ContentGeneratorCst.NS_JCR);

        Element publicationTranslationNode = new Element("translation_en", ContentGeneratorCst.NS_J);
        publicationTranslationNode.setAttribute("author", "Jahia Content Generator");
        publicationTranslationNode.setAttribute("body", "&lt;p&gt;  Random publication&lt;/p&gt;");
        publicationTranslationNode.setAttribute("title", "Random publication", ContentGeneratorCst.NS_JCR);
        publicationTranslationNode.setAttribute("file", "/sites/" + siteKey + "/files/contributed/"
                + org.apache.jackrabbit.util.ISO9075.encode(fileName));
        publicationTranslationNode.setAttribute("language", "en", ContentGeneratorCst.NS_JCR);
        publicationTranslationNode.setAttribute("primaryType", "jnt:translation", ContentGeneratorCst.NS_JCR);
        publicationTranslationNode.setAttribute("source", "Jahia");

        publicationNode.addContent(publicationTranslationNode);

        listNode.addContent(publicationNode);
    }

    if (personalized) {
        if (personalizableElements.isEmpty()) {
            personalized = false;
            pageElement.setName(getName()); // Re-set the root element name: it must change according to page personalization change.
        } else {
            Element element = personalizableElements
                    .get(ThreadLocalRandom.current().nextInt(personalizableElements.size()));
            int elementIndex = listNode.indexOf(element);
            listNode.removeContent(element);
            element = getPersonalizedElement(element);
            listNode.addContent(elementIndex, element);
        }
    }

    // end content list
    pageElement.addContent(listNode);

    if (hasVanity) {

        Element vanityNode = new Element("vanityUrlMapping");
        vanityNode.setAttribute("primaryType", "jnt:vanityUrls", ContentGeneratorCst.NS_JCR);

        Element vanitySubNode = new Element(namePrefix);
        vanitySubNode.setAttribute("active", "true", ContentGeneratorCst.NS_J);
        vanitySubNode.setAttribute("default", "true", ContentGeneratorCst.NS_J);
        vanitySubNode.setAttribute("url", "/" + namePrefix, ContentGeneratorCst.NS_J);
        vanitySubNode.setAttribute("language", "en", ContentGeneratorCst.NS_JCR);
        vanitySubNode.setAttribute("primaryType", "jnt:vanityUrl", ContentGeneratorCst.NS_JCR);

        vanityNode.addContent(vanitySubNode);
        pageElement.addContent(vanityNode);
    }

    if (visibilityEnabled) {

        Element visibilityNode = new Element("conditionalVisibility", ContentGeneratorCst.NS_J);
        visibilityNode.setAttribute("conditionalVisibility", null, ContentGeneratorCst.NS_J);
        visibilityNode.setAttribute("forceMatchAllConditions", "true", ContentGeneratorCst.NS_J);
        visibilityNode.setAttribute("primaryType", "jnt:conditionalVisibility", ContentGeneratorCst.NS_JCR);

        Element visibilityConditionNode = new Element("startEndDateCondition0", ContentGeneratorCst.NS_JNT);
        visibilityConditionNode.setAttribute("primaryType", "jnt:startEndDateCondition",
                ContentGeneratorCst.NS_JCR);
        visibilityConditionNode.setAttribute("start", visibilityStartDate);
        visibilityConditionNode.setAttribute("end", visibilityEndDate);

        visibilityNode.addContent(visibilityConditionNode);
        pageElement.addContent(visibilityNode);
    }

    if (null != subPages) {
        for (Iterator<PageBO> iterator = subPages.iterator(); iterator.hasNext();) {
            PageBO subPage = iterator.next();
            pageElement.addContent(subPage.getElement());
        }
    }
}

From source file:org.apache.druid.server.coordinator.CostBalancerStrategy.java

/**
 * For assignment, we want to move to the lowest cost server that isn't already serving the segment.
 *
 * @param proposalSegment A DataSegment that we are proposing to move.
 * @param serverHolders   An iterable of ServerHolders for a particular tier.
 *
 * @return A ServerHolder with the new home for a segment.
 *//*from w  w w  . ja v  a  2  s  . c  o m*/

protected Pair<Double, ServerHolder> chooseBestServer(final DataSegment proposalSegment,
        final Iterable<ServerHolder> serverHolders, final boolean includeCurrentServer) {
    Pair<Double, ServerHolder> bestServer = Pair.of(Double.POSITIVE_INFINITY, null);

    List<ListenableFuture<Pair<Double, ServerHolder>>> futures = Lists.newArrayList();

    for (final ServerHolder server : serverHolders) {
        futures.add(
                exec.submit(() -> Pair.of(computeCost(proposalSegment, server, includeCurrentServer), server)));
    }

    final ListenableFuture<List<Pair<Double, ServerHolder>>> resultsFuture = Futures.allAsList(futures);
    final List<Pair<Double, ServerHolder>> bestServers = new ArrayList<>();
    bestServers.add(bestServer);
    try {
        for (Pair<Double, ServerHolder> server : resultsFuture.get()) {
            if (server.lhs <= bestServers.get(0).lhs) {
                if (server.lhs < bestServers.get(0).lhs) {
                    bestServers.clear();
                }
                bestServers.add(server);
            }
        }

        // Randomly choose a server from the best servers
        bestServer = bestServers.get(ThreadLocalRandom.current().nextInt(bestServers.size()));
    } catch (Exception e) {
        log.makeAlert(e, "Cost Balancer Multithread strategy wasn't able to complete cost computation.").emit();
    }
    return bestServer;
}