Example usage for java.util TimeZone getID

List of usage examples for java.util TimeZone getID

Introduction

In this page you can find the example usage for java.util TimeZone getID.

Prototype

public String getID() 

Source Link

Document

Gets the ID of this time zone.

Usage

From source file:org.obiba.mica.config.locale.AngularCookieLocaleResolver.java

private void parseLocaleCookieIfNecessary(HttpServletRequest request) {
    if (request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME) == null) {
        // Retrieve and parse cookie value.
        Cookie cookie = WebUtils.getCookie(request, getCookieName());
        Locale locale = null;// w  ww  .j  av  a  2s .  com
        TimeZone timeZone = null;
        if (cookie != null) {
            String value = cookie.getValue();

            // Remove the double quote
            value = StringUtils.replace(value, "%22", "");

            String localePart = value;
            String timeZonePart = null;
            int spaceIndex = localePart.indexOf(' ');
            if (spaceIndex != -1) {
                localePart = value.substring(0, spaceIndex);
                timeZonePart = value.substring(spaceIndex + 1);
            }
            locale = "-".equals(localePart) ? null : StringUtils.parseLocaleString(localePart);
            if (timeZonePart != null) {
                timeZone = StringUtils.parseTimeZoneString(timeZonePart);
            }
            if (logger.isTraceEnabled()) {
                logger.trace("Parsed cookie value [" + cookie.getValue() + "] into locale '" + locale + "'"
                        + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : ""));
            }
        }
        request.setAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME,
                locale == null ? determineDefaultLocale(request) : locale);
        request.setAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME,
                timeZone == null ? determineDefaultTimeZone(request) : timeZone);
    }
}

From source file:io.github.jhipster.config.locale.AngularCookieLocaleResolver.java

private void parseLocaleCookieIfNecessary(HttpServletRequest request) {
    if (request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME) == null) {
        // Retrieve and parse cookie value.
        Cookie cookie = WebUtils.getCookie(request, getCookieName());
        Locale locale = null;/*w w w  .j  av  a  2 s .  c  o m*/
        TimeZone timeZone = null;
        if (cookie != null) {
            String value = cookie.getValue();

            // Remove the double quote
            value = StringUtils.replace(value, "%22", "");

            String localePart = value;
            String timeZonePart = null;
            int spaceIndex = localePart.indexOf(' ');
            if (spaceIndex != -1) {
                localePart = value.substring(0, spaceIndex);
                timeZonePart = value.substring(spaceIndex + 1);
            }
            locale = !"-".equals(localePart) ? StringUtils.parseLocaleString(localePart.replace('-', '_'))
                    : null;
            if (timeZonePart != null) {
                timeZone = StringUtils.parseTimeZoneString(timeZonePart);
            }
            if (logger.isTraceEnabled()) {
                logger.trace("Parsed cookie value [" + cookie.getValue() + "] into locale '" + locale + "'"
                        + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : ""));
            }
        }
        request.setAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME,
                locale != null ? locale : determineDefaultLocale(request));

        request.setAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME,
                timeZone != null ? timeZone : determineDefaultTimeZone(request));
    }
}

From source file:org.apache.logging.log4j.core.util.datetime.FastDateParserTest.java

private void validateSdfFormatFdpParseEquality(final String format, final Locale locale, final TimeZone tz,
        final DateParser fdp, final Date in, final int year, final Date cs) throws ParseException {
    final SimpleDateFormat sdf = new SimpleDateFormat(format, locale);
    sdf.setTimeZone(tz);/*  w w w.ja  v a 2s  . com*/
    if (format.equals(SHORT_FORMAT)) {
        sdf.set2DigitYearStart(cs);
    }
    final String fmt = sdf.format(in);
    try {
        final Date out = fdp.parse(fmt);
        assertEquals(locale.toString() + " " + in + " " + format + " " + tz.getID(), in, out);
    } catch (final ParseException pe) {
        if (year >= 1868 || !locale.getCountry().equals("JP")) {// LANG-978
            throw pe;
        }
    }
}

From source file:org.apache.logging.log4j.core.util.datetime.FastDateParserTest.java

@Test
public void testTzParses() throws Exception {
    // Check that all Locales can parse the time formats we use
    for (final Locale locale : Locale.getAvailableLocales()) {
        final FastDateParser fdp = new FastDateParser("yyyy/MM/dd z", TimeZone.getDefault(), locale);

        for (final TimeZone tz : new TimeZone[] { NEW_YORK, REYKJAVIK, GMT }) {
            final Calendar cal = Calendar.getInstance(tz, locale);
            cal.clear();/*from   w w w. j  ava 2 s .  com*/
            cal.set(Calendar.YEAR, 2000);
            cal.set(Calendar.MONTH, 1);
            cal.set(Calendar.DAY_OF_MONTH, 10);
            final Date expected = cal.getTime();

            final Date actual = fdp.parse("2000/02/10 " + tz.getDisplayName(locale));
            Assert.assertEquals("tz:" + tz.getID() + " locale:" + locale.getDisplayName(), expected, actual);
        }
    }
}

From source file:com.ecyrd.jspwiki.ui.TemplateManager.java

/**
 * List all timezones, with special marker for server timezone
 * // w  ww. j av  a 2 s.com
 * @param pageContext
 * @return map of TimeZones
 * @since 2.7.x
 */
public Map listTimeZones(PageContext pageContext) {
    LinkedHashMap<String, String> resultMap = new LinkedHashMap<String, String>();

    String[][] tzs = { { "GMT-12", "Enitwetok, Kwajalien" }, { "GMT-11", "Nome, Midway Island, Samoa" },
            { "GMT-10", "Hawaii" }, { "GMT-9", "Alaska" }, { "GMT-8", "Pacific Time" },
            { "GMT-7", "Mountain Time" }, { "GMT-6", "Central Time, Mexico City" },
            { "GMT-5", "Eastern Time, Bogota, Lima, Quito" }, { "GMT-4", "Atlantic Time, Caracas, La Paz" },
            { "GMT-3:30", "Newfoundland" }, { "GMT-3", "Brazil, Buenos Aires, Georgetown, Falkland Is." },
            { "GMT-2", "Mid-Atlantic, Ascention Is., St Helena" }, { "GMT-1", "Azores, Cape Verde Islands" },
            { "GMT", "Casablanca, Dublin, Edinburgh, London, Lisbon, Monrovia" },
            { "GMT+1", "Berlin, Brussels, Copenhagen, Madrid, Paris, Rome" },
            { "GMT+2", "Helsinki, Athens, Kaliningrad, South Africa, Warsaw" },
            { "GMT+3", "Baghdad, Riyadh, Moscow, Nairobi" }, { "GMT+3:30", "Tehran" },
            { "GMT+4", "Adu Dhabi, Baku, Muscat, Tbilisi" }, { "GMT+4:30", "Kabul" },
            { "GMT+5", "Islamabad, Karachi, Tashkent" }, { "GMT+5:30", "Bombay, Calcutta, Madras, New Delhi" },
            { "GMT+6", "Almaty, Colomba, Dhakra" }, { "GMT+7", "Bangkok, Hanoi, Jakarta" },
            { "GMT+8", "Beijing, Hong Kong, Perth, Singapore, Taipei" },
            { "GMT+9", "Osaka, Sapporo, Seoul, Tokyo, Yakutsk" }, { "GMT+9:30", "Adelaide, Darwin" },
            { "GMT+10", "Melbourne, Papua New Guinea, Sydney, Vladivostok" },
            { "GMT+11", "Magadan, New Caledonia, Solomon Islands" },
            { "GMT+12", "Auckland, Wellington, Fiji, Marshall Island" } };

    java.util.TimeZone servertz = java.util.TimeZone.getDefault();

    for (int i = 0; i < tzs.length; i++) {
        String tzID = tzs[i][0];
        java.util.TimeZone tz = java.util.TimeZone.getTimeZone(tzID);

        String serverTimeZone = "";

        if (servertz.getRawOffset() == tz.getRawOffset()) {
            serverTimeZone = LocaleSupport.getLocalizedMessage(pageContext, I18NSERVER_TIMEZONE);
            tzID = servertz.getID();
        }

        resultMap.put(tzID, "(" + tzs[i][0] + ") " + tzs[i][1] + " " + serverTimeZone);
    }

    return resultMap;
}

From source file:pl.project13.maven.git.GitCommitIdMojoIntegrationTest.java

@Test
@Parameters(method = "useNativeGit")
public void shouldUseDateFormatTimeZone(boolean useNativeGit) throws Exception {
    // given// w w w . j a v  a  2s. com
    mavenSandbox.withParentProject("my-pom-project", "pom").withChildProject("my-jar-module", "jar")
            .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG_DIRTY).create();
    MavenProject targetProject = mavenSandbox.getChildProject();

    setProjectToExecuteMojoIn(targetProject);

    // RFC 822 time zone: Sign TwoDigitHours Minutes
    String dateFormat = "Z"; // we want only the timezone (formated in RFC 822) out of the dateformat (easier for asserts)
    String expectedTimeZoneOffset = "+0200";
    String executionTimeZoneOffset = "-0800";
    TimeZone expectedTimeZone = TimeZone.getTimeZone("GMT" + expectedTimeZoneOffset);
    TimeZone executionTimeZone = TimeZone.getTimeZone("GMT" + executionTimeZoneOffset);

    GitDescribeConfig gitDescribeConfig = createGitDescribeConfig(true, 7);
    alterMojoSettings("gitDescribe", gitDescribeConfig);
    alterMojoSettings("useNativeGit", useNativeGit);
    alterMojoSettings("dateFormat", dateFormat);
    alterMojoSettings("dateFormatTimeZone", expectedTimeZone.getID());

    // override the default timezone for execution and testing
    TimeZone currentDefaultTimeZone = TimeZone.getDefault();
    TimeZone.setDefault(executionTimeZone);

    // when
    mojo.execute();

    // then
    Properties properties = targetProject.getProperties();
    assertThat(properties.stringPropertyNames()).contains("git.commit.time");
    assertThat(properties.getProperty("git.commit.time")).isEqualTo(expectedTimeZoneOffset);

    assertThat(properties.stringPropertyNames()).contains("git.build.time");
    assertThat(properties.getProperty("git.build.time")).isEqualTo(expectedTimeZoneOffset);

    // set the timezone back
    TimeZone.setDefault(currentDefaultTimeZone);
}

From source file:com.intuit.wasabi.api.ExperimentsResource.java

/**
 * Returns all user assignments for a given experiment ID.  Will return null assignments
 * as well as those assigned to buckets within the experiment
 *
 * @param experimentID           the unique experiment ID
 * @param context                context (PROD, QA, etc.); Optional.
 * @param ignoreStringNullBucket if null bucket should be ignored
 * @param fromStringDate         the string formatted of the from date to download assignment
 * @param toStringDate           the string formatted of the to date to download assignment
 * @param timeZoneString         the string formatted of the timezone to use
 * @param authorizationHeader    the authorization headers
 * @return Response object containing metadata
 * @throws ParseException when date or timezone failed to parse
 *///w  ww.  j  a v a2 s .c  o  m
@GET
@Path("{experimentID}/assignments")
@Produces(TEXT_PLAIN)
@ApiOperation(value = "Download a list of user assignments for a given experiment ID", notes = "Shows list of all user assignments for a given experiment ID. Returns both null"
        + "assignments as well as bucket assignments.", response = StreamingOutput.class)
@Timed
public Response exportAssignments(
        @PathParam("experimentID") @ApiParam(value = "Experiment ID") final Experiment.ID experimentID,

        @QueryParam("context") @DefaultValue("PROD") @ApiParam(value = "context for the experiment, eg QA, PROD") final Context context,

        @QueryParam("ignoreNullBucket") @DefaultValue("false") @ApiParam(value = "Filtering on the null bucket") final String ignoreStringNullBucket,

        @QueryParam("fromDate") @ApiParam(value = "from date to download assignments") final String fromStringDate,

        @QueryParam("toDate") @ApiParam(value = "to date to download assignments") final String toStringDate,

        @QueryParam("timeZone") @ApiParam(value = "value of the time zone") final String timeZoneString,

        @HeaderParam(AUTHORIZATION) @ApiParam(value = EXAMPLE_AUTHORIZATION_HEADER, required = true) final String authorizationHeader)
        throws ParseException {
    if (authorizationHeader != null) {
        Username userName = authorization.getUser(authorizationHeader);
        Experiment experiment = experiments.getExperiment(experimentID);

        if (experiment == null) {
            throw new ExperimentNotFoundException(experimentID);
        }

        authorization.checkUserPermissions(userName, experiment.getApplicationName(), READ);
    }

    //Initializing the parameters
    Parameters parameters = new Parameters();
    //Setting the filtering behavior on the null buckets --default is set to get all the assignments
    Boolean ignoreNullBucket = FALSE;

    if (ignoreStringNullBucket != null) {
        ignoreNullBucket = Boolean.parseBoolean(ignoreStringNullBucket);
    }

    parameters.setTimeZone(getTimeZone(defaultTimezone));

    //Input format of the dates
    SimpleDateFormat sdf = new SimpleDateFormat(defaultTimeFormat);

    if (timeZoneString != null) {
        TimeZone timeZone = getTimeZone(timeZoneString);

        //Note: TimeZone.getTimeZone doesn't have an inbuilt error catch. Hence, the below check is necessary.
        // Allowed time zones http://tutorials.jenkov.com/java-date-time/java-util-timezone.html
        if (!timeZone.getID().equals(timeZoneString)) {
            throw new TimeZoneFormatException(timeZoneString);
        }

        sdf.setTimeZone(timeZone);
        // Resetting the default time zone value to user entered time zone.
        parameters.setTimeZone(timeZone);
    }

    if (fromStringDate != null) {
        try {
            Date fromDate = sdf.parse(fromStringDate);

            parameters.setFromTime(fromDate);
        } catch (ParseException e) {
            throw new TimeFormatException(fromStringDate);
        }
    }

    if (toStringDate != null) {
        try {
            Date toDate = sdf.parse(toStringDate);

            parameters.setToTime(toDate);
        } catch (ParseException e) {
            throw new TimeFormatException(toStringDate);
        }
    }

    StreamingOutput streamAssignment = assignments.getAssignmentStream(experimentID, context, parameters,
            ignoreNullBucket);

    return httpHeader.headers().header("Content-Disposition", "attachment; filename =\"assignments.csv\"")
            .entity(streamAssignment).build();
}

From source file:org.apache.openmeetings.db.dao.user.UserDao.java

public User addUser(Set<Right> rights, String firstname, String login, String lastname, long languageId,
        String userpass, Address adress, boolean sendSMS, Date age, String hash, TimeZone timezone,
        boolean forceTimeZoneCheck, String userOffers, String userSearchs, boolean showContactData,
        boolean showContactDataToContacts, String externalId, String externalType, List<Long> groupIds,
        String pictureuri) throws NoSuchAlgorithmException, UnsupportedEncodingException {

    User u = new User();
    u.setFirstname(firstname);//from   w w  w .  j a  va2 s  .co m
    u.setLogin(login);
    u.setLastname(lastname);
    u.setAge(age);
    u.setAddress(adress);
    u.setSendSMS(sendSMS);
    u.setRights(rights);
    u.setLastlogin(new Date());
    u.setLasttrans(new Long(0));
    u.setSalutation(Salutation.mr);
    u.setActivatehash(hash);
    u.setTimeZoneId(timezone.getID());
    u.setForceTimeZoneCheck(forceTimeZoneCheck);
    u.setExternalId(externalId);
    u.setExternalType(externalType);
    if (!Strings.isEmpty(u.getExternalType())) {
        u.setType(Type.external);
    }

    u.setUserOffers(userOffers);
    u.setUserSearchs(userSearchs);
    u.setShowContactData(showContactData);
    u.setShowContactDataToContacts(showContactDataToContacts);

    // this is needed cause the language is not a needed data at registering
    u.setLanguageId(languageId != 0 ? languageId : 1);
    if (!Strings.isEmpty(userpass)) {
        u.updatePassword(cfgDao, userpass);
    }
    u.setDeleted(false);
    u.setPictureuri(pictureuri);
    if (groupIds != null) {
        for (Long grpId : groupIds) {
            u.getGroupUsers().add(new GroupUser(groupDao.get(grpId), u));
        }
    }

    return update(u, null);
}

From source file:org.apache.openmeetings.web.app.WebSession.java

public String getClientTZCode() {
    TimeZone _zone = browserTz;
    if (browserTz == null) {
        try {//  ww w .j  av a 2 s.c o m
            browserTz = getClientInfo().getProperties().getTimeZone();
            if (browserTz != null && !AVAILABLE_TIMEZONE_SET.contains(browserTz.getID())) {
                for (String availableID : AVAILABLE_TIMEZONES) {
                    TimeZone zone = TimeZone.getTimeZone(availableID);
                    if (zone.hasSameRules(browserTz)) {
                        browserTz = zone;
                        break;
                    }
                }
            }
            _zone = browserTz;
        } catch (Exception e) {
            //no-op
        }
        if (browserTz == null) {
            _zone = Calendar.getInstance(getBrowserLocale()).getTimeZone();
        }
    }
    return _zone == null ? null : _zone.getID();
}

From source file:com.savor.ads.core.Session.java

/**
 * ?//from   w  w w.jav  a2s .c o m
 */
public String getDeviceInfo() {
    StringBuffer buffer = new StringBuffer();
    buffer.append("versionname=");
    buffer.append(versionName);
    buffer.append(";versioncode=");
    buffer.append(versionName);
    buffer.append(";macaddress=");
    buffer.append(getMacAddr());
    buffer.append(";buildversion=");
    buffer.append(buildVersion);
    buffer.append(versionCode);

    TimeZone timeZone = TimeZone.getDefault();
    buffer.append(";systemtimezone=");
    buffer.append(timeZone.getID());

    return buffer.toString();
}