List of usage examples for java.util Random nextLong
public long nextLong()
From source file:org.solovyev.android.checkout.PurchasesTest.java
@Test public void testShouldNotContainDuplicates() throws Exception { final List<Purchase> purchases = new ArrayList<Purchase>(1000); final Random r = new Random(currentTimeMillis()); for (int i = 0; i < 1000; i++) { purchases.add(newPurchase(String.valueOf(i % 100), r.nextLong(), Purchase.State.valueOf(r.nextInt(4)))); }/* w w w . j av a 2 s. c o m*/ final List<Purchase> actual = Purchases.neutralize(purchases); final Map<String, Integer> counters = new HashMap<String, Integer>(); for (Purchase purchase : actual) { final Integer counter = counters.get(purchase.sku); assertNull("Several purchases with same SKU are in the neutralized list", counter); counters.put(purchase.sku, 1); } }
From source file:edu.txstate.dmlab.clusteringwiki.web.RegisterController.java
@RequestMapping("captcha.*") public void getCaptcha(HttpServletRequest request, HttpServletResponse response, Model model) { //prepare vars HttpSession session = request.getSession(); String action = request.getParameter("action"); if (action == null) { sendOutput(response, "Error: invalid action received."); return;/*from w w w . j av a 2 s . co m*/ } if (action.equals("verify")) { String captcha = request.getParameter("captcha"); String answer = (String) session.getAttribute("captchaAnswer"); if (captcha == null || captcha.length() < 10 || answer == null) { sendOutput(response, "Error: invalid verify request received."); return; } if (captcha.substring(10).equals(answer)) { sendOutput(response, "{\"status\":\"success\"}"); return; } else { sendOutput(response, "{\"status\":\"error\"}"); return; } } // tops: star: 120, heart: 0; bwm: 56; diamond: 185 List<Integer> topPositions = new ArrayList<Integer>(4); topPositions.add(120); topPositions.add(0); topPositions.add(56); topPositions.add(185); //randomize images Collections.shuffle(topPositions); //generate new codes Random r = new Random(); List<String> codes = new ArrayList<String>(4); codes.add(Long.toString(Math.abs(r.nextLong()), 36)); codes.add(Long.toString(Math.abs(r.nextLong()), 36)); codes.add(Long.toString(Math.abs(r.nextLong()), 36)); codes.add(Long.toString(Math.abs(r.nextLong()), 36)); //pick a random item to check against - between 0 and 4 int chosen = r.nextInt(4); //create the html code String template = "<div class=\"captchaWrapper\" id=\"captchaWrapper\">" + " <a href=\"#\" class=\"captchaRefresh\"></a>" + " <div id=\"draggable_{c0}\" class=\"draggable\" " + " style=\"left: 15px; background-position: -{t0}px -3px\"></div>" + " <a href=\"#\" class=\"captchaRefresh\"></a>" + " <div id=\"draggable_{c1}\" class=\"draggable\" " + " style=\"left: 83px; background-position: -{t1}px -3px;\"></div>" + " <a href=\"#\" class=\"captchaRefresh\"></a>" + " <div id=\"draggable_{c2}\" class=\"draggable\" " + " style=\"left: 151px; background-position: -{t2}px -3px;\"></div>" + " <a href=\"#\" class=\"captchaRefresh\"></a>" + " <div id=\"draggable_{c3}\" class=\"draggable\" " + " style=\"left: 219px; background-position: -{t3}px -3px;\"></div>" + " <div class=\"targetWrapper\">" + " <div class=\"target\" style=\"background-position: -{t4}px -66px;\"></div>" + " </div>" + " <input type=\"hidden\" class=\"captchaAnswer\" name=\"captcha\" value=\"\" />" + "</div>"; template = template.replace("{c0}", codes.get(0)).replace("{c1}", codes.get(1)) .replace("{c2}", codes.get(2)).replace("{c3}", codes.get(3)) .replace("{t0}", String.valueOf(topPositions.get(0))) .replace("{t1}", String.valueOf(topPositions.get(1))) .replace("{t2}", String.valueOf(topPositions.get(2))) .replace("{t3}", String.valueOf(topPositions.get(3))); // the chosen image template = template.replace("{t4}", String.valueOf(topPositions.get(chosen))); //store the chosen code in the session session.setAttribute("captchaAnswer", codes.get(chosen)); //display captcha sendOutput(response, template); }
From source file:com.google.cloud.bigtable.hbase.TestBatch.java
/** * Requirement 8.1//from w ww.j ava2s. co m */ @Test public void testBatchIncrement() throws IOException, InterruptedException { // Initialize data Table table = getConnection().getTable(TABLE_NAME); byte[] rowKey1 = dataHelper.randomData("testrow-"); byte[] qual1 = dataHelper.randomData("qual-"); Random random = new Random(); long value1 = random.nextLong(); byte[] rowKey2 = dataHelper.randomData("testrow-"); byte[] qual2 = dataHelper.randomData("qual-"); long value2 = random.nextLong(); // Put Put put1 = new Put(rowKey1).addColumn(COLUMN_FAMILY, qual1, Bytes.toBytes(value1)); Put put2 = new Put(rowKey2).addColumn(COLUMN_FAMILY, qual2, Bytes.toBytes(value2)); List<Row> batch = new ArrayList<Row>(2); batch.add(put1); batch.add(put2); table.batch(batch, null); // Increment Increment increment1 = new Increment(rowKey1).addColumn(COLUMN_FAMILY, qual1, 1L); Increment increment2 = new Increment(rowKey2).addColumn(COLUMN_FAMILY, qual2, 1L); batch.clear(); batch.add(increment1); batch.add(increment2); Object[] results = new Object[2]; table.batch(batch, results); Assert.assertEquals("Should be value1 + 1", value1 + 1, Bytes.toLong(CellUtil.cloneValue(((Result) results[0]).getColumnLatestCell(COLUMN_FAMILY, qual1)))); Assert.assertEquals("Should be value2 + 1", value2 + 1, Bytes.toLong(CellUtil.cloneValue(((Result) results[1]).getColumnLatestCell(COLUMN_FAMILY, qual2)))); table.close(); }
From source file:org.apache.hadoop.hbase.procedure2.store.TestProcedureStoreTracker.java
@Test public void testRandLoad() { final int NPROCEDURES = 2500; final int NRUNS = 5000; final ProcedureStoreTracker tracker = new ProcedureStoreTracker(); Random rand = new Random(1); for (int i = 0; i < NRUNS; ++i) { assertTrue(tracker.isEmpty());//w w w . j a va 2 s .co m int count = 0; while (count < NPROCEDURES) { long procId = rand.nextLong(); if (procId < 1) continue; tracker.setDeleted(procId, i % 2 == 0); count++; } tracker.clear(); } }
From source file:m.w.sys.module.FileModule.java
/** * kindeditor/* ww w . ja va2s.c o m*/ * * @return */ @At("/upload") @POST @AdaptBy(type = UploadAdaptor.class, args = { "${app.root}/WEB-INF/tmp" }) public Object upload(@Param("imgFile") TempFile imgFile, HttpServletRequest req, ServletContext context) { // return fileService.keupload(type, fileDesc, file, null); HashMap<String, Object> result = new HashMap<String, Object>(); UploadManager uploadManager = new UploadManager(); Random random = new Random(DateTime.now().getMillis()); String key = "test/" + String.valueOf(random.nextLong()).replace("-", "").substring(1, 5) + imgFile.getFile().getName(); try { Response res = uploadManager.put(imgFile.getFile(), key, uptoken()); DefaultPutRet ret = res.jsonToObject(DefaultPutRet.class); if (!res.isOK()) { throw new QiniuException(res); } else { result.put("key", ret.key); result.put("url", getPicUrl(ret.key)); Consts.qiniuEandToken.put("key", ret.key); } } catch (QiniuException e) { // TODO Auto-generated catch block e.printStackTrace(); result.put("failure", e.getMessage()); } result.put("success", true); return result; }
From source file:org.gaixie.micrite.security.service.impl.UserServiceImpl.java
public void forgotPasswordStepOne(String username, String baseUrl, String locale) throws SecurityException { User user = userDAO.findByUsername(username); if (user == null) { throw new SecurityException("forgotPassword.step1.usernameNotFound"); }/*from www .j ava 2s . c o m*/ Random randomGenerator = new Random(); long randomLong = randomGenerator.nextLong(); Date date = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(calendar.DAY_OF_MONTH, +1); date = calendar.getTime(); String key = passwordEncoder.encodePassword(Long.toString(randomLong) + date + username, null); String actionUrl = baseUrl + "forgotPasswordStepTwo.action?key=" + key + "&request_locale=" + locale; String emailText = "Dear " + user.getFullname() + ": \r\n" + "We've received a password reset request for " + user.getLoginname() + " .\r\n" + "To initiate the process, please click the following link: \r\n" + "\r\n" + actionUrl + " \r\n" + "\r\n" + "If clicking the link above does not work, copy and paste the URL in \r\n" + "a new browser window instead. The URL will expire in 24 hours for security \r\n" + "reasons. \r\n" + "\r\n" + "Please disregard this message if you did not make a password reset request. \r\n" + "\r\n" + "This is an automatically generated message. Replies are not monitored or answered. \r\n" + "\r\n" + "Sincerely \r\n" + "The Micrite Support Team"; emailSender.sendEmail(null, user.getEmailaddress(), "Reset Password Assistance", emailText); Token token = new Token(key, "password", date, user); tokenDAO.save(token); }
From source file:bluevia.InitService.java
boolean subscribeNotifications() { boolean result = true; String[] countryShortNumbers = { MO_UK, MO_SP, MO_GE, MO_BR, MO_MX, MO_AR, MO_CH, MO_CO }; int i = 0;//from w ww .ja va2s . c o m for (i = 0; i < countryShortNumbers.length; i++) { try { OAuthConsumer consumer = (OAuthConsumer) new DefaultOAuthConsumer(Util.BlueViaOAuth.consumer_key, Util.BlueViaOAuth.consumer_secret); consumer.setMessageSigner(new HmacSha1MessageSigner()); com.google.appengine.api.urlfetch.FetchOptions.Builder.doNotValidateCertificate(); URL apiURI = new URL( "https://api.bluevia.com/services/REST/SMS/inbound/subscriptions?version=v1&alt=json"); HttpURLConnection request = (HttpURLConnection) apiURI.openConnection(); Random rand = new Random(); Date now = new Date(); rand.setSeed(now.getTime()); Long correlator = rand.nextLong(); if (correlator < 0) correlator = -1 * correlator; String jsonSubscriptionMsg = "{\"smsNotification\":{\"reference\":{\"correlator\": \"%s\",\"endpoint\": \"%s\"},\"destinationAddress\":{\"phoneNumber\":\"%s\"},\"criteria\":\"%s\"}}"; String szBody = String.format(jsonSubscriptionMsg, "bv" + correlator.toString().substring(0, 16), Util.getCallbackDomain() + "/notifySmsReception", countryShortNumbers[i], Util.BlueViaOAuth.app_keyword); request.setRequestProperty("Content-Type", "application/json"); request.setRequestProperty("Content-Length", "" + Integer.toString(szBody.getBytes().length)); request.setRequestMethod("POST"); request.setDoOutput(true); consumer.sign(request); request.connect(); OutputStream os = request.getOutputStream(); os.write(szBody.getBytes()); os.flush(); int rc = request.getResponseCode(); if (rc == HttpURLConnection.HTTP_CREATED) Util.addUnsubscriptionURI(countryShortNumbers[i], request.getHeaderField("Location"), "bv" + correlator.toString().substring(0, 16)); else { logger.severe(String.format("Error %d registering Notification URLs:%s", rc, request.getResponseMessage())); } } catch (Exception e) { logger.severe("Exception raised: %s" + e.getMessage()); } } return result; }
From source file:org.apache.tinkerpop.gremlin.structure.util.star.StarGraphTest.java
@Test @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_USER_SUPPLIED_IDS) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexPropertyFeatures.FEATURE_USER_SUPPLIED_IDS) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_USER_SUPPLIED_IDS) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_PROPERTY) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_META_PROPERTIES) @FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_MULTI_PROPERTIES) @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES) @FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_PROPERTY) public void shouldAttachWithCreateMethod() { final Random random = new Random(234335l); StarGraph starGraph = StarGraph.open(); Vertex starVertex = starGraph.addVertex(T.label, "person", "name", "stephen", "name", "spmallete"); starVertex.property("acl", true, "timestamp", random.nextLong(), "creator", "marko"); for (int i = 0; i < 100; i++) { starVertex.addEdge("knows", starGraph.addVertex("person", "name", new UUID(random.nextLong(), random.nextLong()), "since", random.nextLong())); starGraph.addVertex(T.label, "project").addEdge("developedBy", starVertex, "public", random.nextBoolean());/* w w w . j av a 2 s. c o m*/ } final Vertex createdVertex = starGraph.getStarVertex().attach(Attachable.Method.create(graph)); starGraph.getStarVertex().edges(Direction.BOTH).forEachRemaining(edge -> ((Attachable<Edge>) edge) .attach(Attachable.Method.create(random.nextBoolean() ? graph : createdVertex))); TestHelper.validateEquality(starVertex, createdVertex); }
From source file:org.apache.hadoop.hdfs.server.diskbalancer.TestDiskBalancerRPC.java
@Test public void testMoveBlockAcrossVolume() throws Exception { Configuration conf = new HdfsConfiguration(); final int defaultBlockSize = 100; conf.setBoolean(DFSConfigKeys.DFS_DISK_BALANCER_ENABLED, true); conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, defaultBlockSize); conf.setInt(DFSConfigKeys.DFS_BYTES_PER_CHECKSUM_KEY, defaultBlockSize); String fileName = "/tmp.txt"; Path filePath = new Path(fileName); final int numDatanodes = 1; final int dnIndex = 0; cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numDatanodes).build(); FsVolumeImpl source = null;//ww w . j av a 2s.c o m FsVolumeImpl dest = null; try { cluster.waitActive(); Random r = new Random(); FileSystem fs = cluster.getFileSystem(dnIndex); DFSTestUtil.createFile(fs, filePath, 10 * 1024, (short) 1, r.nextLong()); DataNode dnNode = cluster.getDataNodes().get(dnIndex); FsDatasetSpi.FsVolumeReferences refs = dnNode.getFSDataset().getFsVolumeReferences(); try { source = (FsVolumeImpl) refs.get(0); dest = (FsVolumeImpl) refs.get(1); DiskBalancerTestUtil.moveAllDataToDestVolume(dnNode.getFSDataset(), source, dest); assertTrue(DiskBalancerTestUtil.getBlockCount(source) == 0); } finally { refs.close(); } } finally { cluster.shutdown(); } }
From source file:org.syncope.core.notification.NotificationTest.java
@Test public void notifyByMail() { // 1. create suitable notification for subsequent tests Notification notification = new Notification(); notification.addEvent("create"); MembershipCond membCond = new MembershipCond(); membCond.setRoleId(7L);//from w w w . j a v a2s . c om notification.setAbout(NodeCond.getLeafCond(membCond)); membCond = new MembershipCond(); membCond.setRoleId(8L); notification.setRecipients(NodeCond.getLeafCond(membCond)); notification.setSelfAsRecipient(true); Random random = new Random(System.currentTimeMillis()); String sender = "syncopetest-" + String.valueOf(random.nextLong()) + "@syncope-idm.org"; notification.setSender(sender); String subject = "Test notification " + random.nextLong(); notification.setSubject(subject); notification.setTemplate("optin"); Notification actual = notificationDAO.save(notification); assertNotNull(actual); notificationDAO.flush(); // 2. use a real SMTP server try { SyncopeConf smtpHostConf = confDAO.find("smtp.host"); smtpHostConf.setValue(smtpHost); confDAO.save(smtpHostConf); } catch (Throwable t) { LOG.error("Unexpected exception", t); fail("Unexpected exception while setting SMTP host"); } confDAO.flush(); confDAO.clear(); // 3. create user UserTO userTO = getSampleTO(mailAddress); MembershipTO membershipTO = new MembershipTO(); membershipTO.setRoleId(7); userTO.addMembership(membershipTO); try { userController.create(new MockHttpServletResponse(), userTO); } catch (Throwable t) { LOG.error("Unexpected exception", t); fail("Unexpected exception while creating"); } // 4. force Quartz job execution and verify e-mail try { notificationJob.execute(null); } catch (SchedulerException e) { LOG.error("Unexpected exception", e); fail("Unexpected exception while triggering notification job"); } assertTrue(verifyMail(sender, subject)); List<NotificationTask> tasks = taskDAO.findAll(NotificationTask.class); Long taskId = null; for (NotificationTask task : tasks) { if (sender.equals(task.getSender())) { taskId = task.getId(); } } assertNotNull(taskId); // 5. execute Notification task and verify e-mail try { taskController.execute(taskId, false); } catch (Throwable t) { LOG.error("Unexpected exception", t); fail("Unexpected exception while executing notification task"); } assertTrue(verifyMail(sender, subject)); }