List of usage examples for java.util Random nextLong
public long nextLong()
From source file:org.apache.hadoop.yarn.util.TestFSDownload.java
@Test(timeout = 10000) public void testDownload() throws IOException, URISyntaxException, InterruptedException { Configuration conf = new Configuration(); conf.set(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY, "077"); FileContext files = FileContext.getLocalFSFileContext(conf); final Path basedir = files.makeQualified(new Path("target", TestFSDownload.class.getSimpleName())); files.mkdir(basedir, null, true);/*from ww w. j ava 2s. c o m*/ conf.setStrings(TestFSDownload.class.getName(), basedir.toString()); Map<LocalResource, LocalResourceVisibility> rsrcVis = new HashMap<LocalResource, LocalResourceVisibility>(); Random rand = new Random(); long sharedSeed = rand.nextLong(); rand.setSeed(sharedSeed); System.out.println("SEED: " + sharedSeed); Map<LocalResource, Future<Path>> pending = new HashMap<LocalResource, Future<Path>>(); ExecutorService exec = Executors.newSingleThreadExecutor(); LocalDirAllocator dirs = new LocalDirAllocator(TestFSDownload.class.getName()); int[] sizes = new int[10]; for (int i = 0; i < 10; ++i) { sizes[i] = rand.nextInt(512) + 512; LocalResourceVisibility vis = LocalResourceVisibility.PRIVATE; if (i % 2 == 1) { vis = LocalResourceVisibility.APPLICATION; } Path p = new Path(basedir, "" + i); LocalResource rsrc = createFile(files, p, sizes[i], rand, vis); rsrcVis.put(rsrc, vis); Path destPath = dirs.getLocalPathForWrite(basedir.toString(), sizes[i], conf); destPath = new Path(destPath, Long.toString(uniqueNumberGenerator.incrementAndGet())); FSDownload fsd = new FSDownload(files, UserGroupInformation.getCurrentUser(), conf, destPath, rsrc); pending.put(rsrc, exec.submit(fsd)); } exec.shutdown(); while (!exec.awaitTermination(1000, TimeUnit.MILLISECONDS)) ; for (Future<Path> path : pending.values()) { Assert.assertTrue(path.isDone()); } try { for (Map.Entry<LocalResource, Future<Path>> p : pending.entrySet()) { Path localized = p.getValue().get(); assertEquals(sizes[Integer.parseInt(localized.getName())], p.getKey().getSize()); FileStatus status = files.getFileStatus(localized.getParent()); FsPermission perm = status.getPermission(); assertEquals("Cache directory permissions are incorrect", new FsPermission((short) 0755), perm); status = files.getFileStatus(localized); perm = status.getPermission(); System.out .println("File permission " + perm + " for rsrc vis " + p.getKey().getVisibility().name()); assert (rsrcVis.containsKey(p.getKey())); Assert.assertTrue("Private file should be 500", perm.toShort() == FSDownload.PRIVATE_FILE_PERMS.toShort()); } } catch (ExecutionException e) { throw new IOException("Failed exec", e); } }
From source file:org.apache.syncope.core.notification.NotificationTest.java
@Test public void notifyByMail() throws Exception { // 1. create suitable notification for subsequent tests Notification notification = new Notification(); notification.addEvent("[REST]:[UserController]:[]:[create]:[SUCCESS]"); notification.setUserAbout(SyncopeClient.getUserSearchConditionBuilder().hasRoles(7L).query()); notification.setRecipients(SyncopeClient.getUserSearchConditionBuilder().hasRoles(8L).query()); notification.setSelfAsRecipient(true); notification.setRecipientAttrName("email"); notification.setRecipientAttrType(IntMappingType.UserSchema); Random random = new Random(System.currentTimeMillis()); String sender = "syncopetest-" + random.nextLong() + "@syncope.apache.org"; notification.setSender(sender);/*from w ww . j a v a 2 s .com*/ String subject = "Test notification " + random.nextLong(); notification.setSubject(subject); notification.setTemplate("optin"); Notification actual = notificationDAO.save(notification); assertNotNull(actual); notificationDAO.flush(); // 2. create user UserTO userTO = UserTestITCase.getSampleTO(mailAddress); MembershipTO membershipTO = new MembershipTO(); membershipTO.setRoleId(7); userTO.getMemberships().add(membershipTO); userController.create(userTO); // 3. force Quartz job execution and verify e-mail notificationJob.execute(null); assertTrue(verifyMail(sender, subject)); // 4. get NotificationTask id and text body Long taskId = null; String textBody = null; for (NotificationTask task : taskDAO.findAll(NotificationTask.class)) { if (sender.equals(task.getSender())) { taskId = task.getId(); textBody = task.getTextBody(); } } assertNotNull(taskId); assertNotNull(textBody); assertTrue("Notification mail text doesn't contain expected content.", textBody.contains("Your email address is notificationtest@syncope.apache.org.")); assertTrue("Notification mail text doesn't contain expected content.", textBody.contains("Your email address inside a link: " + "http://localhost/?email=notificationtest%40syncope.apache.org .")); // 5. execute Notification task and verify e-mail taskController.execute(taskId, false); assertTrue(verifyMail(sender, subject)); }
From source file:org.apache.syncope.core.notification.NotificationTest.java
@Test public void issueSYNCOPE445() throws Exception { // 1. create suitable notification for subsequent tests Notification notification = new Notification(); notification.addEvent("[REST]:[UserController]:[]:[create]:[SUCCESS]"); notification.setUserAbout(SyncopeClient.getUserSearchConditionBuilder().hasRoles(7L).query()); notification.setRecipients(SyncopeClient.getUserSearchConditionBuilder().hasRoles(8L).query()); notification.setSelfAsRecipient(true); notification.setRecipientAttrName("email"); notification.setRecipientAttrType(IntMappingType.UserSchema); notification.getStaticRecipients().add("syncope445@syncope.apache.org"); Random random = new Random(System.currentTimeMillis()); String sender = "syncopetest-" + random.nextLong() + "@syncope.apache.org"; notification.setSender(sender);// ww w . j a v a2s .co m String subject = "Test notification " + random.nextLong(); notification.setSubject(subject); notification.setTemplate("optin"); Notification actual = notificationDAO.save(notification); assertNotNull(actual); notificationDAO.flush(); // 2. create user UserTO userTO = UserTestITCase.getSampleTO(mailAddress); MembershipTO membershipTO = new MembershipTO(); membershipTO.setRoleId(7); userTO.getMemberships().add(membershipTO); userController.create(userTO); // 3. force Quartz job execution and verify e-mail notificationJob.execute(null); assertTrue(verifyMail(sender, subject)); // 4. get NotificationTask id and text body Long taskId = null; String textBody = null; Set<String> recipients = null; for (NotificationTask task : taskDAO.findAll(NotificationTask.class)) { if (sender.equals(task.getSender())) { taskId = task.getId(); textBody = task.getTextBody(); recipients = task.getRecipients(); } } assertNotNull(taskId); assertNotNull(textBody); assertTrue(recipients.contains("syncope445@syncope.apache.org")); // 5. execute Notification task and verify e-mail taskController.execute(taskId, false); assertTrue(verifyMail(sender, subject)); }
From source file:org.apache.hadoop.yarn.util.TestFSDownload.java
private void downloadWithFileType(TEST_FILE_TYPE fileType) throws IOException, URISyntaxException, InterruptedException { Configuration conf = new Configuration(); conf.set(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY, "077"); FileContext files = FileContext.getLocalFSFileContext(conf); final Path basedir = files.makeQualified(new Path("target", TestFSDownload.class.getSimpleName())); files.mkdir(basedir, null, true);/*from ww w . ja v a 2 s. c o m*/ conf.setStrings(TestFSDownload.class.getName(), basedir.toString()); Random rand = new Random(); long sharedSeed = rand.nextLong(); rand.setSeed(sharedSeed); System.out.println("SEED: " + sharedSeed); Map<LocalResource, Future<Path>> pending = new HashMap<LocalResource, Future<Path>>(); ExecutorService exec = Executors.newSingleThreadExecutor(); LocalDirAllocator dirs = new LocalDirAllocator(TestFSDownload.class.getName()); int size = rand.nextInt(512) + 512; LocalResourceVisibility vis = LocalResourceVisibility.PRIVATE; Path p = new Path(basedir, "" + 1); String strFileName = ""; LocalResource rsrc = null; switch (fileType) { case TAR: rsrc = createTarFile(files, p, size, rand, vis); break; case JAR: rsrc = createJarFile(files, p, size, rand, vis); rsrc.setType(LocalResourceType.PATTERN); break; case ZIP: rsrc = createZipFile(files, p, size, rand, vis); strFileName = p.getName() + ".ZIP"; break; case TGZ: rsrc = createTgzFile(files, p, size, rand, vis); break; } Path destPath = dirs.getLocalPathForWrite(basedir.toString(), size, conf); destPath = new Path(destPath, Long.toString(uniqueNumberGenerator.incrementAndGet())); FSDownload fsd = new FSDownload(files, UserGroupInformation.getCurrentUser(), conf, destPath, rsrc); pending.put(rsrc, exec.submit(fsd)); exec.shutdown(); while (!exec.awaitTermination(1000, TimeUnit.MILLISECONDS)) ; try { pending.get(rsrc).get(); // see if there was an Exception during download FileStatus[] filesstatus = files.getDefaultFileSystem().listStatus(basedir); for (FileStatus filestatus : filesstatus) { if (filestatus.isDirectory()) { FileStatus[] childFiles = files.getDefaultFileSystem().listStatus(filestatus.getPath()); for (FileStatus childfile : childFiles) { if (strFileName.endsWith(".ZIP") && childfile.getPath().getName().equals(strFileName) && !childfile.isDirectory()) { Assert.fail("Failure...After unzip, there should have been a" + " directory formed with zip file name but found a file. " + childfile.getPath()); } if (childfile.getPath().getName().startsWith("tmp")) { Assert.fail("Tmp File should not have been there " + childfile.getPath()); } } } } } catch (Exception e) { throw new IOException("Failed exec", e); } }
From source file:org.apache.syncope.core.notification.NotificationTest.java
@Test public void issueSYNCOPE446() throws Exception { // 1. create suitable notification for subsequent tests Notification notification = new Notification(); notification.addEvent("[REST]:[RoleController]:[]:[create]:[SUCCESS]"); notification//from w w w .ja va 2 s .c om .setRoleAbout(SyncopeClient.getRoleSearchConditionBuilder().is("name").equalTo("role446").query()); notification.setSelfAsRecipient(false); notification.setRecipientAttrName("email"); notification.setRecipientAttrType(IntMappingType.UserSchema); notification.getStaticRecipients().add(mailAddress); Random random = new Random(System.currentTimeMillis()); String sender = "syncopetest-" + random.nextLong() + "@syncope.apache.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. create role RoleTO roleTO = new RoleTO(); roleTO.setName("role446"); roleTO.setParent(1L); RoleTO createdRole = roleController.create(roleTO); assertNotNull(createdRole); // 3. force Quartz job execution and verify e-mail notificationJob.execute(null); assertTrue(verifyMail(sender, subject)); // 4. get NotificationTask id and text body Long taskId = null; String textBody = null; Set<String> recipients = null; for (NotificationTask task : taskDAO.findAll(NotificationTask.class)) { if (sender.equals(task.getSender())) { taskId = task.getId(); textBody = task.getTextBody(); recipients = task.getRecipients(); } } assertNotNull(taskId); assertNotNull(textBody); assertTrue(recipients.contains(mailAddress)); // 5. execute Notification task and verify e-mail taskController.execute(taskId, false); assertTrue(verifyMail(sender, subject)); }
From source file:org.apache.hadoop.yarn.util.TestFSDownload.java
@Test(timeout = 60000) public void testDownloadPublicWithStatCache() throws IOException, URISyntaxException, InterruptedException, ExecutionException { final Configuration conf = new Configuration(); FileContext files = FileContext.getLocalFSFileContext(conf); Path basedir = files.makeQualified(new Path("target", TestFSDownload.class.getSimpleName())); // if test directory doesn't have ancestor permission, skip this test FileSystem f = basedir.getFileSystem(conf); assumeTrue(FSDownload.ancestorsHaveExecutePermissions(f, basedir, null)); files.mkdir(basedir, null, true);/*from w w w. ja v a 2 s . c o m*/ conf.setStrings(TestFSDownload.class.getName(), basedir.toString()); int size = 512; final ConcurrentMap<Path, AtomicInteger> counts = new ConcurrentHashMap<Path, AtomicInteger>(); final CacheLoader<Path, Future<FileStatus>> loader = FSDownload.createStatusCacheLoader(conf); final LoadingCache<Path, Future<FileStatus>> statCache = CacheBuilder.newBuilder() .build(new CacheLoader<Path, Future<FileStatus>>() { public Future<FileStatus> load(Path path) throws Exception { // increment the count AtomicInteger count = counts.get(path); if (count == null) { count = new AtomicInteger(0); AtomicInteger existing = counts.putIfAbsent(path, count); if (existing != null) { count = existing; } } count.incrementAndGet(); // use the default loader return loader.load(path); } }); // test FSDownload.isPublic() concurrently final int fileCount = 3; List<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>(); for (int i = 0; i < fileCount; i++) { Random rand = new Random(); long sharedSeed = rand.nextLong(); rand.setSeed(sharedSeed); System.out.println("SEED: " + sharedSeed); final Path path = new Path(basedir, "test-file-" + i); createFile(files, path, size, rand); final FileSystem fs = path.getFileSystem(conf); final FileStatus sStat = fs.getFileStatus(path); tasks.add(new Callable<Boolean>() { public Boolean call() throws IOException { return FSDownload.isPublic(fs, path, sStat, statCache); } }); } ExecutorService exec = Executors.newFixedThreadPool(fileCount); try { List<Future<Boolean>> futures = exec.invokeAll(tasks); // files should be public for (Future<Boolean> future : futures) { assertTrue(future.get()); } // for each path exactly one file status call should be made for (AtomicInteger count : counts.values()) { assertSame(count.get(), 1); } } finally { exec.shutdown(); } }
From source file:org.apache.syncope.core.notification.NotificationTest.java
@Test public void notifyByMailWithRetry() throws Exception { // 1. create suitable notification for subsequent tests Notification notification = new Notification(); notification.addEvent("[REST]:[UserController]:[]:[create]:[SUCCESS]"); notification.setUserAbout(null);//w w w .j av a 2 s . c o m notification.setRecipients(SyncopeClient.getUserSearchConditionBuilder().hasRoles(8L).query()); notification.setSelfAsRecipient(true); notification.setRecipientAttrName("email"); notification.setRecipientAttrType(IntMappingType.UserSchema); Random random = new Random(System.currentTimeMillis()); String sender = "syncopetest-" + random.nextLong() + "@syncope.apache.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. create user UserTO userTO = UserTestITCase.getSampleTO(mailAddress); MembershipTO membershipTO = new MembershipTO(); membershipTO.setRoleId(7); userTO.getMemberships().add(membershipTO); userController.create(userTO); // 3. Set number of retries CAttr maxRetries = confDAO.find("notification.maxRetries", "5"); maxRetries.getValues().clear(); maxRetries.addValue("5", AttributableUtil.getInstance(AttributableType.CONFIGURATION)); confDAO.save(maxRetries); confDAO.flush(); // 4. Stop mail server to force error sending mail stopGreenMail(); // 5. force Quartz job execution multiple times for (int i = 0; i < 10; i++) { notificationJob.execute(null); } // 6. get NotificationTask, count number of executions NotificationTask foundTask = null; for (NotificationTask task : taskDAO.findAll(NotificationTask.class)) { if (sender.equals(task.getSender())) { foundTask = task; } } assertNotNull(foundTask); assertEquals(6, notificationManager.countExecutionsWithStatus(foundTask.getId(), NotificationJob.Status.NOT_SENT.name())); // 7. start mail server again startGreenMail(); // 8. reset number of retries maxRetries = confDAO.find("notification.maxRetries", "5"); maxRetries.getValues().clear(); maxRetries.addValue("0", AttributableUtil.getInstance(AttributableType.CONFIGURATION)); confDAO.save(maxRetries); confDAO.flush(); }
From source file:org.apache.hadoop.hive.serde2.binarysortable.MyTestClass.java
public int randomFill(Random r, ExtraTypeInfo extraTypeInfo) { int randField = r.nextInt(MyTestClass.fieldCount); int field = 0; myBool = (randField == field++) ? null : (r.nextInt(1) == 1); myByte = (randField == field++) ? null : Byte.valueOf((byte) r.nextInt()); myShort = (randField == field++) ? null : Short.valueOf((short) r.nextInt()); myInt = (randField == field++) ? null : Integer.valueOf(r.nextInt()); myLong = (randField == field++) ? null : Long.valueOf(r.nextLong()); myFloat = (randField == field++) ? null : Float.valueOf(r.nextFloat() * 10 - 5); myDouble = (randField == field++) ? null : Double.valueOf(r.nextDouble() * 10 - 5); myString = (randField == field++) ? null : MyTestPrimitiveClass.getRandString(r); myHiveChar = (randField == field++) ? null : MyTestPrimitiveClass.getRandHiveChar(r, extraTypeInfo); myHiveVarchar = (randField == field++) ? null : MyTestPrimitiveClass.getRandHiveVarchar(r, extraTypeInfo); myBinary = MyTestPrimitiveClass.getRandBinary(r, r.nextInt(1000)); myDecimal = (randField == field++) ? null : MyTestPrimitiveClass.getRandHiveDecimal(r, extraTypeInfo); myDate = (randField == field++) ? null : MyTestPrimitiveClass.getRandDate(r); myTimestamp = (randField == field++) ? null : RandomTypeUtil.getRandTimestamp(r); myIntervalYearMonth = (randField == field++) ? null : MyTestPrimitiveClass.getRandIntervalYearMonth(r); myIntervalDayTime = (randField == field++) ? null : MyTestPrimitiveClass.getRandIntervalDayTime(r); myStruct = (randField == field++) ? null : new MyTestInnerStruct(r.nextInt(5) - 2, r.nextInt(5) - 2); myList = (randField == field++) ? null : getRandIntegerArray(r); return field; }
From source file:org.apache.hadoop.hbase.client.TestAdmin2.java
@Test(timeout = 30000) public void testAbortProcedureFail() throws Exception { Random randomGenerator = new Random(); long procId = randomGenerator.nextLong(); boolean abortResult = admin.abortProcedure(procId, true); assertFalse(abortResult);//from w ww .ja v a 2s. c o m }
From source file:com.coderdojo.libretalk.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); appName = mTitle = getTitle();//from w w w. j ava2 s. c o m getActionBar().setTitle(appName); // Read the User data from the database datasource = new DBManager(this); datasource.open(); userList = datasource.getAllUsers(); mFriendsListArray = new ArrayList<SpannableString>(); mMessageListArray = new ArrayList<SpannableString>(); for (int i = 0; i < userList.size(); i++) { mFriendsListArray.add(new SpannableString(userList.get(i).getProfile().getName())); } mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.left_drawer); friendlist = getResources().getString(R.string.friendlist); // set a custom shadow that overlays the main content when the drawer opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); // set up the drawer's list view with items and click listener mDrawerList .setAdapter(new ArrayAdapter<SpannableString>(this, R.layout.drawer_list_item, mFriendsListArray)); mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); // enable ActionBar app icon to behave as action to toggle nav drawer getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); // ActionBarDrawerToggle ties together the the proper interactions // between the sliding drawer and the action bar app icon mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */ R.string.drawer_open, /* "open drawer" description for accessibility */ R.string.drawer_close /* "close drawer" description for accessibility */ ) { public void onDrawerClosed(View view) { getActionBar().setTitle(friendlist); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } public void onDrawerOpened(View drawerView) { getActionBar().setTitle(appName); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }; mDrawerLayout.setDrawerListener(mDrawerToggle); if (savedInstanceState == null) { setTitle(friendlist); selectItem(0); } //XXX NETWORKING CODE BEGIN //[!] TODO: This is configured to use Android's localhost. Change the host value to whatever our server's address is. Random randomGenerator = new Random(); long tempuserhash = randomGenerator.nextLong(); String host = getString(R.string.ipaddress); Log.v("Libretalk", host); String user = getString(R.string.rabbituser); Log.v("Libretalk", user); String password = getString(R.string.rabbitpassword); Log.v("Libretalk", password); this.connection = new LibretalkConnection(host, user, password, tempuserhash); final ILibretalkMessageEventHandler eventHandler = new ILibretalkMessageEventHandler() { @Override public void onMessageReceived(final LibretalkMessageData message) { try { //printMsg(message.getSenderTag() + ": " + message.getData()); printMsg(message); } catch (Exception ex) { showErrDialog("Fatal Error! - " + ex.getClass().getSimpleName(), "An error has occurred while attempting to proccess a message from " + message.getSenderTag() + ".\n " + ex.getMessage(), ":'("); } } @Override public void onDisconnect(final Exception ex) { showErrDialog("Disconnected! - " + ex.getClass().getSimpleName(), "A network error has occurred and you have been disconnected! " + "Please check you are connected to the internet.", ":("); } }; this.receiver = new LibretalkMessageReceiver(this.connection, eventHandler); this.sender = new LibretalkMessageSender(this.connection); try { this.connection.connect(); this.receiver.startConsuming(); } catch (LibretalkNetworkException ex) { this.showErrDialog("Connection failure - " + ex.getClass().getSimpleName(), "Unfortunately, an error has occurred and we were unable to connect you to" + "the Libretalk Network, please check you are connected to the internet.", ":("); ex.printStackTrace(); return; } //XXX NETWORKING CODE END }