List of usage examples for org.apache.commons.lang RandomStringUtils randomAlphanumeric
public static String randomAlphanumeric(int count)
Creates a random string whose length is the number of characters specified.
Characters will be chosen from the set of alpha-numeric characters.
From source file:com.xtructure.xutil.valid.UTestValidateUtils.java
public void validateArgWithMultiplePredicatesBehavesAsExpected() { String argName = RandomStringUtils.randomAlphanumeric(10); boolean valid = validateArg(argName, new Object(), isNotNull(), isNotNull()); if (!valid) { throw new AssertionError(); }/* w w w . j ava 2 s. co m*/ try { validateArg(argName, null, isNotNull(), isNotNull()); } catch (IllegalArgumentException e) { if (!String.format("%s (%s): %s", argName, null, isNotNull()).equals(e.getMessage())) { throw new AssertionError(); } } }
From source file:info.bluefoot.winter.controller.PlaylistController.java
@RequestMapping(value = { "/playlist/add" }, method = RequestMethod.POST, produces = "application/json") public @ResponseBody ResponseEntity<Map<String, String>> addPlaylist( @ModelAttribute("addplaylistform") AddPlaylistForm addPlaylistForm, HttpServletResponse response) { Set<Video> videos = new HashSet<Video>(); int sort = 0; for (String url : addPlaylistForm.getVideos().split("\n")) { if (!url.trim().isEmpty()) { videos.add(new Video(url.trim(), sort++).setPlaylist(addPlaylistForm.getPlaylist())); }/* w w w. j a v a 2s . com*/ } addPlaylistForm.getPlaylist().setVideos(new ArrayList<Video>(videos)); User user = Utils.getCurrentLoggedUser(); addPlaylistForm.getPlaylist().setUser(user); try { playlistService.addPlaylistAndVideos(addPlaylistForm.getPlaylist()); } catch (Exception e) { String errorId = RandomStringUtils.randomAlphanumeric(6).toUpperCase(); logger.error("[" + errorId + "] Can't create playlist", e); return new ResponseEntity<Map<String, String>>( Collections.singletonMap("error", "Can't create 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); }
From source file:com.edgenius.wiki.util.WikiUtil.java
/** * Return an unique UUID and initial it in repository. * @param spacename/* w w w . j ava 2 s .c o m*/ * @param username * @param password * @param repositoryService * @return * @throws PageException */ public static String createPageUuid(String spacename, String username, String password, RepositoryService repositoryService) throws PageException { //DON'T user repository created UUID for future export/import function: //always keep page UUID unchanged whatever import to any new database //UUID.randomUUID().toString(); - use smaller string to replace 32 length UUID, I test possible duplicated case //if it is case sensitive, it is almost impossible duplicated even 50 million. But I have to make to lowerCase // 1 million no duplicate, but 50 million will have 9 duplicate -- this make need make duplciate try-catch check? String uuid = RandomStringUtils.randomAlphanumeric(WikiConstants.UUID_KEY_SIZE).toLowerCase(); try { ITicket ticket = repositoryService.login(spacename, username, password); repositoryService.createIdentifier(ticket, RepositoryService.TYPE_ATTACHMENT, uuid); } catch (RepositoryException e) { log.error("Create page UUID failed request from repository :", e); throw new PageException(e); } catch (RepositoryTiemoutExcetpion e) { log.error("Create page UUID failed request from repository :", e); throw new PageException(e); } return uuid; }
From source file:com.sjsu.crawler.util.RandomStringUtilsTest.java
/** * Make sure boundary alphanumeric characters are generated by randomAlphaNumeric * This test will fail randomly with probability = 6 * (61/62)**1000 ~ 5.2E-7 *//*from ww w .jav a 2s . c om*/ @Test public void testRandomAlphaNumeric() { final char[] testChars = { 'a', 'z', 'A', 'Z', '0', '9' }; final boolean[] found = { false, false, false, false, false, false }; for (int i = 0; i < 100; i++) { final String randString = RandomStringUtils.randomAlphanumeric(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("alphanumeric character not generated in 1000 attempts: " + testChars[i] + " -- repeated failures indicate a problem "); } } }
From source file:com.blackberry.logtools.loggrep.java
public int run(String[] argv) throws Exception { //Configuring configuration and filesystem to work on HDFS final Configuration conf = getConf(); //Configuration processed by ToolRunner FileSystem fs = FileSystem.get(conf); //Initiate tools used for running search LogTools tools = new LogTools(); //Other options String date_format = "RFC5424"; String field_separator = ""; ArrayList<String> D_options = new ArrayList<String>(); boolean quiet = true; boolean silent = false; boolean log = false; boolean forcelocal = false; boolean forceremote = false; //The arguments are // - regex/*from w ww . j a va2 s . com*/ // - dc number // - service // - component // - startTime (Something 'date' can parse, or just a time in ms from epoch) // - endTime (Same as start) // - outputDir //Indexing for arguments to be passed for Mapreduce int regexNum = 0; int dcNum = 1; int svcNum = 2; int compNum = 3; int startNum = 4; int endNum = 5; int outNum = 6; //Parsing through user arguments String[] args = new String[7]; int count = 0; //Count created to track the parse of all arguments int argcount = 0; //Count created to track number of arguments to be passed on while (count < argv.length) { String arg = argv[count]; count++; if (arg.equals("--")) { break; } else if (arg.startsWith("-")) { if (arg.equals("--v")) { quiet = tools.parseV(silent); } else if (arg.equals("--i")) { conf.set("logdriver.search.case.insensitive", "true"); } else if (arg.startsWith("--dateFormat=")) { arg = arg.replace("--dateFormat=", ""); date_format = arg; } else if (arg.startsWith("--fieldSeparator=")) { arg = arg.replace("--fieldSeparator=", ""); field_separator = arg; } else if (arg.startsWith("-regex=")) { arg = arg.replace("-regex=", ""); args[regexNum] = arg; argcount++; } else if (arg.startsWith("-dc=")) { arg = arg.replace("-dc=", ""); args[dcNum] = arg; argcount++; } else if (arg.startsWith("-svc=")) { arg = arg.replace("-svc=", ""); args[svcNum] = arg; argcount++; } else if (arg.startsWith("-comp=")) { arg = arg.replace("-comp=", ""); args[compNum] = arg; argcount++; } else if (arg.startsWith("-start=")) { arg = arg.replace("-start=", ""); args[startNum] = arg; argcount++; } else if (arg.startsWith("-end=")) { arg = arg.replace("-end=", ""); args[endNum] = arg; argcount++; } //User inputs output directory that is to be created //Check to see if parent directory exists && output directory does not exist else if (arg.startsWith("--out=")) { args[outNum] = tools.parseOut(arg, fs); argcount++; } else if (arg.startsWith("-D")) { D_options.add(arg); } else if (arg.equals("--silent")) { silent = tools.parseSilent(quiet); } else if (arg.equals("--log")) { log = true; } else if (arg.equals("--l")) { forcelocal = tools.parsePigMode(forceremote); } else if (arg.equals("--r")) { forceremote = tools.parsePigMode(forcelocal); } else { LogTools.logConsole(quiet, silent, error, "Unrecognized option: " + arg); System.exit(1); } } else { LogTools.logConsole(quiet, silent, error, "Unrecognized option: " + arg); System.exit(1); } } //Default output should be stdout represented by "-" if (args[outNum] == null) { args[outNum] = "-"; argcount++; LogTools.logConsole(quiet, silent, info, "Output set to default stdout."); } if (argcount < 7) { System.err.println(";****************************************" + "\n\t\t\t NOT ENOUGH ARGUMENTS\n" + "\n\tUSAGE: loggrep [REQUIRED ARGUMENTS] [OPTIONS] (Order does not matter)" + "\n\tREQUIRED ARGUMENTS:" + "\n\t\t-regex=[REGEX] Java style regular expression." + "\n\t\t-dc=[DATACENTER] Data Center." + "\n\t\t-svc=[SERVICE] Service." + "\n\t\t-comp=[COMPONENT] Component." + "\n\t\t-start=[START] Start time." + "\n\t\t-end=[END] End time." + "\n\tOptions:" + "\n\t\t--out=[DIRECTORY] Desired output directory. If not defined, output to stdout." + "\n\t\t--v Verbose output." + "\n\t\t--r Force remote sort." + "\n\t\t--l Force local sort." + "\n\t\t--dateFormat=[FORMAT] Valid formats are RFC822, RFC3164 (zero padded day)," + "\n\t RFC5424 (default), or any valid format string for FastDateFormat." + "\n\t\t--fieldSeparator=X The separator to use to separate fields in intermediate" + "\n\t files. Defaults to 'INFORMATION SEPARATOR ONE' (U+001F)." + "\n\t\t--silent Output only the data." + "\n\t\t--i Make search case insensitive." + "\n\t\t--log Save all the logs.\n" + ";****************************************"); System.exit(1); } //Parse time inputs for start and end of search args[startNum] = tools.parseDate(args[startNum]); args[endNum] = tools.parseDate(args[endNum]); tools.checkTime(args[startNum], args[endNum]); //Retrieve 'out' argument to determine where output of results should be sent String out = args[outNum]; //Generate files to temporarily store output of mapreduce jobs and pig logs locally File local_output = File.createTempFile("tmp.", RandomStringUtils.randomAlphanumeric(10)); if (log != true) { local_output.deleteOnExit(); } File pig_tmp = File.createTempFile("tmp.", RandomStringUtils.randomAlphanumeric(10)); if (log != true) { pig_tmp.deleteOnExit(); } //Name the temp directory for storing results in HDFS String tmp = "tmp/loggrep-" + RandomStringUtils.randomAlphanumeric(10); //Set args[outNum] to be temp output directory to be passed onto GrepByTime instead of UserInput argument args[outNum] = (StringEscapeUtils.escapeJava(tmp) + "/rawlines"); //Managing console output - deal with --v/--silent Logger LOG = LoggerFactory.getLogger(loggrep.class); tools.setConsoleOutput(local_output, quiet, silent); //Create temp directory in HDFS to store logsearch logs before sorting tools.tmpDirHDFS(quiet, silent, fs, conf, tmp, log); LogTools.logConsole(quiet, silent, warn, "Searching for " + args[regexNum] + "..."); LogTools.logConsole(quiet, silent, warn, "Passing Arguments: Regex=" + args[regexNum] + " DC=" + args[dcNum] + " Service=" + args[svcNum] + " Component=" + args[compNum] + " StartTime=" + args[startNum] + " EndTime=" + args[endNum] + " Output=" + out); //Set standard configuration for running Mapreduce and PIG String queue_name = "logsearch"; //Start Mapreduce job tools.runMRJob(quiet, silent, conf, D_options, out, LOG, field_separator, queue_name, args, "GrepByTime", new GrepByTime()); //Before sorting, determine the number of records and size of the results found long foundresults = tools.getResults(local_output); long size = tools.getSize(foundresults, tmp, fs); //Run PIG job if results found tools.runPig(silent, quiet, foundresults, size, tmp, out, D_options, queue_name, date_format, field_separator, pig_tmp, fs, conf, forcelocal, forceremote); //Display location of tmp files if log enabled tools.logs(log, local_output, pig_tmp, tmp); return 0; }
From source file:gov.nih.nci.cabig.caaers.service.ProxyWebServiceFacade.java
public String send(String entity, String operationName, boolean sync, Map<String, String> criteria) { String corelationId = RandomStringUtils.randomAlphanumeric(15); String message = buildMessage(corelationId, "adeers", entity, operationName, sync ? "sync" : "async", criteria);/*from ww w.ja v a 2 s .com*/ simpleSendAndReceive(message); return corelationId; }
From source file:com.blackberry.logtools.logsearch.java
public int run(String[] argv) throws Exception { //Configuring configuration and filesystem to work on HDFS final Configuration conf = getConf(); //Configuration processed by ToolRunner FileSystem fs = FileSystem.get(conf); //Initiate tools used for running search LogTools tools = new LogTools(); //Other options String date_format = "RFC5424"; String field_separator = ""; ArrayList<String> D_options = new ArrayList<String>(); boolean quiet = true; boolean silent = false; boolean log = false; boolean forcelocal = false; boolean forceremote = false; //The arguments are // - search string // - dc number // - service// www. j a v a2s . c o m // - component // - startTime (Something 'date' can parse, or just a time in ms from epoch) // - endTime (Same as start) // - outputDir //Indexing for arguments to be passed for Mapreduce int stringNum = 0; int dcNum = 1; int svcNum = 2; int compNum = 3; int startNum = 4; int endNum = 5; int outNum = 6; //Parsing through user arguments String[] args = new String[7]; int count = 0; //Count created to track the parse of all arguments int argcount = 0; //Count created to track number of arguments to be passed on while (count < argv.length) { String arg = argv[count]; count++; if (arg.equals("--")) { break; } else if (arg.startsWith("-")) { if (arg.equals("--v")) { quiet = tools.parseV(silent); } else if (arg.equals("--i")) { conf.set("logdriver.search.case.insensitive", "true"); } else if (arg.startsWith("--dateFormat=")) { arg = arg.replace("--dateFormat=", ""); date_format = arg; } else if (arg.startsWith("--fieldSeparator=")) { arg = arg.replace("--fieldSeparator=", ""); field_separator = arg; } else if (arg.startsWith("-string=")) { arg = arg.replace("-string=", ""); args[stringNum] = arg; argcount++; } else if (arg.startsWith("-dc=")) { arg = arg.replace("-dc=", ""); args[dcNum] = arg; argcount++; } else if (arg.startsWith("-svc=")) { arg = arg.replace("-svc=", ""); args[svcNum] = arg; argcount++; } else if (arg.startsWith("-comp=")) { arg = arg.replace("-comp=", ""); args[compNum] = arg; argcount++; } else if (arg.startsWith("-start=")) { arg = arg.replace("-start=", ""); args[startNum] = arg; argcount++; } else if (arg.startsWith("-end=")) { arg = arg.replace("-end=", ""); args[endNum] = arg; argcount++; } //User inputs output directory that is to be created //Check to see if parent directory exists && output directory does not exist else if (arg.startsWith("--out=")) { args[outNum] = tools.parseOut(arg, fs); argcount++; } else if (arg.startsWith("-D")) { D_options.add(arg); } else if (arg.equals("--silent")) { silent = tools.parseSilent(quiet); } else if (arg.equals("--log")) { log = true; } else if (arg.equals("--l")) { forcelocal = tools.parsePigMode(forceremote); } else if (arg.equals("--r")) { forceremote = tools.parsePigMode(forcelocal); } else { LogTools.logConsole(quiet, silent, error, "Unrecognized option: " + arg); System.exit(1); } } else { LogTools.logConsole(quiet, silent, error, "Unrecognized option: " + arg); System.exit(1); } } //Default output should be stdout represented by "-" if (args[outNum] == null) { args[outNum] = "-"; argcount++; LogTools.logConsole(quiet, silent, info, "Output set to default stdout."); } if (argcount < 7) { System.err.println(";****************************************" + "\n\t\t\t NOT ENOUGH ARGUMENTS\n" + "\n\tUSAGE: logsearch [REQUIRED ARGUMENTS] [OPTIONS] (Order does not matter)" + "\n\tREQUIRED ARGUMENTS:" + "\n\t\t-string=[STRING] String to search." + "\n\t\t-dc=[DATACENTER] Data Center." + "\n\t\t-svc=[SERVICE] Service." + "\n\t\t-comp=[COMPONENT] Component." + "\n\t\t-start=[START] Start time." + "\n\t\t-end=[END] End time." + "\n\tOptions:" + "\n\t\t--out=[DIRECTORY] Desired output directory. If not defined, output to stdout." + "\n\t\t--v Verbose output." + "\n\t\t--r Force remote sort." + "\n\t\t--l Force local sort." + "\n\t\t--dateFormat=[FORMAT] Valid formats are RFC822, RFC3164 (zero padded day)," + "\n\t RFC5424 (default), or any valid format string for FastDateFormat." + "\n\t\t--fieldSeparator=X The separator to use to separate fields in intermediate" + "\n\t files. Defaults to 'INFORMATION SEPARATOR ONE' (U+001F)." + "\n\t\t--silent Output only the data." + "\n\t\t--i Make search case insensitive." + "\n\t\t--log Save all the logs.\n" + ";****************************************"); System.exit(1); } //Parse time inputs for start and end of search args[startNum] = tools.parseDate(args[startNum]); args[endNum] = tools.parseDate(args[endNum]); tools.checkTime(args[startNum], args[endNum]); //Retrieve 'out' argument to determine where output of results should be sent String out = args[outNum]; //Generate files to temporarily store output of mapreduce jobs and pig logs locally File local_output = File.createTempFile("tmp.", RandomStringUtils.randomAlphanumeric(10)); if (log != true) { local_output.deleteOnExit(); } File pig_tmp = File.createTempFile("tmp.", RandomStringUtils.randomAlphanumeric(10)); if (log != true) { pig_tmp.deleteOnExit(); } //Name the temp directory for storing results in HDFS String tmp = "tmp/logsearch-" + RandomStringUtils.randomAlphanumeric(10); //Set args[outNum] to be temp output directory to be passed onto FastSearchByTime instead of UserInput argument args[outNum] = (StringEscapeUtils.escapeJava(tmp) + "/rawlines"); //Managing console output - deal with --v/--silent Logger LOG = LoggerFactory.getLogger(logsearch.class); tools.setConsoleOutput(local_output, quiet, silent); //Create temp directory in HDFS to store logsearch logs before sorting tools.tmpDirHDFS(quiet, silent, fs, conf, tmp, log); LogTools.logConsole(quiet, silent, warn, "Searching for " + args[stringNum] + "..."); LogTools.logConsole(quiet, silent, warn, "Passing Arguments: SearchString=" + args[stringNum] + " DC=" + args[dcNum] + " Service=" + args[svcNum] + " Component=" + args[compNum] + " StartTime=" + args[startNum] + " EndTime=" + args[endNum] + " Output=" + out); //Set standard configuration for running Mapreduce and PIG String queue_name = "logsearch"; //Start Mapreduce job tools.runMRJob(quiet, silent, conf, D_options, out, LOG, field_separator, queue_name, args, "FastSearchByTime", new FastSearchByTime()); //Before sorting, determine the number of records and size of the results found long foundresults = tools.getResults(local_output); long size = tools.getSize(foundresults, tmp, fs); //Run PIG job if results found tools.runPig(silent, quiet, foundresults, size, tmp, out, D_options, queue_name, date_format, field_separator, pig_tmp, fs, conf, forcelocal, forceremote); //Display location of tmp files if log enabled tools.logs(log, local_output, pig_tmp, tmp); return 0; }
From source file:jp.co.nemuzuka.core.controller.AbsController.java
/** * Token./* w w w . jav a2s .c om*/ * Session?Token??? * @return Token */ protected String setToken() { String token = RandomStringUtils.randomAlphanumeric(32); sessionScope(TOKEN_KEY, token); return token; }
From source file:edu.duke.cabig.c3pr.webservice.integration.SubjectRegistryWebServicePerformanceTest.java
private void importStudySubjects(int sbegin, int send, int pbegin, int pend, String batch) throws Exception { SubjectRegistry service = getService(); // successful creation final ImportStudySubjectRegistryRequest request = new ImportStudySubjectRegistryRequest(); request.setStudySubjects(new DSETStudySubject()); //String batch = ""; for (int start = sbegin; start < send; start++) { int study = start; //batch += "-"+(400-20*(study-500)); for (int subject = pbegin; subject < pend; subject++) { StudySubject studySubject = createStudySubjectForImport(); //Override some values ((Person) studySubject.getEntity()).setRaceCode(iso.DSETCD(iso.CD(RACE_WHITE))); ((Person) studySubject.getEntity()).setTelecomAddress(iso.BAGTEL(iso.TEL(TEST_EMAIL_ADDR_ISO))); ((Person) studySubject.getEntity()).getBiologicEntityIdentifier().get(0).getIdentifier() .setExtension(subject + ""); studySubject.getSubjectIdentifier().get(0).getIdentifier() .setExtension(RandomStringUtils.randomAlphanumeric(6) + "--" + batch); studySubject.getSubjectIdentifier().get(0).setPrimaryIndicator(iso.BL(true)); studySubject.getStudySubjectProtocolVersion().getStudySiteProtocolVersion() .getStudyProtocolVersion().getStudyProtocolDocument().getDocument().getDocumentIdentifier() .get(0).getIdentifier().setExtension(study + ""); //add 1st consent studySubject.getStudySubjectProtocolVersion().getStudySubjectConsentVersion().clear(); StudySubjectConsentVersion studySubjectConsentVersion = new StudySubjectConsentVersion(); studySubjectConsentVersion.setConsentDeliveryDate(iso.TSDateTime(TEST_CONSENT_DELIVERY_DATE1)); studySubjectConsentVersion.setInformedConsentDate(iso.TSDateTime(TEST_CONSENT_SIGNED_DATE1)); studySubjectConsentVersion.setConsentingMethod(iso.CD(TEST_CONSENTING_METHOD1)); studySubjectConsentVersion.setConsentPresenter(iso.ST(TEST_CONSENT_PRESENTER1)); studySubjectConsentVersion.setConsent(new DocumentVersion()); studySubjectConsentVersion.getConsent().setOfficialTitle(iso.ST(TEST_CONSENT_NAME1)); studySubjectConsentVersion.getConsent().setVersionNumberText(iso.ST(TEST_CONSENT_VERSION1)); PerformedStudySubjectMilestone subjectAnswer = new PerformedStudySubjectMilestone(); subjectAnswer.setMissedIndicator(iso.BL(TEST_CONSENT_ANS11)); subjectAnswer.setConsentQuestion(new DocumentVersion()); subjectAnswer.getConsentQuestion().setOfficialTitle(iso.ST(TEST_CONSENT_QUES11)); studySubjectConsentVersion.getSubjectConsentAnswer().add(subjectAnswer); studySubject.getStudySubjectProtocolVersion().getStudySubjectConsentVersion() .add(studySubjectConsentVersion); request.getStudySubjects().getItem().add(studySubject); }// www . jav a 2 s. co m } JAXBContext context = JAXBContext.newInstance("edu.duke.cabig.c3pr.webservice.subjectregistry"); Marshaller marshaller = context.createMarshaller(); marshaller.marshal(request, System.out); System.out.flush(); DSETStudySubject createdStudySubjects = service.importSubjectRegistry(request).getStudySubjects(); assertNotNull(createdStudySubjects); // assertEquals(scount*pcount, createdStudySubjects.getItem().size()); }
From source file:com.google.cloud.bigtable.hbase.TestPut.java
@Test @Category(KnownGap.class) public void testAtomicPut() throws Exception { Table table = getConnection().getTable(TABLE_NAME); byte[] rowKey = Bytes.toBytes("testrow-" + RandomStringUtils.randomAlphanumeric(8)); byte[] goodQual = Bytes.toBytes("testQualifier-" + RandomStringUtils.randomAlphanumeric(8)); byte[] goodValue = Bytes.toBytes("testValue-" + RandomStringUtils.randomAlphanumeric(8)); byte[] badQual = Bytes.toBytes("testQualifier-" + RandomStringUtils.randomAlphanumeric(8)); byte[] badValue = Bytes.toBytes("testValue-" + RandomStringUtils.randomAlphanumeric(8)); byte[] badfamily = Bytes.toBytes("badcolumnfamily-" + RandomStringUtils.randomAlphanumeric(8)); Put put = new Put(rowKey); put.addColumn(COLUMN_FAMILY, goodQual, goodValue); put.addColumn(badfamily, badQual, badValue); RetriesExhaustedWithDetailsException thrownException = null; try {/*w w w .j a v a 2 s . c o m*/ table.put(put); } catch (RetriesExhaustedWithDetailsException e) { thrownException = e; } Assert.assertNotNull("Exception should have been thrown", thrownException); Assert.assertEquals("Expecting one exception", 1, thrownException.getNumExceptions()); Assert.assertArrayEquals("Row key", rowKey, thrownException.getRow(0).getRow()); Assert.assertTrue("Cause: NoSuchColumnFamilyException", thrownException.getCause(0) instanceof NoSuchColumnFamilyException); Get get = new Get(rowKey); Result result = table.get(get); Assert.assertEquals("Atomic behavior means there should be nothing here", 0, result.size()); table.close(); }