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.sjsu.crawler.util.RandomStringUtilsTest.java

/**
 * Test the implementation/*from w  ww.j a  va  2  s  .  c  o  m*/
 */
@Test
public void testRandomStringUtils() {
    String r1 = RandomStringUtils.random(50);
    assertEquals("random(50) length", 50, r1.length());
    String r2 = RandomStringUtils.random(50);
    assertEquals("random(50) length", 50, r2.length());
    assertTrue("!r1.equals(r2)", !r1.equals(r2));

    r1 = RandomStringUtils.randomAscii(50);
    assertEquals("randomAscii(50) length", 50, r1.length());
    for (int i = 0; i < r1.length(); i++) {
        assertTrue("char between 32 and 127", r1.charAt(i) >= 32 && r1.charAt(i) <= 127);
    }
    r2 = RandomStringUtils.randomAscii(50);
    assertTrue("!r1.equals(r2)", !r1.equals(r2));

    r1 = RandomStringUtils.randomAlphabetic(50);
    assertEquals("randomAlphabetic(50)", 50, r1.length());
    for (int i = 0; i < r1.length(); i++) {
        assertTrue("r1 contains alphabetic",
                Character.isLetter(r1.charAt(i)) && !Character.isDigit(r1.charAt(i)));
    }
    r2 = RandomStringUtils.randomAlphabetic(50);
    assertTrue("!r1.equals(r2)", !r1.equals(r2));

    r1 = RandomStringUtils.randomAlphanumeric(50);
    assertEquals("randomAlphanumeric(50)", 50, r1.length());
    for (int i = 0; i < r1.length(); i++) {
        assertTrue("r1 contains alphanumeric", Character.isLetterOrDigit(r1.charAt(i)));
    }
    r2 = RandomStringUtils.randomAlphabetic(50);
    assertTrue("!r1.equals(r2)", !r1.equals(r2));

    r1 = RandomStringUtils.randomNumeric(50);
    assertEquals("randomNumeric(50)", 50, r1.length());
    for (int i = 0; i < r1.length(); i++) {
        assertTrue("r1 contains numeric", Character.isDigit(r1.charAt(i)) && !Character.isLetter(r1.charAt(i)));
    }
    r2 = RandomStringUtils.randomNumeric(50);
    assertTrue("!r1.equals(r2)", !r1.equals(r2));

    String set = "abcdefg";
    r1 = RandomStringUtils.random(50, set);
    assertEquals("random(50, \"abcdefg\")", 50, r1.length());
    for (int i = 0; i < r1.length(); i++) {
        assertTrue("random char in set", set.indexOf(r1.charAt(i)) > -1);
    }
    r2 = RandomStringUtils.random(50, set);
    assertTrue("!r1.equals(r2)", !r1.equals(r2));

    r1 = RandomStringUtils.random(50, (String) null);
    assertEquals("random(50) length", 50, r1.length());
    r2 = RandomStringUtils.random(50, (String) null);
    assertEquals("random(50) length", 50, r2.length());
    assertTrue("!r1.equals(r2)", !r1.equals(r2));

    set = "stuvwxyz";
    r1 = RandomStringUtils.random(50, set.toCharArray());
    assertEquals("random(50, \"stuvwxyz\")", 50, r1.length());
    for (int i = 0; i < r1.length(); i++) {
        assertTrue("random char in set", set.indexOf(r1.charAt(i)) > -1);
    }
    r2 = RandomStringUtils.random(50, set);
    assertTrue("!r1.equals(r2)", !r1.equals(r2));

    r1 = RandomStringUtils.random(50, (char[]) null);
    assertEquals("random(50) length", 50, r1.length());
    r2 = RandomStringUtils.random(50, (char[]) null);
    assertEquals("random(50) length", 50, r2.length());
    assertTrue("!r1.equals(r2)", !r1.equals(r2));

    final long seed = System.currentTimeMillis();
    r1 = RandomStringUtils.random(50, 0, 0, true, true, null, new Random(seed));
    r2 = RandomStringUtils.random(50, 0, 0, true, true, null, new Random(seed));
    assertEquals("r1.equals(r2)", r1, r2);

    r1 = RandomStringUtils.random(0);
    assertEquals("random(0).equals(\"\")", "", r1);
}

From source file:com.redhat.rhn.domain.kickstart.test.KickstartScriptTest.java

public void testLargeScript() throws Exception {
    String largeString = RandomStringUtils.randomAscii(4000);
    KickstartData ksdata = KickstartDataTest.createKickstartWithOptions(user.getOrg());
    ksdata.getScripts().clear();/*  ww  w. j  a v  a  2s.com*/
    KickstartFactory.saveKickstartData(ksdata);
    ksdata = (KickstartData) reload(ksdata);

    // Create 2 scripts, one with data, one without.
    KickstartScript script = createPost(ksdata);
    script.setPosition(1L);
    KickstartScript scriptEmpty = createPost(ksdata);
    script.setData(largeString.getBytes("UTF-8"));

    // Make sure we are setting the blob to be an empty byte
    // array.  The bug happens when one script is empty.
    scriptEmpty.setData(new byte[0]);
    scriptEmpty.setPosition(2L);
    ksdata.addScript(script);
    ksdata.addScript(scriptEmpty);
    TestUtils.saveAndFlush(script);
    TestUtils.saveAndFlush(scriptEmpty);

    KickstartFactory.saveKickstartData(ksdata);
    ksdata = (KickstartData) reload(ksdata);
    Iterator i = ksdata.getScripts().iterator();
    boolean found = false;
    assertTrue(ksdata.getScripts().size() == 2);
    while (i.hasNext()) {
        KickstartScript loaded = (KickstartScript) i.next();
        if (loaded.getDataContents().equals(largeString)) {
            found = true;
        }
    }
    assertTrue(found);
}

From source file:com.keybox.common.db.DBInitServlet.java

/**
 * task init method that created DB and generated public/private keys
 *
 * @param config task config/*from ww w.  j  a va 2  s  . co  m*/
 * @throws ServletException
 */
public void init(ServletConfig config) throws ServletException {

    super.init(config);

    Connection connection = null;
    Statement statement = null;
    //check if reset ssh application key is set
    boolean resetSSHKey = "true".equals(AppConfig.getProperty("resetApplicationSSHKey"));

    //if DB password is empty generate a random
    if (StringUtils.isEmpty(AppConfig.getProperty("dbPassword"))) {
        String dbPassword = null;
        String dbPasswordConfirm = null;
        //prompt for password and confirmation
        while (dbPassword == null || !dbPassword.equals(dbPasswordConfirm)) {
            dbPassword = new String(System.console().readPassword("Please enter database password: "));
            dbPasswordConfirm = new String(System.console().readPassword("Please confirm database password: "));
            if (!dbPassword.equals(dbPasswordConfirm)) {
                System.out.println("Passwords do not match");
            }
        }
        //set password
        if (StringUtils.isNotEmpty(dbPassword)) {
            AppConfig.encryptProperty("dbPassword", dbPassword);
            //if password not set generate a random
        } else {
            System.out.println("Generating random database password");
            AppConfig.encryptProperty("dbPassword", RandomStringUtils.randomAscii(32));
        }
        //else encrypt password if plain-text
    } else if (!AppConfig.isPropertyEncrypted("dbPassword")) {
        AppConfig.encryptProperty("dbPassword", AppConfig.getProperty("dbPassword"));
    }

    try {
        connection = DBUtils.getConn();
        statement = connection.createStatement();

        ResultSet rs = statement.executeQuery(
                "select * from information_schema.tables where upper(table_name) = 'USERS' and table_schema='PUBLIC'");
        if (!rs.next()) {
            resetSSHKey = true;

            //create DB objects
            statement.executeUpdate(
                    "create table if not exists users (id INTEGER PRIMARY KEY AUTO_INCREMENT, first_nm varchar, last_nm varchar, email varchar, username varchar not null, password varchar, auth_token varchar, enabled boolean not null default true, auth_type varchar not null default '"
                            + Auth.AUTH_BASIC + "', user_type varchar not null default '" + Auth.ADMINISTRATOR
                            + "', salt varchar, otp_secret varchar)");
            statement.executeUpdate(
                    "create table if not exists user_theme (user_id INTEGER PRIMARY KEY, bg varchar(7), fg varchar(7), d1 varchar(7), d2 varchar(7), d3 varchar(7), d4 varchar(7), d5 varchar(7), d6 varchar(7), d7 varchar(7), d8 varchar(7), b1 varchar(7), b2 varchar(7), b3 varchar(7), b4 varchar(7), b5 varchar(7), b6 varchar(7), b7 varchar(7), b8 varchar(7), foreign key (user_id) references users(id) on delete cascade) ");
            statement.executeUpdate(
                    "create table if not exists system (id INTEGER PRIMARY KEY AUTO_INCREMENT, display_nm varchar not null, user varchar not null, host varchar not null, port INTEGER not null, authorized_keys varchar not null, status_cd varchar not null default 'INITIAL')");
            statement.executeUpdate(
                    "create table if not exists profiles (id INTEGER PRIMARY KEY AUTO_INCREMENT, nm varchar not null, desc varchar not null)");
            statement.executeUpdate(
                    "create table if not exists system_map (profile_id INTEGER, system_id INTEGER, foreign key (profile_id) references profiles(id) on delete cascade , foreign key (system_id) references system(id) on delete cascade, primary key (profile_id, system_id))");
            statement.executeUpdate(
                    "create table if not exists user_map (user_id INTEGER, profile_id INTEGER, foreign key (user_id) references users(id) on delete cascade, foreign key (profile_id) references profiles(id) on delete cascade, primary key (user_id, profile_id))");
            statement.executeUpdate(
                    "create table if not exists application_key (id INTEGER PRIMARY KEY AUTO_INCREMENT, public_key varchar not null, private_key varchar not null, passphrase varchar)");

            statement.executeUpdate(
                    "create table if not exists status (id INTEGER, user_id INTEGER, status_cd varchar not null default 'INITIAL', foreign key (id) references system(id) on delete cascade, foreign key (user_id) references users(id) on delete cascade, primary key(id, user_id))");
            statement.executeUpdate(
                    "create table if not exists scripts (id INTEGER PRIMARY KEY AUTO_INCREMENT, user_id INTEGER, display_nm varchar not null, script varchar not null, foreign key (user_id) references users(id) on delete cascade)");

            statement.executeUpdate(
                    "create table if not exists public_keys (id INTEGER PRIMARY KEY AUTO_INCREMENT, key_nm varchar not null, type varchar, fingerprint varchar, public_key varchar, enabled boolean not null default true, create_dt timestamp not null default CURRENT_TIMESTAMP(),  user_id INTEGER, profile_id INTEGER, foreign key (profile_id) references profiles(id) on delete cascade, foreign key (user_id) references users(id) on delete cascade)");

            statement.executeUpdate(
                    "create table if not exists session_log (id BIGINT PRIMARY KEY AUTO_INCREMENT, user_id INTEGER, session_tm timestamp default CURRENT_TIMESTAMP, foreign key (user_id) references users(id) on delete cascade )");
            statement.executeUpdate(
                    "create table if not exists terminal_log (session_id BIGINT, instance_id INTEGER, system_id INTEGER, output varchar not null, log_tm timestamp default CURRENT_TIMESTAMP, foreign key (session_id) references session_log(id) on delete cascade, foreign key (system_id) references system(id) on delete cascade)");

            //insert default admin user
            String salt = EncryptionUtil.generateSalt();
            PreparedStatement pStmt = connection.prepareStatement(
                    "insert into users (username, password, user_type, salt) values(?,?,?,?)");
            pStmt.setString(1, "admin");
            pStmt.setString(2, EncryptionUtil.hash("changeme" + salt));
            pStmt.setString(3, Auth.MANAGER);
            pStmt.setString(4, salt);
            pStmt.execute();
            DBUtils.closeStmt(pStmt);

        }
        DBUtils.closeRs(rs);

        //if reset ssh application key then generate new key
        if (resetSSHKey) {

            //delete old key entry
            PreparedStatement pStmt = connection.prepareStatement("delete from application_key");
            pStmt.execute();
            DBUtils.closeStmt(pStmt);

            //generate new key and insert passphrase
            System.out.println("Setting KeyBox SSH public/private key pair");

            //generate application pub/pvt key and get values
            String passphrase = SSHUtil.keyGen();
            String publicKey = SSHUtil.getPublicKey();
            String privateKey = SSHUtil.getPrivateKey();

            //insert new keys
            pStmt = connection.prepareStatement(
                    "insert into application_key (public_key, private_key, passphrase) values(?,?,?)");
            pStmt.setString(1, publicKey);
            pStmt.setString(2, EncryptionUtil.encrypt(privateKey));
            pStmt.setString(3, EncryptionUtil.encrypt(passphrase));
            pStmt.execute();
            DBUtils.closeStmt(pStmt);

            System.out.println("KeyBox Generated Global Public Key:");
            System.out.println(publicKey);

            //set config to default
            AppConfig.updateProperty("publicKey", "");
            AppConfig.updateProperty("privateKey", "");
            AppConfig.updateProperty("defaultSSHPassphrase", "${randomPassphrase}");

            //set to false
            AppConfig.updateProperty("resetApplicationSSHKey", "false");

        }

        //delete ssh keys
        SSHUtil.deletePvtGenSSHKey();

    } catch (Exception ex) {
        log.error(ex.toString(), ex);
    } finally {
        DBUtils.closeStmt(statement);
        DBUtils.closeConn(connection);
    }

    RefreshAuthKeyUtil.startRefreshAllSystemsTimerTask();
}

From source file:com.redhat.rhn.frontend.action.kickstart.test.KickstartScriptActionTest.java

public void testExecuteSubmit() throws Exception {
    // Lets zero out the scripts
    ksdata = clearScripts(ksdata);// w w  w  .  j  av  a  2 s .  c  o  m

    String contents = "some script value";
    String language = "/usr/bin/perl";
    addRequestParameter(KickstartScriptCreateAction.CONTENTS, contents);
    addRequestParameter(KickstartScriptCreateAction.LANGUAGE, language);
    addRequestParameter(KickstartScriptCreateAction.TYPE, KickstartScript.TYPE_POST);
    addRequestParameter(KickstartScriptCreateAction.SUBMITTED, Boolean.TRUE.toString());
    addRequestParameter(KickstartScriptCreateAction.SCRIPTNAME, RandomStringUtils.randomAscii(20));

    setRequestPathInfo("/kickstart/KickstartScriptCreate");
    actionPerform();
    String[] keys = { "kickstart.script.success" };
    verifyActionMessages(keys);
    assertNotNull(ksdata.getScripts());
    KickstartScript ks = ksdata.getScripts().iterator().next();
    assertEquals(contents, ks.getDataContents());
    assertEquals(language, ks.getInterpreter());
    assertEquals(KickstartScript.TYPE_POST, ks.getScriptType());
    verifyForward("success");
}

From source file:com.kixeye.janus.client.http.async.AsyncHttpClientTest.java

@Test
public void testPost() throws Exception {
    final byte[] sentData = RandomStringUtils.randomAscii(32).getBytes(Charsets.US_ASCII);

    Janus janus = new Janus(VIP_TEST, new ConstServerList(VIP_TEST, "http://localhost:" + port),
            new RandomLoadBalancer(), new ServerStatsFactory(ServerStats.class, new MetricRegistry()));

    try (AsyncHttpClient client = new AsyncHttpClient(janus, 0)) {
        ListenableFuture<HttpResponse> responseFuture = client
                .execute(new HttpRequest(HttpMethod.POST, null, new ByteArrayInputStream(sentData)), "/");
        HttpResponse response = responseFuture.get(5, TimeUnit.SECONDS);
        Assert.assertNotNull(response);/* w ww.j a  va 2 s.  com*/
        Assert.assertEquals(new String(sentData, Charsets.US_ASCII).trim(),
                new String(IOUtils.toByteArray(response.getBody()), Charsets.US_ASCII).trim());
    }
}

From source file:fm.last.moji.integration.AbstractMojiIT.java

String newData() {
    return RandomStringUtils.randomAscii(RandomUtils.nextInt(4096) + 512);
}

From source file:com.bloatit.model.Member.java

/**
 * Create a new DaoActor. Initialize the creation date to now. Create a new
 * {@link DaoInternalAccount} and a new {@link DaoExternalAccount}.
 *
 * @param login is the login or name of this actor. It must be non null,
 *            unique, longer than 2 chars and do not contains space chars
 *            ("[^\\p{Space}]+").//from  w  w  w. j a v a2 s.  co m
 * @throws NonOptionalParameterException if login or mail is null.
 * @throws MalformedArgumentException if the login is to small or contain
 *             space chars.
 */
private static DaoMember createDaoMember(final String login, final String password, final String email,
        final Locale locale) {
    final String salt = RandomStringUtils.randomAscii(PASSWORD_SALT_LENGTH);
    final String passwd = Hash.calculateHash(password, salt);
    Reporting.reporter.reportMemberCreation(login);
    return DaoMember.createAndPersist(login, passwd, salt, email, locale);
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.tests.unit.MfencedTest.java

@Test
public void testRenderContentListWithSameSeparators() throws Exception {
    int count = new Random().nextInt(31) + 2;
    logger.debug("Content list length: " + count);
    final String separator = RandomStringUtils.randomAscii(1);
    mfenced.setSeparators(separator);//  w  ww.j a  v  a 2  s.c  om

    List<FormulaElement> list = new ArrayList<>();
    for (int i = 0; i < count; i++) {
        FormulaElement mockedFormulaElement = mock(FormulaElement.class);
        when(mockedFormulaElement.render(or(any(FormulaElement.class), isNull(FormulaElement.class)),
                or(anyListOf(FormulaElement.class), isNull(List.class)))).thenReturn(new Element(HTML_SPAN));
        list.add(mockedFormulaElement);
    }

    mfenced.setContent(list);

    Element result = mfenced.render(possibleParent, null);

    assertEquals(HTML_SPAN, result.getName());
    assertEquals("mfenced", result.getAttributeValue(HTML_CLASS));

    for (FormulaElement mockedElement : list) {
        verify(mockedElement).render(or(eq(mfenced), isNull(FormulaElement.class)),
                or(anyListOf(FormulaElement.class), isNull(List.class)));
    }
    List<Element> spans = result.getChildren(HTML_SPAN);
    Element openingFence = spans.get(0);
    assertEquals("mfenced-open", openingFence.getAttributeValue(HTML_CLASS));

    for (int i = 1; i < spans.size() - 1; i = i + 2) {
        assertEquals("mfenced-content", spans.get(i).getAttributeValue(HTML_CLASS));
    }

    // Check separators
    for (int i = 2; i < spans.size() - 1; i = i + 2) {
        Element separatorSpan = spans.get(i);
        assertEquals("mo mfenced-separator", separatorSpan.getAttributeValue(HTML_CLASS));

        assertEquals(separator, spans.get(i).getText());
    }

    Element closingFence = result.getChildren().get(result.getChildren(HTML_SPAN).size() - 1);
    assertEquals("mfenced-close", closingFence.getAttributeValue(HTML_CLASS));

}

From source file:com.redhat.rhn.frontend.action.kickstart.test.KickstartScriptActionTest.java

public void testEditExecuteSubmit() throws Exception {
    String contents = "some script value " + TestUtils.randomString();
    String language = "/usr/bin/perl";
    addRequestParameter(KickstartScriptCreateAction.CONTENTS, contents);
    addRequestParameter(KickstartScriptCreateAction.LANGUAGE, language);
    addRequestParameter(KickstartScriptCreateAction.TYPE, KickstartScript.TYPE_POST);
    addRequestParameter(KickstartScriptCreateAction.SUBMITTED, Boolean.TRUE.toString());
    addRequestParameter(KickstartScriptCreateAction.SCRIPTNAME, RandomStringUtils.randomAscii(20));
    KickstartScript kss = ksdata.getScripts().iterator().next();
    addRequestParameter(RequestContext.KICKSTART_SCRIPT_ID, kss.getId().toString());
    setRequestPathInfo("/kickstart/KickstartScriptEdit");
    actionPerform();/*  ww  w  . j  a v a2s . c  om*/
    String[] keys = { "kickstart.script.success" };
    verifyActionMessages(keys);
    assertNotNull(ksdata.getScripts());
    KickstartScript ks = ksdata.getScripts().iterator().next();
    assertEquals(contents, ks.getDataContents());
    assertEquals(language, ks.getInterpreter());
    assertEquals(KickstartScript.TYPE_POST, ks.getScriptType());
    verifyForward("success");
}

From source file:com.linkedin.pinot.segments.v1.creator.OnHeapDictionariesTest.java

/**
 * Helper method to build a segment with random data as per the schema.
 *
 * @param segmentDirName Name of segment directory
 * @param segmentName Name of segment//from w w w. j  a  v a2 s  .  c  om
 * @param schema Schema for segment
 * @return Schema built for the segment
 * @throws Exception
 */
private Schema buildSegment(String segmentDirName, String segmentName, Schema schema) throws Exception {

    SegmentGeneratorConfig config = new SegmentGeneratorConfig(schema);
    config.setOutDir(segmentDirName);
    config.setFormat(FileFormat.AVRO);
    config.setSegmentName(segmentName);

    Random random = new Random(RANDOM_SEED);

    List<GenericRow> rows = new ArrayList<>(NUM_ROWS);

    for (int rowId = 0; rowId < NUM_ROWS; rowId++) {
        HashMap<String, Object> map = new HashMap<>();

        map.put(INT_COLUMN, random.nextInt());
        map.put(LONG_COLUMN, random.nextLong());
        map.put(FLOAT_COLUMN, random.nextFloat());
        map.put(DOUBLE_COLUMN, random.nextDouble());
        map.put(STRING_COLUMN, RandomStringUtils.randomAscii(100));

        GenericRow genericRow = new GenericRow();
        genericRow.init(map);
        rows.add(genericRow);
    }

    SegmentIndexCreationDriverImpl driver = new SegmentIndexCreationDriverImpl();
    driver.init(config, new GenericRowRecordReader(rows, schema));
    driver.build();

    LOGGER.info("Built segment {} at {}", segmentName, segmentDirName);
    return schema;
}