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.bridge.resources.DemoGenerator.java

License:Apache License

/**
 * Send task.//from   w  w  w.  j  ava2  s  .c o m
 *
 * @param planName
 *            the plan name
 * @param type
 *            the type
 * @param latitude
 *            the latitude
 * @param longitude
 *            the longitude
 * @param minutes
 *            the minutes
 * @param taskParams
 *            the task params
 */
public void sendTask(@Name("plan") String planName, @Name("type") String type, @Name("lat") Double latitude,
        @Name("lon") Double longitude, @Name("inMinutes") int minutes,
        @Name("taskParams") ObjectNode taskParams) {
    final Params params = new Params();
    final ObjectNode config = JOM.createObjectNode();

    config.put("lat", latitude);
    config.put("lon", longitude);
    config.put("before", DateTime.now().plusMinutes(minutes).getMillis());
    config.put("planName", planName);
    config.put("resType", type);
    config.set("taskParams", taskParams);
    config.put("id", new UUID().toString());
    tasks.put(config.get("id").asText(), new Task(config));

    params.add("task", config);
    params.add("reportTo", getUrls().get(0));

    events.sendEvent(new JSONRequest("taskRequest", params));

    schedule("handleTask", config, 10000);
    LOG.warning("Added task:" + config);
}

From source file:com.almende.bridge.resources.DemoGenerator.java

License:Apache License

/**
 * Generate agents./*from   w w w . ja  v  a  2  s  .  c o  m*/
 *
 * @param type
 *            the type
 * @param at
 *            At what type of location?
 * @param nofAgents
 *            the nof agents
 * @param icon
 *            the icon
 * @param tag
 *            the tag
 */
public void generateAgents(@Name("type") String type, @Name("at") String at, @Name("nofAgents") int nofAgents,
        @Name("icon") String icon, @Name("tag") String tag) {
    // Generate X agents, at random stations
    for (int i = 0; i < nofAgents; i++) {
        SimulatedResource agent = new SimulatedResource();
        AgentConfig agentConfig = new AgentConfig();
        agentConfig.setId(URIUtil.encode(type) + "-" + i + "-" + DateTime.now().getMillis());
        agentConfig.setAll((ObjectNode) getConfig().get("simAgents"));
        List<double[]> stations = placesOfInterest.get(at);
        agentConfig.set("initLocation",
                JOM.getInstance().valueToTree(stations.get((int) (Math.random() * stations.size()))));
        agentConfig.put("resType", type);
        agentConfig.put("guid", new UUID().toString());
        agentConfig.put("tag", tag);
        agentConfig.put("icon", icon);
        agent.setConfig(agentConfig);
    }
}

From source file:com.almende.bridge.resources.SimulatedResource.java

License:Apache License

/**
 * Task request.//www.  ja  v  a  2 s .c o  m
 * -Check if busy
 * -Check if capable of that task
 * -Check distance to start (rough guess if reachable in time) (TODO,
 * somewhat problematic due to datum issues)
 * -Check ETA to start
 * If all true, report possible match plus ETA.
 *
 * @param task
 *            the task
 * @param reportTo
 *            the report to
 */
public void taskRequest(final @Name("task") ObjectNode task, final @Name("reportTo") URI reportTo) {
    String resType = getResType();
    if (task.has("resType")) {
        if (!resType.equals(task.get("resType").asText())) {
            return;
        }
    }
    if (deploymentState.equals(DEPLOYMENTSTATE.Unassigned)) {
        boolean capable = false;
        String planName = task.get("planName").asText();
        if ("Goto".equals(planName) || "GotoAndStay".equals(planName)) {
            capable = true;
        } else if (resType.equals("medic vehicle")) {
            if (task.get("planName").asText().equals("Evac")) {
                capable = true;
            }
        }
        if (!capable) {
            return;
        }
        // distance/speed on Highway (~80km/h)

        final Params params = new Params();
        params.put("startLat", geoJsonPos[1]);
        params.put("startLon", geoJsonPos[0]);
        params.put("endLat", task.get("lat").asDouble());
        params.put("endLon", task.get("lon").asDouble());

        try {
            getRoute(params, new AsyncCallback<ObjectNode>() {
                /*
                 * (non-Javadoc)
                 * @see
                 * com.almende.util.callback.AsyncCallback#onSuccess(java.lang
                 * .Object
                 * )
                 */
                @Override
                public void onSuccess(ObjectNode result) {
                    Route myRoute = new Route();
                    myRoute.routeBase = DateTime.now();
                    myRoute.route = ROUTETYPE.inject(result.get("route"));
                    myRoute.index = 0;
                    myRoute.eta = new Duration(result.get("millis").asLong());

                    if (myRoute.routeBase.plus(myRoute.eta).isBefore(task.get("before").asLong())) {
                        // Potential!
                        Params params = new Params();
                        params.add("task", task);
                        params.add("eta", myRoute.eta.plus((long) Math.floor(Math.random() * 5000)));
                        try {
                            call(reportTo, "volunteer", params);
                        } catch (IOException e) {
                            LOG.log(Level.WARNING, "Couldn't volunteer for task", e);
                        }
                    }
                }

                @Override
                public void onFailure(Exception exception) {
                    LOG.log(Level.WARNING, "Couldn't plan route:", exception);
                }
            });
        } catch (IOException e) {
            LOG.log(Level.WARNING, "Couldn't plan route:", e);
        }
    }
}

From source file:com.almende.bridge.resources.SimulatedResource.java

License:Apache License

/**
 * Gets the current location of this resource.
 *
 * @return the current location/*from   w  w  w.  j  a  v  a 2s . com*/
 */
public synchronized ObjectNode getCurrentLocation() {
    final ObjectNode result = JOM.createObjectNode();
    if (route != null) {
        final long millis = new Duration(route.routeBase, DateTime.now().plus((long) (Math.random() * 1000)))
                .getMillis();
        double[] pos = null;
        if (getEta().isBeforeNow()) {
            pos = route.route.get(route.route.size() - 1);
            route = null;
        } else {
            double[] last = null;
            for (int i = route.index; i < route.route.size(); i++) {
                double[] item = route.route.get(i);
                if (item[3] > millis) {
                    if (last != null) {
                        double length = item[3] - last[3];
                        double latDiff = item[1] - last[1];
                        double lonDiff = item[0] - last[0];
                        double part = millis - last[3];

                        final double[] loc = new double[4];
                        loc[0] = last[0] + lonDiff * (part / length) + (Math.random() * 0.0001 - 0.00005);
                        loc[1] = last[1] + latDiff * (part / length) + (Math.random() * 0.0001 - 0.00005);
                        loc[2] = 0;
                        loc[3] = millis;
                        pos = loc;
                    } else {
                        pos = item;
                    }
                    break;
                }
                last = item;
                route.index = route.index > 0 ? route.index - 1 : 0;
            }
        }

        if (pos != null) {
            result.put("lon", pos[0]);
            result.put("lat", pos[1]);
            if (route != null) {
                result.put("eta", getEtaString());
            }
            geoJsonPos = pos;
        }
    } else {
        result.put("lon", geoJsonPos[0]);
        result.put("lat", geoJsonPos[1]);
    }
    if (properties.has("icon")) {
        result.put("icon", properties.get("icon").asText());
    }
    result.put("name", getId());
    return result;
}

From source file:com.almende.bridge.resources.SimulatedResource.java

License:Apache License

/**
 * Gets the eta./* ww  w.  jav a2  s  .c o  m*/
 *
 * @return the eta
 */
@JsonIgnore
public DateTime getEta() {
    if (route != null) {
        return route.routeBase.plus(route.eta);
    } else {
        return DateTime.now();
    }
}

From source file:com.almende.bridge.resources.SimulatedResource.java

License:Apache License

private void addRouteProperties(Feature feature) {
    if (route != null) {
        feature.setProperty("eta", getEtaString());
        if (getEta().isAfterNow()) {
            Period period = new Duration(DateTime.now(), getEta()).toPeriod();
            feature.setProperty("minutesRemaining", period.toString(MINANDSECS));
            feature.setProperty("etaShort", getEta().toString("kk:mm:ss"));
        } else {//from w  w w.j a  va 2 s. com
            feature.setProperty("minutesRemaining", 0);
            feature.setProperty("etaShort", "00:00:00");
        }
    }
}

From source file:com.almende.bridge.resources.SimulatedResource.java

License:Apache License

/**
 * Gets the geo json description of this Resource.
 *
 * @param incTrack//ww w. ja  v a 2  s.c o m
 *            Should the track data be included?
 * @param incTarget
 *            the inc target
 * @return the geo json
 */

public FeatureCollection getGeoJson(@Optional @Name("includeTrack") Boolean incTrack,
        @Optional @Name("includeTarget") Boolean incTarget) {
    getCurrentLocation();

    final FeatureCollection fc = new FeatureCollection();
    fc.setProperty("id", getId());

    final Feature origin = new Feature();
    origin.setId(getId());
    final Point originPoint = new Point();
    originPoint.setCoordinates(new LngLatAlt(geoJsonPos[0], geoJsonPos[1]));
    origin.setGeometry(originPoint);
    origin.setProperty("type", "currentLocation");
    addProperties(origin);
    addTaskProperties(origin);
    // TODO: add resource icon

    fc.add(origin);

    if (route != null) {
        if (incTrack != null && incTrack) {
            final Feature track = new Feature();
            track.setId(getId());
            final LineString tracksteps = new LineString();
            tracksteps.add(new LngLatAlt(geoJsonPos[0], geoJsonPos[1]));
            final long millis = new Duration(route.routeBase, DateTime.now()).getMillis();

            for (double[] step : route.route) {
                if (step[3] > millis) {
                    tracksteps.add(new LngLatAlt(step[0], step[1]));
                }
            }
            track.setGeometry(tracksteps);
            track.setProperty("type", "route");
            addProperties(track);
            addTaskProperties(track);
            fc.add(track);
        }
        if (incTarget != null && incTarget) {
            final Feature goal = new Feature();
            goal.setId(getId());
            final Point goalPoint = new Point();
            goalPoint.setCoordinates(new LngLatAlt(geoJsonGoal[0], geoJsonGoal[1]));
            goal.setGeometry(goalPoint);
            goal.setProperty("type", "targetLocation");
            addRouteProperties(goal);

            addProperties(goal);
            addTaskProperties(goal);

            fc.add(goal);
        }
        addRouteProperties(origin);
    }
    return fc;
}

From source file:com.almende.bridge.resources.SimulatedResource.java

License:Apache License

private void planRoute() throws IOException {
    final Params params = new Params();
    params.put("startLat", geoJsonPos[1]);
    params.put("startLon", geoJsonPos[0]);
    params.put("endLat", geoJsonGoal[1]);
    params.put("endLon", geoJsonGoal[0]);
    getRoute(params, new AsyncCallback<ObjectNode>() {

        /*//ww w  .  jav  a2  s . c  om
         * (non-Javadoc)
         * @see
         * com.almende.util.callback.AsyncCallback#onSuccess(java.lang.Object
         * )
         */
        @Override
        public void onSuccess(ObjectNode result) {
            if (route == null) {
                route = new Route();
            }
            route.routeBase = DateTime.now().plus((long) (Math.random() * 10000));
            route.route = ROUTETYPE.inject(result.get("route"));
            route.index = 0;
            route.eta = new Duration(result.get("millis").asLong());
            checkArrival();
        }

        @Override
        public void onFailure(Exception exception) {
            LOG.log(Level.WARNING, "Couldn't get route:", exception);
            route = null;
        }
    });
}

From source file:com.almende.bridge.resources.SimulatedResource.java

License:Apache License

/**
 * Request status./*from   www  .ja v  a2s. c om*/
 *
 * @return the object node
 */
public ObjectNode requestStatus() {
    ObjectNode status = JOM.createObjectNode();
    status.put("name", getId());
    status.put("id", guid); // Some global uid, for .NET id
    // separation.
    status.put("type", getResType());
    status.put("deploymentStatus", deploymentState.toString());

    getCurrentLocation();
    Location location = new Location(new Double(geoJsonPos[1]).toString(), new Double(geoJsonPos[0]).toString(),
            DateTime.now().toString());
    if (location != null) {
        status.set("current", JOM.getInstance().valueToTree(location));
    }

    if (route != null) {
        Location goal = new Location(new Double(geoJsonGoal[1]).toString(),
                new Double(geoJsonGoal[0]).toString(), getEtaString());
        if (goal != null) {
            status.set("goal", JOM.getInstance().valueToTree(goal));
        }
    }

    if (plan != null) {
        String taskDescription = plan.getTitle() + " (" + plan.getCurrentTitle() + ")";
        if (taskDescription != null) {
            status.put("task", taskDescription);
        }
    }
    return status;
}

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

License:Apache License

/**
 * Inits the.//from   w  w w . j  av a2s.co  m
 * 
 * @param ctx
 *            the ctx
 */
public void init(Context ctx) {
    ConferenceAgent.ctx = ctx;
    final TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
    final AgentConfig config = new AgentConfig();
    config.setId(tm.getDeviceId());

    final FileStateConfig stateConfig = new FileStateConfig();
    stateConfig.setJson(true);
    stateConfig.setPath(ctx.getFilesDir().getAbsolutePath() + "/agentStates/");
    stateConfig.setId("conferenceAgent");

    config.setState(stateConfig);

    SimpleSchedulerConfig schedulerConfig = new SimpleSchedulerConfig();
    config.setScheduler(schedulerConfig);

    loadConfig(config);

    if (!getState().containsKey(CONTACTKEY.getKey())) {
        getState().put(CONTACTKEY.getKey(), new HashMap<String, Info>());
    }
    DetectionUtil.getInstance().startScan();
    getScheduler().schedule(this.getRpc().buildMsg("refresh", null, null), DateTime.now().plus(60000));

    reconnect();
}