Example usage for org.apache.commons.lang RandomStringUtils randomAscii

List of usage examples for org.apache.commons.lang RandomStringUtils randomAscii

Introduction

In this page you can find the example usage for org.apache.commons.lang RandomStringUtils randomAscii.

Prototype

public static String randomAscii(int count) 

Source Link

Document

Creates a random string whose length is the number of characters specified.

Characters will be chosen from the set of characters whose ASCII value is between 32 and 126 (inclusive).

Usage

From source file:com.linkedin.pinot.core.realtime.impl.dictionary.MutableDictionaryTest.java

private Object makeRandomObjectOfType(FieldSpec.DataType dataType) {
    switch (dataType) {
    case INT:/*from   w ww .  j  a v a  2s. c o  m*/
        return RANDOM.nextInt();
    case LONG:
        return RANDOM.nextLong();
    case FLOAT:
        return RANDOM.nextFloat();
    case DOUBLE:
        return RANDOM.nextDouble();
    case STRING:
        return RandomStringUtils.randomAscii(RANDOM.nextInt(1024));
    default:
        throw new UnsupportedOperationException("Unsupported data type: " + dataType);
    }
}

From source file:com.apress.progwt.server.service.impl.UserServiceImpl.java

/**
 * Question, what should we return for user == null? We'll avoid
 * putting it in the cache, and just return another random string.
 * There's no way to get this value again and that's probably what we
 * want.//  w  w  w  .j  av  a2  s  . c o m
 */
public String getToken(User user) {

    if (user == null) {
        return RandomStringUtils.randomAscii(10);
    }
    Element e = userTokenCache.get(user);
    if (e != null) {
        String token = (String) e.getValue();
        log.debug("Found existing token for: " + user + " token: " + token);
        return token;
    } else {

        String token = RandomStringUtils.randomAscii(10);
        log.debug("No existing token for: " + user + " new token: " + token);
        Element newElement = new Element(user, (Serializable) token);
        userTokenCache.put(newElement);
        return token;
    }
}

From source file:com.sjsu.crawler.util.RandomStringUtilsTest.java

/**
 * Make sure 32 and 127 are generated by randomNumeric
 * This test will fail randomly with probability = 2*(95/96)**1000 ~ 5.7E-5
 *//*from  w  ww.j  a va2  s . c o  m*/
@Test
public void testRandomAscii() {
    final char[] testChars = { (char) 32, (char) 126 };
    final boolean[] found = { false, false };
    for (int i = 0; i < 100; i++) {
        final String randString = RandomStringUtils.randomAscii(10);
        for (int j = 0; j < testChars.length; j++) {
            if (randString.indexOf(testChars[j]) > 0) {
                found[j] = true;
            }
        }
    }
    for (int i = 0; i < testChars.length; i++) {
        if (!found[i]) {
            fail("ascii character not generated in 1000 attempts: " + (int) testChars[i]
                    + " -- repeated failures indicate a problem");
        }
    }
}

From source file:com.redhat.rhn.frontend.xmlrpc.errata.test.ErrataHandlerTest.java

public void testAdvisoryLength() throws Exception {
    Channel channel = ChannelFactoryTest.createBaseChannel(admin);

    Map errataInfo = new HashMap();

    String advisoryName = RandomStringUtils.randomAscii(101);
    populateErrataInfo(errataInfo);//from   www.j a  va2  s.  co m
    errataInfo.put("advisory_name", advisoryName);

    ArrayList packages = new ArrayList();
    ArrayList bugs = new ArrayList();
    ArrayList keywords = new ArrayList();
    ArrayList channels = new ArrayList();
    channels.add(channel.getLabel());

    try {
        Errata errata = handler.create(admin, errataInfo, bugs, keywords, packages, true, channels);
        fail("large advisory name was accepted");
    } catch (Exception e) {
        // we expect this to fail
        assertTrue(true);
    }
}

From source file:org.apache.hadoop.hdfs.server.namenode.TestAuditLogger.java

/**
 * Verify that the audit logger is aware of the call context
 *///  w ww  .j a  v  a  2 s  . c  o m
@Test
public void testAuditLoggerWithCallContext() throws IOException {
    Configuration conf = new HdfsConfiguration();
    conf.setBoolean(HADOOP_CALLER_CONTEXT_ENABLED_KEY, true);
    conf.setInt(HADOOP_CALLER_CONTEXT_MAX_SIZE_KEY, 128);
    conf.setInt(HADOOP_CALLER_CONTEXT_SIGNATURE_MAX_SIZE_KEY, 40);
    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build();
    LogCapturer auditlog = LogCapturer.captureLogs(FSNamesystem.auditLog);

    try {
        cluster.waitClusterUp();
        final FileSystem fs = cluster.getFileSystem();
        final long time = System.currentTimeMillis();
        final Path p = new Path("/");

        assertNull(CallerContext.getCurrent());

        // context-only
        CallerContext context = new CallerContext.Builder("setTimes").build();
        CallerContext.setCurrent(context);
        LOG.info("Set current caller context as {}", CallerContext.getCurrent());
        fs.setTimes(p, time, time);
        assertTrue(auditlog.getOutput().endsWith(String.format("callerContext=setTimes%n")));
        auditlog.clearOutput();

        // context with signature
        context = new CallerContext.Builder("setTimes")
                .setSignature("L".getBytes(CallerContext.SIGNATURE_ENCODING)).build();
        CallerContext.setCurrent(context);
        LOG.info("Set current caller context as {}", CallerContext.getCurrent());
        fs.setTimes(p, time, time);
        assertTrue(auditlog.getOutput().endsWith(String.format("callerContext=setTimes:L%n")));
        auditlog.clearOutput();

        // long context is truncated
        final String longContext = RandomStringUtils.randomAscii(200);
        context = new CallerContext.Builder(longContext)
                .setSignature("L".getBytes(CallerContext.SIGNATURE_ENCODING)).build();
        CallerContext.setCurrent(context);
        LOG.info("Set current caller context as {}", CallerContext.getCurrent());
        fs.setTimes(p, time, time);
        assertTrue(auditlog.getOutput()
                .endsWith(String.format("callerContext=%s:L%n", longContext.substring(0, 128))));
        auditlog.clearOutput();

        // empty context is ignored
        context = new CallerContext.Builder("").setSignature("L".getBytes(CallerContext.SIGNATURE_ENCODING))
                .build();
        CallerContext.setCurrent(context);
        LOG.info("Set empty caller context");
        fs.setTimes(p, time, time);
        assertFalse(auditlog.getOutput().contains("callerContext="));
        auditlog.clearOutput();

        // caller context is inherited in child thread
        context = new CallerContext.Builder("setTimes")
                .setSignature("L".getBytes(CallerContext.SIGNATURE_ENCODING)).build();
        CallerContext.setCurrent(context);
        LOG.info("Set current caller context as {}", CallerContext.getCurrent());
        Thread child = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    fs.setTimes(p, time, time);
                } catch (IOException e) {
                    fail("Unexpected exception found." + e);
                }
            }
        });
        child.start();
        try {
            child.join();
        } catch (InterruptedException ignored) {
            // Ignore
        }
        assertTrue(auditlog.getOutput().endsWith(String.format("callerContext=setTimes:L%n")));
        auditlog.clearOutput();

        // caller context is overridden in child thread
        final CallerContext childContext = new CallerContext.Builder("setPermission")
                .setSignature("L".getBytes(CallerContext.SIGNATURE_ENCODING)).build();
        LOG.info("Set current caller context as {}", CallerContext.getCurrent());
        child = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    CallerContext.setCurrent(childContext);
                    fs.setPermission(p, new FsPermission((short) 777));
                } catch (IOException e) {
                    fail("Unexpected exception found." + e);
                }
            }
        });
        child.start();
        try {
            child.join();
        } catch (InterruptedException ignored) {
            // Ignore
        }
        assertTrue(auditlog.getOutput().endsWith(String.format("callerContext=setPermission:L%n")));
        auditlog.clearOutput();

        // reuse the current context's signature
        context = new CallerContext.Builder("mkdirs").setSignature(CallerContext.getCurrent().getSignature())
                .build();
        CallerContext.setCurrent(context);
        LOG.info("Set current caller context as {}", CallerContext.getCurrent());
        fs.mkdirs(new Path("/reuse-context-signature"));
        assertTrue(auditlog.getOutput().endsWith(String.format("callerContext=mkdirs:L%n")));
        auditlog.clearOutput();

        // too long signature is ignored
        context = new CallerContext.Builder("setTimes").setSignature(new byte[41]).build();
        CallerContext.setCurrent(context);
        LOG.info("Set current caller context as {}", CallerContext.getCurrent());
        fs.setTimes(p, time, time);
        assertTrue(auditlog.getOutput().endsWith(String.format("callerContext=setTimes%n")));
        auditlog.clearOutput();

        // null signature is ignored
        context = new CallerContext.Builder("setTimes").setSignature(null).build();
        CallerContext.setCurrent(context);
        LOG.info("Set current caller context as {}", CallerContext.getCurrent());
        fs.setTimes(p, time, time);
        assertTrue(auditlog.getOutput().endsWith(String.format("callerContext=setTimes%n")));
        auditlog.clearOutput();

        // empty signature is ignored
        context = new CallerContext.Builder("mkdirs")
                .setSignature("".getBytes(CallerContext.SIGNATURE_ENCODING)).build();
        CallerContext.setCurrent(context);
        LOG.info("Set current caller context as {}", CallerContext.getCurrent());
        fs.mkdirs(new Path("/empty-signature"));
        assertTrue(auditlog.getOutput().endsWith(String.format("callerContext=mkdirs%n")));
        auditlog.clearOutput();

        // invalid context is not passed to the rpc
        context = new CallerContext.Builder(null).build();
        CallerContext.setCurrent(context);
        LOG.info("Set current caller context as {}", CallerContext.getCurrent());
        fs.mkdirs(new Path("/empty-signature"));
        assertFalse(auditlog.getOutput().contains("callerContext="));
        auditlog.clearOutput();

    } finally {
        cluster.shutdown();
    }
}

From source file:org.apache.hadoop.hdfs.TestDFSUtil.java

@Test
public void testUTFconversion() throws Exception {

    Random r = new Random(System.currentTimeMillis());
    for (int i = 0; i < 100000; i++) {
        // create random length string
        int len = r.nextInt(50) + 1;
        // full unicode string
        validateStringConversion(RandomStringUtils.random(len));
        // only ascii characters
        validateStringConversion(RandomStringUtils.randomAscii(len));
        // only alphanumeric characters
        validateStringConversion(RandomStringUtils.randomAlphanumeric(len));
        // validate singe-character, which translates to 1,2,3 bytes
        validateStringConversion(generateOneCharString(1));
        validateStringConversion(generateOneCharString(2));
        validateStringConversion(generateOneCharString(3));
    }/* w w w.  j a  v a2 s  .  co m*/
}

From source file:org.apache.hadoop.hdfs.TestDFSUtil.java

@Test
public void testTextSerDe() throws Exception {
    File f = new File(TEST_DIR, "test.out");
    // for testing increase the count to at least 1M
    int count = 10000;
    String randomAscii = RandomStringUtils.randomAscii(100);
    String prefAscii = RandomStringUtils.randomAscii(50);
    String randomUTF = prefAscii + RandomStringUtils.random(50);

    long time;//from ww  w  .  ja va2  s . c  o m

    FileOutputStream fos = new FileOutputStream(f);
    DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(fos));

    time = write(count, randomAscii, dos, false);
    LOG.info("Written " + count + " of ascii strings using default encoding in :" + time);

    time = write(count, randomAscii, dos, true);
    LOG.info("Written " + count + " of ascii strings using optimized in :" + time);

    time = write(count, randomUTF, dos, false);
    LOG.info("Written " + count + " of non-ascii strings using default encoding in :" + time);

    time = write(count, randomUTF, dos, true);
    LOG.info("Written " + count + " of non-ascii strings using optimized in :" + time);
    dos.close();

    //////////////////////////////////////////

    FileInputStream fis = new FileInputStream(f);
    DataInputStream dis = new DataInputStream(new BufferedInputStream(fis));

    time = read(count, dis, false);
    LOG.info("Read " + count + " of ascii strings using default decoding in :" + time);

    time = read(count, dis, true);
    LOG.info("Read " + count + " of ascii strings using optimized decoding in :" + time);

    time = read(count, dis, false);
    LOG.info("Read " + count + " of non-ascii strings using default decoding in :" + time);

    time = read(count, dis, true);
    LOG.info("Read " + count + " of non-ascii strings using optimized decoding in :" + time);
}

From source file:org.apache.hadoop.hdfs.TestDFSUtil.java

private void validatePathConversion(boolean full, boolean isDirectory) throws UnsupportedEncodingException {
    Random r = new Random(System.currentTimeMillis());
    // random depth
    int depth = r.nextInt(20) + 1;
    // random length
    int len = r.nextInt(20) + 1;
    String path = "";
    // "xxx" are used to ensure that "/" are not neighbors at the front
    // or the path does not unintentionally end with "/"
    for (int i = 0; i < depth; i++) {
        path += "/xxx" + (full ? RandomStringUtils.random(len) : RandomStringUtils.randomAscii(len)) + "xxx";
    }//from   ww  w  . jav  a  2 s. co m
    if (isDirectory)
        path += "xxx/";

    byte[][] pathComponentsFast = DFSUtil.splitAndGetPathComponents(path);
    byte[][] pathComponentsJava = getPathComponentsJavaBased(path);
    comparePathComponents(pathComponentsFast, pathComponentsJava);

    assertNull(DFSUtil.splitAndGetPathComponents("non-separator" + path));
    assertNull(DFSUtil.splitAndGetPathComponents(null));
    assertNull(DFSUtil.splitAndGetPathComponents(""));
}

From source file:org.apache.hadoop.io.TestUTF8.java

/**
 * Test optimized writes//from  w  ww. j  a va 2  s . c om
 * @param utf - true for unicode, false for ascii
 */
private void testOpt(boolean unicode) throws Exception {
    DataOutputBuffer outOpt = new DataOutputBuffer();
    DataOutputBuffer outReg = new DataOutputBuffer();

    DataInputBuffer in = new DataInputBuffer();

    for (int i = 0; i < 10000; i++) {
        // generate a random string
        String before = null;
        if (unicode) {
            before = RandomStringUtils.random(1010);
        } else {
            before = RandomStringUtils.randomAscii(1010);
        }
        // write it
        outOpt.reset();
        outReg.reset();
        UTF8.writeStringOpt(outOpt, before);
        UTF8.writeString(outReg, before);

        // test that it reads correctly (opt)
        in.reset(outOpt.getData(), outOpt.getLength());
        String afterOpt = UTF8.readString(in);
        assertTrue(before.equals(afterOpt));

        // test that it reads correctly (reg)
        in.reset(outReg.getData(), outReg.getLength());
        String afterReg = UTF8.readString(in);
        assertTrue(before.equals(afterReg));

        // test setters
        UTF8 optUTF8 = new UTF8();
        optUTF8.set(before, true);

        UTF8 regUTF8 = new UTF8();
        regUTF8.set(before, false);

        assertEquals(optUTF8.toString(), regUTF8.toString());
        assertTrue(Arrays.equals(UTF8.getBytes(before), optUTF8.getBytes()));
        assertTrue(Arrays.equals(UTF8.getBytes(before), regUTF8.getBytes()));
    }

}

From source file:org.apache.sling.settings.impl.SlingSettingsServiceImplTest.java

@Test
public void testGetSlingIdFromTooLargeData() throws IOException {
    final String expected = SlingIdUtil.createSlingId();
    final String data = expected + RandomStringUtils.randomAscii(1024 * 1024); // 1MB long random String
    SlingIdUtil.writeSlingId(slingIdFile, data);
    final SlingSettingsService slingSettingsService = createSlingSettingsService(slingIdFile, optionsFile);

    final String slingId = slingSettingsService.getSlingId();
    assertNotNull(slingId);//ww w.  java  2s  .c  om
    assertEquals(expected, slingId);
}