Example usage for org.joda.time DateTime parse

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

Introduction

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

Prototype

@FromString
public static DateTime parse(String str) 

Source Link

Document

Parses a DateTime from the specified string.

Usage

From source file:org.waarp.openr66.protocol.http.rest.handler.DbTaskRunnerR66RestMethodHandler.java

License:Open Source License

@Override
protected DbPreparedStatement getPreparedStatement(HttpRestHandler handler, RestArgument arguments,
        RestArgument result, Object body)
        throws HttpIncorrectRequestException, HttpInvalidAuthenticationException {
    ObjectNode arg = arguments.getUriArgs().deepCopy();
    arg.setAll(arguments.getBody());//from w  w  w . j  av a  2 s.  c o m
    int limit = arg.path(FILTER_ARGS.LIMIT.name()).asInt(0);
    boolean orderBySpecialId = arg.path(FILTER_ARGS.ORDERBYID.name()).asBoolean(false);
    JsonNode node = arg.path(FILTER_ARGS.STARTID.name());
    String startid = null;
    if (!node.isMissingNode()) {
        startid = node.asText();
    }
    if (startid == null || startid.isEmpty()) {
        startid = null;
    }
    node = arg.path(FILTER_ARGS.STOPID.name());
    String stopid = null;
    if (!node.isMissingNode()) {
        stopid = node.asText();
    }
    if (stopid == null || stopid.isEmpty()) {
        stopid = null;
    }
    String rule = arg.path(FILTER_ARGS.IDRULE.name()).asText();
    if (rule == null || rule.isEmpty()) {
        rule = null;
    }
    String req = arg.path(FILTER_ARGS.PARTNER.name()).asText();
    if (req == null || req.isEmpty()) {
        req = null;
    }
    String owner = arg.path(DbTaskRunner.Columns.OWNERREQ.name()).asText();
    if (owner == null || owner.isEmpty()) {
        owner = null;
    }
    boolean pending = arg.path(FILTER_ARGS.PENDING.name()).asBoolean(false);
    boolean transfer = arg.path(FILTER_ARGS.INTRANSFER.name()).asBoolean(false);
    boolean error = arg.path(FILTER_ARGS.INERROR.name()).asBoolean(false);
    boolean done = arg.path(FILTER_ARGS.DONE.name()).asBoolean(false);
    boolean all = arg.path(FILTER_ARGS.ALLSTATUS.name()).asBoolean(false);
    Timestamp start = null;
    node = arg.path(FILTER_ARGS.STARTTRANS.name());
    if (!node.isMissingNode()) {
        long val = node.asLong();
        if (val == 0) {
            DateTime received = DateTime.parse(node.asText());
            val = received.getMillis();
        }
        start = new Timestamp(val);
    }
    Timestamp stop = null;
    node = arg.path(FILTER_ARGS.STOPTRANS.name());
    if (!node.isMissingNode()) {
        long val = node.asLong();
        if (val == 0) {
            DateTime received = DateTime.parse(node.asText());
            val = received.getMillis();
        }
        stop = new Timestamp(val);
    }
    try {
        return DbTaskRunner.getFilterPrepareStatement(handler.getDbSession(), limit, orderBySpecialId, startid,
                stopid, start, stop, rule, req, pending, transfer, error, done, all, owner);
    } catch (WaarpDatabaseNoConnectionException e) {
        throw new HttpIncorrectRequestException("Issue while reading from database", e);
    } catch (WaarpDatabaseSqlException e) {
        throw new HttpIncorrectRequestException("Issue while reading from database", e);
    }
}

From source file:org.xbib.elasticsearch.jdbc.strategy.standard.StandardContext.java

License:Apache License

@Override
public StandardContext setSource(S source) {
    this.source = source;
    Map<String, String> map = settings.getAsMap();
    if (map.containsKey("metrics.lastexecutionstart")) {
        DateTime lastexecutionstart = DateTime.parse(settings.get("metrics.lastexecutionstart"));
        source.getMetric().setLastExecutionStart(lastexecutionstart);
    }/*www  .  j  av a2  s.c o  m*/
    if (map.containsKey("metrics.lastexecutionend")) {
        DateTime lastexecutionend = DateTime.parse(settings.get("metrics.lastexecutionend"));
        source.getMetric().setLastExecutionEnd(lastexecutionend);
    }
    if (map.containsKey("metrics.counter")) {
        int counter = Integer.parseInt(settings.get("metrics.counter"));
        if (counter > 0) {
            source.getMetric().setCounter(counter);
        }
    }
    return this;
}

From source file:org.xsystem.utils.DateUtil.java

License:Apache License

public static String plusISODateAsString(String sd, long mc) {
    DateTime dt = DateTime.parse(sd);
    DateTime dt2 = dt.plus(mc);//w w w .ja v  a 2 s. c  o m
    long l = dt2.getMillis();
    String result = ISODateTimeFormat.dateTimeNoMillis().print(l);
    return result;
}

From source file:org.yamj.core.service.metadata.online.TheTVDbApiWrapper.java

License:Open Source License

/**
 * Get the Series ID by title and year//  w  ww . j  a  v a 2s  . c  om
 *
 * @param title
 * @param year
 * @return
 */
public String getSeriesId(String title, int year, boolean throwTempError) {
    String tvdbId = null;
    if (StringUtils.isNotBlank(title)) {
        seriesLock.lock();
        try {
            String defaultLanguage = localeService.getLocaleForConfig("thetvdb").getLanguage();
            String altLanguage = configService.getProperty("thetvdb.language.alternate", StringUtils.EMPTY);

            boolean usedDefault = true;
            List<Series> seriesList = tvdbApi.searchSeries(title, defaultLanguage);

            if (CollectionUtils.isEmpty(seriesList) && StringUtils.isNotBlank(altLanguage)) {
                seriesList = tvdbApi.searchSeries(title, altLanguage);
                usedDefault = false;
            }

            if (CollectionUtils.isNotEmpty(seriesList)) {
                Series series = null;
                for (Series s : seriesList) {
                    if (s.getFirstAired() != null && !s.getFirstAired().isEmpty()
                            && (year > YEAR_MIN && year < YEAR_MAX)) {
                        DateTime firstAired = DateTime.parse(s.getFirstAired());
                        firstAired.getYear();
                        if (firstAired.getYear() == year) {
                            series = s;
                            break;
                        }
                    } else {
                        series = s;
                        break;
                    }
                }

                if (series != null) {
                    tvdbId = series.getId();
                    Series gotSeries = tvdbApi.getSeries(tvdbId, usedDefault ? defaultLanguage : altLanguage);
                    if (gotSeries != null) {
                        tvdbCache.put("series###" + tvdbId, gotSeries);
                    }
                }
            }
        } catch (TvDbException ex) {
            if (throwTempError && ResponseTools.isTemporaryError(ex)) {
                throw new TemporaryUnavailableException(
                        "TheTVDb service temporary not available: " + ex.getResponseCode(), ex);
            }
            LOG.error("Failed retrieving TVDb id for series '{}': {}", title, ex.getMessage());
            LOG.trace("TheTVDb error", ex);
        } finally {
            seriesLock.unlock();
        }
    }
    return tvdbId;
}

From source file:org.zgis.wps.swat.WeatherFetchAlgorithm.java

License:Apache License

private static String getObservations(String sosUrl, String sensor, String observedProperty, int years)
        throws IOException {
    String result = null;/*from  ww w  .j a  v  a  2s . c o m*/
    String offering = null; // "SOE_GWL_MASL";
    String procedure = sensor;
    // String observedProperty =
    // "http://vocab.smart-project.info/sensorweb/phenomenon/Humidity";
    String responseFormat = "http://www.opengis.net/om/2.0"; // "http://www.opengis.net/waterml/2.0";
    // String temporalFilter =
    // "om:phenomenonTime,2014-02-17T12:00:00/2014-02-18T20:00:00";

    DateTimeFormatter fmt = DateTimeFormat.forPattern(" yyyy-MM-dd'T'HH:mm:ss");
    DateTimeFormatter fmtTz = DateTimeFormat.forPattern(" yyyy-MM-dd'T'HH:mm:ssZZ");
    DateTimeFormatter fmtIso = ISODateTimeFormat.dateTime();

    DateTime now = DateTime.parse("2016-01-01 00:00:00");
    DateTime minusYears = now.minusYears(years);

    String temporalFilter = "om:phenomenonTime," + minusYears.toString(fmtIso) + "/" + now.toString(fmtIso);

    StringBuilder resultList = new StringBuilder();
    StringBuilder kvpRequestParams = new StringBuilder();
    kvpRequestParams.append("?service=" + "SOS");
    kvpRequestParams.append("&version=" + "2.0.0");
    kvpRequestParams.append("&request=" + "GetObservation");

    if (procedure != null && !procedure.isEmpty()) {
        kvpRequestParams.append("&procedure=" + URLEncoder.encode(procedure, "UTF-8"));
    }

    if (observedProperty != null && !observedProperty.isEmpty()) {
        kvpRequestParams.append("&observedProperty=" + URLEncoder.encode(observedProperty, "UTF-8"));
    }

    if (responseFormat != null && !responseFormat.isEmpty()) {
        kvpRequestParams.append("&responseFormat=" + URLEncoder.encode(responseFormat, "UTF-8"));
    }
    // om:phenomenonTime,2010-01-01T12:00:00/2011-07-01T14:00:00
    if (temporalFilter != null && !temporalFilter.isEmpty()) {
        kvpRequestParams.append("&temporalFilter=" + URLEncoder.encode(temporalFilter, "UTF-8"));
    }

    // set the connection timeout value to xx milliseconds
    final HttpParams httpParams = new BasicHttpParams();
    HttpClient httpclient = new DefaultHttpClient(httpParams);
    HttpGet httpget = new HttpGet(sosUrl + kvpRequestParams.toString());

    HttpResponse response;
    HttpEntity entity;

    response = httpclient.execute(httpget);
    HttpEntity resEntity = response.getEntity();
    BufferedReader rd = new BufferedReader(new InputStreamReader(resEntity.getContent()));
    String line;
    while ((line = rd.readLine()) != null) {
        resultList.append(line);
    }
    final String responseBody = resultList.toString();
    OM2MeasParse read = new OM2MeasParse();
    List<ObservationModel> tvps = read.readData(responseBody);

    httpclient.getConnectionManager().shutdown();

    Collections.sort(tvps, new Comparator<ObservationModel>() {
        public int compare(ObservationModel m1, ObservationModel m2) {
            return m1.getDatetime().compareTo(m2.getDatetime());
        }
    });

    if (tvps.size() > 0) {
        return "OK - [" + sensor + "] last: " + tvps.get(tvps.size() - 1).getDate();
    } else {
        return "MISSING";
    }
}

From source file:pi.bestdeal.dao.ChartDAO.java

public List<Integer> daysvaluesConsultation(String start, String end, int idDeal) {
    List<Integer> listofvalue = new ArrayList<>();
    int a;//from   w w w  .  jav a 2  s .c  om
    DateTime dateTime = DateTime.parse(start);
    DateTime dateTime1 = DateTime.parse(end);
    while (dateTime.isBefore(dateTime1)) {

        DateTime dateTimeplus = dateTime.plusDays(1);
        // DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");

        String sqlrequest = "SELECT count(pi_dev.Consultation.idConsultation) as compteur FROM pi_dev.consultation,pi_dev.Deal where pi_dev.Consultation.IdDeal=pi_dev.Deal.idDeal and pi_dev.Deal.idDeal=? and pi_dev.Consultation.dateCreation between ? and ?;";
        /* DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");
         DateTime dateTime = DateTime.parse(start, fmt);
         DateTime dateTime1 = DateTime.parse(end, fmt);*/
        try {
            PreparedStatement ps = MySQLConnection.getInstance().prepareStatement(sqlrequest);

            java.sql.Date sqlDate = new java.sql.Date(dateTime.getMillis());
            DateTime d2 = DateTime.parse(end);
            java.sql.Date sqlDate2 = new java.sql.Date(dateTimeplus.getMillis());

            ps.setInt(1, idDeal);
            ps.setDate(2, sqlDate);
            ps.setDate(3, sqlDate2);
            //System.err.println(sqlDate2.toString());

            ResultSet result = ps.executeQuery();

            while (result.next()) {

                a = result.getInt(1);
                listofvalue.add(a);
            }
        } catch (SQLException ex) {
            Logger.getLogger(ChartDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        dateTime = dateTime.plusDays(1);
    }
    return listofvalue;
}

From source file:pi.bestdeal.dao.ChartDAO.java

public List<Integer> daysvaluesReservation(String start, String end, int idDeal) {
    List<Integer> listofvalue = new ArrayList<>();
    int a;//from w  w  w .ja v a 2s .co  m
    DateTime dateTime = DateTime.parse(start);
    DateTime dateTime1 = DateTime.parse(end);
    while (dateTime.isBefore(dateTime1)) {

        DateTime dateTimeplus = dateTime.plusDays(1);
        // DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");

        String sqlrequest = "SELECT count(pi_dev.Reservation.idReservation) as compteur FROM pi_dev.reservation,pi_dev.Deal where pi_dev.reservation.IdDeal=pi_dev.Deal.idDeal and pi_dev.Deal.idDeal=? and pi_dev.reservation.dateRerservation between ? and ?;";
        /* DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");
         DateTime dateTime = DateTime.parse(start, fmt);
         DateTime dateTime1 = DateTime.parse(end, fmt);*/
        try {
            PreparedStatement ps = MySQLConnection.getInstance().prepareStatement(sqlrequest);

            java.sql.Date sqlDate = new java.sql.Date(dateTime.getMillis());
            DateTime d2 = DateTime.parse(end);
            java.sql.Date sqlDate2 = new java.sql.Date(dateTimeplus.getMillis());

            ps.setInt(1, idDeal);
            ps.setDate(2, sqlDate);
            ps.setDate(3, sqlDate2);
            //System.err.println(sqlDate2.toString());

            ResultSet result = ps.executeQuery();

            while (result.next()) {

                a = result.getInt(1);
                listofvalue.add(a);
            }
        } catch (SQLException ex) {
            Logger.getLogger(ChartDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        dateTime = dateTime.plusDays(1);
    }
    return listofvalue;
}

From source file:se.frikod.payday.Holidays.java

License:Open Source License

Holidays(Context context) {
    InputStream holidaysFile;/*  w ww  .  j  a v  a 2  s .  c  o m*/
    holidays = new HashMap<DateTime, String>();

    weekend = Arrays.asList(DateTimeConstants.SATURDAY, DateTimeConstants.SUNDAY);

    try {
        holidaysFile = context.getResources().getAssets().open("Holidays_SE.json");
        String holidaysString = convertStreamToString(holidaysFile);
        JSONObject holidaysData = new JSONObject(holidaysString);
        Iterator<?> dates = holidaysData.keys();
        while (dates.hasNext()) {
            String key = (String) dates.next();
            String description = (String) holidaysData.get(key);
            DateTime date = DateTime.parse(key);
            holidays.put(date, description);
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    catch (JSONException e) {
        // TODO Auto-generated catch block

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

}

From source file:se.softhouse.jargo.stringparsers.custom.DateTimeParser.java

License:Apache License

@Override
public DateTime parse(final String value, Locale locale) throws ArgumentException {
    try {//from  w  w  w. ja v  a 2s  .  c o  m
        return DateTime.parse(value);
    } catch (IllegalArgumentException wrongDateFormat) {
        throw ArgumentExceptions.withMessage(wrongDateFormat.getLocalizedMessage());
    }
}

From source file:securesocial.core.java.SecureSocial.java

License:Apache License

/**
 * Creates a UserId from the session//  w  w w  .  java2s  .c om
 *
 * @param ctx the current context
 * @return the UserId or null if there's no user in the session
 */
private static securesocial.core.UserId getUserIdFromSession(Http.Context ctx) {
    final String user = ctx.session().get(USER_KEY);
    final String provider = ctx.session().get(PROVIDER_KEY);

    UserId result = null;

    if (user != null && provider != null) {
        final String dateTimeString = ctx.session().get(LAST_ACCESS);
        final DateTime lastAccess = DateTime.parse(dateTimeString);
        if (!isSessionExpired(lastAccess)) {
            result = new UserId(user, provider);
        }
    }
    return result;
}