Example usage for java.lang Math random

List of usage examples for java.lang Math random

Introduction

In this page you can find the example usage for java.lang Math random.

Prototype

public static double random() 

Source Link

Document

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0 .

Usage

From source file:edu.kit.dama.transfer.client.util.TestDataBuilder.java

/**
 * Build a random data array with the provided size
 *
 * @param size The byte array size/*from   w  w w.  j a v a  2  s  .c om*/
 *
 * @return The byte array containing random data
 */
private static byte[] buildRandomData(int size) {
    byte[] oneMegaByte = new byte[size];
    for (int i = 0; i < size; i++) {
        oneMegaByte[i] = (byte) (Math.random() * MAX_BYTES);
    }
    return oneMegaByte;
}

From source file:com.streamreduce.util.SecurityUtil.java

public static String generateRandomString(int n) {

    Random rd = new Random();

    char lowerChars[] = "abcdefghijklmnopqrstuvwxyz".toCharArray();
    char upperChars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    char numbers[] = "0123456789".toCharArray();
    //char specialChars[] = "~!@#$%^&*()-_=+[{]}|;:<>/?".toCharArray();
    char specialChars[] = "!$-_+".toCharArray(); // limited subset

    List<Character> pwdLst = new ArrayList<>();
    for (int g = 0; g <= n; g++) {
        for (int z = 0; z < 1; z++) {
            if (g == 0) {
                pwdLst.add(numbers[rd.nextInt(10)]); // must match char array length(s) above
            } else if (g == 1) {
                pwdLst.add(lowerChars[rd.nextInt(26)]);
            } else if (g == 2) {
                pwdLst.add(upperChars[rd.nextInt(26)]);
            } else if (g == 3) {
                pwdLst.add(specialChars[rd.nextInt(5)]);
            }/*  w w  w . ja  va 2 s. c o  m*/
        }
        if (pwdLst.size() == n) {
            break;
        }
        if (g + 1 == 4) {
            g = (int) (Math.random() * 5);

        }
    }
    StringBuilder password = new StringBuilder();
    Collections.shuffle(pwdLst);
    for (Character aPwdLst : pwdLst) {
        password.append(aPwdLst);
    }
    return password.toString();
}

From source file:com.github.jmnarloch.spring.cloud.feign.app.resource.InvoiceResource.java

private List<Invoice> createInvoiceList(int count) {
    final List<Invoice> invoices = new ArrayList<>();
    for (int ind = 0; ind < count; ind++) {
        final Invoice invoice = new Invoice();
        invoice.setTitle("Invoice " + (ind + 1));
        invoice.setAmount(new BigDecimal(String.format(Locale.US, "%.2f", Math.random() * 1000)));
        invoices.add(invoice);//from   w w w.  ja va2s  .c  o m
    }
    return invoices;
}

From source file:io.apiman.test.integration.runner.handlers.AbstractAnnotationHandler.java

/**
 * Create semi-unique name by appending current system time millis if requested
 *
 * @param name base name//from   w w w. j  a v  a 2s  .c  om
 * @return unique name
 */
protected String uniqueName(String name, boolean unique) {
    if (!unique) {
        return name;
    }
    return name + System.currentTimeMillis() + (int) (Math.random() * 10000 + 1);
}

From source file:ch.entwine.weblounge.test.site.GreeterTag.java

/**
 * {@inheritDoc}//  w ww . j  a  v  a 2s .c  o  m
 * 
 * @see javax.servlet.jsp.tagext.TagSupport#doStartTag()
 */
public int doStartTag() throws JspException {
    try {
        Map<String, String> greetings = TestSiteUtils.loadGreetings();
        String greeting = null;
        if (language != null) {
            greeting = greetings.get(language);
            if (greeting == null)
                greeting = "Excuse me?";
        } else {
            String[] languages = greetings.keySet().toArray(new String[greetings.size()]);
            language = languages[(int) Math.random() * languages.length];
            greeting = greetings.get(language);
        }
        String encodedGreeting = StringEscapeUtils.escapeHtml(greeting);
        pageContext.getOut().print("<div id=\"greeting\">");
        pageContext.getOut().print(encodedGreeting);
        pageContext.getOut().println("</div>");
        pageContext.getOut().flush();
    } catch (IOException ioe) {
        throw new JspException("IOException while writing to client" + ioe.getMessage());
    }
    return SKIP_BODY;
}

From source file:com.ciphertool.genetics.algorithms.mutation.GroupMutationAlgorithm.java

@Override
public void mutateChromosome(Chromosome chromosome) {
    if (maxMutationsPerChromosome == null) {
        throw new IllegalStateException("The maxMutationsPerChromosome cannot be null.");
    }/*from   w w  w  .  j  a va 2s.c om*/

    /*
     * Choose a random number of mutations constrained by the configurable
     * max and the total number of genes
     */
    int numMutations = (int) (Math.random() * Math.min(maxMutationsPerChromosome, chromosome.getGenes().size()))
            + 1;

    Map<Integer, Integer> geneIndices = new HashMap<Integer, Integer>();
    for (int i = 0; i < numMutations; i++) {
        // Keep track of the mutated indices by passing the map by reference
        mutateRandomGeneGroup(chromosome, geneIndices);
    }
}

From source file:ThreeThreadsTest.java

public void run() {
    for (int i = 0; i < 10; i++) {
        System.out.println(i + " " + getName());
        try {/*w w w . j  a  v  a 2  s  .com*/
            sleep((long) (Math.random() * 1000));
        } catch (InterruptedException e) {
        }
    }
    System.out.println("DONE! " + getName());
}

From source file:com.siblinks.ws.common.BaseException.java

/**
 * @param aThrowable//www . j a  v  a 2  s  . co m
 * @param aUserMessage
 * @param level
 */
public BaseException(final Throwable aThrowable, final String aUserMessageKey,
        final Serializable[] aValueReplacementArray, final ErrorLevel level) {
    this.throwable = aThrowable;
    this.userMessageKey = aUserMessageKey;
    this.valueReplacementArray = aValueReplacementArray;
    this.errorLevel = level;
    this.uniqueID = new Double(Math.random()).toString();
}

From source file:dk.itst.oiosaml.sp.ConfigurationTest.java

@Before
public void setUp() throws Exception {
    tmpdir = new File(System.getProperty("java.io.tmpdir") + "/oiosaml-" + Math.random());
    if (tmpdir.exists()) {
        FileUtils.cleanDirectory(tmpdir);
    }//from  w w  w  . ja va 2 s  .  c o m
    tmpdir.mkdir();

    SAMLConfiguration.setSystemConfiguration(null);
    IdpMetadata.setMetadata(null);
    SPMetadata.setMetadata(null);
    System.setProperty(SAMLUtil.OIOSAML_HOME, tmpdir.getAbsolutePath());

    server = new Server(8808);
    WebAppContext wac = new WebAppContext();
    wac.setClassLoader(Thread.currentThread().getContextClassLoader());
    wac.setContextPath("/saml");
    wac.setWar("webapp/");

    server.setHandler(wac);
    server.start();

    client = new WebClient();
    page = (HtmlPage) client.getPage(BASE + "/saml/configure");
}

From source file:jetbrains.exodus.entitystore.BackupTests.java

public void testSingular() throws Exception {
    final PersistentEntityStoreImpl store = getEntityStore();
    store.getConfig().setMaxInPlaceBlobSize(0); // no in-place blobs
    final String randomDescription[] = { null };
    store.executeInTransaction(new StoreTransactionalExecutable() {
        @Override/*  ww w  .  j av  a2 s .c  o m*/
        public void execute(@NotNull StoreTransaction txn) {
            final Entity issue = txn.newEntity("Issue");
            randomDescription[0] = Double.toString(Math.random());
            issue.setBlobString("description", randomDescription[0]);
        }
    });
    final File backupDir = TestUtil.createTempDir();
    try {
        final File backup = CompressBackupUtil.backup(store, backupDir, null, true);
        final File restoreDir = TestUtil.createTempDir();
        try {
            extractEntireZip(backup, restoreDir);
            final PersistentEntityStoreImpl newStore = PersistentEntityStores.newInstance(restoreDir);
            try {
                newStore.executeInReadonlyTransaction(new StoreTransactionalExecutable() {
                    @Override
                    public void execute(@NotNull final StoreTransaction txn) {
                        assertEquals(1, txn.getAll("Issue").size());
                        final Entity issue = txn.getAll("Issue").getFirst();
                        assertNotNull(issue);
                        assertEquals(randomDescription[0], issue.getBlobString("description"));
                    }
                });
            } finally {
                newStore.close();
            }
        } finally {
            IOUtil.deleteRecursively(restoreDir);
        }
    } finally {
        IOUtil.deleteRecursively(backupDir);
    }
}