Example usage for java.util TimeZone setDefault

List of usage examples for java.util TimeZone setDefault

Introduction

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

Prototype

public static void setDefault(TimeZone zone) 

Source Link

Document

Sets the TimeZone that is returned by the getDefault method.

Usage

From source file:ca.oson.json.gson.functional.DefaultTypeAdaptersTest.java

public void testTimestampSerialization() throws Exception {
    TimeZone defaultTimeZone = TimeZone.getDefault();
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    Locale defaultLocale = Locale.getDefault();
    Locale.setDefault(Locale.US);
    try {//from w  w  w .ja va 2  s.c  om
        Timestamp timestamp = new Timestamp(0L);
        //Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        String json = oson.setDateFormat("yyyy-MM-dd").toJson(timestamp, Timestamp.class);
        assertEquals("1970-01-01", json);
        assertEquals(0, oson.fromJson("\"1970-01-01\"", Timestamp.class).getTime());
    } finally {
        TimeZone.setDefault(defaultTimeZone);
        Locale.setDefault(defaultLocale);
    }
}

From source file:ca.oson.json.gson.functional.DefaultTypeAdaptersTest.java

public void testSqlDateSerialization() throws Exception {
    TimeZone defaultTimeZone = TimeZone.getDefault();
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    Locale defaultLocale = Locale.getDefault();
    Locale.setDefault(Locale.US);
    try {//from w w w . j av a2s  .c  om
        java.sql.Date sqlDate = new java.sql.Date(0L);
        //Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        String json = oson.setDateFormat("yyyy-MM-dd").toJson(sqlDate, Timestamp.class);
        assertEquals("1970-01-01", json);
        assertEquals(0, oson.fromJson("\"1970-01-01\"", java.sql.Date.class).getTime());
    } finally {
        TimeZone.setDefault(defaultTimeZone);
        Locale.setDefault(defaultLocale);
    }
}

From source file:org.alfresco.repo.search.impl.solr.SolrQueryHTTPClientTest.java

@Test
public void testBuildRangeDate() throws UnsupportedEncodingException {
    TimeZone defaultTimeZone = TimeZone.getDefault();
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

    SearchParameters params = new SearchParameters();
    params.setSearchTerm("A*");
    List<RangeParameters> ranges = new ArrayList<RangeParameters>();
    ranges.add(new RangeParameters("created", "2015", "2016", "+1MONTH", true, Collections.emptyList(),
            Collections.emptyList(), null, null));
    params.setRanges(ranges);//from w  w  w .j  a va2 s  .c  o m
    StringBuilder urlBuilder = new StringBuilder();
    client.buildRangeParameters(params, encoder, urlBuilder);
    String url = urlBuilder.toString();
    assertNotNull(url);
    assertTrue(url.contains("&facet=true"));
    assertTrue(url.contains("&facet.range=created"));
    assertTrue(url.contains("&f.created.facet.range.start=2015-01-01T00%3A00%3A00.000Z"));
    assertTrue(url.contains("&f.created.facet.range.end=2016-12-31T23%3A59%3A59.999Z"));
    assertTrue(url.contains("&f.created.facet.range.gap=%2B1MONTH"));

    TimeZone.setDefault(defaultTimeZone);
}

From source file:se.sics.kompics.p2p.experiment.dsl.SimulationScenario.java

/**
 * Executes simulation.// w  w  w.  ja va  2 s  .  co  m
 * 
 * @param main
 *            the main
 */
public final void simulate(Class<? extends ComponentDefinition> main) {
    store();

    try {
        Loader cl = AccessController.doPrivileged(new PrivilegedAction<Loader>() {
            @Override
            public Loader run() {
                return new Loader();
            }
        });
        cl.addTranslator(ClassPool.getDefault(), new TimeInterceptor(null));
        Thread.currentThread().setContextClassLoader(cl);
        TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
        cl.run(main.getCanonicalName(), null);
    } catch (Throwable e) {
        throw new RuntimeException("Exception caught during simulation", e);
    }
}

From source file:se.sics.kompics.p2p.experiment.dsl.SimulationScenario.java

/**
 * Transform.//w w  w.j av a 2s. c o m
 * 
 * @param main
 *            the main
 * @param directory
 *            the directory
 */
public final void transform(Class<? extends ComponentDefinition> main, String directory) {
    Properties p = new Properties();

    File dir = null;
    File file = null;
    try {
        dir = new File(directory);
        dir.mkdirs();
        dir.setWritable(true);
        file = File.createTempFile("scenario", ".bin", dir);
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
        oos.writeObject(this);
        oos.flush();
        oos.close();
        System.setProperty("scenario", file.getAbsolutePath());
        p.setProperty("scenario", file.getAbsolutePath());
        p.store(new FileOutputStream(file.getAbsolutePath() + ".properties"), null);
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        Loader cl = AccessController.doPrivileged(new PrivilegedAction<Loader>() {
            @Override
            public Loader run() {
                return new Loader();
            }
        });
        cl.addTranslator(ClassPool.getDefault(), new TimeInterceptor(dir));
        Thread.currentThread().setContextClassLoader(cl);
        TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
        cl.run(main.getCanonicalName(), null);
    } catch (Throwable e) {
        throw new RuntimeException("Exception caught during simulation", e);
    }
}

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

@Test
@Parameters(method = "useNativeGit")
public void shouldUseDateFormatTimeZone(boolean useNativeGit) throws Exception {
    // given//from www . j a va  2s. c o  m
    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.mb.framework.util.DateTimeUtil.java

/**
 * This method is used for convert Milli seconds into Date
 * /*  w w w  .  java2s .  c o  m*/
 * @param milliSeconds
 * @return Date
 * @throws ParseException
 */
public static Date convertMilliSecIntoDate(String milliSeconds) throws ParseException {
    String dateStr = null;
    Date d = null;
    TimeZone.setDefault(TimeZone.getTimeZone(AppConstant.DEFAULT_TIMEZONE));

    if (null != milliSeconds) {
        long milliSecondsLong = Long.parseLong(milliSeconds);

        logger.info("milliSecondsLong: " + milliSecondsLong);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(milliSecondsLong);

        SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // formatter1.setTimeZone(TimeZone.getTimeZone(AppConstant.DEFAULT_TIMEZONE));
        dateStr = formatter1.format(calendar.getTime());

        d = formatter1.parse(dateStr);

        logger.info("date in default time zone: " + d);

    }

    return d;
}

From source file:org.joget.apps.app.service.AppServiceImpl.java

/**
 * Create a new app definition and duplicate the other app
 * @param appDefinition/*  w ww .ja v  a2s .  c om*/
 * @param copyAppDefinition
 * @return A Collection of errors (if any).
 */
@Transactional
public Collection<String> createAppDefinition(AppDefinition appDefinition, AppDefinition copy) {
    Collection<String> errors = new ArrayList<String>();

    // check for duplicate
    String appId = appDefinition.getId();
    AppDefinition appDef = appDefinitionDao.loadById(appId);
    if (appDef != null) {
        errors.add("console.app.error.label.idExists");
    } else {
        if (copy != null) {
            byte[] appDefinitionXml = null;
            byte[] xpdl = null;
            ByteArrayOutputStream baos = null;

            TimeZone current = TimeZone.getDefault();
            TimeZone.setDefault(TimeZone.getTimeZone("GMT 0"));

            try {
                baos = new ByteArrayOutputStream();

                Serializer serializer = new Persister();
                serializer.write(copy, baos);

                appDefinitionXml = baos.toByteArray();
                baos.close();

                String value = new String(appDefinitionXml, "UTF-8");

                //replace id and name
                value = value.replaceAll("<id>" + copy.getAppId() + "</id>", "<id>" + appId + "</id>");
                value = value.replaceAll("<name>" + copy.getName() + "</name>",
                        "<name>" + appDefinition.getName() + "</name>");
                value = value.replaceAll("<appId>" + copy.getAppId() + "</appId>",
                        "<appId>" + appId + "</appId>");

                appDefinitionXml = value.getBytes("UTF-8");

                PackageDefinition packageDef = copy.getPackageDefinition();
                if (packageDef != null) {
                    xpdl = workflowManager.getPackageContent(packageDef.getId(),
                            packageDef.getVersion().toString());
                    Map<String, String> replace = new HashMap<String, String>();
                    replace.put(copy.getAppId(), appId);
                    replace.put(copy.getName(), appDefinition.getName());
                    xpdl = StringUtil.searchAndReplaceByteContent(xpdl, replace);
                }

                //import
                appDef = serializer.read(AppDefinition.class, new ByteArrayInputStream(appDefinitionXml),
                        false);
                @SuppressWarnings("unused")
                AppDefinition newAppDef = importAppDefinition(appDef, 1L, xpdl);
            } catch (Exception ex) {
                LogUtil.error(getClass().getName(), ex, "");
                appDefinitionDao.saveOrUpdate(appDefinition);
            } finally {
                if (baos != null) {
                    try {
                        baos.close();
                    } catch (Exception e) {
                        LogUtil.error(getClass().getName(), e, "");
                    }
                }

                TimeZone.setDefault(current);
            }

        } else {
            // create app
            appDefinitionDao.saveOrUpdate(appDefinition);
        }
    }

    return errors;
}

From source file:org.obm.opush.command.sync.SyncHandlerTest.java

@Test
public void testAddLeadingToNoPermissionExceptionReplyNothing() throws Exception {
    TimeZone defaultTimeZone = TimeZone.getDefault();
    TimeZone.setDefault(DateTimeZone.UTC.toTimeZone());

    SyncKey syncKey = new SyncKey("13424");
    CollectionId collectionId = CollectionId.of(1);
    ServerId serverId = collectionId.serverId(1);
    String clientId = "156";

    DataDelta serverDataDelta = DataDelta.newEmptyDelta(date("2012-10-10T16:22:53"), syncKey);

    MSEmail clientData = MSEmail.builder().header(MSEmailHeader.builder().build())
            .body(MSEmailBody.builder().mimeData(Optional.of(new SerializableInputStream("obm")))
                    .bodyType(MSEmailBodyType.PlainText).estimatedDataSize(0).charset(Charsets.UTF_8)
                    .truncated(false).build())
            .build();/* w w w  . ja v  a  2 s  .  c  o  m*/

    syncKeyTestUtils.mockNextGeneratedSyncKey(new SyncKey("2342"));
    syncTestUtils.mockEmailSyncClasses(syncKey, serverDataDelta, userAsList);

    UserDataRequest udr = new UserDataRequest(users.jaures.credentials, "Sync", users.jaures.device);
    expect(contentsImporter.importMessageChange(udr, collectionId, serverId, clientId, clientData))
            .andThrow(new NoPermissionException());

    mocksControl.replay();
    opushServer.start();

    OPClient opClient = testUtils.buildWBXMLOpushClient(users.jaures, opushServer.getHttpPort(), httpClient);
    SyncResponse syncResponse = opClient
            .run(syncBuilder.device(users.jaures.device)
                    .request(ClientSyncRequest.builder().addCollection(AnalysedSyncCollection.builder()
                            .collectionId(collectionId).syncKey(syncKey).dataType(PIMDataType.EMAIL)
                            .command(SyncCollectionCommandRequest.builder().type(SyncCommand.ADD)
                                    .serverId(serverId).clientId(clientId).applicationData(clientData).build())
                            .build()).build())
                    .build());

    assertThat(syncResponse.getStatus()).isEqualTo(SyncStatus.OK);
    syncTestUtils.checkMailFolderHasNoChange(syncResponse, collectionId);
    TimeZone.setDefault(defaultTimeZone);
}

From source file:com.mb.framework.util.DateTimeUtil.java

/**
 * This method is used for convert Date into Milli seconds
 * /* ww w . ja va  2 s  .  c  o m*/
 * @param Date
 * @return String
 * @throws ParseException
 */
public static String convertDateIntoMilliSec(Date date) throws ParseException {
    String milliSec = null;
    TimeZone.setDefault(TimeZone.getTimeZone(AppConstant.DEFAULT_TIMEZONE));

    if (null != date) {
        milliSec = String.valueOf(date.getTime());
    }
    return milliSec;
}