Example usage for org.joda.time DateTime now

List of usage examples for org.joda.time DateTime now

Introduction

In this page you can find the example usage for org.joda.time DateTime now.

Prototype

public static DateTime now() 

Source Link

Document

Obtains a DateTime set to the current system millisecond time using ISOChronology in the default time zone.

Usage

From source file:com.almende.demo.conferenceApp.ConferenceAgent.java

License:Apache License

public void refresh() {
    DetectionUtil.getInstance().startScan();
    getScheduler().schedule(this.getRpc().buildMsg("refresh", null, null), DateTime.now().plus(60000));
}

From source file:com.almende.demo.conferenceApp.ConferenceAgent.java

License:Apache License

/**
 * On event async.//from ww w  .j a v  a2 s . c o  m
 * 
 * @param event
 *            the event
 */
public void onEventAsync(final StateEvent event) {
    if (event.getValue().equals("scanRes")) {
        System.err.println("Checking:" + event.getId());
        String id = event.getId();

        if (getState() != null) {
            if (!getState().containsKey(CONTACTKEY.getKey())) {
                getState().put(CONTACTKEY.getKey(), new HashMap<String, Info>());
            }
            HashMap<String, Info> contacts = getState().get(CONTACTKEY);
            Info info = contacts.get(id);
            if (info == null) {
                info = new Info(id);
            }
            info.setLastSeen(DateTime.now());
            contacts.put(id, info);
            getState().put(CONTACTKEY.getKey(), contacts);
            EventBus.getDefault().post(new StateEvent(getId(), "listUpdated"));

            check(id, info);
        }
    } else if (event.getValue().equals("settingsUpdated")) {
        reconnect();
        sendMyInfo();
    }
}

From source file:com.almende.demo.conferenceCloud.ConferenceCloudAgent.java

License:Apache License

/**
 * Gets the my info.//  www .j  a va 2  s  .c o  m
 * 
 * @return the my info
 */
public Info getMyInfo() {

    if (myInfo != null && lastUpdate != null && lastUpdate.plus(300000).isAfterNow()) {
        return myInfo;
    }
    final ObjectNode params = JOM.createObjectNode();
    final SyncCallback<Info> callback = new SyncCallback<Info>() {
    };
    try {
        caller.call(new URI(WSCLIENTURL + getId()), "getMyInfo", params, callback);
        myInfo = myInfo.merge(callback.get());
        lastUpdate = DateTime.now();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return myInfo;
}

From source file:com.almende.demo.conferenceCloud.ConferenceCloudAgent.java

License:Apache License

/**
 * Sets the my info./*  ww w .j  a v a 2 s  .co m*/
 * 
 * @param myInfo
 *            the new my info
 */
public void setMyInfo(final @Name("info") Info myInfo) {
    System.err.println("Updating myInfo:" + myInfo);
    this.myInfo = myInfo;
    this.lastUpdate = DateTime.now();
}

From source file:com.almende.demo.tuneswarm.ConductorAgent.java

License:Apache License

/**
 * Inits the Conference Cloud Agent./* w  w  w  . ja va  2 s  . c o m*/
 */
public void init() {
    String host;
    try {
        host = getHostAddress() + ":8082";
    } catch (SocketException e) {
        LOG.warning("Couldn't determine ipaddress, defaulting to 10.10.1.105");
        host = "10.10.1.105:8082";
    }
    final String id = "conductor";
    final AgentConfig config = new AgentConfig(id);

    final ArrayNode transports = JOM.createArrayNode();
    final WebsocketTransportConfig serverConfig = new WebsocketTransportConfig();
    serverConfig.setId("conductor");
    serverConfig.setServer(true);
    serverConfig.setAddress("ws://" + host + "/ws/" + id);
    serverConfig.setServletLauncher("JettyLauncher");
    final ObjectNode jettyParms = JOM.createObjectNode();
    jettyParms.put("port", 8082);
    serverConfig.set("jetty", jettyParms);
    transports.add(serverConfig);

    final HttpTransportConfig debugConfig = new HttpTransportConfig();
    debugConfig.setId("conductor");
    debugConfig.setDoAuthentication(false);
    debugConfig.setServletUrl("http://" + host + "/www/");
    debugConfig.setServletClass("com.almende.eve.transport.http.DebugServlet");
    debugConfig.setServletLauncher("JettyLauncher");
    debugConfig.set("jetty", jettyParms);
    transports.add(debugConfig);

    config.setTransport(transports);

    final SyncSchedulerConfig schedulerConfig = new SyncSchedulerConfig();
    config.setScheduler(schedulerConfig);

    setConfig(config);

    final SyncScheduler scheduler = (SyncScheduler) getScheduler();
    scheduler.setCaller(caller);
    LOG.warning("Started Conductor at:" + host);

    schedule("pingAgents", JOM.createObjectNode(), DateTime.now().plus(10000));
}

From source file:com.almende.demo.tuneswarm.ConductorAgent.java

License:Apache License

/**
 * Ping agents.//w  w  w.j  a v  a 2s. co m
 */
public void pingAgents() {
    for (final ToneAgent agent : agents2.values()) {
        try {
            caller.call(agent.address, "ping", null, new AsyncCallback<Long>() {

                @Override
                public void onSuccess(Long result) {
                    // GOOD, nothing to do!
                    agent.offline = false;
                }

                @Override
                public void onFailure(Exception exception) {
                    // Oops, disable agent in list
                    agent.offline = true;
                }
            });
        } catch (IOException e) {
            agent.offline = true;
        }
    }
    onAgentsChange();
    schedule("pingAgents", JOM.createObjectNode(), DateTime.now().plus(10000));
}

From source file:com.almende.dsol.example.datacenters.FederationModelSimulationGUI.java

License:Apache License

private void simStart() {
    this.startButton.setText("Running");

    disableGUI(true);/*w  w  w.  j  av a2s .  co  m*/
    doChartUpdate(this.sac.getData());

    // clear current indicators and chart series data
    Datacenter.ID_COUNT = 0;
    synchronized (this.sac.getData()) {
        this.sac.getData().clear();
        this.indicators.clear();
    }

    this.model = new FederationModel(FEDERATION_SIZE, !AllocationPolicy.LOCAL.equals(policySelect.getValue()),
            AllocationPolicy.BROKERED.equals(policySelect.getValue()));

    // listen for new data centers to synchronize update graph time series
    this.model.addListener(new EventListenerInterface() {

        @Override
        public void notify(final EventInterface event) throws RemoteException {
            final Datacenter dc = (Datacenter) event.getContent();

            setupSeries(chooseIndicator(dc));
        }
    }, FederationModelComponent.NEW_DC);

    this.endReport = false;
    try {

        LOG.trace("Replication initializing...");
        final DEVSSimulatorInterface sim = new DEVSSimulator();
        final Context ctx = new InitialContext();
        final short mode = Treatment.REPLICATION_MODE_TERMINATING;
        final Experiment exp = new Experiment(ctx.createSubcontext("/exp"));
        final TimeUnitInterface timeUnit = TimeUnitInterface.DAY;

        exp.setSimulator(sim);
        exp.setModel(this.model);
        exp.setAnalyst("A4G");
        exp.setDescription("WP5 Phase 2");
        exp.setTreatment(new Treatment(exp, mode));
        exp.getTreatment().setStartTime(DateTime.now().withDayOfMonth(1).withTimeAtStartOfDay().getMillis());
        exp.getTreatment().setTimeUnit(timeUnit);
        exp.getTreatment().setWarmupPeriod(Double.valueOf(this.warmUpField.getText()));
        exp.getTreatment().setRunLength(Double.valueOf(this.lengthField.getText()) + .000001);
        final Replication repl = new Replication(exp.getContext().createSubcontext("/rep"), exp);
        final long seed = Long.valueOf(this.seedStartField.getText());
        this.seedStartField.setText(Long.toString(seed + 1));
        repl.setStreams(
                Collections.singletonMap(FederationModel.RNG_ID, (StreamInterface) new MersenneTwister()));
        sim.initialize(repl, mode);

        // start statistics flow to listen and draw
        scheduleStats(Duration.ZERO);

        ((NumberAxis) this.sac.getXAxis()).setLowerBound(sim.getReplication().getTreatment().getWarmupPeriod());
        ((NumberAxis) this.sac.getXAxis()).setUpperBound(sim.getReplication().getTreatment().getRunLength());

        // listen for simulation start/resume
        sim.addListener(new EventListenerInterface() {
            @Override
            public void notify(final EventInterface event) {
                LOG.trace("Sim started/resumed, t= " + model.getDateTime());
            }
        }, Simulator.START_EVENT);

        // listen for simulation ended
        sim.addListener(new EventListenerInterface() {
            @Override
            public void notify(final EventInterface event) {
                simEnded();
            }
        }, Simulator.END_OF_REPLICATION_EVENT);

        LOG.trace("Replication initialized, starting...");
        sim.start();
    } catch (final Exception e) {
        LOG.error("Problem reaching/starting sim", e);
    }
}

From source file:com.almende.dsol.example.datacenters.FederationModelSimulationGUI.java

License:Apache License

private void simEnded() {
    if (this.endReport)
        return;/*www  .j  a v a  2  s  . c o m*/
    this.endReport = true;

    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            startButton.setText("Complete");
        }
    });

    // trigger chart update to empty current data point cache
    // synchronized (this.newData) {
    // this.newData.notifyAll();
    // }

    LOG.trace("Sim ended, t= " + this.model.getDateTime());
    double fedCash = 0.0d, fedConsKWh = 0.0d, fedEmitCO2 = 0.0d;
    int fedAdapt = 0, fedSvcCount = 0, fedXchCount = 0;
    for (Datacenter dc : this.model.getDatacenters()) {
        fedAdapt += dc.adaptionHours.getValue().intValue();
        fedCash += dc.getCashflow().getValue().doubleValue();
        fedConsKWh += dc.getConsumptionKWh().getValue().doubleValue();
        fedEmitCO2 += dc.getEmissionsKgCO2().getValue().doubleValue();
        fedSvcCount += dc.getTotalServiceCount().getValue().intValue();
        fedXchCount += dc.exchangedServiceCount.getValue().intValue();
    }
    LOG.trace(String.format(
            "Federation report:%n" + "\tAllocation:                 \t%7s%n"
                    + "\tSimulation seed:            \t%7d%n" + "\tDuration (days):            \t%7d%n"
                    + "\tFederated datacenters:      \t%7d%n" + "\tAdaptions (hours):          \t%7d%n"
                    + "\tTotal cash generated (EUR): \t%10.2f%n" + "\tTotal energy consumed (MWh):\t%11.3f%n"
                    + "\tTotal CO2 emitted (kg):     \t%11.3f%n" + "\tTotal IT services completed:\t%7d%n"
                    + "\tTotal IT services exchanged:\t%7d%n" + "\tTotal federation efficiency:\t%10.2f%%",
            policySelect.getValue(), Long.valueOf(seedStartField.getText()),
            DsolUtil.getRunInterval(this.model.getTreatment()).toDuration().getStandardDays(),
            fedSizeField.getValue(), fedAdapt, fedCash, fedConsKWh / 1000, fedEmitCO2 / 1000, fedSvcCount,
            fedXchCount, 100.0 * fedXchCount / fedSvcCount));

    final String fileName = this.csvFileNameField.getText();
    try (final FileOutputStream out = new FileOutputStream(fileName, this.csvAppendField.isSelected())) {
        out.write(String.format("%s,%s,%d,%d,%d,%d,%f,%f,%f,%d,%d,%f%n", DateTime.now().toString(),
                policySelect.getValue(), Long.valueOf(seedStartField.getText()),
                DsolUtil.getRunInterval(this.model.getTreatment()).toDuration().getStandardDays(),
                fedSizeField.getValue(), fedAdapt, fedCash, fedConsKWh / 1000, fedEmitCO2 / 1000, fedSvcCount,
                fedXchCount, 100.0 * fedXchCount / fedSvcCount).getBytes());
    } catch (final IOException e) {
        LOG.error("Problem writing to file: " + fileName, e);
    }

    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            try {
                // reset simulator's pending event list
                model.getSimulator().setEventList(new RedBlackTree());
            } catch (final RemoteException | SimRuntimeException e) {
                LOG.warn("Problem resetting event list", e);
            }
            model = null;
            System.gc();

            if (Long.valueOf(seedStartField.getText()) < Long.valueOf(seedEndField.getText()))
                simStart();
            else {
                startButton.setText("Start");
                disableGUI(false);
            }
            // startButton.fire();
        }
    });
}

From source file:com.almende.eve.agent.google.GoogleCalendarAgent.java

License:Apache License

/**
 * Calculate the expiration time from a life time
 * //  w  w w .  jav a  2 s. co m
 * @param expires_in
 *            Expiration time in seconds
 * @return
 */
private DateTime calculateExpiresAt(final Integer expires_in) {
    DateTime expires_at = null;
    if (expires_in != null && expires_in != 0) {
        // calculate expiration time, and subtract 5 minutes for safety
        expires_at = DateTime.now().plusSeconds(expires_in).minusMinutes(5);
    }
    return expires_at;
}

From source file:com.almende.eve.agent.google.GoogleCalendarAgent.java

License:Apache License

/**
 * Get todays events. A convenience method for easy testing
 * /*from  w  w w.j  a  va 2 s .  c  om*/
 * @param calendarId
 *            the calendar id
 * @return the events today
 * @throws Exception
 *             the exception
 */
public ArrayNode getEventsToday(@Optional @Name("calendarId") final String calendarId) throws Exception {
    final DateTime now = DateTime.now();
    final DateTime timeMin = now.minusMillis(now.getMillisOfDay());
    final DateTime timeMax = timeMin.plusDays(1);

    return getEvents(timeMin.toString(), timeMax.toString(), calendarId);
}