Example usage for java.util Calendar getTimeZone

List of usage examples for java.util Calendar getTimeZone

Introduction

In this page you can find the example usage for java.util Calendar getTimeZone.

Prototype

public TimeZone getTimeZone() 

Source Link

Document

Gets the time zone.

Usage

From source file:calendarexportplugin.exporter.GoogleExporter.java

public boolean exportPrograms(Program[] programs, CalendarExportSettings settings,
        AbstractPluginProgramFormating formatting) {
    try {/*from w w w .  j a va2 s .c  o m*/
        boolean uploadedItems = false;
        mPassword = IOUtilities.xorDecode(settings.getExporterProperty(PASSWORD), 345903).trim();

        if (!settings.getExporterProperty(STORE_PASSWORD, false)) {
            if (!showLoginDialog(settings)) {
                return false;
            }
        }

        if (!settings.getExporterProperty(STORE_SETTINGS, false)) {
            if (!showCalendarSettings(settings)) {
                return false;
            }
        }

        GoogleService myService = new GoogleService("cl", "tvbrowser-tvbrowsercalenderplugin-"
                + CalendarExportPlugin.getInstance().getInfo().getVersion().toString());
        myService.setUserCredentials(settings.getExporterProperty(USERNAME).trim(), mPassword);

        URL postUrl = new URL("http://www.google.com/calendar/feeds/"
                + settings.getExporterProperty(SELECTED_CALENDAR) + "/private/full");

        SimpleDateFormat formatDay = new SimpleDateFormat("yyyy-MM-dd");
        formatDay.setTimeZone(TimeZone.getTimeZone("GMT"));
        SimpleDateFormat formatTime = new SimpleDateFormat("HH:mm:ss");
        formatTime.setTimeZone(TimeZone.getTimeZone("GMT"));

        ParamParser parser = new ParamParser();
        for (Program program : programs) {
            final String title = parser.analyse(formatting.getTitleValue(), program);

            // First step: search for event in calendar
            boolean createEvent = true;

            CalendarEventEntry entry = findEntryForProgram(myService, postUrl, title, program);

            if (entry != null) {
                int ret = JOptionPane.showConfirmDialog(null,
                        mLocalizer.msg("alreadyAvailable", "already available", program.getTitle()),
                        mLocalizer.msg("title", "Add event?"), JOptionPane.YES_NO_OPTION,
                        JOptionPane.QUESTION_MESSAGE);

                if (ret != JOptionPane.YES_OPTION) {
                    createEvent = false;
                }
            }

            // add event to calendar
            if (createEvent) {
                EventEntry myEntry = new EventEntry();

                myEntry.setTitle(new PlainTextConstruct(title));

                String desc = parser.analyse(formatting.getContentValue(), program);
                myEntry.setContent(new PlainTextConstruct(desc));

                Calendar c = CalendarToolbox.getStartAsCalendar(program);

                DateTime startTime = new DateTime(c.getTime(), c.getTimeZone());

                c = CalendarToolbox.getEndAsCalendar(program);

                DateTime endTime = new DateTime(c.getTime(), c.getTimeZone());

                When eventTimes = new When();

                eventTimes.setStartTime(startTime);
                eventTimes.setEndTime(endTime);

                myEntry.addTime(eventTimes);

                if (settings.getExporterProperty(REMINDER, false)) {
                    int reminderMinutes = 0;

                    try {
                        reminderMinutes = settings.getExporterProperty(REMINDER_MINUTES, 0);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }

                    if (settings.getExporterProperty(REMINDER_ALERT, false)) {
                        addReminder(myEntry, reminderMinutes, Reminder.Method.ALERT);
                    }

                    if (settings.getExporterProperty(REMINDER_EMAIL, false)) {
                        addReminder(myEntry, reminderMinutes, Reminder.Method.EMAIL);
                    }

                    if (settings.getExporterProperty(REMINDER_SMS, false)) {
                        addReminder(myEntry, reminderMinutes, Reminder.Method.SMS);
                    }

                }

                if (settings.isShowBusy()) {
                    myEntry.setTransparency(BaseEventEntry.Transparency.OPAQUE);
                } else {
                    myEntry.setTransparency(BaseEventEntry.Transparency.TRANSPARENT);
                }
                // Send the request and receive the response:
                myService.insert(postUrl, myEntry);
                uploadedItems = true;
            }
        }

        if (uploadedItems) {
            JOptionPane.showMessageDialog(CalendarExportPlugin.getInstance().getBestParentFrame(),
                    mLocalizer.msg("exportDone", "Google Export done."), mLocalizer.msg("export", "Export"),
                    JOptionPane.INFORMATION_MESSAGE);
        }

        return true;
    } catch (AuthenticationException e) {
        ErrorHandler.handle(mLocalizer.msg("loginFailure",
                "Problems during login to Service.\nMaybe bad username or password?"), e);
        settings.setExporterProperty(STORE_PASSWORD, false);
    } catch (Exception e) {
        ErrorHandler.handle(mLocalizer.msg("commError", "Error while communicating with Google!"), e);
    }

    return false;
}

From source file:com.rsltc.profiledata.main.MainActivity.java

private static void processDataSet(DataSet dataSet, InfoType type) {
    Log.i(TAG, "Data returned for Data type: " + dataSet.getDataType().getName());
    Calendar calendar = Calendar.getInstance();
    User user = new User();
    for (DataPoint dp : dataSet.getDataPoints()) {
        if (type == InfoType.BPM) {
            Float min = null, max = null, avg = null;
            Log.i(TAG, "Data point:");
            Log.i(TAG, "\tType: " + dp.getDataType().getName());
            calendar.setTimeInMillis(dp.getStartTime(TimeUnit.MILLISECONDS));
            Log.i(TAG, "\tStart: " + calendar.getTime());
            calendar.setTimeInMillis(dp.getEndTime(TimeUnit.MILLISECONDS));
            Log.i(TAG, "\tStop: " + calendar.getTime());
            Log.i(TAG, "Timezone: " + calendar.getTimeZone().getDisplayName());
            for (Field field : dp.getDataType().getFields()) {
                Log.i(TAG, "\tField: " + field.getName() + " Value: " + dp.getValue(field));
                if (field.equals(Field.FIELD_AVERAGE)) {
                    avg = dp.getValue(field).asFloat();
                } else if (field.equals(Field.FIELD_MIN)) {
                    min = dp.getValue(field).asFloat();
                } else if (field.equals(Field.FIELD_MAX)) {
                    max = dp.getValue(field).asFloat();
                } else {
                    Log.e(TAG, "Unsupported field found");
                }/*from ww  w  .ja  va2s  .  co  m*/
            }
            boolean valid = true;
            if (min != null && max != null && avg != null) {
                if (!HealthStatValidityChecker.checkIfNormal(avg, type)) {
                    avg = (max + min) / 2;
                    valid = HealthStatValidityChecker.checkIfNormal(avg, type);
                }
            } else {
                valid = false;
            }
            DailyHeartRate dailyHeartRate = new DailyHeartRate(avg != null ? avg : -1, max != null ? max : -1,
                    min != null ? min : -1, valid, DateUtils.dateToDateRelated(calendar));
        } else if (type == InfoType.USER_STATS) {
            Log.e(TAG, dp.toString());
            Log.i(TAG, "Data point:");
            Log.i(TAG, "\tType: " + dp.getDataType().getName());
            DataType datatype = dp.getDataType();
            calendar.setTimeInMillis(dp.getStartTime(TimeUnit.MILLISECONDS));
            String dayOfMeasurement = DateUtils.dateToDateRelated(calendar);
            if (datatype.equals(DataType.TYPE_HEIGHT)) {
                Log.e(TAG, "I have height");
                user.setHeight(dp.getValue(dp.getDataType().getFields().get(0)).asFloat());
            } else {
                Log.e(TAG, "I have weight");
                user.setWeight(MathUtil.round(dp.getValue(dp.getDataType().getFields().get(0)).asFloat(), 3));
            }

            Log.i(TAG, "\tStart: " + calendar.getTime());
            calendar.setTimeInMillis(dp.getEndTime(TimeUnit.MILLISECONDS));
            Log.i(TAG, "\tStop: " + calendar.getTime());
            for (Field field : dp.getDataType().getFields()) {
                Log.i(TAG, field.getName() + " " + dp.getValue(field));
            }

        }
    }
    if (type == InfoType.USER_STATS) {
        //persist the user
        Log.i(TAG, user.toString());
    }
}

From source file:helper.lang.DateHelperTest.java

@Test
public void testAsUtcDayDate() {
    Calendar localTime = Calendar.getInstance(TimeZone.getTimeZone("CST"));
    Calendar cal = DateHelper.asUtcDay(localTime.getTime());
    assertEquals(0, cal.get(Calendar.MILLISECOND));
    assertEquals(0, cal.get(Calendar.MINUTE));
    assertEquals(0, cal.get(Calendar.HOUR));
    assertEquals(0, cal.get(Calendar.HOUR_OF_DAY));
    assertEquals(DateHelper.UTC_TIME_ZONE, cal.getTimeZone());
    //assertEquals(TimeZone.getTimeZone("CST"), localTime.getTimeZone());
    //assertEquals(localTime.get(Calendar.YEAR), cal.get(Calendar.YEAR));
    //assertEquals(localTime.get(Calendar.MONTH), cal.get(Calendar.MONTH));
    //assertEquals(localTime.get(Calendar.DATE), cal.get(Calendar.DATE));
}

From source file:helper.lang.DateHelperTest.java

@Test
public void testTodayUtc() {
    Calendar localTime = Calendar.getInstance(DateHelper.UTC_TIME_ZONE);
    Calendar cal = DateHelper.todayUtc();
    assertEquals(localTime.get(Calendar.YEAR), cal.get(Calendar.YEAR));
    assertEquals(localTime.get(Calendar.MONTH), cal.get(Calendar.MONTH));
    assertEquals(localTime.get(Calendar.DATE), cal.get(Calendar.DATE));

    assertEquals(DateHelper.UTC_TIME_ZONE, cal.getTimeZone());
    assertEquals(0, cal.get(Calendar.MILLISECOND));
    assertEquals(0, cal.get(Calendar.MINUTE));
    assertEquals(0, cal.get(Calendar.HOUR));
    assertEquals(0, cal.get(Calendar.HOUR_OF_DAY));
}

From source file:RhodesService.java

public static String getTimezoneStr() {
    Calendar cal = Calendar.getInstance();
    TimeZone tz = cal.getTimeZone();
    return tz.getDisplayName();
}

From source file:com.rsltc.profiledata.main.MainActivity.java

private static void processSpeedSumary(DataSet dataSet, InfoType type, SpeedSummary summary,
        String currentType) {/*from w  w  w.jav  a2  s .  com*/
    Calendar calendar = Calendar.getInstance();
    for (DataPoint dp : dataSet.getDataPoints()) {
        Float min = null, max = null, avg = null;
        Log.i(TAG, "Data point:");
        Log.i(TAG, "\tType: " + dp.getDataType().getName());
        Long startTime = dp.getStartTime(TimeUnit.MILLISECONDS);
        calendar.setTimeInMillis(startTime);
        Log.i(TAG, "\tStart: " + calendar.getTime());
        Long stopTime = dp.getEndTime(TimeUnit.MILLISECONDS);
        calendar.setTimeInMillis(stopTime);
        Log.i(TAG, "\tStop: " + calendar.getTime());

        Long duration = stopTime - startTime;
        Log.i(TAG, "Timezone: " + calendar.getTimeZone().getDisplayName());
        for (Field field : dp.getDataType().getFields()) {
            Log.i(TAG, "\tField: " + field.getName() + " Value: " + dp.getValue(field));
            if (field.equals(Field.FIELD_AVERAGE)) {
                avg = dp.getValue(field).asFloat();
            } else if (field.equals(Field.FIELD_MIN)) {
                min = dp.getValue(field).asFloat();
            } else if (field.equals(Field.FIELD_MAX)) {
                max = dp.getValue(field).asFloat();
            } else {
                Log.e(TAG, "Unsupported field found");
            }
        }
        boolean valid = false;
        if (min != null && max != null && avg != null) {
            // TODO: build check for speeds
            if (!(valid = HealthStatValidityChecker.checkAvgSpeed(avg, currentType))) {
                avg = (max + min) / 2;
                valid = HealthStatValidityChecker.checkAvgSpeed(avg, currentType);
            }
        }
        if (valid) {
            summary.setMaxSpeedIfGreater(max);
            summary.setMinSpeedIfSmaller(min);
            summary.setMaxDurationIfLonger(duration);
            summary.setMinDurationIfShorter(duration);
            double count = summary.getCount();
            summary.setAvgSpeed((summary.getAvgSpeed() * count + avg) / (count + 1));
            summary.setAvgDuration((float) ((summary.getAvgDuration() * count + duration) / (count + 1)));
            summary.increaseCount();
        }

    }
}

From source file:org.pentaho.cdf.context.ContextEngine.java

protected JSONObject buildContextDates(final JSONObject contextObj) throws JSONException {
    Calendar cal = Calendar.getInstance();

    long utcTime = cal.getTimeInMillis();
    contextObj.put("serverLocalDate", utcTime + cal.getTimeZone().getOffset(utcTime));
    contextObj.put("serverUTCDate", utcTime);
    return contextObj;
}

From source file:org.jasig.portlet.cms.controller.EditPostController.java

private void savePost(final ActionRequest request, final BindingResult result, Post post,
        boolean postIsScheduled, String scheduledDate, boolean removeExistingPost)
        throws PortletRequestBindingException, JcrRepositoryException {

    final PortletPreferencesWrapper pref = new PortletPreferencesWrapper(request);
    final Calendar cldr = Calendar.getInstance(request.getLocale());

    final DateTimeZone zone = DateTimeZone.forTimeZone(cldr.getTimeZone());
    final DateTime today = new DateTime(zone);

    final DateTimeFormatter fmt = DateTimeFormat.forPattern(PortletPreferencesWrapper.DEFAULT_POST_DATE_FORMAT);
    post.setLastModifiedDate(today.toString(fmt));

    post.setLanguage(request.getLocale().getLanguage());

    if (postIsScheduled) {
        if (StringUtils.isBlank(scheduledDate))
            result.rejectValue("scheduledDate", "invalid.scheduled.post.publish.date");
        else {//  www  .jav a 2  s.  co  m

            logDebug("Post is scheduled to be published on " + scheduledDate);
            final DateTime dt = DateTime.parse(scheduledDate, fmt);
            post.setScheduledDate(dt.toString(fmt));

            if (removeExistingPost) {
                if (getRepositoryDao().exists(post.getPath())) {
                    logDebug("Preparing scheduled post. Removing existing post at " + post.getPath());
                    getRepositoryDao().removePost(post.getPath());
                }
            }

            getRepositoryDao().schedulePost(post, pref.getPortletRepositoryRoot());
            ensureRepositoryRootIsScheduled(pref);
        }
    } else {
        post = preparePost(post, request);

        getRepositoryDao().setPost(post);
    }
}

From source file:com.exadel.flamingo.flex.messaging.amf.io.AMF0Deserializer.java

/**
 * Reads date/* w w w.j  a  va2 s .  co m*/
 *
 * @return
 * @throws IOException
 */
protected Date readDate() throws IOException {
    long ms = (long) inputStream.readDouble(); // Date in millis from 01/01/1970

    // here we have to read in the raw
    // timezone offset (which comes in minutes, but incorrectly signed),
    // make it millis, and fix the sign.
    int timeoffset = inputStream.readShort() * 60000 * -1; // now we have millis

    TimeZone serverTimeZone = TimeZone.getDefault();

    // now we subtract the current timezone offset and add the one that was passed
    // in (which is of the Flash client), which gives us the appropriate ms (i think)
    // -alon
    Calendar sent = new GregorianCalendar();
    sent.setTime((new Date(ms - serverTimeZone.getRawOffset() + timeoffset)));

    TimeZone sentTimeZone = sent.getTimeZone();

    // we have to handle daylight savings ms as well
    if (sentTimeZone.inDaylightTime(sent.getTime())) {
        //
        // Implementation note: we are trying to maintain compatibility
        // with J2SE 1.3.1
        //
        // As such, we can't use java.util.Calendar.getDSTSavings() here
        // 
        sent.setTime(new java.util.Date(sent.getTime().getTime() - 3600000));
    }

    return sent.getTime();
}

From source file:org.eclipse.skalli.services.scheduler.Schedule.java

/**
 * Returns <code>true</code> if the recurring task that this schedule describes
 * was due somewhen between <code>first</code> and <code>last</code> (including the
 * interval boundaries)./* w  ww. j a va 2s  .c  om*/
 *
 * @param first  the begin of the interval to check, or <code>null</code>. In that case
 * the method is equivalent to {@link #isDue(Calendar)}.
 * @param last  the end of the interval to check
 *
 * @return  <code>true</code>, if the task is due.
 */
public boolean isDue(Calendar first, Calendar last) {
    if (isDue(last)) {
        return true;
    }

    if (first == null) {
        return false;
    }

    Calendar i = new GregorianCalendar(first.getTimeZone());
    i.setTime(first.getTime());
    i.add(Calendar.MINUTE, 1);
    while (i.before(last)) {
        if (isDue(i)) {
            return true;
        }
        i.add(Calendar.MINUTE, 1);
    }

    return false;
}