Example usage for java.util Random nextInt

List of usage examples for java.util Random nextInt

Introduction

In this page you can find the example usage for java.util Random nextInt.

Prototype

public int nextInt() 

Source Link

Document

Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence.

Usage

From source file:Main.java

public static <T> T generateRandom(Class<T> objectClass) {
    Random r = new Random();
    if (objectClass.equals(String.class)) {
        String s = "";
        for (int i = 0; i < 10; i++) {
            char c = (char) (Math.abs(r.nextInt()) % ('Z' - 'A') + 'A');
            s = s + c;//from   w w w  . j  a v a 2 s  .c o m
        }
        return objectClass.cast(s);
    } else if (objectClass.equals(Integer.class)) {
        Integer s = r.nextInt();
        return objectClass.cast(s);
    } else if (objectClass.equals(Long.class)) {
        Long s = r.nextLong();
        return objectClass.cast(s);
    } else if (objectClass.equals(java.util.Date.class)) {
        java.util.Calendar c = java.util.Calendar.getInstance();
        c.set(java.util.Calendar.MONTH, Math.abs(r.nextInt()) % 12);
        c.set(java.util.Calendar.DAY_OF_MONTH, Math.abs(r.nextInt()) % 30);
        return objectClass.cast(c.getTime());
    }
    return null;
}

From source file:net.frygo.findmybuddy.GCMIntentService.java

private static void generateNotification(Context context, String message) {

    Random rand = new Random();
    int x = rand.nextInt();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    String title = context.getString(R.string.app_name);
    Intent notificationIntent = new Intent(context, customlistview.class);
    notificationIntent.putExtra("alert", message);
    message = message + " would like to add you as friend";
    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_CANCEL_CURRENT);

    Notification notification = new Notification(R.drawable.logo, message, System.currentTimeMillis());
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(x, notification);

    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    final PowerManager.WakeLock mWakelock = pm
            .newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, title);
    mWakelock.acquire();/* w  w w. j  av  a 2 s  .c  o m*/

    // Timer before putting Android Device to sleep mode.
    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        public void run() {
            mWakelock.release();
        }
    };
    timer.schedule(task, 5000);

}

From source file:net.frygo.findmybuddy.GCMIntentService.java

private static void generateAcceptfriendNotification(Context context, String message, String status) {

    Random rand = new Random();
    int x = rand.nextInt();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    String title = context.getString(R.string.app_name);
    Intent notificationIntent = new Intent(context, customlistview.class);
    if (status.equalsIgnoreCase("accept"))
        message = message + " added you as buddy";
    else/*  www .  ja  v  a2 s  . c o  m*/
        message = message + " rejected you as buddy";
    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_CANCEL_CURRENT);

    Notification notification = new Notification(R.drawable.logo, message, System.currentTimeMillis());
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(x, notification);

    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    final PowerManager.WakeLock mWakelock = pm
            .newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, title);
    mWakelock.acquire();

    // Timer before putting Android Device to sleep mode.
    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        public void run() {
            mWakelock.release();
        }
    };
    timer.schedule(task, 5000);

}

From source file:org.ofbiz.passport.util.PassportUtil.java

private static int rand(int lo, int hi) {
    java.util.Random rn = new java.util.Random();
    int n = hi - lo + 1;
    int i = rn.nextInt() % n;
    if (i < 0)
        i = -i;//from  ww  w.  j  a  v  a 2s.co m
    return lo + i;
}

From source file:com.linkedin.kafka.clients.utils.tests.KafkaTestUtils.java

public static String getRandomString(int length) {
    char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    Random random = new Random();
    StringBuilder stringBuiler = new StringBuilder();
    for (int i = 0; i < length; i++) {
        stringBuiler.append(chars[Math.abs(random.nextInt()) % 16]);
    }//from  ww  w.  j av a  2 s.  c om
    return stringBuiler.toString();
}

From source file:Main.java

public static void genRandom(long seed, int factor, int offset, int array[], int stride, int skip) {
    Random r = new Random(seed);
    for (int i = 0; i < array.length / stride; i++) {
        for (int j = 0; j < stride; j++) {
            if (j >= stride - skip)
                array[i * stride + j] = 0;
            else/* w  w  w. j  a  v  a  2  s.  co  m*/
                array[i * stride + j] = r.nextInt() * factor + offset;
        }
    }
}

From source file:com.jimplush.goose.images.ImageSaver.java

/**
 * stores an image to disk and returns the path where the file was written
 *
 * @param imageSrc//from   w ww  . ja  v  a  2  s.  c  o  m
 * @return
 */
public static String storeTempImage(HttpClient httpClient, String linkhash, String imageSrc,
        Configuration config) throws SecretGifException {

    String localSrcPath = null;
    HttpGet httpget = null;
    HttpResponse response = null;

    try {

        imageSrc = imageSrc.replace(" ", "%20");
        if (logger.isDebugEnabled()) {
            logger.debug("Starting to download image: " + imageSrc);
        }

        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, HtmlFetcher.emptyCookieStore);

        httpget = new HttpGet(imageSrc);

        response = httpClient.execute(httpget, localContext);

        String respStatus = response.getStatusLine().toString();
        if (!respStatus.contains("200")) {
            return null;
        }

        HttpEntity entity = response.getEntity();

        String fileExtension = "";
        try {
            Header contentType = entity.getContentType();
        } catch (Exception e) {
            logger.error(e.getMessage());

        }

        // generate random token
        Random generator = new Random();
        int randInt = generator.nextInt();

        localSrcPath = config.getLocalStoragePath() + "/" + linkhash + "_" + randInt;

        if (logger.isDebugEnabled()) {
            logger.debug("Storing image locally: " + localSrcPath);
        }
        if (entity != null) {
            InputStream instream = entity.getContent();
            OutputStream outstream = new FileOutputStream(localSrcPath);
            try {
                try {
                    IOUtils.copy(instream, outstream);
                } catch (Exception e) {
                    throw e;
                } finally {
                    entity.consumeContent();
                    instream.close();
                    outstream.close();
                }

                // get mime type and store the image extension based on that shiz
                fileExtension = ImageSaver.getFileExtension(config, localSrcPath);
                if (fileExtension == "" || fileExtension == null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("EMPTY FILE EXTENSION: " + localSrcPath);
                    }
                    return null;
                }
                File f = new File(localSrcPath);
                if (f.length() < config.getMinBytesForImages()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("TOO SMALL AN IMAGE: " + localSrcPath + " bytes: " + f.length());
                    }
                    return null;
                }

                File newFile = new File(localSrcPath + fileExtension);
                f.renameTo(newFile);
                localSrcPath = localSrcPath + fileExtension;

                if (logger.isDebugEnabled()) {
                    logger.debug("Image successfully Written to Disk");
                }

            } catch (IOException e) {
                logger.error(e.toString(), e);
            } catch (SecretGifException e) {
                throw e;
            } catch (Exception e) {
                logger.error(e.getMessage());
            }

        }

    } catch (IllegalArgumentException e) {
        logger.warn(e.getMessage());
    } catch (SecretGifException e) {
        raise(e);
    } catch (ClientProtocolException e) {

        logger.error(e.toString());
    } catch (IOException e) {
        logger.error(e.toString());
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.toString());
        e.printStackTrace();
    } finally {

        httpget.abort();

    }

    return localSrcPath;
}

From source file:io.joynr.util.JoynrUtil.java

public static File createTempDir() {

    Random rand = new Random();
    int randomInt = 1 + rand.nextInt();

    return createTempDir("tempDir" + randomInt);
}

From source file:ru.org.linux.user.UserModificationController.java

private static String getNoCacheLinkToProfile(User user) throws UnsupportedEncodingException {
    Random random = new Random();
    return "/people/" + URLEncoder.encode(user.getNick(), "UTF-8") + "/profile?nocache=" + random.nextInt();
}

From source file:com.adito.applications.server.FileReplacement.java

static File getTempFile(File near) throws IOException {
    String path = null;/*  w ww. j  a  v a  2 s  .co  m*/
    if (near != null)
        if (near.isFile())
            path = near.getParent();
        else if (near.isDirectory())
            path = near.getPath();

    Random wheel = new Random(); // seeded from the clock
    File tempFile = null;
    do {
        // generate random a number 10,000,000 .. 99,999,999
        int unique = (wheel.nextInt() & Integer.MAX_VALUE) % 90000000 + 10000000;
        tempFile = new File(path, Integer.toString(unique) + ".tmp");
    } while (tempFile.exists());
    // We "finally" found a name not already used. Nearly always the first
    // time.
    // Quickly stake our claim to it by opening/closing it to create it.
    // In theory somebody could have grabbed it in that tiny window since
    // we checked if it exists, but that is highly unlikely.
    new FileOutputStream(tempFile).close();

    // debugging peek at the name generated.
    if (false) {
        System.out.println(tempFile.getCanonicalPath());
    }
    return tempFile;
}