Example usage for java.util.concurrent ScheduledExecutorService scheduleAtFixedRate

List of usage examples for java.util.concurrent ScheduledExecutorService scheduleAtFixedRate

Introduction

In this page you can find the example usage for java.util.concurrent ScheduledExecutorService scheduleAtFixedRate.

Prototype

public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);

Source Link

Document

Submits a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is, executions will commence after initialDelay , then initialDelay + period , then initialDelay + 2 * period , and so on.

Usage

From source file:Main.java

public static void main(String[] args) {
    // Get the scheduler
    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

    // Get a handle, starting now, with a 10 second delay
    final ScheduledFuture<?> timeHandle = scheduler.scheduleAtFixedRate(new TimePrinter(System.out), 0, 10,
            SECONDS);//from www .  j  ava2 s  . c o  m

    // Schedule the event, and run for 1 hour (60 * 60 seconds)
    scheduler.schedule(new Runnable() {
        public void run() {
            timeHandle.cancel(false);
        }
    }, 60 * 60, SECONDS);

    /**
     * On some platforms, you'll have to setup this infinite loop to see output
    while (true) { }
     */
}

From source file:example.ReceiveNumbers.java

/**
 * @param args// w w  w  .  ja  v  a  2s.  com
 * @throws MalformedURLException
 * @throws JSONException
 */
public static void main(String[] args) throws MalformedURLException, JSONException {
    // TODO Auto-generated method stub

    JSONObject previousSub = new JSONObject(
            "{'id':'test-java-666','desc':'test-java-666', 'subkey':'GPS-71454020-queu'}");

    MyAEONCallbacks myCallBack = new MyAEONCallbacks();
    final AEONSDK sdk = new AEONSDK(Config.SUB_URL, Config.YOUR_ID, Config.YOUR_DESC);
    //final AEONSDK sdk = new AEONSDK(Config.SUB_URL, previousSub);
    JSONObject subscription = sdk.subscribe(myCallBack);

    if (subscription == null) {
        System.out.println("Something went wrong I dont have a subscription");
        return;
    }
    System.out.println("subscription received " + subscription.toString());

    try {
        TimeUnit.SECONDS.sleep(3);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    /*   
          sdk.deleteSubscription();
                  
          System.out.println("Deleted subscription: if some one is publish in the channel you will lost it for ever.");
                  
          try {
             TimeUnit.SECONDS.sleep(3);
          } catch (InterruptedException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
          }
                  
          System.out.println("Ok, lets have another new subscription.");
                  
          subscription = sdk.subscribe(myCallBack);      */

    ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
    exec.scheduleAtFixedRate(new Runnable() {
        boolean paused = false;

        @Override
        public void run() {

            System.out.println("Ok lets make a little break of 5 seconds. After that the subscription"
                    + " will continue. And messages published while our break will be delivered inmediatly");
            if (!paused) {
                sdk.pauseSusbscription();
                paused = true;
            } else {
                sdk.continueSubscription();
                paused = false;
            }

        }
    }, 1, 5, TimeUnit.SECONDS);

}

From source file:org.sourcepit.consul.forwarder.Main.java

public static void main(String[] args) {

    final String dockerUri = "http://192.168.56.101:2375";
    final String consulUri = "http://192.168.56.101:8500";

    final int fetchConsulStateInterval = 30;
    final int fetchDockerStateInterval = 30;
    final int dispatchItemsInterval = 2;
    final int requestDockerStateDelay = 5;

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setDefaultMaxPerRoute(10);
    final HttpClient httpClient = HttpClients.createMinimal(connManager);

    final BlockingQueue<JsonObject> queue = new LinkedBlockingQueue<>();

    final FetchConsulStateCmd fetchConsulStateCmd = new FetchConsulStateCmd(httpClient, consulUri) {
        @Override/*  www. j a  va  2s.  c  om*/
        protected void doHandle(JsonObject consulState) {
            final JsonObject item = createItem("ConsulState", consulState);
            LOG.debug(item.toString());
            queue.add(item);
        }

    };

    final FetchDockerStateCmd fetchDockerStateCmd = new FetchDockerStateCmd(httpClient, dockerUri) {
        @Override
        protected void doHandle(JsonArray dockerState) {
            final JsonObject item = createItem("DockerState", dockerState);
            LOG.debug(item.toString());
            queue.add(item);
        }
    };

    final ConsulForwarderState forwarderState = new ConsulForwarderState();

    final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    scheduler.scheduleAtFixedRate(fetchConsulStateCmd, 0, fetchConsulStateInterval, TimeUnit.SECONDS);
    scheduler.scheduleAtFixedRate(fetchDockerStateCmd, 0, fetchDockerStateInterval, TimeUnit.SECONDS);
    scheduler.scheduleAtFixedRate(new DispatchItemsCmd(queue) {
        @Override
        protected void handleDockerState(JsonArray dockerState) {
            forwarderState.applyDockerState(dockerState);
        }

        @Override
        protected void handleDockerEvents(JsonArray dockerEvents) {
            // trigger docker state update
            scheduler.schedule(fetchDockerStateCmd, requestDockerStateDelay, TimeUnit.SECONDS);
        }

        @Override
        protected void handleConsulState(JsonObject consulState) {
            forwarderState.applyConsulState(consulState);
        }
    }, 0, dispatchItemsInterval, TimeUnit.SECONDS);

    final DockerEventObserver eventObserver = new DockerEventObserver(httpClient, dockerUri) {
        @Override
        protected void handle(JsonObject event) {
            queue.add(createItem("DockerEvent", event));
        }
    };

    final Thread eventObserverThread = new Thread(eventObserver, "Docker Event Observer") {
        @Override
        public void interrupt() {
            eventObserver.die();
            super.interrupt();
        }
    };
    eventObserverThread.start();
}

From source file:gobblin.restli.throttling.LocalStressTest.java

public static void main(String[] args) throws Exception {

    CommandLine cli = StressTestUtils.parseCommandLine(OPTIONS, args);

    int stressorThreads = Integer.parseInt(
            cli.getOptionValue(STRESSOR_THREADS.getOpt(), Integer.toString(DEFAULT_STRESSOR_THREADS)));
    int processorThreads = Integer.parseInt(
            cli.getOptionValue(PROCESSOR_THREADS.getOpt(), Integer.toString(DEFAULT_PROCESSOR_THREADS)));
    int artificialLatency = Integer.parseInt(
            cli.getOptionValue(ARTIFICIAL_LATENCY.getOpt(), Integer.toString(DEFAULT_ARTIFICIAL_LATENCY)));
    long targetQps = Integer.parseInt(cli.getOptionValue(QPS.getOpt(), Integer.toString(DEFAULT_TARGET_QPS)));

    Configuration configuration = new Configuration();
    StressTestUtils.populateConfigFromCli(configuration, cli);

    String resourceLimited = LocalStressTest.class.getSimpleName();

    Map<String, String> configMap = Maps.newHashMap();

    ThrottlingPolicyFactory factory = new ThrottlingPolicyFactory();
    SharedLimiterKey res1key = new SharedLimiterKey(resourceLimited);
    configMap.put(BrokerConfigurationKeyGenerator.generateKey(factory, res1key, null,
            ThrottlingPolicyFactory.POLICY_KEY), QPSPolicy.FACTORY_ALIAS);
    configMap.put(BrokerConfigurationKeyGenerator.generateKey(factory, res1key, null, QPSPolicy.QPS),
            Long.toString(targetQps));

    ThrottlingGuiceServletConfig guiceServletConfig = new ThrottlingGuiceServletConfig();
    guiceServletConfig.initialize(ConfigFactory.parseMap(configMap));
    LimiterServerResource limiterServer = guiceServletConfig.getInjector()
            .getInstance(LimiterServerResource.class);

    RateComputingLimiterContainer limiterContainer = new RateComputingLimiterContainer();

    Class<? extends Stressor> stressorClass = configuration.getClass(StressTestUtils.STRESSOR_CLASS,
            StressTestUtils.DEFAULT_STRESSOR_CLASS, Stressor.class);

    ExecutorService executorService = Executors.newFixedThreadPool(stressorThreads);

    SharedResourcesBroker broker = guiceServletConfig.getInjector().getInstance(
            Key.get(SharedResourcesBroker.class, Names.named(LimiterServerResource.BROKER_INJECT_NAME)));
    ThrottlingPolicy policy = (ThrottlingPolicy) broker.getSharedResource(new ThrottlingPolicyFactory(),
            new SharedLimiterKey(resourceLimited));
    ScheduledExecutorService reportingThread = Executors.newSingleThreadScheduledExecutor();
    reportingThread.scheduleAtFixedRate(new Reporter(limiterContainer, policy), 0, 15, TimeUnit.SECONDS);

    Queue<Future<?>> futures = new LinkedList<>();
    MockRequester requester = new MockRequester(limiterServer, artificialLatency, processorThreads);

    requester.start();//from   ww w .  j a v  a 2  s. co  m
    for (int i = 0; i < stressorThreads; i++) {
        RestliServiceBasedLimiter restliLimiter = RestliServiceBasedLimiter.builder()
                .resourceLimited(resourceLimited).requestSender(requester).serviceIdentifier("stressor" + i)
                .build();

        Stressor stressor = stressorClass.newInstance();
        stressor.configure(configuration);
        futures.add(executorService
                .submit(new StressorRunner(limiterContainer.decorateLimiter(restliLimiter), stressor)));
    }
    int stressorFailures = 0;
    for (Future<?> future : futures) {
        try {
            future.get();
        } catch (ExecutionException ee) {
            stressorFailures++;
        }
    }
    requester.stop();

    executorService.shutdownNow();

    if (stressorFailures > 0) {
        log.error("There were " + stressorFailures + " failed stressor threads.");
    }
    System.exit(stressorFailures);
}

From source file:ScheduledTask.java

public static void main(String[] args) {
    // Get an executor with 3 threads
    ScheduledExecutorService sexec = Executors.newScheduledThreadPool(3);

    ScheduledTask task1 = new ScheduledTask(1);
    ScheduledTask task2 = new ScheduledTask(2);

    // Task #1 will run after 2 seconds
    sexec.schedule(task1, 2, TimeUnit.SECONDS);

    // Task #2 runs after 5 seconds delay and keep running every 10 seconds
    sexec.scheduleAtFixedRate(task2, 5, 10, TimeUnit.SECONDS);

    try {// ww w.  ja  v  a  2 s.c  om
        TimeUnit.SECONDS.sleep(60);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    sexec.shutdown();
}

From source file:com.amazonaws.services.iot.demo.danbo.rpi.Danbo.java

public static void main(String[] args) throws Exception {
    log.debug("starting");

    // uses pin 6 for the red Led
    final Led redLed = new Led(6);
    // uses pin 26 for the green Led
    final Led greenLed = new Led(26);

    // turns the red led on initially
    redLed.on();//from  w  w  w.  ja  va  2 s  .  co  m

    // turns the green led off initially
    greenLed.off();

    // loads properties from danbo.properties file - make sure this file is
    // available on the pi's home directory
    InputStream input = new FileInputStream("/home/pi/danbo/danbo.properties");
    Properties properties = new Properties();
    properties.load(input);
    endpoint = properties.getProperty("awsiot.endpoint");
    rootCA = properties.getProperty("awsiot.rootCA");
    privateKey = properties.getProperty("awsiot.privateKey");
    certificate = properties.getProperty("awsiot.certificate");
    url = protocol + endpoint + ":" + port;

    log.debug("properties loaded");

    // turns off both eyes
    RGBLed rgbLed = new RGBLed("RGBLed1", Danbo.pinLayout1, Danbo.pinLayout2, new Color(0, 0, 0),
            new Color(0, 0, 0), 0, 100);
    new Thread(rgbLed).start();

    // resets servo to initial positon
    Servo servo = new Servo("Servo", 1);
    new Thread(servo).start();

    // gets the Pi serial number and uses it as part of the thing
    // registration name
    clientId = clientId + getSerialNumber();

    // AWS IoT things shadow topics
    updateTopic = "$aws/things/" + clientId + "/shadow/update";
    deltaTopic = "$aws/things/" + clientId + "/shadow/update/delta";
    rejectedTopic = "$aws/things/" + clientId + "/shadow/update/rejected";

    // AWS IoT controller things shadow topic (used to register new things)
    controllerUpdateTopic = "$aws/things/Controller/shadow/update";

    // defines an empty danbo shadow POJO
    final DanboShadow danboShadow = new DanboShadow();
    DanboShadow.State state = danboShadow.new State();
    final DanboShadow.State.Reported reported = state.new Reported();
    reported.setEyes("readyToBlink");
    reported.setHead("readyToMove");
    reported.setMouth("readyToSing");
    reported.setName(clientId);
    state.setReported(reported);
    danboShadow.setState(state);

    // defines an empty controller shadow POJO
    final ControllerShadow controllerShadow = new ControllerShadow();
    ControllerShadow.State controllerState = controllerShadow.new State();
    final ControllerShadow.State.Reported controllerReported = controllerState.new Reported();
    controllerReported.setThingName(clientId);
    controllerState.setReported(controllerReported);
    controllerShadow.setState(controllerState);

    try {
        log.debug("registering");

        // registers the thing (creates a new thing) by updating the
        // controller
        String message = gson.toJson(controllerShadow);
        MQTTPublisher controllerUpdatePublisher = new MQTTPublisher(controllerUpdateTopic, qos, message, url,
                clientId + "-controllerupdate" + rand.nextInt(100000), cleanSession, rootCA, privateKey,
                certificate);
        new Thread(controllerUpdatePublisher).start();

        log.debug("registered");

        // clears the thing status (in case the thing already existed)
        Danbo.deleteStatus("initialDelete");

        // creates an MQTT subscriber to the things shadow delta topic
        // (command execution notification)
        MQTTSubscriber deltaSubscriber = new MQTTSubscriber(new DanboShadowDeltaCallback(), deltaTopic, qos,
                url, clientId + "-delta" + rand.nextInt(100000), cleanSession, rootCA, privateKey, certificate);
        new Thread(deltaSubscriber).start();

        // creates an MQTT subscriber to the things shadow error topic
        MQTTSubscriber errorSubscriber = new MQTTSubscriber(new DanboShadowRejectedCallback(), rejectedTopic,
                qos, url, clientId + "-rejected" + rand.nextInt(100000), cleanSession, rootCA, privateKey,
                certificate);
        new Thread(errorSubscriber).start();

        // turns the red LED off
        redLed.off();

        ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
        exec.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                // turns the green LED on
                greenLed.on();

                log.debug("running publish state thread");

                int temp = -300;
                int humid = -300;

                reported.setTemperature(new Integer(temp).toString());
                reported.setHumidity(new Integer(humid).toString());

                try {
                    // reads the temperature and humidity data
                    Set<Sensor> sensors = Sensors.getSensors();
                    log.debug(sensors.size());

                    for (Sensor sensor : sensors) {
                        log.debug(sensor.getPhysicalQuantity());
                        log.debug(sensor.getValue());
                        if (sensor.getPhysicalQuantity().toString().equals("Temperature")) {
                            temp = sensor.getValue().intValue();
                        }
                        if (sensor.getPhysicalQuantity().toString().equals("Humidity")) {
                            humid = sensor.getValue().intValue();
                        }
                    }

                    log.debug("temperature: " + temp);
                    log.debug("humidity: " + humid);
                    reported.setTemperature(new Integer(temp).toString());
                    reported.setHumidity(new Integer(humid).toString());
                } catch (Exception e) {
                    log.error("an error has ocurred: " + e.getMessage());
                    e.printStackTrace();
                }

                try {
                    // reports current state - last temperature and humidity
                    // read
                    String message = gson.toJson(danboShadow);
                    MQTTPublisher updatePublisher = new MQTTPublisher(updateTopic, qos, message, url,
                            clientId + "-update" + rand.nextInt(100000), cleanSession, rootCA, privateKey,
                            certificate);
                    new Thread(updatePublisher).start();
                } catch (Exception e) {
                    log.error("an error has ocurred: " + e.getMessage());
                    e.printStackTrace();
                }

                // turns the green LED off
                greenLed.off();
            }
        }, 0, 5, TimeUnit.SECONDS); // runs this thread every 5 seconds,
        // with an initial delay of 5 seconds
    } catch (MqttException me) {
        // Display full details of any exception that occurs
        log.error("reason " + me.getReasonCode());
        log.error("msg " + me.getMessage());
        log.error("loc " + me.getLocalizedMessage());
        log.error("cause " + me.getCause());
        log.error("excep " + me);
        me.printStackTrace();
    } catch (Throwable th) {
        log.error("msg " + th.getMessage());
        log.error("loc " + th.getLocalizedMessage());
        log.error("cause " + th.getCause());
        log.error("excep " + th);
        th.printStackTrace();
    }
}

From source file:com.mch.registry.ccs.server.CcsClient.java

/**
 * Sends messages to registered devices/*from www .ja  va  2 s  .c  o m*/
 */
public static void main(String[] args) {

    Config config = new Config();
    final String projectId = config.getProjectId();
    final String key = config.getKey();

    final CcsClient ccsClient = CcsClient.prepareClient(projectId, key, true);

    try {
        ccsClient.connect();
    } catch (XMPPException e) {
        logger.log(Level.WARNING, "XMPP Exception ", e);
    }

    final Runnable sendNotifications = new Runnable() {
        public void run() {
            try {
                logger.log(Level.INFO, "Working Q!");
                if (!isOffHours()) {
                    //Prepare downstream message
                    String toRegId = "";
                    String message = "";
                    String messageId = "";
                    Map<String, String> payload = new HashMap<String, String>();
                    String collapseKey = null;
                    Long timeToLive = 10000L;
                    Boolean delayWhileIdle = true;
                    String messagePrefix = "";
                    int notificationQueueID = 0;
                    boolean sucessfullySent = false;

                    //Read from mysql database
                    MySqlHandler mysql = new MySqlHandler();
                    ArrayList<Notification> queue = new ArrayList<Notification>();

                    for (int i = 1; i < 3; i++) {
                        queue = mysql.getNotificationQueue(i);
                        if (queue.size() > 0) {

                            switch (i) {
                            case 1:
                                messagePrefix = "_V: ";
                                break;
                            case 2:
                                messagePrefix = "_R: ";
                                break;
                            default:
                                messagePrefix = "";
                                logger.log(Level.WARNING, "Unknown message type!");
                            }

                            Notification notification = new Notification();
                            Iterator<Notification> iterator = queue.iterator();

                            while (iterator.hasNext()) {
                                notification = iterator.next();

                                toRegId = notification.getGcmRegID();
                                message = notification.getNotificationText();
                                notificationQueueID = notification.getNotificationQueueID();
                                messageId = "m-" + Long.toString(random.nextLong());

                                payload = new HashMap<String, String>();
                                payload.put("message", messagePrefix + message);

                                try {
                                    // Send the downstream message to a device.
                                    ccsClient.send(createJsonMessage(toRegId, messageId, payload, collapseKey,
                                            timeToLive, delayWhileIdle));
                                    sucessfullySent = true;
                                    logger.log(Level.INFO, "Message sent. ID: " + notificationQueueID
                                            + ", RegID: " + toRegId + ", Text: " + message);
                                } catch (Exception e) {
                                    mysql.prepareNotificationForTheNextDay(notificationQueueID);
                                    sucessfullySent = false;
                                    logger.log(Level.WARNING,
                                            "Message could not be sent! ID: " + notificationQueueID
                                                    + ", RegID: " + toRegId + ", Text: " + message);
                                }

                                if (sucessfullySent) {
                                    mysql.moveNotificationToHistory(notificationQueueID);
                                }
                            }
                        } else {
                            logger.log(Level.INFO, "No notifications to send. Type: " + Integer.toString(i));
                        }
                    }
                }
            } catch (Exception e) {
                logger.log(Level.WARNING, "Exception ", e);
            }
        }
    };

    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    //Start when server starts and every 30 minutes after
    ScheduledFuture task = executor.scheduleAtFixedRate(sendNotifications, 0, 30, TimeUnit.MINUTES);
    try {
        task.get();
    } catch (ExecutionException e) {
        logger.log(Level.SEVERE, "Exception ", e);
    } catch (InterruptedException e) {
        logger.log(Level.SEVERE, "Exception ", e);
    }
    task.cancel(false);

    try {
        executor.shutdown();
        executor.awaitTermination(30, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        logger.log(Level.SEVERE, "Exception ", e);
    }

}

From source file:com.mapr.synth.Synth.java

public static void main(String[] args)
        throws IOException, CmdLineException, InterruptedException, ExecutionException {
    final Options opts = new Options();
    CmdLineParser parser = new CmdLineParser(opts);
    try {/*from   w  w  w .  j  a va2 s  .  c o m*/
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println("Usage: " + "[ -count <number>G|M|K ] " + "-schema schema-file "
                + "[-quote DOUBLE_QUOTE|BACK_SLASH|OPTIMISTIC] " + "[-format JSON|TSV|CSV|XML ] "
                + "[-threads n] " + "[-output output-directory-name] ");
        throw e;
    }
    Preconditions.checkArgument(opts.threads > 0 && opts.threads <= 2000,
            "Must have at least one thread and no more than 2000");

    if (opts.threads > 1) {
        Preconditions.checkArgument(!"-".equals(opts.output),
                "If more than on thread is used, you have to use -output to set the output directory");
    }

    File outputDir = new File(opts.output);
    if (!"-".equals(opts.output)) {
        if (!outputDir.exists()) {
            Preconditions.checkState(outputDir.mkdirs(),
                    String.format("Couldn't create output directory %s", opts.output));
        }
        Preconditions.checkArgument(outputDir.exists() && outputDir.isDirectory(),
                String.format("Couldn't create directory %s", opts.output));
    }

    if (opts.schema == null) {
        throw new IllegalArgumentException("Must specify schema file using [-schema filename] option");
    }
    final SchemaSampler sampler = new SchemaSampler(opts.schema);
    final AtomicLong rowCount = new AtomicLong();

    final List<ReportingWorker> tasks = Lists.newArrayList();
    int limit = (opts.count + opts.threads - 1) / opts.threads;
    int remaining = opts.count;
    for (int i = 0; i < opts.threads; i++) {

        final int count = Math.min(limit, remaining);
        remaining -= count;

        tasks.add(new ReportingWorker(opts, sampler, rowCount, count, i));
    }

    final double t0 = System.nanoTime() * 1e-9;
    ExecutorService pool = Executors.newFixedThreadPool(opts.threads);
    ScheduledExecutorService blinker = Executors.newScheduledThreadPool(1);
    final AtomicBoolean finalRun = new AtomicBoolean(false);

    final PrintStream sideLog = new PrintStream(new FileOutputStream("side-log"));
    Runnable blink = new Runnable() {
        public double oldT;
        private long oldN;

        @Override
        public void run() {
            double t = System.nanoTime() * 1e-9;
            long n = rowCount.get();
            System.err.printf("%s\t%d\t%.1f\t%d\t%.1f\t%.3f\n", finalRun.get() ? "F" : "R", opts.threads,
                    t - t0, n, n / (t - t0), (n - oldN) / (t - oldT));
            for (ReportingWorker task : tasks) {
                ReportingWorker.ThreadReport r = task.report();
                sideLog.printf("\t%d\t%.2f\t%.2f\t%.2f\t%.1f\t%.1f\n", r.fileNumber, r.threadTime, r.userTime,
                        r.wallTime, r.rows / r.threadTime, r.rows / r.wallTime);
            }
            oldN = n;
            oldT = t;
        }
    };
    if (!"-".equals(opts.output)) {
        blinker.scheduleAtFixedRate(blink, 0, 10, TimeUnit.SECONDS);
    }
    List<Future<Integer>> results = pool.invokeAll(tasks);

    int total = 0;
    for (Future<Integer> result : results) {
        total += result.get();
    }
    Preconditions.checkState(total == opts.count, String
            .format("Expected to generate %d lines of output, but actually generated %d", opts.count, total));
    pool.shutdownNow();
    blinker.shutdownNow();
    finalRun.set(true);
    sideLog.close();
    blink.run();
}

From source file:com.web.server.WebServer.java

/**
 * This is the start of the all the services in web server
 * @param args//w  w w  .j  a  v a2s.c o  m
 * @throws IOException 
 * @throws SAXException 
 */
public static void main(String[] args) throws IOException, SAXException {

    Hashtable urlClassLoaderMap = new Hashtable();
    Hashtable executorServicesMap = new Hashtable();
    Hashtable ataMap = new Hashtable<String, ATAConfig>();
    Hashtable messagingClassMap = new Hashtable();
    ConcurrentHashMap servletMapping = new ConcurrentHashMap();
    DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

        protected void loadRules() {
            // TODO Auto-generated method stub
            try {
                loadXMLRules(new InputSource(new FileInputStream("./config/serverconfig-rules.xml")));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });
    Digester serverdigester = serverdigesterLoader.newDigester();
    final ServerConfig serverconfig = (ServerConfig) serverdigester
            .parse(new InputSource(new FileInputStream("./config/serverconfig.xml")));
    DigesterLoader messagingdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

        protected void loadRules() {
            // TODO Auto-generated method stub
            try {
                loadXMLRules(new InputSource(new FileInputStream("./config/messagingconfig-rules.xml")));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });
    Digester messagingdigester = messagingdigesterLoader.newDigester();
    MessagingElem messagingconfig = (MessagingElem) messagingdigester
            .parse(new InputSource(new FileInputStream("./config/messaging.xml")));
    //System.out.println(messagingconfig);
    ////System.out.println(serverconfig.getDeploydirectory());
    PropertyConfigurator.configure("log4j.properties");
    /*MemcachedClient cache=new MemcachedClient(
        new InetSocketAddress("localhost", 1000));*/

    // Store a value (async) for one hour
    //c.set("someKey", 36, new String("arun"));
    // Retrieve a value.        
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
    System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
    ExecutorService executor = java.util.concurrent.Executors.newCachedThreadPool();

    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    ObjectName name = null;
    try {
        name = new ObjectName("com.web.server:type=WarDeployer");
    } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    WarDeployer warDeployer = new WarDeployer(serverconfig.getDeploydirectory(), serverconfig.getFarmWarDir(),
            serverconfig.getClustergroup(), urlClassLoaderMap, executorServicesMap, messagingClassMap,
            servletMapping, messagingconfig, sessionObjects);
    warDeployer.setPriority(MIN_PRIORITY);
    try {
        mbs.registerMBean(warDeployer, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    //warDeployer.start();
    executor.execute(warDeployer);

    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

    serverSocketChannel.bind(new InetSocketAddress("0.0.0.0", Integer.parseInt(serverconfig.getPort())));

    serverSocketChannel.configureBlocking(false);

    final byte[] shutdownBt = new byte[50];
    WebServerRequestProcessor webserverRequestProcessor = new WebServer().new WebServerRequestProcessor(
            servletMapping, urlClassLoaderMap, serverSocketChannel, serverconfig.getDeploydirectory(),
            Integer.parseInt(serverconfig.getShutdownport()), 1);
    webserverRequestProcessor.setPriority(MIN_PRIORITY);
    try {
        name = new ObjectName("com.web.server:type=WebServerRequestProcessor");
    } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        mbs.registerMBean(webserverRequestProcessor, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    //webserverRequestProcessor.start();
    executor.execute(webserverRequestProcessor);

    for (int i = 0; i < 10; i++) {
        WebServerRequestProcessor webserverRequestProcessor1 = new WebServer().new WebServerRequestProcessor(
                servletMapping, urlClassLoaderMap, serverSocketChannel, serverconfig.getDeploydirectory(),
                Integer.parseInt(serverconfig.getShutdownport()), 2);
        webserverRequestProcessor1.setPriority(MIN_PRIORITY);
        try {
            name = new ObjectName("com.web.server:type=WebServerRequestProcessor" + (i + 1));
        } catch (MalformedObjectNameException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        try {
            mbs.registerMBean(webserverRequestProcessor1, name);
        } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        executor.execute(webserverRequestProcessor1);
    }

    ServerSocketChannel serverSocketChannelServices = ServerSocketChannel.open();

    serverSocketChannelServices
            .bind(new InetSocketAddress("0.0.0.0", Integer.parseInt(serverconfig.getServicesport())));

    serverSocketChannelServices.configureBlocking(false);

    ExecutorServiceThread executorService = new ExecutorServiceThread(serverSocketChannelServices,
            executorServicesMap, Integer.parseInt(serverconfig.getShutdownport()), ataMap, urlClassLoaderMap,
            serverconfig.getDeploydirectory(), serverconfig.getServicesdirectory(),
            serverconfig.getEarservicesdirectory(), serverconfig.getNodesport());

    try {
        name = new ObjectName("com.web.services:type=ExecutorServiceThread");
    } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        mbs.registerMBean(executorService, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    //executorService.start();
    executor.execute(executorService);

    for (int i = 0; i < 10; i++) {
        ExecutorServiceThread executorService1 = new ExecutorServiceThread(serverSocketChannelServices,
                executorServicesMap, Integer.parseInt(serverconfig.getShutdownport()), ataMap,
                urlClassLoaderMap, serverconfig.getDeploydirectory(), serverconfig.getServicesdirectory(),
                serverconfig.getEarservicesdirectory(), serverconfig.getNodesport());

        try {
            name = new ObjectName("com.web.services:type=ExecutorServiceThread" + (i + 1));
        } catch (MalformedObjectNameException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        try {
            mbs.registerMBean(executorService1, name);
        } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        executor.execute(executorService1);
    }

    WebServerHttpsRequestProcessor webserverHttpsRequestProcessor = new WebServer().new WebServerHttpsRequestProcessor(
            servletMapping, urlClassLoaderMap, Integer.parseInt(serverconfig.getHttpsport()),
            serverconfig.getDeploydirectory(), Integer.parseInt(serverconfig.getShutdownport()),
            serverconfig.getHttpscertificatepath(), serverconfig.getHttpscertificatepasscode(), 1);
    try {
        name = new ObjectName("com.web.server:type=WebServerHttpsRequestProcessor");
    } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        mbs.registerMBean(webserverHttpsRequestProcessor, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    webserverHttpsRequestProcessor.setPriority(MAX_PRIORITY);
    //webserverRequestProcessor.start();
    executor.execute(webserverHttpsRequestProcessor);

    /* for(int i=0;i<2;i++){
        webserverHttpsRequestProcessor=new WebServer().new WebServerHttpsRequestProcessor(urlClassLoaderMap,Integer.parseInt(serverconfig.getHttpsport())+(i+1),serverconfig.getDeploydirectory(),Integer.parseInt(serverconfig.getShutdownport()),serverconfig.getHttpscertificatepath(),serverconfig.getHttpscertificatepasscode(),1);
              
      try {
    name = new ObjectName("com.web.server:type=WebServerHttpsRequestProcessor"+(i+1));
      } catch (MalformedObjectNameException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
      } 
              
      try {
    mbs.registerMBean(webserverHttpsRequestProcessor, name);
      } catch (InstanceAlreadyExistsException | MBeanRegistrationException
       | NotCompliantMBeanException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
      }
              
      executor.execute(webserverHttpsRequestProcessor);
    }*/

    /*ATAServer ataServer=new ATAServer(serverconfig.getAtaaddress(),serverconfig.getAtaport(),ataMap);
            
    try {
       name = new ObjectName("com.web.services:type=ATAServer");
    } catch (MalformedObjectNameException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } 
            
    try {
       mbs.registerMBean(ataServer, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException
    | NotCompliantMBeanException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    }
            
            
    ataServer.start();*/

    /*ATAConfigClient ataClient=new ATAConfigClient(serverconfig.getAtaaddress(),serverconfig.getAtaport(),serverconfig.getServicesport(),executorServicesMap);
            
    try {
       name = new ObjectName("com.web.services:type=ATAConfigClient");
    } catch (MalformedObjectNameException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } 
            
    try {
       mbs.registerMBean(ataClient, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException
    | NotCompliantMBeanException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    }
    ataClient.start();*/

    MessagingServer messageServer = new MessagingServer(serverconfig.getMessageport(), messagingClassMap);

    try {
        name = new ObjectName("com.web.messaging:type=MessagingServer");
    } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        mbs.registerMBean(messageServer, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    //messageServer.start();
    executor.execute(messageServer);

    RandomQueueMessagePicker randomqueuemessagepicker = new RandomQueueMessagePicker(messagingClassMap);

    try {
        name = new ObjectName("com.web.messaging:type=RandomQueueMessagePicker");
    } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        mbs.registerMBean(randomqueuemessagepicker, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    //randomqueuemessagepicker.start();
    executor.execute(randomqueuemessagepicker);

    RoundRobinQueueMessagePicker roundrobinqueuemessagepicker = new RoundRobinQueueMessagePicker(
            messagingClassMap);

    try {
        name = new ObjectName("com.web.messaging:type=RoundRobinQueueMessagePicker");
    } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        mbs.registerMBean(roundrobinqueuemessagepicker, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    //roundrobinqueuemessagepicker.start();
    executor.execute(roundrobinqueuemessagepicker);

    TopicMessagePicker topicpicker = new TopicMessagePicker(messagingClassMap);

    try {
        name = new ObjectName("com.web.messaging:type=TopicMessagePicker");
    } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        mbs.registerMBean(topicpicker, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    //topicpicker.start();
    executor.execute(topicpicker);

    try {
        name = new ObjectName("com.web.server:type=SARDeployer");
    } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    SARDeployer sarDeployer = SARDeployer.newInstance(serverconfig.getDeploydirectory());
    try {
        mbs.registerMBean(sarDeployer, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    executor.execute(sarDeployer);
    /*try {
       mbs.invoke(name, "startDeployer", null, null);
    } catch (InstanceNotFoundException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } catch (ReflectionException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } catch (MBeanException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    }
    */
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
    System.setProperty(Context.PROVIDER_URL, "rmi://localhost:" + serverconfig.getServicesregistryport());
    ;
    Registry registry = LocateRegistry.createRegistry(Integer.parseInt(serverconfig.getServicesregistryport()));

    /*JarDeployer jarDeployer=new JarDeployer(registry,serverconfig.getServicesdirectory(), serverconfig.getServiceslibdirectory(),serverconfig.getCachedir(),executorServicesMap, urlClassLoaderMap);
    try {
       name = new ObjectName("com.web.server:type=JarDeployer");
    } catch (MalformedObjectNameException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } 
            
    try {
       mbs.registerMBean(jarDeployer, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException
    | NotCompliantMBeanException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    }
            
    //jarDeployer.start();
    executor.execute(jarDeployer);*/

    EARDeployer earDeployer = new EARDeployer(registry, serverconfig.getEarservicesdirectory(),
            serverconfig.getDeploydirectory(), executorServicesMap, urlClassLoaderMap,
            serverconfig.getCachedir(), warDeployer);
    try {
        name = new ObjectName("com.web.server:type=EARDeployer");
    } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        mbs.registerMBean(earDeployer, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    //earDeployer.start();
    executor.execute(earDeployer);

    JVMConsole jvmConsole = new JVMConsole(Integer.parseInt(serverconfig.getJvmConsolePort()));

    try {
        name = new ObjectName("com.web.server:type=JVMConsole");
    } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        mbs.registerMBean(jvmConsole, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    executor.execute(jvmConsole);

    ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
    XMLDeploymentScanner xmlDeploymentScanner = new XMLDeploymentScanner(serverconfig.getDeploydirectory(),
            serverconfig.getServiceslibdirectory());
    exec.scheduleAtFixedRate(xmlDeploymentScanner, 0, 1000, TimeUnit.MILLISECONDS);

    EmbeddedJMS embeddedJMS = null;
    try {
        embeddedJMS = new EmbeddedJMS();
        embeddedJMS.start();
    } catch (Exception ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace();
    }

    EJBDeployer ejbDeployer = new EJBDeployer(serverconfig.getServicesdirectory(), registry,
            Integer.parseInt(serverconfig.getServicesregistryport()), embeddedJMS);
    try {
        name = new ObjectName("com.web.server:type=EJBDeployer");
    } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        mbs.registerMBean(ejbDeployer, name);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    //jarDeployer.start();
    executor.execute(ejbDeployer);

    new Thread() {
        public void run() {
            try {
                ServerSocket serverSocket = new ServerSocket(Integer.parseInt(serverconfig.getShutdownport()));
                while (true) {
                    Socket sock = serverSocket.accept();
                    InputStream istream = sock.getInputStream();
                    istream.read(shutdownBt);
                    String shutdownStr = new String(shutdownBt);
                    String[] shutdownToken = shutdownStr.split("\r\n\r\n");
                    //System.out.println(shutdownStr);
                    if (shutdownToken[0].startsWith("shutdown WebServer")) {
                        synchronized (shutDownObject) {
                            shutDownObject.notifyAll();
                        }
                    }
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }.start();

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        public void run() {
            System.out.println("IN shutdown Hook");
            synchronized (shutDownObject) {
                shutDownObject.notifyAll();
            }
        }
    }));
    try {
        synchronized (shutDownObject) {
            shutDownObject.wait();
        }
        executor.shutdownNow();
        serverSocketChannel.close();
        serverSocketChannelServices.close();
        embeddedJMS.stop();

    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    System.out.println("IN shutdown Hook1");
    /*try{
       Thread.sleep(10000);
    }
    catch(Exception ex){
               
    }*/

    //webserverRequestProcessor.stop();
    //webserverRequestProcessor1.stop();

    /*warDeployer.stop();
    executorService.stop();
    //ataServer.stop();
    //ataClient.stop();
    messageServer.stop();
    randomqueuemessagepicker.stop();
    roundrobinqueuemessagepicker.stop();
    topicpicker.stop();*/
    /*try {
       mbs.invoke(new ObjectName("com.web.server:type=SARDeployer"), "destroyDeployer", null, null);
    } catch (InstanceNotFoundException | MalformedObjectNameException
    | ReflectionException | MBeanException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
    }*/
    //earDeployer.stop();
    System.exit(0);
}

From source file:Main.java

public static void newScheduledThreadPoolAtFixedRate(Runnable runnable, long delayTime, long period, int size) {
    ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(size);
    scheduledThreadPool.scheduleAtFixedRate(runnable, delayTime, period, TimeUnit.SECONDS);
}