Example usage for java.lang Thread sleep

List of usage examples for java.lang Thread sleep

Introduction

In this page you can find the example usage for java.lang Thread sleep.

Prototype

public static native void sleep(long millis) throws InterruptedException;

Source Link

Document

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.

Usage

From source file:examples.StatePersistence.java

public static void main(String[] args) throws Exception {
    // Connect to localhost and use the travel-sample bucket
    final Client client = Client.configure().hostnames("localhost").bucket(BUCKET).build();

    // Don't do anything with control events in this example
    client.controlEventHandler(new ControlEventHandler() {
        @Override//from   w w w.j a  v a 2  s  . c om
        public void onEvent(ChannelFlowController flowController, ByteBuf event) {
            if (DcpSnapshotMarkerRequest.is(event)) {
                flowController.ack(event);
            }
            event.release();
        }
    });

    // Print out Mutations and Deletions
    client.dataEventHandler(new DataEventHandler() {
        @Override
        public void onEvent(ChannelFlowController flowController, ByteBuf event) {
            if (DcpMutationMessage.is(event)) {
                System.out.println("Mutation: " + DcpMutationMessage.toString(event));
                // You can print the content via DcpMutationMessage.content(event).toString(CharsetUtil.UTF_8);
            } else if (DcpDeletionMessage.is(event)) {
                System.out.println("Deletion: " + DcpDeletionMessage.toString(event));
            }
            event.release();
        }
    });

    // Connect the sockets
    client.connect().await();

    // Try to load the persisted state from file if it exists
    File file = new File(FILENAME);
    byte[] persisted = null;
    if (file.exists()) {
        FileInputStream fis = new FileInputStream(FILENAME);
        persisted = IOUtils.toByteArray(fis);
        fis.close();
    }

    // if the persisted file exists recover, if not start from beginning
    client.recoverOrInitializeState(StateFormat.JSON, persisted, StreamFrom.BEGINNING, StreamTo.INFINITY)
            .await();

    // Start streaming on all partitions
    client.startStreaming().await();

    // Persist the State ever 10 seconds
    while (true) {
        Thread.sleep(TimeUnit.SECONDS.toMillis(10));

        // export the state as a JSON byte array
        byte[] state = client.sessionState().export(StateFormat.JSON);

        // Write it to a file
        FileOutputStream output = new FileOutputStream(new File(FILENAME));
        IOUtils.write(state, output);
        output.close();

        System.out.println(System.currentTimeMillis() + " - Persisted State!");
    }
}

From source file:httpclient.client.ClientEvictExpiredConnections.java

public static void main(String[] args) throws Exception {
    // Create and initialize HTTP parameters
    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 100);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

    // Create and initialize scheme registry 
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    HttpClient httpclient = new DefaultHttpClient(cm, params);

    // create an array of URIs to perform GETs on
    String[] urisToGet = { "http://jakarta.apache.org/", "http://jakarta.apache.org/commons/",
            "http://jakarta.apache.org/commons/httpclient/",
            "http://svn.apache.org/viewvc/jakarta/httpcomponents/" };

    IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm);
    connEvictor.start();//  ww  w  . j a  v a  2 s .c o  m

    for (int i = 0; i < urisToGet.length; i++) {
        String requestURI = urisToGet[i];
        HttpGet req = new HttpGet(requestURI);

        System.out.println("executing request " + requestURI);

        HttpResponse rsp = httpclient.execute(req);
        HttpEntity entity = rsp.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(rsp.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        System.out.println("----------------------------------------");

        if (entity != null) {
            entity.consumeContent();
        }
    }

    // Sleep 10 sec and let the connection evictor do its job
    Thread.sleep(20000);

    // Shut down the evictor thread
    connEvictor.shutdown();
    connEvictor.join();

    // When HttpClient instance is no longer needed, 
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
}

From source file:com.stratio.decision.executables.DataFlowFromCsvMain.java

public static void main(String[] args) throws IOException, NumberFormatException, InterruptedException {
    if (args.length < 4) {
        log.info(/*www.  jav a2s  .  c  o m*/
                "Usage: \n param 1 - path to file \n param 2 - stream name to send the data \n param 3 - time in ms to wait to send each data \n param 4 - broker list");
    } else {
        Producer<String, String> producer = new Producer<String, String>(createProducerConfig(args[3]));
        Gson gson = new Gson();

        Reader in = new FileReader(args[0]);
        CSVParser parser = CSVFormat.DEFAULT.parse(in);

        List<String> columnNames = new ArrayList<>();
        for (CSVRecord csvRecord : parser.getRecords()) {

            if (columnNames.size() == 0) {
                Iterator<String> iterator = csvRecord.iterator();
                while (iterator.hasNext()) {
                    columnNames.add(iterator.next());
                }
            } else {
                StratioStreamingMessage message = new StratioStreamingMessage();

                message.setOperation(STREAM_OPERATIONS.MANIPULATION.INSERT.toLowerCase());
                message.setStreamName(args[1]);
                message.setTimestamp(System.currentTimeMillis());
                message.setSession_id(String.valueOf(System.currentTimeMillis()));
                message.setRequest_id(String.valueOf(System.currentTimeMillis()));
                message.setRequest("dummy request");

                List<ColumnNameTypeValue> sensorData = new ArrayList<>();
                for (int i = 0; i < columnNames.size(); i++) {

                    // Workaround
                    Object value = null;
                    try {
                        value = Double.valueOf(csvRecord.get(i));
                    } catch (NumberFormatException e) {
                        value = csvRecord.get(i);
                    }
                    sensorData.add(new ColumnNameTypeValue(columnNames.get(i), null, value));
                }

                message.setColumns(sensorData);

                String json = gson.toJson(message);
                log.info("Sending data: {}", json);
                producer.send(new KeyedMessage<String, String>(InternalTopic.TOPIC_DATA.getTopicName(),
                        STREAM_OPERATIONS.MANIPULATION.INSERT, json));

                log.info("Sleeping {} ms...", args[2]);
                Thread.sleep(Long.valueOf(args[2]));
            }
        }
        log.info("Program completed.");
    }
}

From source file:com.mycompany.asyncreq.Main.java

public static void main(String[] args) throws JsonProcessingException, JSONException, IOException {

    Configuration config = new Configuration();
    // Name tables with lowercase_underscore_separated
    RestTemplate restTemplate = new RestTemplate();
    config.setNamingStrategy(new ImprovedNamingStrategy());
    try {/*w ww.j av a  2 s. c  om*/

        ArrayList<String> ArrReq = GenData();
        String addr;
        for (Iterator<String> i = ArrReq.iterator(); i.hasNext();) {
            try {
                addr = i.next();
                Thread.sleep(1000);
                Root tRoot = restTemplate.getForObject(addr, Root.class);
                tRoot.addr = addr;
                if (!tRoot.dataset.isEmpty())
                    if (tRoot.dataset.size() == tRoot.validation.count.value)
                        ObjToCsv(tRoot, "all");

                    else {
                        for (int reg = 1; reg < 5; reg++) {
                            Thread.sleep(1000);
                            addr = "http://comtrade.un.org/api/get?max=50000&type=C&freq=M&px=HS&ps=2014&r=804&p="
                                    + tRoot.dataset.get(0).getptCode() + "&rg=" + reg + "&cc=All&fmt=json";
                            Root tRootImp = restTemplate.getForObject(addr, Root.class);
                            tRootImp.addr = addr;
                            if (!tRootImp.dataset.isEmpty())
                                if (tRootImp.dataset.size() == tRootImp.validation.count.value)
                                    ObjToCsv(tRootImp, Integer.toString(reg));
                                else
                                    System.out.println("addr:  " + tRootImp.addr + "\n");
                        }
                    }
                else
                    System.out.println("addr:  " + tRoot.addr + ":null" + "\n");
            } catch (Exception e) {
                System.err.println(e.getMessage());

            }
        }

    } catch (Exception e) {
        System.err.println("Got an exception! ");
        System.err.println(e.getMessage());
    }
}

From source file:com.impetus.ankush.agent.daemon.AnkushAgent.java

/**
 * The main method./*from  www. jav  a  2 s.  c  om*/
 * 
 * @param args
 *            the arguments
 */
public static void main(String[] args) {

    // taskable file name.
    String file = System.getProperty(Constant.AGENT_INSTALL_DIR) + "/.ankush/agent/conf/taskable.conf";

    // iterate always

    try {
        // reading the class name lines from the file
        List<String> classNames = FileUtils.readLines(new File(file));
        // iterate over the class names to start the newly added task.
        for (String className : classNames) {
            // if an empty string from the file then continue the loop.
            if (className.isEmpty()) {
                continue;
            }
            // if not started.
            if (!objMap.containsKey(className)) {
                // create taskable object
                LOGGER.info("Creating " + className + " object.");

                try {
                    Taskable taskable = ActionFactory.getTaskableObject(className);
                    objMap.put(className, taskable);
                    // call start on object ...
                    taskable.start();
                } catch (Exception e) {
                    LOGGER.error("Could not start the " + className + " taskable.");
                }
            }
        }

        // iterating over the existing tasks to stop if it is removed
        // from the file.
        Set<String> existingClassNames = new HashSet<String>(objMap.keySet());
        for (String className : existingClassNames) {
            // if not started.
            if (!classNames.contains(className)) {
                // create taskable object

                LOGGER.info("Removing " + className + " object.");

                Taskable taskable = objMap.get(className);
                objMap.remove(className);
                // call stop on object ...
                taskable.stop();
            }
        }

    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }

    while (true) {
        try {
            Thread.sleep(TASK_SEARCH_SLEEP_TIME);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
}

From source file:fr.ritaly.dungeonmaster.Main.java

public static void main(String[] args) throws Exception {
    if (log.isInfoEnabled()) {
        log.info("Start");
    }//www.  ja v  a 2  s  .  com

    SoundSystem.getInstance().init(new File("src/main/resources/sound"));

    log.debug("Building dungeon ...");

    final Door door = new Door(Door.Style.WOODEN, Orientation.NORTH_SOUTH);

    final Dungeon dungeon = new Dungeon();
    dungeon.createLevel(1, 10, 10);
    dungeon.getLevel(1).setElement(3, 3, door);

    door.open();

    Clock.getInstance().setPeriod(166);
    Clock.getInstance().start();

    log.info("Dungeon built");

    if (true) {
        log.debug("Creating party ...");

        final Champion wuuf = ChampionFactory.getFactory().newChampion(Name.WUUF);
        wuuf.getStats().getHealth().baseValue(10);
        wuuf.getStats().getMana().baseValue(10);

        final Champion tiggy = ChampionFactory.getFactory().newChampion(Name.TIGGY);

        final Party party = new Party();
        party.addChampion(wuuf);
        party.addChampion(tiggy);

        wuuf.getBody().getWeaponHand().putOn(new Torch());

        if (true) {
            // champion.getBody().getWeaponHand().disable();

            log.info("Max load = " + wuuf.getMaxLoad() + " Kg");

            tiggy.getStats().getHealth().baseValue(200);

            log.info("Party created");

            dungeon.setParty(5, 5, 1, party);

            for (int i = 0; i < 4; i++) {
                dungeon.moveParty(Move.TURN_LEFT, false, AudioClip.STEP);
            }
            for (int i = 0; i < 5; i++) {
                dungeon.moveParty(Move.FORWARD, false, AudioClip.STEP);
            }

            // party.removeChampion(champion);

            tiggy.getBody().getShieldHand().putOn(ItemFactory.getFactory().newItem(Item.Type.TORCH));
            tiggy.getBody().getShieldHand().putOn(ItemFactory.getFactory().newItem(Item.Type.WATER_FLASK));

            for (int i = 0; i < 50; i++) {
                wuuf.gainExperience(Skill.NINJA, 50);
            }

            tiggy.cast(PowerRune.LO, ElementRune.FUL, FormRune.IR);
            wuuf.cast(PowerRune.LO, ElementRune.FUL);
        }
    }

    Thread.sleep(10000);

    // Clock.getInstance().pause();
    //
    // Thread.sleep(500);
    //
    // Clock.getInstance().resume();
    //
    // Thread.sleep(500);

    Clock.getInstance().stop();

    if (log.isInfoEnabled()) {
        log.info("End");
    }
}

From source file:io.github.gsteckman.doorcontroller.INA219Util.java

/**
 * Reads the Current from the INA219 with an I2C address and for a duration specified on the command line.
 * /*from  ww  w  .j a  va 2  s.  c  o m*/
 * @param args
 *            Command line arguments.
 * @throws IOException
 *             If an error occurs reading/writing to the INA219
 * @throws ParseException
 *             If the command line arguments could not be parsed.
 */
public static void main(String[] args) throws IOException, ParseException {
    Options options = new Options();
    options.addOption("addr", true, "I2C Address");
    options.addOption("d", true, "Acquisition duration, in seconds");
    options.addOption("bv", false, "Also read bus voltage");
    options.addOption("sv", false, "Also read shunt voltage");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    Address addr = Address.ADDR_40;
    if (cmd.hasOption("addr")) {
        int opt = Integer.parseInt(cmd.getOptionValue("addr"), 16);
        Address a = Address.getAddress(opt);
        if (a != null) {
            addr = a;
        } else {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("INA219Util", options);
            return;
        }
    }

    int duration = 0;
    if (cmd.hasOption("d")) {
        String opt = cmd.getOptionValue("d");
        duration = Integer.parseInt(opt);
    } else {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("INA219Util", options);
        return;

    }

    boolean readBusVoltage = false;
    if (cmd.hasOption("bv")) {
        readBusVoltage = true;
    }

    boolean readShuntVoltage = false;
    if (cmd.hasOption("sv")) {
        readShuntVoltage = true;
    }

    INA219 i219 = new INA219(addr, 0.1, 3.2, INA219.Brng.V16, INA219.Pga.GAIN_8, INA219.Adc.BITS_12,
            INA219.Adc.SAMPLES_128);

    System.out.printf("Time\tCurrent");
    if (readBusVoltage) {
        System.out.printf("\tBus");
    }
    if (readShuntVoltage) {
        System.out.printf("\tShunt");
    }
    System.out.printf("\n");
    long start = System.currentTimeMillis();
    do {
        try {
            System.out.printf("%d\t%f", System.currentTimeMillis() - start, i219.getCurrent());
            if (readBusVoltage) {
                System.out.printf("\t%f", i219.getBusVoltage());
            }
            if (readShuntVoltage) {
                System.out.printf("\t%f", i219.getShuntVoltage());
            }
            System.out.printf("\n");
            Thread.sleep(100);
        } catch (IOException e) {
            LOG.error("Exception while reading I2C bus", e);
        } catch (InterruptedException e) {
            break;
        }
    } while (System.currentTimeMillis() - start < duration * 1000);
}

From source file:ca.brood.softlogger.Softlogger.java

public static void main(String[] args) {
    if (softlogger.configure(Softlogger.DEFAULT_CONFIG_FILE)) {
        softlogger.softloggerStart();/*from w w w .  j a  v a 2  s.co m*/
        try {
            Thread.sleep(600000);
        } catch (InterruptedException e) {
        }
        softlogger.softloggerStop();
        //Wait a second for the threads to quit before printing performance data
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
        ThreadPerformanceMonitor.printPerformanceData();
    } else {
        softlogger.log.fatal("Error loading config file: " + Softlogger.DEFAULT_CONFIG_FILE);
    }
    softlogger.log.info("All done");
}

From source file:GoogleImages.java

public static void main(String[] args) throws InterruptedException {
    String searchTerm = "s woman"; // term to search for (use spaces to separate terms)
    int offset = 40; // we can only 20 results at a time - use this to offset and get more!
    String fileSize = "50mp"; // specify file size in mexapixels (S/M/L not figured out yet)
    String source = null; // string to save raw HTML source code

    // format spaces in URL to avoid problems
    searchTerm = searchTerm.replaceAll(" ", "%20");

    // get Google image search HTML source code; mostly built from PhyloWidget example:
    // http://code.google.com/p/phylowidget/source/browse/trunk/PhyloWidget/src/org/phylowidget/render/images/ImageSearcher.java
    int offset2 = 0;
    Set urlsss = new HashSet<String>();
    while (offset2 < 600) {
        try {/*from  ww w . j  av  a2 s .com*/
            URL query = new URL("https://www.google.ru/search?start=" + offset2
                    + "&q=angry+woman&newwindow=1&client=opera&hs=bPE&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiAgcKozIfNAhWoHJoKHSb_AUoQ_AUIBygB&biw=1517&bih=731&dpr=0.9#imgrc=G_1tH3YOPcc8KM%3A");
            HttpURLConnection urlc = (HttpURLConnection) query.openConnection(); // start connection...
            urlc.setInstanceFollowRedirects(true);
            urlc.setRequestProperty("User-Agent", "");
            urlc.connect();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream())); // stream in HTTP source to file
            StringBuffer response = new StringBuffer();
            char[] buffer = new char[1024];
            while (true) {
                int charsRead = in.read(buffer);
                if (charsRead == -1) {
                    break;
                }
                response.append(buffer, 0, charsRead);
            }
            in.close(); // close input stream (also closes network connection)
            source = response.toString();
        } // any problems connecting? let us know
        catch (Exception e) {
            e.printStackTrace();
        }

        // print full source code (for debugging)
        // println(source);
        // extract image URLs only, starting with 'imgurl'
        if (source != null) {
            //                System.out.println(source);
            int c = StringUtils.countMatches(source, "http://www.vmir.su");
            System.out.println(c);
            int index = source.indexOf("src=");
            System.out.println(source.subSequence(index, index + 200));
            while (index >= 0) {
                System.out.println(index);
                index = source.indexOf("src=", index + 1);
                if (index == -1) {
                    break;
                }
                String rr = source.substring(index,
                        index + 200 > source.length() ? source.length() : index + 200);

                if (rr.contains("\"")) {
                    rr = rr.substring(5, rr.indexOf("\"", 5));
                }
                System.out.println(rr);
                urlsss.add(rr);
            }
        }
        offset2 += 20;
        Thread.sleep(1000);
        System.out.println("off set = " + offset2);

    }

    System.out.println(urlsss);
    urlsss.forEach(new Consumer<String>() {

        public void accept(String s) {
            try {
                saveImage(s, "C:\\Users\\Java\\Desktop\\ang\\" + UUID.randomUUID().toString() + ".jpg");
            } catch (IOException ex) {
                Logger.getLogger(GoogleImages.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
    //            String[][] m = matchAll(source, "img height=\"\\d+\" src=\"([^\"]+)\"");

    // older regex, no longer working but left for posterity
    // built partially from: http://www.mkyong.com/regular-expressions/how-to-validate-image-file-extension-with-regular-expression
    // String[][] m = matchAll(source, "imgurl=(.*?\\.(?i)(jpg|jpeg|png|gif|bmp|tif|tiff))");    // (?i) means case-insensitive
    //            for (int i = 0; i < m.length; i++) {                                                          // iterate all results of the match
    //                println(i + ":\t" + m[i][1]);                                                         // print (or store them)**
    //            }
}

From source file:it.cnr.isti.labse.glimpse.MainMonitoring.java

/**
 * Read the properties and init the connections to the enterprise service bus
 * /*from  www.  j a  v a  2 s.co  m*/
 * @param is the systemSettings file
 */
public static void main(String[] args) {
    try {
        FileOutputStream fos = new FileOutputStream("glimpseLog.log");
        PrintStream ps = new PrintStream(fos);
        System.setErr(ps);

        if (MainMonitoring.initProps(args[0]) && MainMonitoring.init()) {

            SplashScreen.Show();
            System.out.println("Please wait until setup is done...");
            //the buffer where the events are stored to be analyzed
            EventsBuffer<GlimpseBaseEvent<?>> buffer = new EventsBufferImpl<GlimpseBaseEvent<?>>();

            //The complex event engine that will be used (in this case drools)
            ComplexEventProcessor engine = new ComplexEventProcessorImpl(Manager.Read(MANAGERPARAMETERFILE),
                    buffer, connFact, initConn);
            engine.start();

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //the manager of all the architecture
            GlimpseManager manager = new GlimpseManager(Manager.Read(MANAGERPARAMETERFILE), connFact, initConn,
                    engine.getRuleManager());
            manager.start();
        }
    } catch (Exception e) {
        System.out.println("USAGE: java -jar MainMonitoring.jar \"systemSettings\"");
    }
}