Example usage for org.joda.time DateTime DateTime

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

Introduction

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

Prototype

public DateTime() 

Source Link

Document

Constructs an instance set to the current system millisecond time using ISOChronology in the default time zone.

Usage

From source file:ch.windmobile.server.file.FileDataSource.java

License:Open Source License

public FileDataSource(Resource stationInfosResource, Resource stationDatasResource, Resource windChartResource)
        throws JAXBException {
    this.stationInfosResource = stationInfosResource;
    this.stationDatasResource = stationDatasResource;
    this.windChartResource = windChartResource;

    lastUpdate = new DateTime();
    jaxbContext = JAXBContext.newInstance("ch.windmobile.server.model.xml");
}

From source file:ch.windmobile.server.mongo.MongoDataSource.java

License:Open Source License

private StationInfo createStationInfo(BasicDBObject stationJson) {
    StationInfo stationInfo = new StationInfo();

    stationInfo.setId(stationJson.getString("_id"));
    stationInfo.setShortName(stationJson.getString("short"));
    stationInfo.setName(stationJson.getString("name"));
    stationInfo.setDataValidity(getDataValidity(new DateTime()));
    stationInfo.setStationLocationType(StationLocationType.TAKEOFF);
    BasicDBList locationJson = (BasicDBList) stationJson.get("loc");
    stationInfo.setWgs84Longitude((Double) locationJson.get(0));
    stationInfo.setWgs84Latitude((Double) locationJson.get(1));
    ;//from  w w  w  .ja v a2 s .c  o m
    stationInfo.setAltitude(stationJson.getInt("alt"));
    stationInfo.setMaintenanceStatus(Status.fromValue(stationJson.getString("status")));

    return stationInfo;
}

From source file:ch.windmobile.server.mongo.MongoDataSource.java

License:Open Source License

private StationData createStationData(String stationId) throws DataSourceException {
    BasicDBObject stationJson = findStationJson(stationId);
    BasicDBObject lastDataJson = (BasicDBObject) stationJson.get("last");
    if (lastDataJson == null) {
        throw new DataSourceException(DataSourceException.Error.INVALID_DATA,
                "No last data for station '" + stationId + "'");
    }// w  ww.j a  v a2 s  .  c  om

    StationData stationData = new StationData();
    stationData.setStationId(stationId);

    DateTime lastUpdate = getLastUpdateDateTime(lastDataJson);
    stationData.setLastUpdate(lastUpdate);
    DateTime now = new DateTime();
    DateTime expirationDate = getExpirationDate(now, lastUpdate);
    stationData.setExpirationDate(expirationDate);

    // Status
    stationData.setStatus(getDataStatus(stationJson.getString("status"), now, expirationDate));

    // Wind average
    stationData.setWindAverage((float) lastDataJson.getDouble(DataTypeConstant.windAverage.getJsonKey()));

    // Wind max
    stationData.setWindMax((float) lastDataJson.getDouble(DataTypeConstant.windMax.getJsonKey()));

    List<BasicDBObject> datas = getHistoricData(stationId, lastUpdate, getHistoricDuration());
    if (datas.size() > 0) {
        // Wind direction chart
        Serie windDirectionSerie = createSerie(datas, DataTypeConstant.windDirection.getJsonKey());
        windDirectionSerie.setName(DataTypeConstant.windDirection.getName());
        Chart windDirectionChart = new Chart();
        windDirectionChart.setDuration(getHistoricDuration());
        windDirectionChart.getSeries().add(windDirectionSerie);
        stationData.setWindDirectionChart(windDirectionChart);

        // Wind history min/average
        double minValue = Double.MAX_VALUE;
        double maxValue = Double.MIN_VALUE;
        double sum = 0;
        double[][] windTrendMaxDatas = new double[datas.size()][2];
        // double[][] windTrendAverageDatas = new double[windAverageDatas.size()][2];
        for (int i = 0; i < datas.size(); i++) {
            BasicDBObject data = datas.get(i);
            // JDC unix-time is in seconds, windmobile java-time in millis
            long millis = data.getLong("_id") * 1000;
            double windAverage = data.getDouble(DataTypeConstant.windAverage.getJsonKey());
            double windMax = data.getDouble(DataTypeConstant.windMax.getJsonKey());
            minValue = Math.min(minValue, windAverage);
            maxValue = Math.max(maxValue, windMax);
            sum += windAverage;
            windTrendMaxDatas[i][0] = millis;
            windTrendMaxDatas[i][1] = windMax;
        }
        stationData.setWindHistoryMin((float) minValue);
        stationData.setWindHistoryAverage((float) (sum / datas.size()));
        stationData.setWindHistoryMax((float) maxValue);

        // Wind trend
        LinearRegression linearRegression = new LinearRegression(windTrendMaxDatas);
        linearRegression.compute();
        double slope = linearRegression.getBeta1();
        double angle = Math.toDegrees(Math.atan(slope * getWindTrendScale()));
        stationData.setWindTrend((int) Math.round(angle));
    }

    // Air temperature
    stationData.setAirTemperature(
            (float) lastDataJson.getDouble(DataTypeConstant.airTemperature.getJsonKey(), -1));

    // Air humidity
    stationData.setAirHumidity((float) lastDataJson.getDouble(DataTypeConstant.airHumidity.getJsonKey(), -1));

    // Air pressure
    String key = DataTypeConstant.airPressure.getJsonKey();
    if (lastDataJson.containsField(key)) {
        stationData.setAirPressure((float) lastDataJson.getDouble(key));
    }

    // Rain
    key = DataTypeConstant.rain.getJsonKey();
    if (lastDataJson.containsField(key)) {
        stationData.setRain((float) lastDataJson.getDouble(key));
    }

    return stationData;
}

From source file:ch.windmobile.server.mongo.MongoDataSource.java

License:Open Source License

@Override
public Chart getWindChart(String stationId, int duration) throws DataSourceException {
    try {//from w  w w. j  a v  a 2 s  .  c  o  m
        Chart windChart = new Chart();
        windChart.setStationId(stationId);

        BasicDBObject lastDataJson = (BasicDBObject) findStationJson(stationId).get("last");
        if (lastDataJson == null) {
            throw new DataSourceException(DataSourceException.Error.INVALID_DATA,
                    "No last data for station '" + stationId + "'");
        }
        DateTime lastUpdate = getLastUpdateDateTime(lastDataJson);
        windChart.setLastUpdate(lastUpdate);
        DateTime now = new DateTime();
        DateTime expirationDate = getExpirationDate(now, lastUpdate);
        windChart.setExpirationDate(expirationDate);

        List<BasicDBObject> datas = getHistoricData(stationId, lastUpdate, duration);

        // Wind historic chart
        Serie windAverageSerie = createSerie(datas, DataTypeConstant.windAverage.getJsonKey());
        windAverageSerie.setName(DataTypeConstant.windAverage.getName());
        Serie windMaxSerie = createSerie(datas, DataTypeConstant.windMax.getJsonKey());
        windMaxSerie.setName(DataTypeConstant.windMax.getName());
        Serie windDirectionSerie = createSerie(datas, DataTypeConstant.windDirection.getJsonKey());
        windDirectionSerie.setName(DataTypeConstant.windDirection.getName());
        windChart.setDuration(duration);
        windChart.getSeries().add(windAverageSerie);
        windChart.getSeries().add(windMaxSerie);
        windChart.getSeries().add(windDirectionSerie);

        return windChart;
    } catch (Exception e) {
        throw exceptionHandler(e);
    }
}

From source file:ch.windmobile.server.social.mongodb.ChatServiceImpl.java

License:Open Source License

@Override
public Message postMessage(String chatRoomId, String pseudo, String text, String emailHash) {
    String collectionName = computeCollectionName(chatRoomId);
    DBCollection col = getOrCreateCappedCollection(collectionName);

    DBObject chatItem = new BasicDBObject();
    Double id = (Double) db.eval(counter, chatRoomId);
    chatItem.put("_id", id.longValue());
    chatItem.put(MongoDBConstants.CHAT_PROP_TEXT, text);
    chatItem.put(MongoDBConstants.CHAT_PROP_USER, pseudo);
    DateTime date = new DateTime().toDateTimeISO();
    chatItem.put(MongoDBConstants.CHAT_PROP_TIME, date.toString());
    chatItem.put(MongoDBConstants.CHAT_PROP_EMAIL_HASH, emailHash);
    col.insert(chatItem);/*w ww. j a  va2 s. c  o  m*/

    Message message = new Message();
    message.setId(id.toString());
    message.setDate(date);
    message.setPseudo(pseudo);
    message.setText(text);
    message.setEmailHash(emailHash);

    return message;
}

From source file:co.mv.wb.framework.DatabaseHelper.java

License:Open Source License

/**
 * Gets DateTimeOffset to log time, it is timezone aware
 *
 * @return time as String/*from w w w  .j av  a  2s  .  c  o m*/
 * @since 4.0
 */
public static DateTime getInstant() {
    return new DateTime();
}

From source file:CollectionOfMentions.ControllerCollectionOfMentions.java

License:Open Source License

public void run() {

    startDateTime = new DateTime();

    //checks on dates to make sure it's not abobe 7 days
    if (numberOfMinutes < 0) {
        numberOfMinutes = 0;/*from ww w .ja v a  2  s . c om*/
    }
    if (numberOfMinutes > 59) {
        numberOfMinutes = 59;
    }
    if (numberOfHours > 24) {
        numberOfHours = 24;
    }
    if (numberOfHours < 0) {
        numberOfHours = 0;
    }
    if (numberOfDays > 7) {
        numberOfDays = 7;
    }
    if (numberOfDays < 0) {
        numberOfDays = 0;
    }

    stopTime = startDateTime.getMillis() + numberOfMinutes * 60000 + numberOfHours * 3600000
            + numberOfDays * 3600000 * 24;
    if (stopTime - startDateTime.getMillis() > 3600000 * 24 * 7) {
        stopTime = startDateTime.getMillis() + 3600000 * 24 * 7;
    }

    //registers actual start time in the status field
    opsJobInfo = dsJobsInfo.createUpdateOperations(JobInfo.class).set("status",
            String.valueOf(startDateTime.getMillis()));
    dsJobsInfo.update(updateQueryJobInfo, opsJobInfo, false, WriteConcern.UNACKNOWLEDGED);

    //registers actual end time in the end field
    opsJobInfo = dsJobsInfo.createUpdateOperations(JobInfo.class).set("end", String.valueOf(stopTime));
    dsJobsInfo.update(updateQueryJobInfo, opsJobInfo, false, WriteConcern.UNACKNOWLEDGED);

    final Object lock = new Object();

    StatusListener listener;
    listener = new StatusListener() {
        @Override
        public void onStatus(Status status) {
            nbTweets++;

            if (System.currentTimeMillis() > stopTime) {

                //updating the job a last time;
                //**************************************
                //saving statuses to the db.
                //                    if (!twitterStatuses.isEmpty()) {
                //                        opsJob = dsJobs.createUpdateOperations(Job.class).addAll("statuses", statusesIds, true);
                //                        dsJobs.update(updateQueryJob, opsJob);
                //
                //                        dsTweets.save(twitterStatuses);
                //                    }
                // 91 is the code for twitter stream has stopped collecting.
                progress = 91;

                //recording the progress, nbTweets and end time of the job
                opsJobInfo = dsJobsInfo.createUpdateOperations(JobInfo.class).set("progress", progress)
                        .set("nbTweets", nbTweets).set("end", System.currentTimeMillis());
                dsJobsInfo.update(updateQueryJobInfo, opsJobInfo);

                synchronized (lock) {
                    lock.notify();
                }

            } else {

                tweet = new Tweet();
                tweet.setStatus(TwitterObjectFactory.getRawJSON(status));
                tweet.setIdTweet(nbTweets);
                tweet.setJobId(jobUUID);
                ////                    System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
                //                    twitterStatus = convertStatus.convertOneToTwitterStatus(status);
                //                    twitterStatus.setJobId(jobUUID);
                //                    twitterStatuses.add(twitterStatus);
                //                    
                //                    
                //
                //                    statusesIds.add(status.getId());
                //                    timeSinceLastStatus = System.currentTimeMillis() - timeLastStatus;
                //
                //                    //**************************************
                //                    //adjusting the frequency of saves to DB, function of number of statuses received per second
                //                    if (timeSinceLastStatus < 200) {
                //                        sizeBatch = 100;
                //                    } else {
                //                        sizeBatch = 25;
                //                    }
                //                    timeLastStatus = System.currentTimeMillis();
                //                    progressLong = (Long) ((System.currentTimeMillis() - startDateTime.getMillis()) * 98 / (stopTime - startDateTime.getMillis()));

                //                    if (statusesIds.size() > sizeBatch || progressLong.intValue() > progress) {
                //**************************************
                //saving statuses to the db.
                try {
                    dsTweets.save(tweet, WriteConcern.UNACKNOWLEDGED);
                    opsJobInfo = dsJobsInfo.createUpdateOperations(JobInfo.class).set("nbTweets", nbTweets);
                    dsJobsInfo.update(updateQueryJobInfo, opsJobInfo, false, WriteConcern.UNACKNOWLEDGED);
                } catch (MongoException m) {
                    System.out.println("saving of statuses to the db failed");
                }
                //                        twitterStatuses = new ArrayList();
                //
                //                        //**************************************
                //                        //updating list of status ids of the job.
                //                        opsJob = dsJobs.createUpdateOperations(Job.class).addAll("statuses", statusesIds, true);
                //                        dsJobs.update(updateQueryJob, opsJob);
                //                        statusesIds = new ArrayList();
                //
                //                        //updating progress.
                //                        System.out.println("progress: " + progressLong);
                //                        progress = progressLong.intValue();
                //                        opsJobInfo = dsJobsInfo.createUpdateOperations(JobInfo.class).set("progress", progress).set("nbTweets", nbTweets);
                //                        dsJobsInfo.update(updateQueryJobInfo, opsJobInfo);

                //**************************************
                //                    }
            }
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
        }

        @Override
        public void onScrubGeo(long userId, long upToStatusId) {
            System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
        }

        @Override
        public void onException(Exception ex) {
            System.out.println("Exception: " + ex);
        }

        @Override
        public void onStallWarning(StallWarning sw) {
            System.out.println("Got stall warning:" + sw.getMessage());

        }
    };
    twitterStream.addListener(listener);

    FilterQuery fq = new FilterQuery();
    String[] mentions = mention.split(",");
    fq.track(mentions);

    //        twitterStream.filter(new FilterQuery(0, users, keywords));
    twitterStream.filter(fq);

    try {
        synchronized (lock) {
            lock.wait();
        }
    } catch (InterruptedException e) {
    }
    try {
        twitterStream.shutdown();
    } catch (Exception e) {
        System.out.println("exception when shutdown of twitter stream");
        System.out.println("error: " + e.getMessage());
    }
    System.out.println("shutdown of twitter stream was successful");

}

From source file:com.actimem.blog.jackson.custometypeannotation.CustomTypesDemo.java

License:Apache License

public static void main(String[] args) throws IOException {
    Company company = new Company();
    company.setCompanyId(new CompanyId("id"));
    company.setName("Actimem");
    company.setFounded(new DateTime());

    ObjectMapper mapper = new ObjectMapper();

    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    String json = mapper.writeValueAsString(company);
    System.out.println(json);//from w ww  . jav  a 2  s.  c o  m

    Company company2 = mapper.readValue(json, Company.class);
    System.out.println(company2.toString());
}

From source file:com.actimem.blog.jackson.customtypes.CustomTypesDemo.java

License:Apache License

public static void main(String[] args) throws IOException {
    Company company = new Company();
    company.setCompanyId(new CompanyId("id"));
    company.setName("Actimem");
    company.setFounded(new DateTime());

    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule("Module");
    module.addSerializer(CompanyId.class, new CompanyIdSerializer());
    module.addDeserializer(CompanyId.class, new CompanyIdDeserializer());
    module.addSerializer(DateTime.class, new DateTimeSerializer());
    module.addDeserializer(DateTime.class, new DateTimeDeserializer());
    mapper.registerModule(module);//from w  w w  . j  a  va 2s  .  c o m

    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    String json = mapper.writeValueAsString(company);
    System.out.println(json);

    Company company2 = mapper.readValue(json, Company.class);
    System.out.println(company2.toString());
}

From source file:com.actimem.blog.jackson.datesjoda.JodaDemo.java

License:Apache License

public static void main(String[] args) throws IOException {
    Company company = new Company();
    company.setName("Actimem");
    company.setFounded(new LocalDate());
    company.setUpdatedTS(new DateTime());

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JodaModule());
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

    String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(company);
    System.out.println(json);// www  . j av a2  s . c  o m

    Company company2 = mapper.readValue(json, Company.class);
    System.out.println(company2.toString());
}