Example usage for org.joda.time DateTimeZone toString

List of usage examples for org.joda.time DateTimeZone toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Gets the datetime zone as a string, which is simply its ID.

Usage

From source file:com.google.ical.compat.jodatime.TimeZoneConverter.java

License:Apache License

/**
 * return a <code>java.util.Timezone</code> object that delegates to
 * the given Joda <code>DateTimeZone</code>.
 */// w  w  w .  jav  a 2 s. c  om
public static TimeZone toTimeZone(final DateTimeZone dtz) {

    TimeZone tz = new TimeZone() {
        @Override
        public void setRawOffset(int n) {
            throw new UnsupportedOperationException();
        }

        @Override
        public boolean useDaylightTime() {
            long firstTransition = MILLIS_SINCE_1_JAN_2000_UTC;
            return firstTransition != dtz.nextTransition(firstTransition);
        }

        @Override
        public boolean inDaylightTime(Date d) {
            long t = d.getTime();
            return dtz.getStandardOffset(t) != dtz.getOffset(t);
        }

        @Override
        public int getRawOffset() {
            return dtz.getStandardOffset(0);
        }

        @Override
        public int getOffset(long instant) {
            // This method is not abstract, but it normally calls through to the
            // method below.
            // It's optimized here since there's a direct equivalent in
            // DateTimeZone.
            // DateTimeZone and java.util.TimeZone use the same
            // epoch so there's no translation of instant required.
            return dtz.getOffset(instant);
        }

        @Override
        public int getOffset(int era, int year, int month, int day, int dayOfWeek, int milliseconds) {
            int millis = milliseconds; // milliseconds is day in standard time
            int hour = millis / MILLISECONDS_PER_HOUR;
            millis %= MILLISECONDS_PER_HOUR;
            int minute = millis / MILLISECONDS_PER_MINUTE;
            millis %= MILLISECONDS_PER_MINUTE;
            int second = millis / MILLISECONDS_PER_SECOND;
            millis %= MILLISECONDS_PER_SECOND;
            if (era == GregorianCalendar.BC) {
                year = -(year - 1);
            }

            // get the time in UTC in case a timezone has changed it's standard
            // offset, e.g. rid of a half hour from UTC.
            DateTime dt = null;
            try {
                dt = new DateTime(year, month + 1, day, hour, minute, second, millis, dtz);
            } catch (IllegalArgumentException ex) {
                // Java does not complain if you try to convert a Date that does not
                // exist due to the offset shifting forward, but Joda time does.
                // Since we're trying to preserve the semantics of TimeZone, shift
                // forward over the gap so that we're on a time that exists.
                // This assumes that the DST correction is one hour long or less.
                if (hour < 23) {
                    dt = new DateTime(year, month + 1, day, hour + 1, minute, second, millis, dtz);
                } else { // Some timezones shift at midnight.
                    Calendar c = new GregorianCalendar();
                    c.clear();
                    c.setTimeZone(TimeZone.getTimeZone("UTC"));
                    c.set(year, month, day, hour, minute, second);
                    c.add(Calendar.HOUR_OF_DAY, 1);
                    int year2 = c.get(Calendar.YEAR), month2 = c.get(Calendar.MONTH),
                            day2 = c.get(Calendar.DAY_OF_MONTH), hour2 = c.get(Calendar.HOUR_OF_DAY);
                    dt = new DateTime(year2, month2 + 1, day2, hour2, minute, second, millis, dtz);
                }
            }
            // since millis is in standard time, we construct the equivalent
            // GMT+xyz timezone and use that to convert.
            int offset = dtz.getStandardOffset(dt.getMillis());
            DateTime stdDt = new DateTime(year, month + 1, day, hour, minute, second, millis,
                    DateTimeZone.forOffsetMillis(offset));
            return getOffset(stdDt.getMillis());
        }

        @Override
        public String toString() {
            return dtz.toString();
        }

        @Override
        public boolean equals(Object that) {
            if (!(that instanceof TimeZone)) {
                return false;
            }
            TimeZone thatTz = (TimeZone) that;
            return getID().equals(thatTz.getID()) && hasSameRules(thatTz);
        }

        @Override
        public int hashCode() {
            return getID().hashCode();
        }

        private static final long serialVersionUID = 58752546800455L;
    };
    // Now fix the tzids.  DateTimeZone has a bad habit of returning
    // "+06:00" when it should be "GMT+06:00"
    String newTzid = cleanUpTzid(dtz.getID());
    tz.setID(newTzid);
    return tz;
}

From source file:com.google.sampling.experiential.server.ExperimentServlet.java

License:Open Source License

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("application/json;charset=UTF-8");

    User user = AuthUtil.getWhoFromLogin();

    if (user == null) {
        AuthUtil.redirectUserToLogin(req, resp);
    } else {/*from   ww  w  .j a  va 2s.  co m*/
        DateTimeZone timezone = TimeUtil.getTimeZoneForClient(req);
        log.info("Timezone is computed to be: " + timezone.toString());
        logPacoClientVersion(req);

        String email = AuthUtil.getEmailOfUser(req, user);

        String experimentsPublishedToMeParam = req.getParameter("mine");
        String selectedExperimentsParam = req.getParameter("id");
        String experimentsPublishedPubliclyParam = req.getParameter("public");
        String experimentsAdministeredByUserParam = req.getParameter("admin");
        String experimentsJoinedByMeParam = req.getParameter("joined");

        String pacoProtocol = req.getHeader("pacoProtocol");
        if (pacoProtocol == null) {
            pacoProtocol = req.getParameter("pacoProtocol");
        }

        //String offset = req.getParameter("offset");
        String limitStr = req.getParameter("limit");
        Integer limit = null;
        if (limitStr != null) {
            try {
                limit = Integer.parseInt(limitStr);
            } catch (NumberFormatException e) {
            }
        }
        //      if (limit != null && (limit <= 0 || limit >= EXPERIMENT_LIMIT_MAX)) {
        //        throw new IllegalArgumentException("Invalid limit. must be greater than 0 and less than or equal to 50");
        //      }
        String cursor = req.getParameter("cursor");

        String experimentsJson = null;
        ExperimentServletHandler handler;
        if (experimentsPublishedToMeParam != null) {
            handler = new ExperimentServletExperimentsForMeLoadHandler(email, timezone, limit, cursor,
                    pacoProtocol);
        } else if (selectedExperimentsParam != null) {
            handler = new ExperimentServletSelectedExperimentsFullLoadHandler(email, timezone,
                    selectedExperimentsParam, pacoProtocol);
        } else if (experimentsPublishedPubliclyParam != null) {
            handler = new ExperimentServletExperimentsShortPublicLoadHandler(email, timezone, limit, cursor,
                    pacoProtocol);
        } /*else if (experimentsAdministeredByUserParam != null && experimentsJoinedByMeParam != null) {
          handler = new ExperimentServletAdminAndJoinedExperimentsShortLoadHandler(email, timezone, limit, cursor, pacoProtocol);
          } */else if (experimentsJoinedByMeParam != null) {
            handler = new ExperimentServletJoinedExperimentsShortLoadHandler(email, timezone, limit, cursor,
                    pacoProtocol);
        } else if (experimentsAdministeredByUserParam != null) {
            handler = new ExperimentServletAdminExperimentsFullLoadHandler(email, timezone, limit, cursor,
                    pacoProtocol);
        } else {
            handler = null; //new ExperimentServletAllExperimentsFullLoadHandler(email, timezone, limit, cursor, pacoProtocol);
        }
        if (handler != null) {
            log.info("Loading experiments...");
            experimentsJson = handler.performLoad();
            resp.getWriter().println(scriptBust(experimentsJson));
        } else {
            resp.getWriter().println(scriptBust("Unrecognized parameters!"));
        }

    }
}

From source file:com.google.sampling.experiential.server.PacoServiceImpl.java

License:Open Source License

@Override
public boolean joinExperiment(Long experimentId) {
    User loggedInWho = getWhoFromLogin();
    if (loggedInWho == null) {
        throw new IllegalArgumentException("Not logged in");
    }/*w ww .  j av a2 s.c o m*/

    if (experimentId == null) {
        throw new IllegalArgumentException("Must supply experiment Id");
    }

    Experiment experiment = ExperimentRetriever.getInstance().getExperiment(Long.toString(experimentId));

    if (experiment == null) {
        throw new IllegalArgumentException("Unknown experiment!");
    }

    String lowerCase = loggedInWho.getEmail().toLowerCase();
    if (!experiment.isWhoAllowedToPostToExperiment(lowerCase)) {
        throw new IllegalArgumentException("This user is not allowed to post to this experiment");
    }

    try {
        String tz = null;
        DateTimeZone timezone = TimeUtil.getTimeZoneForClient(getThreadLocalRequest());
        if (timezone != null) {
            tz = timezone.toString();
        }
        Date responseTimeDate;
        if (tz != null) {
            responseTimeDate = new DateTime().withZone(timezone).toDate();
        } else {
            responseTimeDate = new Date();
        }

        String experimentName = experiment.getTitle();
        Set<What> whats = Sets.newHashSet();
        whats.add(new What("joined", "true"));
        whats.add(new What("schedule", experiment.getSchedule().toString()));

        EventRetriever.getInstance().postEvent(lowerCase, null, null, new Date(), "webform", "1", whats, false,
                Long.toString(experimentId), experimentName, experiment.getVersion(), responseTimeDate, null,
                null, tz);

        // create entry in table with user Id, experimentId, joinDate

        return true;
    } catch (Throwable e) {
        throw new IllegalArgumentException("Could not join experiment: ", e);
    }
}

From source file:com.google.sampling.experiential.server.PubExperimentServlet.java

License:Open Source License

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("application/json;charset=UTF-8");

    DateTimeZone timezone = TimeUtil.getTimeZoneForClient(req);
    log.info("Timezone is computed to be: " + timezone.toString());
    logPacoClientVersion(req);// w  w  w  . jav  a2 s  . co m

    User user = AuthUtil.getWhoFromLogin();
    String email = null;
    if (user != null) {
        email = AuthUtil.getEmailOfUser(req, user);
    } else {
        email = req.getRemoteAddr();
    }

    String selectedExperimentsParam = req.getParameter("id");

    String pacoProtocol = req.getHeader("pacoProtocol");
    if (pacoProtocol == null) {
        pacoProtocol = req.getParameter("pacoProtocol");
    }

    String experimentsJson = null;
    ExperimentServletHandler handler = null;
    if (selectedExperimentsParam != null) {
        handler = new ExperimentServletSelectedExperimentsFullLoadHandler(email, timezone,
                selectedExperimentsParam, pacoProtocol);
    }
    if (handler != null) {
        log.info("Loading experiments...");
        experimentsJson = handler.performLoad();
        resp.getWriter().println(scriptBust(experimentsJson));
    } else {
        resp.getWriter().println(scriptBust("Unrecognized parameters!"));
    }
}

From source file:com.wso2telco.dep.reportingservice.dao.BillingDAO.java

License:Open Source License

/**
 * Convert to local time.//from www  .j  a  v  a  2 s. com
 *
 * @param timeOffset the time offset
 * @param time the time
 * @return the string
 */
public String convertToLocalTime(String timeOffset, String time) {
    Integer offsetValue = Integer.parseInt(timeOffset);

    log.debug("Offset value = " + offsetValue);
    DateTimeZone systemTimeZone = DateTimeZone.getDefault();
    log.debug("system time zone " + systemTimeZone.toString());
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    DateTime systemDateTime = formatter.parseDateTime(time);
    log.debug("system date time " + systemDateTime.toString());
    systemDateTime = systemDateTime.withZoneRetainFields(systemTimeZone);
    log.debug("system date time after adding systemtimezone === " + systemDateTime.toString());

    int hours = -1 * offsetValue / 60;
    int minutes = offsetValue % 60;
    minutes = Math.abs(minutes);

    DateTimeZone localTimeZone = DateTimeZone.forOffsetHoursMinutes(hours, minutes);

    log.debug("Local time zone ==== " + localTimeZone.toString());

    DateTime convertedDateTime = systemDateTime.withZone(localTimeZone);

    String convertedDateTimeString = formatter.print(convertedDateTime);

    log.debug("converted time  :" + convertedDateTimeString);

    return convertedDateTimeString;

}

From source file:org.graylog2.restclient.lib.DateTools.java

License:Open Source License

public static String getUserTimeZone(User currentUser) {
    DateTimeZone tz = globalTimezone;

    if (currentUser != null && currentUser.getTimeZone() != null) {
        tz = currentUser.getTimeZone();/*from   w  ww.j  a  va 2s.  co m*/
    }

    return tz.toString();
}

From source file:org.jadira.usertype.dateandtime.joda.columnmapper.StringColumnDateTimeZoneMapper.java

License:Apache License

@Override
public String toNonNullValue(DateTimeZone value) {
    return value.toString();
}

From source file:org.jlucrum.realtime.generators.TickGenerator.java

License:Open Source License

private boolean timeout() {
    DateTimeZone timeZone = null;
    DateTime time = null;//from   ww w .j  av  a 2 s.  c  o m
    long startTickerTime = 0;
    long endTickerTime = 0;
    boolean toContinue = false;

    timeZone = DateTimeZone.forID(config.timeZone);

    startTickerTime = config.start_hour * 60 + config.start_minute;
    endTickerTime = config.end_hour * 60 + config.end_minute;

    try {
        time = new DateTime(timeZone);

        System.out.printf("Timezone:%s and week:%d - %d", timeZone.toString(), time.getDayOfWeek(),
                DateTimeConstants.SATURDAY);
        if (DateTimeConstants.SATURDAY == time.getDayOfWeek()) {
            long toSleep = 24 * 60 - time.getMinuteOfDay() + 24 * 60;
            System.out.printf("TickGenerator sleeps until Monday, because it is Saturday\n");
            Thread.sleep(toSleep * 60 * 1000);
            toContinue = true;
        } else if (DateTimeConstants.SUNDAY == time.getDayOfWeek()) {
            long toSleep = 24 * 60 - time.getMinuteOfDay();
            System.out.printf("TickGenerator sleeps until Monday, because it is Sunday\n");
            Thread.sleep(toSleep * 60 * 1000);
            toContinue = true;
        }

        if (time.getMinuteOfDay() < startTickerTime) {
            long minutesToSleep = Math.abs(time.getMinuteOfDay() - startTickerTime);
            System.out.printf("Sleeping (%d) minutes ... Starting 1 at:%d:%d\n", minutesToSleep,
                    config.start_hour, config.start_minute);
            Thread.sleep(minutesToSleep * 60 * 1000);
            toContinue = true;

        } else if (time.getMinuteOfDay() > endTickerTime) {
            long minutesToSleep = 24 * 60 - time.getMinuteOfDay();
            minutesToSleep += startTickerTime;
            System.out.printf("Sleeping (%d) minutes ... Starting 2 at:%d:%d\n", minutesToSleep,
                    config.start_hour, config.start_minute);
            Thread.sleep(minutesToSleep * 60 * 1000);
            toContinue = true;
        }

    } catch (InterruptedException ex) {
        Logger.getLogger(TickGenerator.class.getName()).log(Level.SEVERE, null, ex);
    }

    return toContinue;
}

From source file:org.supercsv.cellprocessor.joda.FmtDateTimeZone.java

License:Apache License

/**
 * {@inheritDoc}/*from  w  w  w  . j  av a 2 s .c  om*/
 * 
 * @throws SuperCsvCellProcessorException
 *             if value is null or not a DateTimeZone
 */
public Object execute(final Object value, final CsvContext context) {
    validateInputNotNull(value, context);
    if (!(value instanceof DateTimeZone)) {
        throw new SuperCsvCellProcessorException(DateTimeZone.class, value, context, this);
    }
    final DateTimeZone dateTimeZone = (DateTimeZone) value;
    final String result = dateTimeZone.toString();
    return next.execute(result, context);
}