Example usage for org.joda.time DateTimeZone setDefault

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

Introduction

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

Prototype

public static void setDefault(DateTimeZone zone) throws SecurityException 

Source Link

Document

Sets the default time zone.

Usage

From source file:org.bigloupe.web.scheduler.InitializeScheduler.java

License:Apache License

public InitializeScheduler(List<File> jobDirs, File logDir, File tempDir, MailerService mailerService,
        BigLoupeConfiguration configuration, boolean enableDevMode) throws IOException {
    this.jobDirs = Utils.nonNull(jobDirs);
    this.logsDir = Utils.nonNull(logDir);
    this.tempDir = Utils.nonNull(tempDir);
    this._mailerService = mailerService;

    if (!this.logsDir.exists())
        this.logsDir.mkdirs();

    if (!this.tempDir.exists())
        this.tempDir.mkdirs();

    for (File jobDir : jobDirs) {
        if (!jobDir.exists()) {
            logger.warn("Job directory " + jobDir + " does not exist. Creating.");
            jobDir.mkdirs();//from   ww w.  j  a  va2  s  . c o  m
        }
    }

    if (jobDirs.size() < 1)
        throw new IllegalArgumentException("No job directory given.");

    Props defaultProps = PropsUtils.loadPropsInDirs(jobDirs, ".properties", ".schema");

    _baseClassLoader = getBaseClassloader();

    String defaultTimezoneID = defaultProps.getString(DEFAULT_TIMEZONE_ID, null);
    if (defaultTimezoneID != null) {
        DateTimeZone.setDefault(DateTimeZone.forID(defaultTimezoneID));
        TimeZone.setDefault(TimeZone.getTimeZone(defaultTimezoneID));
    }

    NamedPermitManager permitManager = getNamedPermitManager(defaultProps);
    JobWrappingFactory factory = new JobWrappingFactory(permitManager, new ReadWriteLockManager(),
            logsDir.getAbsolutePath(), "java",
            new ImmutableMap.Builder<String, Class<? extends Job>>().put("java", JavaJob.class)
                    .put("command", ProcessJob.class).put("javaprocess", JavaProcessJob.class)
                    .put("map-reduce", MapReduceJob.class).put("pig", PigProcessJob.class)
                    .put("propertyPusher", NoopJob.class).put("python", PythonJob.class)
                    .put("ruby", RubyJob.class).put("script", ScriptJob.class)
                    .put("sqoop", SqoopProcessJob.class).put("indexfile", IndexFileProcessJob.class)
                    .put("noop", NoopJob.class).build());

    _hdfsUrl = defaultProps.getString("hdfs.instance.url", null);
    _jobManager = new JobManager(factory, logsDir.getAbsolutePath(), defaultProps, jobDirs, _baseClassLoader,
            configuration);

    String failureEmail = defaultProps.getString("job.failure.email", null);
    String successEmail = defaultProps.getString("job.success.email", null);
    int schedulerThreads = defaultProps.getInt("scheduler.threads", 50);
    _instanceName = defaultProps.getString(INSTANCE_NAME, "");

    final File initialJobDir = jobDirs.get(0);
    File schedule = getScheduleFile(defaultProps, initialJobDir);
    File backup = getBackupFile(defaultProps, initialJobDir);
    File executionsStorageDir = new File(defaultProps.getString("azkaban.executions.storage.dir",
            initialJobDir.getAbsolutePath() + "/executions"));
    if (!executionsStorageDir.exists())
        executionsStorageDir.mkdirs();
    long lastExecutionId = getLastExecutionId(executionsStorageDir);
    logger.info(String.format("Using path[%s] for storing executions.", executionsStorageDir));
    logger.info(String.format("Last known execution id was [%s]", lastExecutionId));

    final ExecutableFlowSerializer flowSerializer = new DefaultExecutableFlowSerializer();
    final ExecutableFlowDeserializer flowDeserializer = new DefaultExecutableFlowDeserializer(_jobManager,
            factory);

    FlowExecutionSerializer flowExecutionSerializer = new FlowExecutionSerializer(flowSerializer);
    FlowExecutionDeserializer flowExecutionDeserializer = new FlowExecutionDeserializer(flowDeserializer);

    _allFlows = new CachingFlowManager(
            new RefreshableFlowManager(_jobManager, flowExecutionSerializer, flowExecutionDeserializer,
                    executionsStorageDir, lastExecutionId),
            defaultProps.getInt("azkaban.flow.cache.size", 1000));
    _jobManager.setFlowManager(_allFlows);

    _jobExecutorManager = new JobExecutorManager(_allFlows, _jobManager, failureEmail, successEmail,
            schedulerThreads);

    this._schedulerManager = new ScheduleManager(_jobExecutorManager,
            new LocalFileScheduleLoader(schedule, backup));

    /* set predefined log url prefix 
    */
    String server_url = defaultProps.getString("server.url", null);
    if (server_url != null) {
        if (server_url.endsWith("/"))
            _jobExecutorManager.setRuntimeProperty(BigLoupeConfiguration.DEFAULT_LOG_URL_PREFIX,
                    server_url + "logs?file=");
        else
            _jobExecutorManager.setRuntimeProperty(BigLoupeConfiguration.DEFAULT_LOG_URL_PREFIX,
                    server_url + "/logs?file=");
    }

}

From source file:org.craftercms.search.service.impl.SolrDocumentBuilder.java

License:Open Source License

@PostConstruct
public void init() {
    DateTimeZone.setDefault(DateTimeZone.UTC);
}

From source file:org.envirocar.server.core.guice.CoreModule.java

License:Open Source License

@Override
protected void configure() {
    bind(DataService.class).to(DataServiceImpl.class);
    bind(UserService.class).to(UserServiceImpl.class);
    bind(FriendService.class).to(FriendServiceImpl.class);
    bind(GroupService.class).to(GroupServiceImpl.class);
    bind(StatisticsService.class).to(StatisticsServiceImpl.class);
    bind(ActivityListener.class).asEagerSingleton();
    bind(PasswordEncoder.class).to(BCryptPasswordEncoder.class);
    DateTimeZone.setDefault(DateTimeZone.UTC);
}

From source file:org.fcrepo.server.utilities.DateUtility.java

License:fedora commons license

/**
 * Attempt to parse the given string of form: yyyy-MM-dd[THH:mm:ss[.SSS][Z]]
 * as a Date./*  w w  w  .j a  va 2  s . c om*/
 * 
 * @param dateString
 *            the date string to parse
 * @return a Date representation of the dateString
 * @throws ParseException
 *             if dateString is null, empty or is otherwise unable to be
 *             parsed.
 */
public static Date parseDateStrict(String dateString) throws ParseException {
    try {
        if (dateString == null) {
            throw new ParseException("Argument cannot be null.", 0);
        }

        final int last = dateString.length() - 1;
        if (last == -1) {
            throw new ParseException("Argument cannot be empty.", 0);
        } else if (dateString.charAt(last) == '.') {
            throw new ParseException("dateString ends with invalid character.", last);
        }
        // SimpleDateFormat formatter = new SimpleDateFormat();
        // formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        final int length = (dateString.charAt(0) != '-') ? last + 1 : last;
        DateTimeFormatter formatter = FORMATTER_MILLISECONDS_T_Z;
        if (dateString.charAt(last) == 'Z') {
            if (length == 11) {
                // formatter.applyPattern("yyyy-MM-dd'Z'");
                formatter = FORMATTER_DATE_Z;
            } else if (length == 20) {
                // formatter.applyPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
                formatter = FORMATTER_SECONDS_T_Z;
            } else if (length > 21 && length < 24) {
                // right-pad the milliseconds with 0s up to three places
                int endIndex = last - 1;
                int dotIndex = dateString.lastIndexOf('.');
                int padding = 3 - (endIndex - dotIndex);
                if (padding > 0) {
                    StringBuilder sb = new StringBuilder(24);
                    sb.append(dateString.subSequence(0, last));
                    switch (padding) {
                    case 3:
                        sb.append('0');
                    case 2:
                        sb.append('0');
                    case 1:
                        sb.append('0');
                    }
                    sb.append('Z');
                    dateString = sb.toString();
                }
                // formatter.applyPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
                formatter = FORMATTER_MILLISECONDS_T_Z;
            } else if (length == 24) {
                // formatter.applyPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
                formatter = FORMATTER_MILLISECONDS_T_Z;
            }
        } else {
            if (length == 10) {
                // formatter.applyPattern("yyyy-MM-dd");
                formatter = FORMATTER_DATE;
            } else if (length == 19) {
                // formatter.applyPattern("yyyy-MM-dd'T'HH:mm:ss");
                formatter = FORMATTER_SECONDS_T;
            } else if (length > 20 && length < 23) {
                // right-pad millis with 0s
                int endIndex = dateString.length() - 1;
                int dotIndex = dateString.lastIndexOf('.');
                int padding = 3 - (endIndex - dotIndex);
                if (padding > 0) {
                    StringBuilder sb = new StringBuilder(23);
                    sb.append(dateString);
                    switch (padding) {
                    case 3:
                        sb.append('0');
                    case 2:
                        sb.append('0');
                    case 1:
                        sb.append('0');
                    }
                    dateString = sb.toString();
                }
                // formatter.applyPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
                formatter = FORMATTER_MILLISECONDS_T;
            } else if (length == 23) {
                // formatter.applyPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
                formatter = FORMATTER_MILLISECONDS_T;
            } else if (dateString.endsWith("GMT") || dateString.endsWith("UTC")) {
                // formatter.applyPattern("EEE, dd MMMM yyyyy HH:mm:ss z");
                // this has to be done by hand since Joda time can't parse
                // the timezone
                // see
                // http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html
                dateString = dateString.substring(0, last - 3);
                formatter = FORMATTER_TIMEZONE;
            }
        }
        DateTimeZone.setDefault(DateTimeZone.UTC);
        DateTime dt = formatter.parseDateTime(dateString);
        return dt.toDate();
    } catch (IllegalArgumentException e) {
        throw new ParseException(e.getLocalizedMessage(), 0);
    }
}

From source file:org.n52.tamis.core.javarepresentations.processes.execute.TimespanToSosTemporalFilterConverter.java

License:Open Source License

/**
 * Converts a timespan String that describes a time interval in IS= 8601
 * format to a SOS temporalFilter String.
 * // w w w .j  a  va 2 s .  co  m
 * E.g.: the timespan "PT12H/2013-08-06" will be converted to the String
 * "2013-08-05T12:00:00.000Z/2013-08-06T00:00:00.000Z", which may serve as
 * temporalFIlter parameter in a SOS GetObservation request.
 * 
 * @param timespan
 *            an ISO 8601 encoded timespan.
 * @return a String, consisting of "{startTime}/{endTime}",which may serve
 *         as temporalFIlter parameter in a SOS GetObservation request
 * @throws IOException
 */
public static String convertIso8601TimespanToSosTemporalFilter(String timespan) throws IOException {
    // /*
    // * if timespan String contains a "Z" then the parsed time shall be
    // interpreted as UTC.
    // * A timespan String like "PT12H/2013-08-06Z" cannot be parsed due to
    // the final Z; parser throws malformed format exception.
    // *
    // * Hence, we set UTC and standard interpretation and remove the Z from
    // the String
    // */
    // if (encodedTimespan.contains("Z")){
    // DateTimeZone.setDefault(DateTimeZone.UTC);
    //
    // encodedTimespan.
    // }

    try {

        // set UTC as standard time
        DateTimeZone.setDefault(DateTimeZone.UTC);

        Interval timeInterval = Interval.parse(timespan);

        DateTime startTime = timeInterval.getStart();
        DateTime endTime = timeInterval.getEnd();

        String sosTemproalFilter = startTime.toString() + "/" + endTime.toString();

        return sosTemproalFilter;

    } catch (IllegalArgumentException e) {
        String message = "Could not parse timespan parameter." + timespan;
        throw new IOException(message, e);
    }
}

From source file:org.plukh.fluffymeow.guice.GuiceContextListener.java

License:Open Source License

@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
    log.info("Initializing Fluffy Meow...");

    //Set DateTime default timezone
    DateTimeZone.setDefault(DateTimeZone.UTC);

    this.servletContext = servletContextEvent.getServletContext();

    try {//from   ww  w.  jav a 2s .  c o m
        config.load(System.getProperty(Config.CONFIG_FILE_NAME_PROPERTY));
    } catch (IOException e) {
        throw new RuntimeException("Cannot load configuration");
    }

    super.contextInitialized(servletContextEvent);

    log.info("Fluffy Meow initialized");
}

From source file:org.powertac.common.Competition.java

License:Apache License

/**
 * Fluent setter for simulation base time that takes a String, interpreted
 * as a standard DateTimeFormat as yyyy-MM-dd. If that fails, try to parse
 * the string as a regular (long) timestamp.
 *//*from  w  ww .  j ava  2 s  . c  om*/
@ConfigurableValue(valueType = "String", description = "Scenario start time of the bootstrap portion of a simulation")
public Competition withSimulationBaseTime(String baseTime) {
    Instant instant;
    try {
        DateTimeZone.setDefault(DateTimeZone.UTC);
        DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");
        instant = fmt.parseDateTime(baseTime).toInstant();
    } catch (IllegalArgumentException e) {
        // Try to interpret the string as a long timestamp instead
        instant = new Instant(Long.parseLong(baseTime));
    }
    return withSimulationBaseTime(instant);
}

From source file:org.powertac.common.TimeService.java

License:Apache License

/**
 * Sets current time to modulo before the desired start time. 
 * This allows scheduling// w w w .  j  av  a2  s.  com
 * of actions to take place on the first tick, which should be at the
 * desired start time. Call this after setting clock parameters.
 */
public void init(Instant start) {
    currentTime = new Instant(start.getMillis() - modulo);
    currentDateTime = new DateTime(currentTime, DateTimeZone.UTC);
    DateTimeZone.setDefault(DateTimeZone.UTC);
}

From source file:org.solovyev.android.messenger.MessengerApplication.java

License:Apache License

@Override
public void onCreate() {
    super.onCreate();

    // if we rename package we need to find module
    RoboGuice.setModulesResourceId(R.array.roboguice_modules);

    ACRA.init(this);

    // initialize Joda time for android
    System.setProperty("org.joda.time.DateTimeZone.Provider", FastDateTimeZoneProvider.class.getName());

    DateTimeZone.setDefault(UTC);

    MessengerPreferences.setDefaultValues(this);

    App.init(this);

    RoboGuice.getBaseApplicationInjector(this).injectMembers(this);

    fillCaches();/*from  w  w w  . j  a  v a 2s  .  c o  m*/
}

From source file:org.wremja.launcher.Launcher.java

License:Open Source License

/**
 * Main method that starts the application.
 * @param arguments the command line arguments
 *//*from   ww w . j  av a2 s.  c  o  m*/
public static void main(final String[] arguments) {
    try {
        final Launcher mainInstance = new Launcher();
        mainInstance.parseCommandLineArguments(arguments);

        mainInstance.initDir();

        mainInstance.initLogger();

        initUncaughtExceptionHandler();

        initLookAndFeel();

        initLockFile();

        @SuppressWarnings("deprecation")
        IUserSettings settings = UserSettings.instance();

        TimeZone tz = TimeZone.getTimeZone(settings.getTimeZone());
        LOG.info("Using timezone: " + tz);
        TimeZone.setDefault(tz);
        DateTimeZone.setDefault(DateTimeZone.forTimeZone(tz));

        final PresentationModel model = initModel(settings);

        mainInstance.initMainFrame(model, settings);

        initTimer(model);

        initShutdownHook(model);

        mainInstance.checkForUpdates();
    } catch (Throwable t) {
        LOG.error(t, t);
        JOptionPane.showMessageDialog(null, textBundle.textFor("Launcher.FatalError.Message", logFileName), //$NON-NLS-1$
                textBundle.textFor("Launcher.FatalError.Title"), //$NON-NLS-1$
                JOptionPane.ERROR_MESSAGE);
        System.exit(-1);
    }
}