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:MainClass.java

public static void main(String[] args) {
    //Random 8 chars string Alphanumeric 
    System.out.print("3) 8 char Alphanumeric string >>>");
    System.out.println(RandomStringUtils.randomAlphanumeric(8));

}

From source file:RandomStringUtilsTrial.java

public static void main(String[] args) {

    //Random 8 chars string Alphanumeric 
    System.out.print("3) 8 char Alphanumeric string >>>");
    System.out.println(RandomStringUtils.randomAlphanumeric(8));

}

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

public static void main(String[] args) {
    String rowKey = String.format("rowKey0");
    Put put = new Put(Bytes.toBytes(rowKey));
    byte[] value = RandomStringUtils.randomAlphanumeric(10000).getBytes();
    put.addColumn(Bytes.toBytes("Family1"), Bytes.toBytes("Qaulifier"), value);

    BigtableOptions options = new BigtableOptions.Builder().setInstanceId("instanceId")
            .setProjectId("projectId").build();
    HBaseRequestAdapter adapter = new HBaseRequestAdapter(options, TableName.valueOf("tableName"),
            new Configuration());
    for (int i = 0; i < 10; i++) {
        putAdapterPerf(adapter, put);//from w  w  w . j  a v a  2  s . c o  m
    }
}

From source file:com.cws.esolutions.security.main.PasswordUtility.java

public static void main(final String[] args) {
    final String methodName = PasswordUtility.CNAME + "#main(final String[] args)";

    if (DEBUG) {/*  w ww .ja  v a2 s  .c o m*/
        DEBUGGER.debug("Value: {}", methodName);
    }

    if (args.length == 0) {
        HelpFormatter usage = new HelpFormatter();
        usage.printHelp(PasswordUtility.CNAME, options, true);

        System.exit(1);
    }

    BufferedReader bReader = null;
    BufferedWriter bWriter = null;

    try {
        // load service config first !!
        SecurityServiceInitializer.initializeService(PasswordUtility.SEC_CONFIG, PasswordUtility.LOG_CONFIG,
                false);

        if (DEBUG) {
            DEBUGGER.debug("Options options: {}", options);

            for (String arg : args) {
                DEBUGGER.debug("Value: {}", arg);
            }
        }

        CommandLineParser parser = new PosixParser();
        CommandLine commandLine = parser.parse(options, args);

        if (DEBUG) {
            DEBUGGER.debug("CommandLineParser parser: {}", parser);
            DEBUGGER.debug("CommandLine commandLine: {}", commandLine);
            DEBUGGER.debug("CommandLine commandLine.getOptions(): {}", (Object[]) commandLine.getOptions());
            DEBUGGER.debug("CommandLine commandLine.getArgList(): {}", commandLine.getArgList());
        }

        final SecurityConfigurationData secConfigData = PasswordUtility.svcBean.getConfigData();
        final SecurityConfig secConfig = secConfigData.getSecurityConfig();
        final PasswordRepositoryConfig repoConfig = secConfigData.getPasswordRepo();
        final SystemConfig systemConfig = secConfigData.getSystemConfig();

        if (DEBUG) {
            DEBUGGER.debug("SecurityConfigurationData secConfig: {}", secConfigData);
            DEBUGGER.debug("SecurityConfig secConfig: {}", secConfig);
            DEBUGGER.debug("RepositoryConfig secConfig: {}", repoConfig);
            DEBUGGER.debug("SystemConfig systemConfig: {}", systemConfig);
        }

        if (commandLine.hasOption("encrypt")) {
            if ((StringUtils.isBlank(repoConfig.getPasswordFile()))
                    || (StringUtils.isBlank(repoConfig.getSaltFile()))) {
                System.err.println("The password/salt files are not configured. Entries will not be stored!");
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            final String entryName = commandLine.getOptionValue("entry");
            final String username = commandLine.getOptionValue("username");
            final String password = commandLine.getOptionValue("password");
            final String salt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength());

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
                DEBUGGER.debug("String password: {}", password);
                DEBUGGER.debug("String salt: {}", salt);
            }

            final String encodedSalt = PasswordUtils.base64Encode(salt);
            final String encodedUserName = PasswordUtils.base64Encode(username);
            final String encryptedPassword = PasswordUtils.encryptText(password, salt,
                    secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                    secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                    systemConfig.getEncoding());
            final String encodedPassword = PasswordUtils.base64Encode(encryptedPassword);

            if (DEBUG) {
                DEBUGGER.debug("String encodedSalt: {}", encodedSalt);
                DEBUGGER.debug("String encodedUserName: {}", encodedUserName);
                DEBUGGER.debug("String encodedPassword: {}", encodedPassword);
            }

            if (commandLine.hasOption("store")) {
                try {
                    new File(passwordFile.getParent()).mkdirs();
                    new File(saltFile.getParent()).mkdirs();

                    boolean saltFileExists = (saltFile.exists()) ? true : saltFile.createNewFile();

                    if (DEBUG) {
                        DEBUGGER.debug("saltFileExists: {}", saltFileExists);
                    }

                    // write the salt out first
                    if (!(saltFileExists)) {
                        throw new IOException("Unable to create salt file");
                    }

                    boolean passwordFileExists = (passwordFile.exists()) ? true : passwordFile.createNewFile();

                    if (!(passwordFileExists)) {
                        throw new IOException("Unable to create password file");
                    }

                    if (commandLine.hasOption("replace")) {
                        File[] files = new File[] { saltFile, passwordFile };

                        if (DEBUG) {
                            DEBUGGER.debug("File[] files: {}", (Object) files);
                        }

                        for (File file : files) {
                            if (DEBUG) {
                                DEBUGGER.debug("File: {}", file);
                            }

                            String currentLine = null;
                            File tmpFile = new File(FileUtils.getTempDirectory() + "/" + "tmpFile");

                            if (DEBUG) {
                                DEBUGGER.debug("File tmpFile: {}", tmpFile);
                            }

                            bReader = new BufferedReader(new FileReader(file));
                            bWriter = new BufferedWriter(new FileWriter(tmpFile));

                            while ((currentLine = bReader.readLine()) != null) {
                                if (!(StringUtils.equals(currentLine.trim().split(",")[0], entryName))) {
                                    bWriter.write(currentLine + System.getProperty("line.separator"));
                                    bWriter.flush();
                                }
                            }

                            bWriter.close();

                            FileUtils.deleteQuietly(file);
                            FileUtils.copyFile(tmpFile, file);
                            FileUtils.deleteQuietly(tmpFile);
                        }
                    }

                    FileUtils.writeStringToFile(saltFile, entryName + "," + encodedUserName + "," + encodedSalt
                            + System.getProperty("line.separator"), true);
                    FileUtils.writeStringToFile(passwordFile, entryName + "," + encodedUserName + ","
                            + encodedPassword + System.getProperty("line.separator"), true);
                } catch (IOException iox) {
                    ERROR_RECORDER.error(iox.getMessage(), iox);
                }
            }

            System.out.println("Entry Name " + entryName + " stored.");
        }

        if (commandLine.hasOption("decrypt")) {
            String saltEntryName = null;
            String saltEntryValue = null;
            String decryptedPassword = null;
            String passwordEntryName = null;

            if ((StringUtils.isEmpty(commandLine.getOptionValue("entry"))
                    && (StringUtils.isEmpty(commandLine.getOptionValue("username"))))) {
                throw new ParseException("No entry or username was provided to decrypt.");
            }

            if (StringUtils.isEmpty(commandLine.getOptionValue("username"))) {
                throw new ParseException("no entry provided to decrypt");
            }

            String entryName = commandLine.getOptionValue("entry");
            String username = commandLine.getOptionValue("username");

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            if ((!(saltFile.canRead())) || (!(passwordFile.canRead()))) {
                throw new IOException(
                        "Unable to read configured password/salt file. Please check configuration and/or permissions.");
            }

            for (String lineEntry : FileUtils.readLines(saltFile, systemConfig.getEncoding())) {
                saltEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String saltEntryName: {}", saltEntryName);
                }

                if (StringUtils.equals(saltEntryName, entryName)) {
                    saltEntryValue = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    break;
                }
            }

            if (StringUtils.isEmpty(saltEntryValue)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            for (String lineEntry : FileUtils.readLines(passwordFile, systemConfig.getEncoding())) {
                passwordEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String passwordEntryName: {}", passwordEntryName);
                }

                if (StringUtils.equals(passwordEntryName, saltEntryName)) {
                    String decodedPassword = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    decryptedPassword = PasswordUtils.decryptText(decodedPassword, saltEntryValue,
                            secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                            secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                            systemConfig.getEncoding());

                    break;
                }
            }

            if (StringUtils.isEmpty(decryptedPassword)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            System.out.println(decryptedPassword);
        } else if (commandLine.hasOption("encode")) {
            System.out.println(PasswordUtils.base64Encode((String) commandLine.getArgList().get(0)));
        } else if (commandLine.hasOption("decode")) {
            System.out.println(PasswordUtils.base64Decode((String) commandLine.getArgList().get(0)));
        }
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        System.err.println("An error occurred during processing: " + iox.getMessage());
        System.exit(1);
    } catch (ParseException px) {
        ERROR_RECORDER.error(px.getMessage(), px);

        System.err.println("An error occurred during processing: " + px.getMessage());
        System.exit(1);
    } catch (SecurityException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        System.err.println("An error occurred during processing: " + sx.getMessage());
        System.exit(1);
    } catch (SecurityServiceException ssx) {
        ERROR_RECORDER.error(ssx.getMessage(), ssx);
        System.exit(1);
    } finally {
        try {
            if (bReader != null) {
                bReader.close();
            }

            if (bWriter != null) {
                bReader.close();
            }
        } catch (IOException iox) {
        }
    }

    System.exit(0);
}

From source file:models.Activation.java

public static Activation generateActivationCode(User u, int validForDays) {
    Activation a = new Activation();
    a.user = u;//  w  ww.  j  a  v  a  2 s . c o  m
    u.activation = a;
    a.activationCode = RandomStringUtils.randomAlphanumeric(40);

    Calendar c = Calendar.getInstance();
    c.add(Calendar.DATE, validForDays);

    a.expirationDate = c.getTime();

    a.save();
    u.save();

    return a;
}

From source file:net.seedboxer.core.domain.Token.java

public static String generate() {
    return RandomStringUtils.randomAlphanumeric(TOKEN_LENGTH);
}

From source file:co.cask.cdap.filetailer.tailer.RunFromSaveStateTest.java

private void write_log(int entryNumber, Logger logger, List<String> logList) {
    for (int i = 0; i < entryNumber; i++) {
        RandomStringUtils randomUtils = new RandomStringUtils();
        String currLine = randomUtils.randomAlphanumeric(LINE_SIZE);
        logger.debug(currLine);//from  w w  w.j a v  a  2s .c  om
        logList.add(currLine);
    }
}

From source file:gov.nih.cadsr.transform.FilesTransformation.java

public static String transformCdeToCSV(String xmlFile) {

    StringBuffer sb = null;//from   w w  w.  j  a  v a 2  s.  c  om

    try {

        File tf = new File("/local/content/cadsrapi/transform/xslt/", "cdebrowser.xslt"); // template file

        String path = "/local/content/cadsrapi/transform/data/";
        String ext = "txt";
        File dir = new File(path);
        String name = String.format("%s.%s", RandomStringUtils.randomAlphanumeric(8), ext);
        File rf = new File(dir, name);

        if (tf == null || !tf.exists() || !tf.canRead()) {
            System.out.println("File path incorrect");
            return "";
        }

        long startTime = System.currentTimeMillis();

        //Obtain a new instance of a TransformerFactory. 
        TransformerFactory f = TransformerFactory.newInstance();
        // Process the Source into a Transformer Object...Construct a StreamSource from a File.
        Transformer t = f.newTransformer(new StreamSource(tf));

        /*
        Source s = new StreamSource(xmlFile);
        Result r = new StreamResult(rf); 
                 
        //Transform the XML Source to a Result.
        t.transform(s,r);
        System.out.println("Tranformation completed ...");   */

        //Construct a StreamSource from input and output
        Source s;
        try {
            s = new StreamSource((new ByteArrayInputStream(xmlFile.getBytes("utf-8"))));
            Result r = new StreamResult(rf);

            //Transform the XML Source to a Result.
            t.transform(s, r);
            System.out.println("Tranformation completed ...");
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            System.out.println(e1.toString());
        }

        try {
            BufferedReader bf = new BufferedReader(new FileReader(rf));
            sb = new StringBuffer();
            try {
                String currentLine;
                while ((currentLine = bf.readLine()) != null) {
                    sb.append(currentLine).append("\n");
                    //System.out.println(bf.readLine());

                }
            } catch (IOException e) {

                e.printStackTrace();
            }

        } catch (FileNotFoundException e) {

            e.printStackTrace();
        }

        long endTime = System.currentTimeMillis();
        System.out.println("Transformation took " + (endTime - startTime) + " milliseconds");
        System.out.println("Transformation took " + (endTime - startTime) / 1000 + " seconds");
    }

    catch (TransformerConfigurationException e) {
        System.out.println(e.toString());
        e.printStackTrace();

    } catch (TransformerException e) {
        System.out.println(e.toString());

    }

    return sb.toString();
}

From source file:de.appsolve.padelcampus.utils.VoucherUtil.java

public static Voucher createNewVoucher(String comment, Long duration, LocalDate validUntil,
        LocalTime validFromTime, LocalTime validUntilTime, Set<CalendarWeekDay> calendarWeekDays,
        Set<Offer> offers) {
    String UUID = RandomStringUtils.randomAlphanumeric(VOUCHER_NUM_CHARS);
    Voucher voucher = new Voucher();
    voucher.setUUID(UUID);// w  w w . j  a v  a 2s .  com
    voucher.setComment(comment);
    voucher.setDuration(duration);
    voucher.setValidUntil(validUntil);
    voucher.setValidFromTime(validFromTime);
    voucher.setValidUntilTime(validUntilTime);
    voucher.setCalendarWeekDays(calendarWeekDays);
    voucher.setOffers(offers);
    return voucher;
}

From source file:com.yolodata.tbana.testutils.FileTestUtils.java

private static String getRandomFilename() {
    return RandomStringUtils.randomAlphanumeric(25);
}