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

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

Introduction

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

Prototype

public static String randomAlphabetic(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 alphabetic characters.

Usage

From source file:com.sammyun.controller.shop.PasswordController.java

/**
 * ???//from   w w  w  . j a  va  2s  .c om
 */
@RequestMapping(value = "/find", method = RequestMethod.POST)
public @ResponseBody Map<String, Object> find(String username, String email) {
    Map<String, Object> data = new HashMap<String, Object>();
    if (StringUtils.isEmpty(username) || StringUtils.isEmpty(email)) {
        data.put("returnCode", 1);
        data.put("returnMessage", SpringUtils.getMessage("shop.common.invalid"));
        return data;
    }
    Member member = memberService.findByUsername(username);
    if (member == null) {
        data.put("returnCode", 1);
        data.put("returnMessage", SpringUtils.getMessage("shop.password.memberNotExist"));
        return data;
    }
    if (!member.getEmail().equalsIgnoreCase(email)) {
        data.put("returnCode", 1);
        data.put("returnMessage", SpringUtils.getMessage("shop.password.invalidEmail"));
        return data;
    }
    Setting setting = SettingUtils.get();
    SafeKey safeKey = new SafeKey();
    safeKey.setValue(UUID.randomUUID().toString() + DigestUtils.md5Hex(RandomStringUtils.randomAlphabetic(30)));
    safeKey.setExpire(setting.getSafeKeyExpiryTime() != 0
            ? DateUtils.addMinutes(new Date(), setting.getSafeKeyExpiryTime())
            : null);
    member.setSafeKey(safeKey);
    memberService.update(member);

    data.put("returnCode", 0);
    data.put("returnMessage", SpringUtils.getMessage("shop.password.sentEmail"));
    return data;
}

From source file:net.shopxx.service.impl.AdminServiceImpl.java

@Transactional(readOnly = true)
@Cacheable(value = "loginToken")
public String getLoginToken() {
    return DigestUtils.md5Hex(UUID.randomUUID() + RandomStringUtils.randomAlphabetic(30));
}

From source file:com.dp2345.controller.mall.CartController.java

/**
 * /*w  w w  . j  a va  2s . c om*/
 */
@RequestMapping(value = "/add", method = RequestMethod.POST)
public @ResponseBody Message add(Long id, Integer quantity, HttpServletRequest request,
        HttpServletResponse response) {
    if (quantity == null || quantity < 1) {
        return ERROR_MESSAGE;
    }
    Product product = productService.find(id);
    if (product == null) {
        return Message.warn("shop.cart.productNotExsit");
    }
    if (!product.getIsMarketable()) {
        return Message.warn("shop.cart.productNotMarketable");
    }
    if (product.getIsGift()) {
        return Message.warn("shop.cart.notForSale");
    }
    // ??
    Cart cart = cartService.getCurrent();
    // ??
    Member member = memberService.getCurrent();
    // 
    if (cart == null) {
        cart = new Cart();
        cart.setKey(UUID.randomUUID().toString() + DigestUtils.md5Hex(RandomStringUtils.randomAlphabetic(30)));
        cart.setMember(member);
        cartService.save(cart);
    }

    // ?????
    if (Cart.MAX_PRODUCT_COUNT != null && cart.getCartItems().size() >= Cart.MAX_PRODUCT_COUNT) {
        return Message.warn("shop.cart.addCountNotAllowed", Cart.MAX_PRODUCT_COUNT);
    }

    //??
    if (cart.contains(product)) {
        CartItem cartItem = cart.getCartItem(product);
        // ????
        if (CartItem.MAX_QUANTITY != null && cartItem.getQuantity() + quantity > CartItem.MAX_QUANTITY) {
            return Message.warn("shop.cart.maxCartItemQuantity", CartItem.MAX_QUANTITY);
        }
        // 
        if (product.getStock() != null && cartItem.getQuantity() + quantity > product.getAvailableStock()) {
            return Message.warn("shop.cart.productLowStock");
        }
        // ?
        cartItem.add(quantity);
        // ??
        cartItemService.update(cartItem);
    } else {
        // ??
        if (CartItem.MAX_QUANTITY != null && quantity > CartItem.MAX_QUANTITY) {
            return Message.warn("shop.cart.maxCartItemQuantity", CartItem.MAX_QUANTITY);
        }
        // 
        if (product.getStock() != null && quantity > product.getAvailableStock()) {
            return Message.warn("shop.cart.productLowStock");
        }
        // 
        CartItem cartItem = new CartItem();
        cartItem.setQuantity(quantity);
        cartItem.setProduct(product);
        cartItem.setCart(cart);
        cartItemService.save(cartItem);
        cart.getCartItems().add(cartItem);
    }

    // ?cookie?
    if (member == null) {
        WebUtils.addCookie(request, response, Cart.ID_COOKIE_NAME, cart.getId().toString(), Cart.TIMEOUT);
        WebUtils.addCookie(request, response, Cart.KEY_COOKIE_NAME, cart.getKey(), Cart.TIMEOUT);
    }
    // ??
    return Message.success("shop.cart.addSuccess", cart.getQuantity(),
            currency(cart.getEffectivePrice(), true, false));
}

From source file:eu.scape_project.archiventory.container.ZipContainer.java

/**
 * Extracts a zip file specified by the zipFilePath to a directory specified by
 * destDirectory (will be created if does not exists)
 * @param containerFileName/* w  w w  .j a  v  a2  s  . c  o  m*/
 * @param destDirectory
 * @throws IOException
 */
public void unzip(String containerFileName, InputStream containerFileStream) throws IOException {
    extractDirectoryName = "/tmp/archiventory_" + RandomStringUtils.randomAlphabetic(10) + "/";
    File destDir = new File(extractDirectoryName);
    destDir.mkdir();
    String subDestDirStr = extractDirectoryName + containerFileName + "/";
    File subDestDir = new File(subDestDirStr);
    subDestDir.mkdir();
    ZipInputStream zipIn = new ZipInputStream(containerFileStream);
    ZipEntry entry = zipIn.getNextEntry();
    while (entry != null) {
        String filePath = subDestDirStr + entry.getName();
        if (!entry.isDirectory()) {
            extractFile(zipIn, filePath);
        } else {
            File dir = new File(filePath);
            dir.mkdir();
        }
        zipIn.closeEntry();
        entry = zipIn.getNextEntry();
    }
    zipIn.close();
}

From source file:com.linkedin.paldb.TestReadThroughputLevelDB.java

private Measure measure(int keysCount, int valueLength, double cacheSizeRatio, final boolean frequentReads) {

    // Generate keys
    long seed = 4242;
    final Integer[] keys = GenerateTestData.generateRandomIntKeys(keysCount, Integer.MAX_VALUE, seed);

    // Write store
    File file = new File(TEST_FOLDER, "leveldb" + keysCount + "-" + valueLength + ".store");
    Options options = new Options();
    options.createIfMissing(true);//from   ww w  . j  ava2  s. com
    options.compressionType(CompressionType.NONE);
    options.verifyChecksums(false);
    options.blockSize(1024);
    options.cacheSize(0l);
    DB db = null;
    try {
        db = factory.open(file, options);

        for (Integer key : keys) {
            if (valueLength == 0) {
                db.put(bytes(key.toString()), bytes("1"));
            } else {
                db.put(bytes(key.toString()), bytes(RandomStringUtils.randomAlphabetic(valueLength)));
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (db != null) {
            try {
                db.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }

    // Open
    NanoBench nanoBench = NanoBench.create();
    try {
        db = factory.open(file, options);
        final DB reader = db;

        // Measure
        nanoBench.cpuOnly().warmUps(5).measurements(20).measure("Measure %d reads for %d keys with cache",
                new Runnable() {
                    @Override
                    public void run() {
                        Random r = new Random();
                        int length = keys.length;
                        for (int i = 0; i < READS; i++) {
                            int index;
                            if (i % 2 == 0 && frequentReads) {
                                index = r.nextInt(length / 10);
                            } else {
                                index = r.nextInt(length);
                            }
                            Integer key = keys[index];
                            reader.get(bytes(key.toString()));
                        }
                    }
                });
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (db != null) {
            try {
                db.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }

    // Return measure
    double rps = READS * nanoBench.getTps();
    return new Measure(DirectoryUtils.folderSize(TEST_FOLDER), rps, valueLength, 0l, keys.length);
}

From source file:com.b2international.index.GroovyMemoryLeakTest.java

@Ignore
@Test// w  ww .  jav  a  2 s .c o m
public void tryToGenerateMemoryLeak() throws Exception {
    final List<String> orderedItems = newArrayList();
    final Map<String, Data> documents = newHashMap();

    for (int i = 0; i < NUM_DOCS; i++) {
        String item = null;
        while (item == null || orderedItems.contains(item)) {
            item = RandomStringUtils.randomAlphabetic(10);
        }
        orderedItems.add(item);

        final Data data = new Data();
        data.setField1(item);
        data.setFloatField(100.0f - i);
        documents.put(Integer.toString(i), data);
    }

    indexDocuments(documents);

    ExecutorService executor = Executors.newFixedThreadPool(2);

    final Runnable theQuery = () -> {
        for (int i = 0; i < 10_000; i++) {
            final Query<Data> query = Query.select(Data.class)
                    .where(Expressions.scriptScore(Expressions.matchAll(), "floatField")).limit(NUM_DOCS)
                    .sortBy(SortBy.SCORE).build();
            search(query);
        }
    };

    // run 4 threads to simulate a bit higher load on the index
    executor.submit(theQuery, null);
    executor.submit(theQuery, null);
    executor.submit(theQuery, null);
    executor.submit(theQuery, null);

    executor.shutdown();
    // this won't pass at all, even if the fix is applied
    // the purpose of this test to detect and verify the GC via external monitoring thus it cannot be automated properly
    assertTrue(executor.awaitTermination(5, TimeUnit.MINUTES));
}

From source file:com.datastax.example.RowCacheVsPartitionCache.java

public void load() {
    Random rnd = new Random();

    logger.info("Beginning RowCacheVsPartitionCache:load");

    PreparedStatement userSearchInsertStatement = session.prepare(
            "insert into user_search_history (id, search_time, search_text, search_results) VALUES (?, ?, ?, ?)");
    BoundStatement userSearchInsert = new BoundStatement(userSearchInsertStatement);

    PreparedStatement userSearchCachedInsertStatement = session.prepare(
            "insert into user_search_history_with_cache (id, search_time, search_text, search_results) VALUES (?, ?, ?, ?)");
    BoundStatement userSearchCachedInsert = new BoundStatement(userSearchCachedInsertStatement);

    //Insert times for 1000 users
    for (int i = 0; i < 1000000; i++) {

        // Create a random number of search history records to create
        Random rand = new Random();

        // We'll need a minimum of 10 and a max of 100 search records
        int randomRecordCount = rand.nextInt(90) + 10;

        for (int j = 0; j < randomRecordCount; j++) {

            session.executeAsync(userSearchInsert.bind(i, randomTimestamp(),
                    RandomStringUtils.randomAlphabetic(10), rnd.nextInt(99999)));
            session.executeAsync(userSearchCachedInsert.bind(i, randomTimestamp(),
                    RandomStringUtils.randomAlphabetic(10), rnd.nextInt(99999)));

        }/*from  w w  w .  ja va 2s  .c om*/

    }

    logger.info("Completed RowCacheVsPartitionCache:load");
}

From source file:com.redhat.rhn.manager.system.test.VirtualizationEntitlementsManagerTest.java

public void testListFlexGuestsOnVirtAddToHost() throws Exception {
    Org org = UserTestUtils.createNewOrgFull(RandomStringUtils.randomAlphabetic(10));
    User user = UserTestUtils.createUser(RandomStringUtils.randomAlphabetic(10), org.getId());
    user.addRole(RoleFactory.ORG_ADMIN);
    UserFactory.save(user);/*from   w ww .  ja va2 s  .  c  om*/

    setupFlexGuestTest(user, true);
    List<ChannelFamilySystemGroup> l = VirtualizationEntitlementsManager.getInstance().listFlexGuests(user);
    //NOW give Virt Entitlement to the Host
    // And make sure flex is not being consumed
    ChannelFamilySystemGroup g = l.get(0);
    ChannelFamilySystem cfs = g.expand().get(0);
    Server s = ServerFactory.lookupById(cfs.getId());
    assertNotNull(s);
    Server host = s.getVirtualInstance().getHostSystem();
    Long hostId = host.getId();
    assertNotNull(host);
    SystemManager.entitleServer(host, EntitlementManager.VIRTUALIZATION);

    l = VirtualizationEntitlementsManager.getInstance().listFlexGuests(user);
    assertTrue(l.isEmpty());

    //NOW do the opposite remove the  virt ent
    //and ensure the guests are consuming flex
    SystemManager.removeServerEntitlement(hostId, EntitlementManager.VIRTUALIZATION);
    l = VirtualizationEntitlementsManager.getInstance().listFlexGuests(user);
    assertTrue(!l.isEmpty());

}

From source file:com.qmetry.qaf.automation.util.StringUtil.java

public static String getRandomString(String format) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < format.length(); i++) {
        char c = format.charAt(i);
        char a = Character.isDigit(c) ? RandomStringUtils.randomNumeric(1).charAt(0)
                : Character.isLetter(c) ? RandomStringUtils.randomAlphabetic(c).charAt(0) : c;
        sb.append(a);/*  w ww  .j av a 2s  .c  om*/
    }
    return sb.toString();
}

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

/**
 * Return a unique ref.//  ww w  .ja va 2  s  .c o m
 * 
 * @param actor
 * @return
 */
private static String createOrderRef(final Actor<?> actor) {
    final StringBuilder ref = new StringBuilder();
    // It is a payline action
    ref.append("MERCANET-");

    // Add the member id
    ref.append(actor.getId());
    ref.append('-');

    PageIterable<BankTransaction> bankTransaction;
    try {
        // Add the last bankTransaction + 1
        bankTransaction = actor.getBankTransactions();
        if (bankTransaction.size() == 0) {
            ref.append('0');
        } else {
            ref.append(bankTransaction.iterator().next().getId() + 1);
        }

        // Add a random string to ensure uniqueness.
        ref.append('-').append(RandomStringUtils.randomAlphabetic(5));
    } catch (final UnauthorizedOperationException e) {
        Log.model().fatal("Unauthorized exception should never append ! ", e);
        ref.append("ERROR");
        return ref.toString();
    }
    return ref.toString();
}