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

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

Introduction

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

Prototype

public static String randomAlphanumeric(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 alpha-numeric characters.

Usage

From source file:com.cws.esolutions.security.dao.usermgmt.impl.LDAPUserManagerTest.java

@Test
public void modifyUserSecurity() {
    try {/*from   w w w.  j av a  2  s  .  com*/
        Assert.assertTrue(manager.modifyUserSecurity(LDAPUserManagerTest.GUID,
                new ArrayList<String>(Arrays.asList(RandomStringUtils.randomAlphanumeric(64),
                        RandomStringUtils.randomAlphanumeric(64), RandomStringUtils.randomAlphanumeric(64),
                        RandomStringUtils.randomAlphanumeric(64)))));
    } catch (UserManagementException umx) {
        Assert.fail(umx.getMessage());
    }
}

From source file:com.google.code.ssm.aop.ReadThroughMultiCacheTest.java

@Test
public void testGenerateResultsException() {
    final List<Object> keyObjects = new ArrayList<Object>();
    final Map<Object, String> obj2key = new HashMap<Object, String>();
    final String keyObject = RandomStringUtils.randomAlphanumeric(8);
    final String key = keyObject + "-" + RandomStringUtils.randomAlphanumeric(4);
    keyObjects.add(keyObject);//from   w w w.  j  a  v  a  2  s. co m
    obj2key.put(keyObject, key);
    AnnotationData data = new AnnotationData();
    data.setListIndexInKeys(0);
    coord = new ReadThroughMultiCacheAdvice.MultiCacheCoordinator(null, data);
    coord.setListKeyObjects(keyObjects);
    coord.getObj2Key().putAll(obj2key);

    try {
        coord.generateResultList();
        fail("Expected Exception");
    } catch (RuntimeException ex) {
    }

}

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

/**
 * Creates KickstartableTree for testing purposes.
 * @param treeChannel Channel this Tree uses.
 * @return Returns a committed KickstartableTree
 * @throws Exception//from  w w  w.  ja v  a2s  .  c o  m
 */
public static KickstartableTree createTestKickstartableTree(Channel treeChannel) throws Exception {
    Date created = new Date();
    Date modified = new Date();
    Date lastmodified = new Date();

    Long testid = new Long(1);
    String query = "KickstartInstallType.findById";
    KickstartInstallType installtype = (KickstartInstallType) TestUtils.lookupFromCacheById(testid, query);

    query = "KickstartTreeType.findById";
    KickstartTreeType treetype = (KickstartTreeType) TestUtils.lookupFromCacheById(testid, query);

    KickstartableTree k = new KickstartableTree();
    k.setLabel("ks-" + treeChannel.getLabel() + RandomStringUtils.randomAlphanumeric(5));

    k.setBasePath(KICKSTART_TREE_PATH.getAbsolutePath());
    k.setCreated(created);
    k.setModified(modified);
    k.setOrg(treeChannel.getOrg());
    k.setLastModified(lastmodified);
    k.setInstallType(installtype);
    k.setTreeType(treetype);
    k.setChannel(treeChannel);

    createKickstartTreeItems(k);

    Distro d = Distro.create(CobblerXMLRPCHelper.getConnection("test"), k.getLabel(), k.getDefaultKernelPath(),
            k.getDefaultInitrdPath()[0], new HashMap(), k.getInstallType().getCobblerBreed(),
            k.getInstallType().getCobblerOsVersion(), k.getChannel().getChannelArch().cobblerArch());
    Distro xend = Distro.create(CobblerXMLRPCHelper.getConnection("test"), k.getLabel(),
            k.getDefaultKernelPath(), k.getDefaultInitrdPath()[0], new HashMap(),
            k.getInstallType().getCobblerBreed(), k.getInstallType().getCobblerOsVersion(),
            k.getChannel().getChannelArch().cobblerArch());

    k.setCobblerId(d.getUid());
    k.setCobblerXenId(xend.getUid());

    TestUtils.saveAndFlush(k);

    return k;
}

From source file:massbank.BatchJobWorker.java

public void run() {
    File attacheDir = null;/*  w  ww.j  a v a 2s  . c  o  m*/
    try {
        GetConfig conf = new GetConfig(BatchService.BASE_URL);
        this.serverUrl = conf.getServerUrl();

        String tempDir = System.getProperty("java.io.tmpdir");
        File temp = File.createTempFile("batchRes", ".txt");
        String queryFilePath = tempDir + "/" + this.fileName;
        String resultFilePath = tempDir + "/" + temp.getName();

        // ** open temporary file
        File f1 = new File(queryFilePath);
        File f2 = new File(resultFilePath);
        BufferedReader in = new BufferedReader(new FileReader(f1));
        PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(f2)));
        String line;
        name = "";
        peak = "";
        sendLen = 0;

        writer.println(mailAddress);
        sendLen += mailAddress.length() + 1;
        String year = this.timeStamp.substring(0, 4);
        String month = this.timeStamp.substring(4, 6);
        String day = this.timeStamp.substring(6, 8);
        String hour = this.timeStamp.substring(8, 10);
        String minute = this.timeStamp.substring(10, 12);
        String second = this.timeStamp.substring(12, 14);
        String time = year + "/" + month + "/" + day + " " + hour + ":" + minute + ":" + second + " JST";
        writer.println(time);
        sendLen += time.length() + 1;
        writer.println();
        sendLen++;
        name = "(none)";
        int flag = 0;
        while ((line = in.readLine()) != null) {
            line = line.trim();
            if (line.startsWith("//")) {
                continue;
            } else if (line.matches("^Name:.*")) {
                name = line;
                name = line.replaceFirst("^Name: *", "").replaceFirst("^ *$", "");
                peak = "";
                flag = 1;
            } else if (line.matches(".*:.*")) {
            } else if (line.matches("^$")) {
                if (flag == 0) {
                    continue;
                }
                flag = 0;
                doSearch(writer);
                if (sendLen >= LIMIT) {
                    break;
                }
            } else {
                peak += "  " + line;
            }

            // Xbh?I
            if (isTerminated) {
                break;
            }
        }
        in.close();

        if (flag == 1 && sendLen < LIMIT) {
            doSearch(writer);
        }
        writer.flush();
        writer.close();

        if (isTerminated) {
            f2.delete();
            return;
        }

        // ??[?M???
        AdminCommon admin = new AdminCommon(BatchService.BASE_URL, BatchService.REAL_PATH);
        SendMailInfo info = new SendMailInfo(admin.getMailSmtp(), admin.getMailFrom(), this.mailAddress);
        info.setFromName(admin.getMailName());
        info.setSubject("MassBank Batch Service Results");
        info.setContents("Dear Users,\n\nThank you for using MassBank Batch Service.\n" + "\n"
                + "The results for your request dated '" + time + "' are attached to this e-mail.\n" + "\n"
                + "--\n" + "MassBank.jp - High Resolution Mass Spectral Database\n"
                + "  URL: http://www.massbank.jp/\n" + "  E-mail: massbank@iab.keio.ac.jp");

        // Ytt@C??fBNg
        attacheDir = new File(tempDir + "/batch_" + RandomStringUtils.randomAlphanumeric(9));
        while (attacheDir.exists()) {
            attacheDir = new File(tempDir + "/batch_" + RandomStringUtils.randomAlphanumeric(9));
        }
        attacheDir.mkdir();

        // Ytt@C???ieLXg`?j
        File textFile = new File(attacheDir.getPath() + "/MassBankResults.txt");
        textFile.createNewFile();
        createTextFile(time, f2, textFile);

        // Ytt@C???iHTML`?j
        File htmlFile = new File(attacheDir.getPath() + "/MassBankResults.html");
        htmlFile.createNewFile();
        createHtmlFile(time, f2, htmlFile);

        info.setFiles(new File[] { textFile, htmlFile });

        // ??[?M
        SendMail.send(info);

        // WuGg??
        BatchJobManager job = new BatchJobManager();
        job.deleteEntry(this.sessionId, this.timeStamp);

        // ** delete temporary file
        f1.delete();
        f2.delete();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (attacheDir != null && attacheDir.isDirectory()) {
            try {
                FileUtils.forceDelete(attacheDir);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:net.nelz.simplesm.aop.ReadThroughMultiCacheTest.java

@Test
public void testGenerateResults() {
    final List<Object> keyObjects = new ArrayList<Object>();
    final Map<Object, String> obj2key = new HashMap<Object, String>();
    final Map<String, Object> key2result = new HashMap<String, Object>();
    final List<Object> expectedResults = new ArrayList<Object>();
    final int length = 10;
    for (int ix = 0; ix < length; ix++) {
        final String keyObject = RandomStringUtils.randomAlphanumeric(8);
        final String key = keyObject + "-" + RandomStringUtils.randomAlphanumeric(4);

        keyObjects.add(keyObject);//from   w  w w  . j  a  v  a 2 s.co  m
        obj2key.put(keyObject, key);

        if (RandomUtils.nextBoolean()) {
            final String result = RandomStringUtils.randomAlphanumeric(15);
            key2result.put(key, result);
            expectedResults.add(result);
        } else {
            key2result.put(key, new PertinentNegativeNull());
            expectedResults.add(null);
        }
    }

    coord.setKeyObjects(keyObjects);
    coord.getObj2Key().putAll(obj2key);
    coord.getKey2Result().putAll(key2result);

    final List<Object> results = coord.generateResultList();

    assertEquals(length, results.size());
    assertEquals(expectedResults, results);
}

From source file:com.google.cloud.bigtable.hbase.TestPut.java

@Test
public void testDefaultTimestamp() throws IOException {
    long now = System.currentTimeMillis();
    long oneMinute = 60 * 1000;
    long fifteenMinutes = 15 * 60 * 1000;

    Table table = getConnection().getTable(TABLE_NAME);
    byte[] rowKey = Bytes.toBytes("testrow-" + RandomStringUtils.randomAlphanumeric(8));
    byte[] qualifier = Bytes.toBytes("testQualifier-" + RandomStringUtils.randomAlphanumeric(8));
    byte[] value = Bytes.toBytes("testValue-" + RandomStringUtils.randomAlphanumeric(8));
    Put put = new Put(rowKey);
    put.addColumn(COLUMN_FAMILY, qualifier, value);
    table.put(put);/*from   w  ww.  ja  v  a2 s .  com*/
    Get get = new Get(rowKey);
    get.addColumn(COLUMN_FAMILY, qualifier);
    Result result = table.get(get);
    long timestamp1 = result.getColumnLatestCell(COLUMN_FAMILY, qualifier).getTimestamp();
    System.out.println(String.format("Timestamp of latest cell: %s now = %s", timestamp1, now));
    Assert.assertTrue("Latest timestamp is off by > 15 minutes", Math.abs(timestamp1 - now) < fifteenMinutes);

    try {
        TimeUnit.MILLISECONDS.sleep(10); // Make sure the clock has a chance to move
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    table.put(put);
    get.addColumn(COLUMN_FAMILY, qualifier);
    result = table.get(get);
    long timestamp2 = result.getColumnLatestCell(COLUMN_FAMILY, qualifier).getTimestamp();
    Assert.assertTrue("Time increases strictly", timestamp2 > timestamp1);
    Assert.assertTrue("Time doesn't move too fast", (timestamp2 - timestamp1) < oneMinute);
    table.close();
}

From source file:com.cws.esolutions.security.dao.usermgmt.impl.SQLUserManagerTest.java

@Test
public void modifyOtpSecret() {
    try {/*from w  w  w .  j av  a  2  s. c om*/
        Assert.assertTrue(manager.modifyOtpSecret(SQLUserManagerTest.GUID, true,
                RandomStringUtils.randomAlphanumeric(64)));
        Assert.assertTrue(manager.modifyOtpSecret(SQLUserManagerTest.GUID, false, null));
    } catch (UserManagementException umx) {
        Assert.fail(umx.getMessage());
    }
}

From source file:com.duroty.task.InitServerTask.java

/**
 * DOCUMENT ME!/*from  w ww.  java2  s .  co  m*/
 *
 * @param dirUsers DOCUMENT ME!
 *
 * @throws Exception DOCUMENT ME!
 */
public void flush() throws Exception {
    SessionFactory hfactory = null;
    Session hsession = null;

    try {
        hfactory = (SessionFactory) ctx.lookup(hibernateSessionFactory);
        hsession = hfactory.openSession();

        Criteria crit1 = hsession.createCriteria(Roles.class);

        List roles = crit1.list();

        if ((roles != null) && (roles.size() > 0)) {
            return;
        } else {
            Roles guest = new Roles();
            guest.setRolName("guest");
            hsession.save(guest);

            Roles member = new Roles();
            member.setRolName("member");
            hsession.save(member);

            Roles mail = new Roles();
            mail.setRolName("mail");
            hsession.save(mail);

            Roles bookmark = new Roles();
            bookmark.setRolName("bookmark");
            hsession.save(bookmark);

            Roles chat = new Roles();
            chat.setRolName("chat");
            hsession.save(chat);

            Roles admin = new Roles();
            admin.setRolName("admin");
            hsession.save(admin);

            hsession.flush();

            Criteria crit2 = hsession.createCriteria(Users.class);
            crit2.add(Restrictions.eq("useUsername", "duroty"));

            Users duroty = (Users) crit2.uniqueResult();

            if (duroty == null) {
                duroty = new Users();
                duroty.setUseActive(true);
                duroty.setUseEmail("duroty@localhost");
                duroty.setUseLanguage("en");
                duroty.setUseName("Duroty System");
                duroty.setUsePassword("duroty");
                duroty.setUseRegisterDate(new Date());
                duroty.setUseUsername("duroty");

                UserRole userRole1 = new UserRole(new UserRoleId(duroty, member));
                UserRole userRole2 = new UserRole(new UserRoleId(duroty, bookmark));
                UserRole userRole3 = new UserRole(new UserRoleId(duroty, chat));
                UserRole userRole4 = new UserRole(new UserRoleId(duroty, admin));

                duroty.addUserRole(userRole1);
                duroty.addUserRole(userRole2);
                duroty.addUserRole(userRole3);
                duroty.addUserRole(userRole4);

                MailPreferences mailPreferences = new MailPreferences();
                mailPreferences.setMaprHtmlMessage(true);
                mailPreferences.setMaprMessagesByPage(20);
                mailPreferences.setMaprQuotaSize(1048576);
                mailPreferences.setUsers(duroty);

                Identity identity = new Identity();
                identity.setIdeActive(true);
                identity.setIdeCode(RandomStringUtils.randomAlphanumeric(25));
                identity.setIdeDefault(true);
                identity.setIdeEmail("duroty@localhost");
                identity.setIdeName("Duroty System");
                identity.setIdeReplyTo("duroty@localhost");
                identity.setUsers(duroty);

                HashSet set = new HashSet();
                set.add(mailPreferences);
                duroty.setMailPreferenceses(set);

                HashSet identities = new HashSet();
                identities.add(identity);
                duroty.setIdentities(identities);

                hsession.save(duroty);

                hsession.flush();
            }

            Criteria crit3 = hsession.createCriteria(Users.class);
            crit3.add(Restrictions.eq("useUsername", "guest"));

            Users userGuest = (Users) crit3.uniqueResult();

            if (userGuest == null) {
                userGuest = new Users();
                userGuest.setUseActive(true);
                userGuest.setUseEmail("guest@localhost");
                userGuest.setUseLanguage("en");
                userGuest.setUseName("Guest System");
                userGuest.setUsePassword("guest");
                userGuest.setUseRegisterDate(new Date());
                userGuest.setUseUsername("guest");

                UserRole userRole1 = new UserRole(new UserRoleId(userGuest, guest));
                ;

                userGuest.addUserRole(userRole1);

                MailPreferences mailPreferences = new MailPreferences();
                mailPreferences.setMaprHtmlMessage(true);
                mailPreferences.setMaprMessagesByPage(20);
                mailPreferences.setMaprQuotaSize(1048576);
                mailPreferences.setUsers(userGuest);

                HashSet set = new HashSet();
                set.add(mailPreferences);
                duroty.setMailPreferenceses(set);

                hsession.save(userGuest);

                hsession.flush();
            }
        }
    } catch (Exception e) {
        System.gc();

        StringWriter writer = new StringWriter();
        e.printStackTrace(new PrintWriter(writer));
        DLog.log(DLog.ERROR, this.getClass(), writer.toString());
    } catch (OutOfMemoryError e) {
        System.gc();

        StringWriter writer = new StringWriter();
        e.printStackTrace(new PrintWriter(writer));
        DLog.log(DLog.ERROR, this.getClass(), writer.toString());
    } catch (Throwable e) {
        System.gc();

        StringWriter writer = new StringWriter();
        e.printStackTrace(new PrintWriter(writer));
        DLog.log(DLog.ERROR, this.getClass(), writer.toString());
    } finally {
        GeneralOperations.closeHibernateSession(hsession);

        System.gc();
    }
}

From source file:com.cws.esolutions.security.dao.usermgmt.impl.LDAPUserManagerTest.java

@Test
public void modifyOtpSecret() {
    try {//from  ww w .j a v a  2  s  . c o  m
        Assert.assertTrue(manager.modifyOtpSecret(LDAPUserManagerTest.GUID, true,
                RandomStringUtils.randomAlphanumeric(64)));
        Assert.assertTrue(manager.modifyOtpSecret(LDAPUserManagerTest.GUID, false, null));
    } catch (UserManagementException umx) {
        Assert.fail(umx.getMessage());
    }
}

From source file:info.bluefoot.winter.controller.PlaylistController.java

@RequestMapping(value = { "/playlist/addvideos" }, method = RequestMethod.POST, produces = "application/json")
public @ResponseBody ResponseEntity<Map<String, String>> addVideosToPlaylist(
        @ModelAttribute("addplaylistform") AddPlaylistForm addPlaylistForm, HttpServletResponse response) {
    Set<Video> videos = new HashSet<Video>();
    for (String url : addPlaylistForm.getVideos().split("\n")) {
        if (!url.trim().isEmpty()) {
            videos.add(new Video(url.trim()));
        }/*from www .  j  ava2  s .c  om*/
    }
    try {
        // checking if user is the owner of the playlist
        Playlist selectedPlaylist = playlistService.getPlaylistByIdAndUser(
                addPlaylistForm.getPlaylist().getPlaylistId(), Utils.getCurrentLoggedUser());
        playlistService.addVideosToPlaylist(selectedPlaylist, videos);
    } catch (PlaylistNotFoundException e) {
        return new ResponseEntity<Map<String, String>>(Collections.singletonMap("error", "Invalid playlist"),
                HttpStatus.INTERNAL_SERVER_ERROR);
    } catch (Exception e) {
        String errorId = RandomStringUtils.randomAlphanumeric(6).toUpperCase();
        logger.error("[" + errorId + "] Can't add videos to playlist", e);
        return new ResponseEntity<Map<String, String>>(
                Collections.singletonMap("error",
                        "Can't add videos to playlist. Try again later. Error id: " + errorId + "."),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }
    return new ResponseEntity<Map<String, String>>(Collections.singletonMap("playlist_id",
            String.valueOf(addPlaylistForm.getPlaylist().getPlaylistId())), HttpStatus.OK);
}