Example usage for org.joda.time DateTimeZone forID

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

Introduction

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

Prototype

@FromString
public static DateTimeZone forID(String id) 

Source Link

Document

Gets a time zone instance for the specified time zone id.

Usage

From source file:TimeZoneListJson.java

License:Mozilla Public License

public static void main(String[] args) throws Exception {
    Set idSet = DateTimeZone.getAvailableIDs();
    LinkedHashMap<String, ArrayList<ZoneData>> zones = new LinkedHashMap<String, ArrayList<ZoneData>>();

    {//from   w w  w  . j a va2  s  . c om
        Iterator it = idSet.iterator();
        int i = 0;
        while (it.hasNext()) {
            String id = (String) it.next();
            // get only standard format (not stuff like Etc/GMT-xx, PST, etc.)
            if (id.matches("^[A-Za-z_-]+?/[A-Za-z_-]+?(/[A-Za-z_-]+?)?")
                    && !id.matches("^Etc/[A-Za-z0-9_-]+?")) {
                String k = id.split("/")[0];
                if (zones.containsKey(k)) {
                    zones.get(k).add(new ZoneData(id, DateTimeZone.forID(id)));
                } else {
                    ArrayList<ZoneData> regionZones = new ArrayList<ZoneData>();
                    regionZones.add(new ZoneData(id, DateTimeZone.forID(id)));
                    zones.put(k, regionZones);
                }
            }
        }
        // add UTC
        ArrayList<ZoneData> otherZones = new ArrayList<ZoneData>();
        otherZones.add(new ZoneData("UTC", DateTimeZone.forID("UTC")));
        zones.put("Other", otherZones);
    }

    PrintStream out = System.out;

    out.println("{");

    for (Map.Entry<String, ArrayList<ZoneData>> entry : zones.entrySet()) {
        // skip 'empty' regions where no canonical zone is present
        boolean hasCanonicalZone = false;
        for (ZoneData z : entry.getValue()) {
            if (z.isCanonical()) {
                hasCanonicalZone = true;
                break;
            }
        }
        if (!hasCanonicalZone)
            continue;

        // sort by std offset
        Collections.sort(entry.getValue());

        out.println(entry.getKey() + ": {");

        for (ZoneData z : entry.getValue()) {
            if (z.isCanonical()) {
                printRow(out, z);
            }
        }

        out.println("},");
    }

    out.println("};");
}

From source file:AgeCalculator.java

License:Apache License

private void addTopArea(Container container) {
    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));

    panel.add(fixedHeight(new JLabel("Birthdate")));
    panel.add(Box.createHorizontalStrut(10));

    final JTextField birthdateField = new JTextField(iBirthdateStr + ' ');
    Document doc = birthdateField.getDocument();
    doc.addDocumentListener(new DocumentListener() {
        public void insertUpdate(DocumentEvent e) {
            update(e);//  ww  w. ja v  a 2s.co  m
        }

        public void removeUpdate(DocumentEvent e) {
            update(e);
        }

        public void changedUpdate(DocumentEvent e) {
            update(e);
        }

        private void update(DocumentEvent e) {
            iBirthdateStr = birthdateField.getText();
            updateResults();
        }
    });
    panel.add(fixedHeight(birthdateField));

    panel.add(Box.createHorizontalStrut(10));

    Object[] ids = DateTimeZone.getAvailableIDs().toArray();
    final JComboBox zoneSelector = new JComboBox(ids);
    zoneSelector.setSelectedItem(DateTimeZone.getDefault().getID());
    panel.add(fixedSize(zoneSelector));

    zoneSelector.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String id = (String) zoneSelector.getSelectedItem();
            iChronology = ISOChronology.getInstance(DateTimeZone.forID(id));
            updateResults();
        }
    });

    container.add(fixedHeight(panel));
}

From source file:adwords.axis.v201502.extensions.AddSiteLinks.java

License:Open Source License

public static void runExample(AdWordsServices adWordsServices, AdWordsSession session, Long campaignId)
        throws ApiException, RemoteException {
    // Get the CustomerService.
    CustomerServiceInterface customerService = adWordsServices.get(session, CustomerServiceInterface.class);
    Customer customer = customerService.get();
    DateTimeZone customerTimeZone = DateTimeZone.forID(customer.getDateTimeZone());

    // Get the CampaignExtensionSettingService.
    CampaignExtensionSettingServiceInterface campaignExtensionSettingService = adWordsServices.get(session,
            CampaignExtensionSettingServiceInterface.class);

    // Create the sitelinks.
    SitelinkFeedItem sitelink1 = createSiteLinkFeedItem("Store Hours", "http://www.example.com/storehours");

    // Show the Thanksgiving specials link only from 20 - 27 Nov.
    SitelinkFeedItem sitelink2 = createSiteLinkFeedItem("Thanksgiving Specials",
            "http://www.example.com/thanksgiving");

    // The time zone of the start and end date/times must match the time zone of the customer.
    DateTime startTime = new DateTime(DateTime.now().getYear(), 11, 20, 0, 0, 0, customerTimeZone);
    sitelink2.setStartTime(startTime.toString("yyyyMMdd HHmmss ZZZ"));
    DateTime endTime = new DateTime(DateTime.now().getYear(), 11, 27, 23, 59, 59, customerTimeZone);
    sitelink2.setEndTime(endTime.toString("yyyyMMdd HHmmss ZZZ"));

    // Show the wifi details primarily for high end mobile users.
    SitelinkFeedItem sitelink3 = createSiteLinkFeedItem("Wifi available", "http://www.example.com/mobile/wifi");
    // See https://developers.google.com/adwords/api/docs/appendix/platforms for device criteria
    // IDs.//from   w  ww.  ja va  2  s  .co  m
    FeedItemDevicePreference devicePreference = new FeedItemDevicePreference(30001L);
    sitelink3.setDevicePreference(devicePreference);

    // Show the happy hours link only during Mon - Fri 6PM to 9PM.
    SitelinkFeedItem sitelink4 = createSiteLinkFeedItem("Happy hours", "http://www.example.com/happyhours");
    sitelink4.setScheduling(new FeedItemScheduling(new FeedItemSchedule[] {
            new FeedItemSchedule(DayOfWeek.MONDAY, 18, MinuteOfHour.ZERO, 21, MinuteOfHour.ZERO),
            new FeedItemSchedule(DayOfWeek.TUESDAY, 18, MinuteOfHour.ZERO, 21, MinuteOfHour.ZERO),
            new FeedItemSchedule(DayOfWeek.WEDNESDAY, 18, MinuteOfHour.ZERO, 21, MinuteOfHour.ZERO),
            new FeedItemSchedule(DayOfWeek.THURSDAY, 18, MinuteOfHour.ZERO, 21, MinuteOfHour.ZERO),
            new FeedItemSchedule(DayOfWeek.FRIDAY, 18, MinuteOfHour.ZERO, 21, MinuteOfHour.ZERO) }));

    // Create your campaign extension settings. This associates the sitelinks
    // to your campaign.
    CampaignExtensionSetting campaignExtensionSetting = new CampaignExtensionSetting();
    campaignExtensionSetting.setCampaignId(campaignId);
    campaignExtensionSetting.setExtensionType(FeedType.SITELINK);
    ExtensionSetting extensionSetting = new ExtensionSetting();
    extensionSetting.setExtensions(new ExtensionFeedItem[] { sitelink1, sitelink2, sitelink3, sitelink4 });
    campaignExtensionSetting.setExtensionSetting(extensionSetting);

    CampaignExtensionSettingOperation operation = new CampaignExtensionSettingOperation();
    operation.setOperand(campaignExtensionSetting);
    operation.setOperator(Operator.ADD);

    // Add the extensions.
    CampaignExtensionSettingReturnValue returnValue = campaignExtensionSettingService
            .mutate(new CampaignExtensionSettingOperation[] { operation });
    if (returnValue.getValue() != null && returnValue.getValue().length > 0) {
        CampaignExtensionSetting newExtensionSetting = returnValue.getValue(0);
        System.out.printf("Extension setting with type = %s was added to campaign ID %d.%n",
                newExtensionSetting.getExtensionType().getValue(), newExtensionSetting.getCampaignId());
    } else {
        System.out.println("No extension settings were created.");
    }
}

From source file:app.rappla.calendar.Date.java

License:Open Source License

/**
 * Constructor/*from  w  w  w .  j a  va2  s  .c o  m*/
 * 
 * @param icalStr
 *            One or more lines of iCalendar that specifies a date
 * @param parseMode
 *            PARSE_STRICT or PARSE_LOOSE
 */
public Date(String icalStr) throws ParseException, BogusDataException {
    super(icalStr);

    year = month = day = 0;
    hour = minute = second = 0;

    for (int i = 0; i < attributeList.size(); i++) {
        Attribute a = attributeAt(i);
        String aname = a.name.toUpperCase(Locale.ENGLISH);
        String aval = a.value.toUpperCase(Locale.ENGLISH);
        // TODO: not sure if any attributes are allowed here...
        // Look for VALUE=DATE or VALUE=DATE-TIME
        // DATE means untimed for the event
        if (aname.equals("VALUE")) {
            if (aval.equals("DATE")) {
                dateOnly = true;
            } else if (aval.equals("DATE-TIME")) {
                dateOnly = false;
            }
        } else if (aname.equals("TZID")) {
            tzid = a.value;
        } else {
            // TODO: anything else allowed here?
        }
    }

    String inDate = value;

    if (inDate.length() < 8) {
        // Invalid format
        throw new ParseException("Invalid date format '" + inDate + "'", inDate);
    }

    // Make sure all parts of the year are numeric.
    for (int i = 0; i < 8; i++) {
        char ch = inDate.charAt(i);
        if (ch < '0' || ch > '9') {
            throw new ParseException("Invalid date format '" + inDate + "'", inDate);
        }
    }
    year = Integer.parseInt(inDate.substring(0, 4));
    month = Integer.parseInt(inDate.substring(4, 6));
    day = Integer.parseInt(inDate.substring(6, 8));
    if (day < 1 || day > 31 || month < 1 || month > 12)
        throw new BogusDataException("Invalid date '" + inDate + "'", inDate);
    // Make sure day of month is valid for specified month
    if (year % 4 == 0) {
        // leap year
        if (day > leapMonthDays[month - 1]) {
            throw new BogusDataException("Invalid day of month '" + inDate + "'", inDate);
        }
    } else {
        if (day > monthDays[month - 1]) {
            throw new BogusDataException("Invalid day of month '" + inDate + "'", inDate);
        }
    }
    // TODO: parse time, handle localtime, handle timezone
    if (inDate.length() > 8) {
        // TODO make sure dateOnly == false
        if (inDate.charAt(8) == 'T') {
            try {
                hour = Integer.parseInt(inDate.substring(9, 11));
                minute = Integer.parseInt(inDate.substring(11, 13));
                second = Integer.parseInt(inDate.substring(13, 15));
                if (hour > 23 || minute > 59 || second > 59) {
                    throw new BogusDataException("Invalid time in date string '" + inDate + "'", inDate);
                }
                if (inDate.length() > 15) {
                    isUTC = inDate.charAt(15) == 'Z';
                }
            } catch (NumberFormatException nef) {
                throw new BogusDataException("Invalid time in date string '" + inDate + "' - " + nef, inDate);
            }
        } else {
            // Invalid format
            throw new ParseException("Invalid date format '" + inDate + "'", inDate);
        }
    } else {
        // Just date, no time
        dateOnly = true;
    }

    if (isUTC && !dateOnly) {
        // Use Joda Time to convert UTC to localtime
        DateTime utcDateTime = new DateTime(DateTimeZone.UTC);
        utcDateTime = utcDateTime.withDate(year, month, day).withTime(hour, minute, second, 0);
        DateTime localDateTime = utcDateTime.withZone(DateTimeZone.getDefault());
        year = localDateTime.getYear();
        month = localDateTime.getMonthOfYear();
        day = localDateTime.getDayOfMonth();
        hour = localDateTime.getHourOfDay();
        minute = localDateTime.getMinuteOfHour();
        second = localDateTime.getSecondOfMinute();
    } else if (tzid != null) {
        DateTimeZone tz = DateTimeZone.forID(tzid);
        if (tz != null) {
            // Convert to localtime
            DateTime utcDateTime = new DateTime(tz);
            utcDateTime = utcDateTime.withDate(year, month, day).withTime(hour, minute, second, 0);
            DateTime localDateTime = utcDateTime.withZone(DateTimeZone.getDefault());
            year = localDateTime.getYear();
            month = localDateTime.getMonthOfYear();
            day = localDateTime.getDayOfMonth();
            hour = localDateTime.getHourOfDay();
            minute = localDateTime.getMinuteOfHour();
            second = localDateTime.getSecondOfMinute();
            // Since we have converted to localtime, remove the TZID
            // attribute
            this.removeNamedAttribute("TZID");
        }
    }
    isUTC = false;

    // Add attribute that says date-only or date with time
    if (dateOnly)
        addAttribute("VALUE", "DATE");
    else
        addAttribute("VALUE", "DATE-TIME");

}

From source file:ar.com.wolox.commons.base.json.JSONSerializableDateTime.java

License:Apache License

/**
 * @return The deserialized date time
 */
public DateTime toDateTime() {
    return ISODateTimeFormat.dateTime().withZone(DateTimeZone.forID(timeZone)).parseDateTime(isoDate);
}

From source file:azkaban.app.AzkabanApplication.java

License:Apache License

public AzkabanApplication(final List<File> jobDirs, final File logDir, final File tempDir,
        final boolean enableDevMode) throws IOException {
    this._jobDirs = Utils.nonNull(jobDirs);
    this._logsDir = Utils.nonNull(logDir);
    this._tempDir = Utils.nonNull(tempDir);

    if (!this._logsDir.exists()) {
        this._logsDir.mkdirs();
    }/*from  www  .j  a v  a2  s.  c  om*/

    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();
        }
    }

    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("pig", PigProcessJob.class).put("propertyPusher", NoopJob.class)
                    .put("python", PythonJob.class).put("ruby", RubyJob.class).put("script", ScriptJob.class)
                    .build());

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

    _mailer = new Mailman(defaultProps.getString("mail.host", "localhost"),
            defaultProps.getString("mail.user", ""), defaultProps.getString("mail.password", ""));

    String failureEmail = defaultProps.getString("job.failure.email", null);
    String successEmail = defaultProps.getString("job.success.email", null);
    int schedulerThreads = defaultProps.getInt("scheduler.threads", 20);
    _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);

    _monitor = MonitorImpl.getMonitor();

    _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, _mailer, 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(AppCommon.DEFAULT_LOG_URL_PREFIX, server_url + "logs?file=");
        } else {
            _jobExecutorManager.setRuntimeProperty(AppCommon.DEFAULT_LOG_URL_PREFIX,
                    server_url + "/logs?file=");
        }
    }

    this._velocityEngine = configureVelocityEngine(enableDevMode);

    configureMBeanServer();
}

From source file:azkaban.execapp.AzkabanExecutorServer.java

License:Apache License

/**
 * Azkaban using Jetty// w w w  .  j a v a 2  s .  c  om
 *
 * @param args
 * @throws IOException
 */
public static void main(String[] args) throws Exception {
    logger.error("Starting Jetty Azkaban Executor...");
    Props azkabanSettings = AzkabanServer.loadProps(args);

    if (azkabanSettings == null) {
        logger.error("Azkaban Properties not loaded.");
        logger.error("Exiting Azkaban Executor Server...");
        return;
    }

    // Setup time zone
    if (azkabanSettings.containsKey(DEFAULT_TIMEZONE_ID)) {
        String timezone = azkabanSettings.getString(DEFAULT_TIMEZONE_ID);
        System.setProperty("user.timezone", timezone);
        TimeZone.setDefault(TimeZone.getTimeZone(timezone));
        DateTimeZone.setDefault(DateTimeZone.forID(timezone));

        logger.info("Setting timezone to " + timezone);
    }

    app = new AzkabanExecutorServer(azkabanSettings);

    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            logger.info("Shutting down http server...");
            try {
                app.stopServer();
            } catch (Exception e) {
                logger.error("Error while shutting down http server.", e);
            }
            logger.info("kk thx bye.");
        }
    });
}

From source file:azkaban.migration.schedule2trigger.Schedule2Trigger.java

License:Apache License

@SuppressWarnings("unchecked")
private static void file2ScheduleTrigger() throws Exception {

    TriggerLoader triggerLoader = new JdbcTriggerLoader(props);
    for (File scheduleFile : outputDir.listFiles()) {
        logger.info("Trying to load schedule from " + scheduleFile.getAbsolutePath());
        if (scheduleFile.isFile()) {
            Props schedProps = new Props(null, scheduleFile);
            String flowName = schedProps.getString("flowName");
            String projectName = schedProps.getString("projectName");
            int projectId = schedProps.getInt("projectId");
            long firstSchedTimeLong = schedProps.getLong("firstScheduleTimeLong");
            // DateTime firstSchedTime = new DateTime(firstSchedTimeLong);
            String timezoneId = schedProps.getString("timezone");
            DateTimeZone timezone = DateTimeZone.forID(timezoneId);
            ReadablePeriod period = Utils.parsePeriodString(schedProps.getString("period"));
            // DateTime lastModifyTime = DateTime.now();
            long nextExecTimeLong = schedProps.getLong("nextExecTimeLong");
            // DateTime nextExecTime = new DateTime(nextExecTimeLong);
            long submitTimeLong = schedProps.getLong("submitTimeLong");
            // DateTime submitTime = new DateTime(submitTimeLong);
            String submitUser = schedProps.getString("submitUser");
            ExecutionOptions executionOptions = null;
            if (schedProps.containsKey("executionOptionsObj")) {
                String executionOptionsObj = schedProps.getString("executionOptionsObj");
                executionOptions = ExecutionOptions
                        .createFromObject(JSONUtils.parseJSONFromString(executionOptionsObj));
            } else {
                executionOptions = new ExecutionOptions();
            }/*from  w  w  w .ja  va2s  .  co  m*/
            List<azkaban.sla.SlaOption> slaOptions = null;
            if (schedProps.containsKey("slaOptionsObj")) {
                slaOptions = new ArrayList<azkaban.sla.SlaOption>();
                List<Map<String, Object>> settingsObj = (List<Map<String, Object>>) JSONUtils
                        .parseJSONFromString(schedProps.getString("slaOptionsObj"));
                for (Map<String, Object> sla : settingsObj) {
                    String type = (String) sla.get("type");
                    Map<String, Object> info = (Map<String, Object>) sla.get("info");
                    List<String> actions = (List<String>) sla.get("actions");
                    azkaban.sla.SlaOption slaOption = new azkaban.sla.SlaOption(type, actions, info);
                    slaOptions.add(slaOption);
                }
            }

            azkaban.scheduler.Schedule schedule = new azkaban.scheduler.Schedule(-1, projectId, projectName,
                    flowName, "ready", firstSchedTimeLong, timezone, period, DateTime.now().getMillis(),
                    nextExecTimeLong, submitTimeLong, submitUser, executionOptions, slaOptions);
            Trigger t = scheduleToTrigger(schedule);
            logger.info("Ready to insert trigger " + t.getDescription());
            triggerLoader.addTrigger(t);

        }

    }
}

From source file:azkaban.migration.scheduler.Schedule.java

License:Apache License

public Schedule(int projectId, String projectName, String flowName, String status, long firstSchedTime,
        String timezoneId, String period, long lastModifyTime, long nextExecTime, long submitTime,
        String submitUser, ExecutionOptions executionOptions, SlaOptions slaOptions) {
    this.projectId = projectId;
    this.projectName = projectName;
    this.flowName = flowName;
    this.firstSchedTime = firstSchedTime;
    this.timezone = DateTimeZone.forID(timezoneId);
    this.lastModifyTime = lastModifyTime;
    this.period = parsePeriodString(period);
    this.nextExecTime = nextExecTime;
    this.submitUser = submitUser;
    this.status = status;
    this.submitTime = submitTime;
    this.executionOptions = executionOptions;
    this.slaOptions = slaOptions;
}

From source file:azkaban.scheduler.Schedule.java

License:Apache License

public Schedule(int scheduleId, int projectId, String projectName, String flowName, String status,
        long firstSchedTime, String timezoneId, String period, long lastModifyTime, long nextExecTime,
        long submitTime, String submitUser, ExecutionOptions executionOptions, List<SlaOption> slaOptions) {
    this(scheduleId, projectId, projectName, flowName, status, firstSchedTime, DateTimeZone.forID(timezoneId),
            parsePeriodString(period), lastModifyTime, nextExecTime, submitTime, submitUser, executionOptions,
            slaOptions);//from   w ww  .  j a  v a  2s  .com
}