Example usage for java.lang Math random

List of usage examples for java.lang Math random

Introduction

In this page you can find the example usage for java.lang Math random.

Prototype

public static double random() 

Source Link

Document

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0 .

Usage

From source file:com.weibo.wesync.client.NHttpClient2.java

public static void main(String[] args) throws Exception {
    RSAPublicKey publicKey = RSAEncrypt.loadPublicKey("D:\\weibo\\meyou_gw\\conf\\public.pem");
    //  //  w  w w  . j a v  a  2 s  .c  om
    byte[] cipher = RSAEncrypt.encrypt(publicKey, password.getBytes());
    password = RSAEncrypt.toHexString(cipher);

    // HTTP parameters for the client
    HttpParams params = new SyncBasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);

    // Create HTTP protocol processing chain
    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Use standard client-side protocol interceptors
            new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(),
            new RequestExpectContinue() });
    // Create client-side HTTP protocol handler
    HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor();
    // Create client-side I/O event dispatch
    final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, params);
    // Create client-side I/O reactor
    IOReactorConfig config = new IOReactorConfig();
    config.setIoThreadCount(1);
    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(config);
    // Create HTTP connection pool
    BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, params);
    // Limit total number of connections to just two
    pool.setDefaultMaxPerRoute(2);
    pool.setMaxTotal(1);

    // Run the I/O reactor in a separate thread
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                // Ready to go!
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }
            System.out.println("Shutdown");
        }

    });
    // Start the client thread
    t.start();
    // Create HTTP requester
    //        HttpAsyncRequester requester = new HttpAsyncRequester(
    //                httpproc, new DefaultConnectionReuseStrategy(), params);
    // Execute HTTP GETs to the following hosts and
    HttpHost[] targets = new HttpHost[] {
            //              new HttpHost("123.125.106.28", 8093, "http"),
            //              new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            new HttpHost("123.125.106.28", 8082, "http") };

    final CountDownLatch latch = new CountDownLatch(targets.length);
    int callbackId = 0;

    for (int i = 0; i < 1; i++) {
        for (final HttpHost target : targets) {
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/wesync");

            //              String usrpwd = Base64.encodeBase64String((username + ":" + password).getBytes());
            //              request.setHeader("authorization", "Basic " + usrpwd);
            request.setHeader("uid", "2565640713");
            Meyou.MeyouPacket packet = null;

            if (callbackId == 0) {
                packet = Meyou.MeyouPacket.newBuilder().setCallbackId(String.valueOf(callbackId++))
                        .setSort(MeyouSort.notice).build();
            } else {
                packet = Meyou.MeyouPacket.newBuilder().setCallbackId(String.valueOf(callbackId++))
                        .setSort(MeyouSort.wesync).build();
            }

            ByteArrayEntity entity = new ByteArrayEntity(packet.toByteArray());
            request.setEntity(entity);
            //           BasicHttpRequest request = new BasicHttpRequest("GET", "/test.html");

            System.out.println("send ...");
            HttpAsyncRequester requester = new HttpAsyncRequester(httpproc,
                    new DefaultConnectionReuseStrategy(), params);
            requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(),
                    pool, new BasicHttpContext(),
                    // Handle HTTP response from a callback
                    new FutureCallback<HttpResponse>() {
                        public void completed(final HttpResponse response) {
                            StatusLine status = response.getStatusLine();
                            int code = status.getStatusCode();

                            if (code == 200) {
                                try {
                                    latch.countDown();
                                    DataInputStream in;
                                    in = new DataInputStream(response.getEntity().getContent());
                                    int packetLength = in.readInt();
                                    int start = 0;

                                    while (packetLength > 0) {
                                        ByteArrayOutputStream outstream = new ByteArrayOutputStream(
                                                packetLength);
                                        byte[] buffer = new byte[1024];
                                        int len = 0;

                                        while (start < packetLength
                                                && (len = in.read(buffer, start, packetLength)) > 0) {
                                            outstream.write(buffer, 0, len);
                                            start += len;
                                        }

                                        Meyou.MeyouPacket packet0 = Meyou.MeyouPacket
                                                .parseFrom(outstream.toByteArray());
                                        System.out.println(target + "->" + packet0);

                                        if ((len = in.read(buffer, start, 4)) > 0) {
                                            packetLength = Util.readPacketLength(buffer);
                                        } else {
                                            break;
                                        }
                                    }
                                } catch (IllegalStateException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            } else {
                                System.out.println("error code=" + code + "|" + status.getReasonPhrase());
                            }
                        }

                        public void failed(final Exception ex) {
                            latch.countDown();
                            System.out.println(target + "->" + ex);
                        }

                        public void cancelled() {
                            latch.countDown();
                            System.out.println(target + " cancelled");
                        }

                    });

            Thread.sleep((long) (Math.random() * 10000));
        }
    }
    //        latch.await();
    //        System.out.println("Shutting down I/O reactor");
    //        ioReactor.shutdown();
    //        System.out.println("Done");
}

From source file:org.belio.service.gateway.AirtelCharging.java

public static void main(String args[]) {
    // new AirtelCharging().chargeSms(new Outbox());

    new Thread(new Runnable() {

        @Override//w  w w .j a v a2s . com
        public void run() {
            try {
                //  System.out.println(url);
                long before, sleepDuration, operationTime;
                int tps = 6500;
                for (int i = 0; i < 100; i++) {
                    before = System.currentTimeMillis();
                    // do your operations
                    operationTime = (long) (tps * Math.random());
                    System.out.print("Doing operations for " + operationTime + "ms\t");
                    Thread.sleep(operationTime);

                    // sleep for up to 1000ms
                    sleepDuration = Math.min(1000, Math.max(1000 - (System.currentTimeMillis() - before), 0));
                    Thread.sleep(sleepDuration);
                    System.out.println("wait\t" + sleepDuration + "ms =\telapsed "
                            + (operationTime + sleepDuration) + (operationTime > 1000 ? "<" : ""));
                }
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }).start();
}

From source file:net.sf.ipsedixit.core.impl.DefaultDataProvider.java

/**
 * {@inheritDoc}/*from  w w  w .jav a 2  s .c  o m*/
 */
public long randomLongInRange(long minInclusive, long maxInclusive) {
    return (long) (Math.random() * (maxInclusive - minInclusive + 1)) + minInclusive;
}

From source file:RegistryTest.java

/**
 * Creates the window's contents//from   w w  w. j  a  v a2s .  co  m
 * 
 * @param parent the parent composite
 * @return Control
 */
protected Control createContents(Composite parent) {
    Composite composite = new Composite(parent, SWT.NONE);
    composite.setLayout(new FillLayout(SWT.VERTICAL));

    // Set up the registries
    CR = new ColorRegistry();
    CR.addListener(this);

    FR = new FontRegistry();
    FR.addListener(this);

    // Create the label
    label = new Label(composite, SWT.CENTER);
    label.setText("Hello from JFace");

    // Create the randomize button
    Button button = new Button(composite, SWT.PUSH);
    button.setText("Randomize");
    button.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            CR.put(FOREGROUND, new RGB((int) (Math.random() * 255), (int) (Math.random() * 255),
                    (int) (Math.random() * 255)));
            CR.put(BACKGROUND, new RGB((int) (Math.random() * 255), (int) (Math.random() * 255),
                    (int) (Math.random() * 255)));
            FontData fontData = new FontData("Times New Roman", (int) (Math.random() * 72), SWT.BOLD);
            FR.put(FONT, new FontData[] { fontData });
        }
    });
    return composite;
}

From source file:CharSequenceDemo.java

private static int random(int max) {
    return (int) Math.round(Math.random() * max + 0.5);
}

From source file:org.bitcoinrt.client.StubMtgoxClient.java

@Override
public void start() {

    this.executor = Executors.newSingleThreadExecutor();

    this.executor.submit(new Runnable() {
        @Override//from ww w.  j a  v  a 2 s .  c  o  m
        public void run() {
            while (!shuttingDown) {

                String expression = "{\"channel\":\"dbf1dee9-4f2e-4a08-8cb7-748919a71b21\",\"op\":\"private\","
                        + "\"origin\":\"broadcast\",\"private\":\"trade\",\"trade\":{\"amount\":[%f],"
                        + "\"date\":[%d],\"price\":12.239,\"exchange\":\"mtgoxUSD\","
                        + "\"price_currency\":\"USD\",\"primary\":\"Y\","
                        + "\"txid\":\"1348679989121772\",\"type\":\"trade\"}}";

                long timestamp = (long) (Math.floor(new Date().getTime() / 1000));
                double amount = Math.floor(Math.random() * 20);
                String message = String.format(expression, amount, timestamp);
                onMessage(message);

                try {
                    Thread.sleep(7000);
                } catch (InterruptedException ex) {
                    logger.debug("Stub MtGox service interrupted");
                }
            }
            logger.debug("Stub MtGox service stopped");
        }
    });

}

From source file:org.openmrs.contrib.metadatarepository.service.MailEngineTest.java

@Test
public void testSend() throws Exception {
    // mock smtp server
    Wiser wiser = new Wiser();
    // set the port to a random value so there's no conflicts between tests
    int port = 2525 + (int) (Math.random() * 100);
    mailSender.setPort(port);/*from w  w w . jav  a 2  s .co m*/
    wiser.setPort(port);
    wiser.start();

    Date dte = new Date();
    this.mailMessage.setTo("foo@bar.com");
    String emailSubject = "grepster testSend: " + dte;
    String emailBody = "Body of the grepster testSend message sent at: " + dte;
    this.mailMessage.setSubject(emailSubject);
    this.mailMessage.setText(emailBody);
    this.mailEngine.send(this.mailMessage);

    wiser.stop();
    assertTrue(wiser.getMessages().size() == 1);
    WiserMessage wm = wiser.getMessages().get(0);
    assertEquals(emailSubject, wm.getMimeMessage().getSubject());
    assertEquals(emailBody, wm.getMimeMessage().getContent());
}

From source file:com.apress.prospringintegration.springenterprise.stocks.transactions.annotation.AnnotationTxStockBrokerService.java

@Transactional
public void preFillStocks(final String exchangeId, final String... symbols) {
    int i = 0;/*from w ww . ja  v  a2s  .c o  m*/
    for (String sym : symbols) {
        float pp = (float) Math.random() * 100.0f;
        int qq = (int) Math.random() * 250;
        Stock s = new Stock(sym, "INV00" + i, exchangeId, pp, qq, Calendar.getInstance().getTime());
        stockDao.insert(s);
        System.out.println("ORIG INVENTORY: " + s.getInventoryCode() + " ");
        int randomized = (random.nextInt(100) % 4) == 0 ? 0 : i;
        s.setInventoryCode("INV00" + randomized);
        System.out.println("NEW RANDOMIZED INVENTORY:" + s.getInventoryCode() + " " + randomized);
        stockDao.update(s);
        i++;
    }
}

From source file:cz.zcu.pia.social.network.frontend.components.profile.profile.ImageUploader.java

@Override
public OutputStream receiveUpload(String filename, String mimeType) {
    if (filename == null) {
        return null;
    }/*w  w w.  ja v  a  2 s . c  o m*/
    // Create upload stream
    FileOutputStream fos; // Stream to write to
    try {

        fileService.createBasicFolders();
        file = fileService.createFile(Constants.BASE_PATH + securityHelper.getLogedInUser().getId() + "-"
                + Math.abs((int) (Math.random() * 10000000)) + "." + FilenameUtils.getExtension(filename));
        if (file == null) {
            Notification.show(msgs.getMessage("error.file.exists"), Notification.Type.ERROR_MESSAGE);
            return null;
        }
        fos = new FileOutputStream(file);

    } catch (final java.io.FileNotFoundException e) {
        logger.error(e.getMessage(), e);
        return null;
    } catch (SecurityException e) {
        logger.error(e.getMessage(), e);
        return null;

    }
    return fos; // Return the output stream to write to
}

From source file:de.snertlab.xdccBee.irc.IrcServer.java

public IrcServer(String id, String hostname, String nickname, String port, String botName, String botVersion) {
    if (id == null) {
        this.id = (new Date().getTime() + Math.random()) + "";
    } else {//from ww w.  j  a v  a  2s . co  m
        this.id = id;
    }
    this.hostname = hostname;
    this.nickname = nickname;
    this.port = port;
    this.mapIrcChannels = new LinkedHashMap<String, IrcChannel>();
    this.mapDccPackets = new LinkedHashMap<String, DccPacket>();
    this.dccBot = new DccBot(this, Application.getSettings().getBotName(),
            Application.getSettings().getBotVersion(), Application.getSettings().getDownloadFolder() + "/");
}