Example usage for java.util TimeZone inDaylightTime

List of usage examples for java.util TimeZone inDaylightTime

Introduction

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

Prototype

public abstract boolean inDaylightTime(Date date);

Source Link

Document

Queries if the given date is in Daylight Saving Time in this time zone.

Usage

From source file:org.apache.cordova.Globalization.java

private JSONObject getDatePattern(JSONArray options) throws GlobalizationError {
    JSONObject obj = new JSONObject();

    try {//from   w  w  w . ja  va 2  s .c o  m
        SimpleDateFormat fmtDate = (SimpleDateFormat) android.text.format.DateFormat
                .getDateFormat(this.cordova.getActivity()); //default user preference for date
        SimpleDateFormat fmtTime = (SimpleDateFormat) android.text.format.DateFormat
                .getTimeFormat(this.cordova.getActivity()); //default user preference for time

        String fmt = fmtDate.toLocalizedPattern() + " " + fmtTime.toLocalizedPattern(); //default SHORT date/time format. ex. dd/MM/yyyy h:mm a

        //get Date value + options (if available)
        boolean test = options.getJSONObject(0).has(OPTIONS);
        if (options.getJSONObject(0).has(OPTIONS)) {
            //options were included
            JSONObject innerOptions = options.getJSONObject(0).getJSONObject(OPTIONS);
            //get formatLength option
            if (!innerOptions.isNull(FORMATLENGTH)) {
                String fmtOpt = innerOptions.getString(FORMATLENGTH);
                if (fmtOpt.equalsIgnoreCase(MEDIUM)) {//medium
                    fmtDate = (SimpleDateFormat) android.text.format.DateFormat
                            .getMediumDateFormat(this.cordova.getActivity());
                } else if (fmtOpt.equalsIgnoreCase(LONG) || fmtOpt.equalsIgnoreCase(FULL)) { //long/full
                    fmtDate = (SimpleDateFormat) android.text.format.DateFormat
                            .getLongDateFormat(this.cordova.getActivity());
                }
            }

            //return pattern type
            fmt = fmtDate.toLocalizedPattern() + " " + fmtTime.toLocalizedPattern();
            if (!innerOptions.isNull(SELECTOR)) {
                String selOpt = innerOptions.getString(SELECTOR);
                if (selOpt.equalsIgnoreCase(DATE)) {
                    fmt = fmtDate.toLocalizedPattern();
                } else if (selOpt.equalsIgnoreCase(TIME)) {
                    fmt = fmtTime.toLocalizedPattern();
                }
            }
        }

        //TimeZone from users device
        //TimeZone tz = Calendar.getInstance(Locale.getDefault()).getTimeZone(); //substitute method
        TimeZone tz = TimeZone.getTimeZone(Time.getCurrentTimezone());

        obj.put("pattern", fmt);
        obj.put("timezone",
                tz.getDisplayName(tz.inDaylightTime(Calendar.getInstance().getTime()), TimeZone.SHORT));
        obj.put("utc_offset", tz.getRawOffset() / 1000);
        obj.put("dst_offset", tz.getDSTSavings() / 1000);
        return obj;

    } catch (Exception ge) {
        throw new GlobalizationError(GlobalizationError.PATTERN_ERROR);
    }
}

From source file:io.teak.sdk.Session.java

private void identifyUser() {
    final Session _this = this;

    new Thread(new Runnable() {
        public void run() {
            synchronized (_this.stateMutex) {
                HashMap<String, Object> payload = new HashMap<>();

                if (_this.state == State.UserIdentified) {
                    payload.put("do_not_track_event", Boolean.TRUE);
                }/*from   ww w  .j  av a  2 s. c  o  m*/

                TimeZone tz = TimeZone.getDefault();
                long rawTz = tz.getRawOffset();
                if (tz.inDaylightTime(new Date())) {
                    rawTz += tz.getDSTSavings();
                }
                long minutes = TimeUnit.MINUTES.convert(rawTz, TimeUnit.MILLISECONDS);
                String tzOffset = new DecimalFormat("#0.00").format(minutes / 60.0f);
                payload.put("timezone", tzOffset);

                String locale = Locale.getDefault().toString();
                payload.put("locale", locale);

                if (_this.deviceConfiguration.advertsingInfo != null) {
                    payload.put("android_ad_id", _this.deviceConfiguration.advertsingInfo.getId());
                    payload.put("android_limit_ad_tracking",
                            _this.deviceConfiguration.advertsingInfo.isLimitAdTrackingEnabled());
                }

                if (_this.facebookAccessToken != null) {
                    payload.put("access_token", _this.facebookAccessToken);
                }

                if (_this.launchedFromTeakNotifId != null) {
                    payload.put("teak_notif_id", Long.valueOf(_this.launchedFromTeakNotifId));
                }

                if (_this.launchedFromDeepLink != null) {
                    payload.put("deep_link", _this.launchedFromDeepLink);
                }

                if (_this.deviceConfiguration.gcmId != null) {
                    payload.put("gcm_push_key", _this.deviceConfiguration.gcmId);
                } else {
                    payload.put("gcm_push_key", "");
                }

                Log.d(LOG_TAG, "Identifying user: " + _this.userId);
                Log.d(LOG_TAG, "        Timezone: " + tzOffset);
                Log.d(LOG_TAG, "          Locale: " + locale);

                new Request("/games/" + _this.appConfiguration.appId + "/users.json", payload, _this) {
                    @Override
                    protected void done(int responseCode, String responseBody) {
                        try {
                            JSONObject response = new JSONObject(responseBody);

                            // TODO: Grab 'id' and 'game_id' from response and store for Parsnip

                            // Enable verbose logging if flagged
                            boolean enableVerboseLogging = response.optBoolean("verbose_logging");
                            if (Teak.debugConfiguration != null) {
                                Teak.debugConfiguration.setPreferenceForceDebug(enableVerboseLogging);
                            }

                            // Server requesting new push key.
                            if (response.optBoolean("reset_push_key", false)) {
                                _this.deviceConfiguration.reRegisterPushToken(_this.appConfiguration);
                            }

                            if (response.has("country_code")) {
                                _this.countryCode = response.getString("country_code");
                            }

                            // Prevent warning for 'do_not_track_event'
                            if (_this.state != State.UserIdentified) {
                                _this.setState(State.UserIdentified);
                            }
                        } catch (Exception ignored) {
                        }

                        super.done(responseCode, responseBody);
                    }
                }.run();
            }
        }
    }).start();
}

From source file:org.nodatime.tzvalidate.Java7Dump.java

@Override
public ZoneTransitions getTransitions(String id, int fromYear, int toYear) {
    TimeZone zone = TimeZone.getTimeZone(id);
    DateFormat nameFormat = new SimpleDateFormat("zzz", Locale.US);
    nameFormat.setTimeZone(zone);/*from  w ww. j  a  va2 s. co  m*/

    // Given the way we find transitions, we really don't want to go
    // from any earlier than this...
    if (fromYear < 1800) {
        fromYear = 1800;
    }

    Calendar calendar = GregorianCalendar.getInstance(UTC);
    calendar.set(fromYear, 0, 1, 0, 0, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    long start = calendar.getTimeInMillis();
    calendar.set(toYear, 0, 1, 0, 0, 0);
    long end = calendar.getTimeInMillis();
    Date date = new Date(start);

    ZoneTransitions transitions = new ZoneTransitions(id);
    transitions.addTransition(null, zone.getOffset(start), zone.inDaylightTime(date), nameFormat.format(date));

    Long transition = getNextTransition(zone, start - 1, end);
    while (transition != null) {
        date.setTime(transition);
        transitions.addTransition(date, zone.getOffset(transition), zone.inDaylightTime(date),
                nameFormat.format(date));
        transition = getNextTransition(zone, transition, end);
    }
    return transitions;
}

From source file:org.opencastproject.scheduler.impl.SchedulerServiceImpl.java

@Override
public DublinCoreCatalogList findConflictingEvents(String captureDeviceID, String rrule, Date startDate,
        Date endDate, long duration, String timezone) throws SchedulerException {
    RRule rule;//w  ww. j av  a2 s . c o m
    try {
        rule = new RRule(rrule);
        rule.validate();
    } catch (Exception e) {
        logger.error("Could not create rule for finding conflicting events: {}", e.getMessage());
        throw new SchedulerException(e);
    }
    Recur recur = rule.getRecur();
    TimeZone tz = TimeZone.getTimeZone(timezone);
    DateTime seed = new DateTime(true);
    DateTime period = new DateTime(true);
    if (tz.inDaylightTime(startDate) && !tz.inDaylightTime(endDate)) {
        seed.setTime(startDate.getTime() + 3600000);
        period.setTime(endDate.getTime());
    } else if (!tz.inDaylightTime(startDate) && tz.inDaylightTime(endDate)) {
        seed.setTime(startDate.getTime());
        period.setTime(endDate.getTime() + 3600000);
    } else {
        seed.setTime(startDate.getTime());
        period.setTime(endDate.getTime());
    }
    DateList dates = recur.getDates(seed, period, Value.DATE_TIME);
    List<DublinCoreCatalog> events = new ArrayList<DublinCoreCatalog>();

    for (Object date : dates) {
        // Date filterStart = (Date) d;
        Date d = (Date) date;
        // Adjust for DST, if start of event
        if (tz.inDaylightTime(seed)) { // Event starts in DST
            if (!tz.inDaylightTime(d)) { // Date not in DST?
                d.setTime(d.getTime() + tz.getDSTSavings()); // Adjust for Fall back one hour
            }
        } else { // Event doesn't start in DST
            if (tz.inDaylightTime(d)) {
                d.setTime(d.getTime() - tz.getDSTSavings()); // Adjust for Spring forward one hour
            }
        }
        // TODO optimize: create only one query and execute it
        List<DublinCoreCatalog> filterEvents = findConflictingEvents(captureDeviceID, d,
                new Date(d.getTime() + duration)).getCatalogList();
        events.addAll(filterEvents);
    }

    return new DublinCoreCatalogList(events, events.size());
}

From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java

@Override
public String getServerTimezone(Locale locale) {
    TimeZone timeZone = TimeZone.getDefault();
    boolean daylight = timeZone.inDaylightTime(new Date());

    // Get the short timezone display name with respect to DST
    String timeZoneDisplay = timeZone.getDisplayName(daylight, TimeZone.SHORT, locale);

    // Get the offset in hours (divide by number of milliseconds in an hour)
    int offset = timeZone.getOffset(System.currentTimeMillis()) / (3600000);

    // Get the offset display in either UTC -x or UTC +x
    String offsetDisplay = (offset < 0) ? String.valueOf(offset) : "+" + offset;
    timeZoneDisplay += " (UTC " + offsetDisplay + ")";

    return timeZoneDisplay;
}

From source file:com.betfair.testing.utils.cougar.helpers.CougarHelpers.java

public Date convertToSystemTimeZone(String datetoconvert) {
    TimeZone tz = TimeZone.getDefault();
    Date date = new Date();
    try {/*w w  w .jav a  2s .c o  m*/
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        String s = datetoconvert;
        String[] tmp = s.split(".0Z");
        String s1 = tmp[0];
        logger.debug("given string is" + s1);
        date = dateFormat.parse(s1);
        logger.debug("OffsetValue is " + tz.getRawOffset());
        if (tz.getRawOffset() != 0)

            date = new Date(date.getTime() + tz.getRawOffset());
        logger.debug("After adding offset" + date);
        if (tz.inDaylightTime(date)) {
            Date dstDate = new Date(date.getTime() + tz.getDSTSavings());
            logger.debug("Day Light Saving is  " + tz.getDSTSavings());
            logger.debug("Dst is   " + dstDate);

            if (tz.inDaylightTime(dstDate)) {
                date = dstDate;
                //            logger.debug("dst date  "+ dstDate);
            }
        }
        logger.debug("After the day light saving" + date);

    } catch (Exception e) {
        logger.debug("System exception caught" + e);
    }
    return date;
}

From source file:org.opencastproject.scheduler.impl.SchedulerServiceImpl.java

/**
 * Given recurrence pattern and template DublinCore, DublinCores for multiple events are generated. Each event will
 * have template's title plus sequential number. Spatial property of DublinCore is set to represent time period in
 * which event will take place.//from   ww  w . jav a 2s. com
 * 
 * @param template
 *          {@link DublinCoreCatalog} used as template
 * @return list of {@link DublinCoreCatalog}s
 * @throws ParseException
 *           if recurrence pattern cannot be parsed
 */
protected List<DublinCoreCatalog> createEventCatalogsFromReccurence(DublinCoreCatalog template)
        throws ParseException, IllegalArgumentException {

    if (!template.hasValue(DublinCoreCatalogImpl.PROPERTY_RECURRENCE)) {
        throw new IllegalArgumentException("Event has no recurrence pattern.");
    }

    DCMIPeriod temporal = EncodingSchemeUtils
            .decodeMandatoryPeriod(template.getFirst(DublinCore.PROPERTY_TEMPORAL));
    if (!temporal.hasEnd() || !temporal.hasStart()) {
        throw new IllegalArgumentException(
                "Dublin core field dc:temporal does not contain information about start and end of event");
    }

    Date start = temporal.getStart();
    Date end = temporal.getEnd();
    Long duration = 0L;

    TimeZone tz = null; // Create timezone based on CA's reported TZ.
    if (template.hasValue(DublinCoreCatalogImpl.PROPERTY_AGENT_TIMEZONE)) {
        tz = TimeZone.getTimeZone(template.getFirst(DublinCoreCatalogImpl.PROPERTY_AGENT_TIMEZONE));
    } else { // No timezone was present, assume the serve's local timezone.
        tz = TimeZone.getDefault();
    }

    Recur recur = new RRule(template.getFirst(DublinCoreCatalogImpl.PROPERTY_RECURRENCE)).getRecur();
    DateTime seed = new DateTime(true);
    DateTime period = new DateTime(true);
    if (tz.inDaylightTime(start) && !tz.inDaylightTime(end)) {
        seed.setTime(start.getTime() + 3600000);
        period.setTime(end.getTime());
        duration = (end.getTime() - (start.getTime() + 3600000)) % (24 * 60 * 60 * 1000);
    } else if (!tz.inDaylightTime(start) && tz.inDaylightTime(end)) {
        seed.setTime(start.getTime());
        period.setTime(end.getTime() + 3600000);
        duration = ((end.getTime() + 3600000) - start.getTime()) % (24 * 60 * 60 * 1000);
    } else {
        seed.setTime(start.getTime());
        period.setTime(end.getTime());
        duration = (end.getTime() - start.getTime()) % (24 * 60 * 60 * 1000);
    }
    DateList dates = recur.getDates(seed, period, Value.DATE_TIME);
    logger.debug("DateList: {}", dates);

    List<DublinCoreCatalog> events = new LinkedList<DublinCoreCatalog>();
    int i = 1;
    int length = Integer.toString(dates.size()).length();
    for (Object date : dates) {
        Date d = (Date) date;
        // Adjust for DST, if start of event
        if (tz.inDaylightTime(seed)) { // Event starts in DST
            if (!tz.inDaylightTime(d)) { // Date not in DST?
                d.setTime(d.getTime() + tz.getDSTSavings()); // Adjust for Fall back one hour
            }
        } else { // Event doesn't start in DST
            if (tz.inDaylightTime(d)) {
                d.setTime(d.getTime() - tz.getDSTSavings()); // Adjust for Spring forward one hour
            }
        }
        DublinCoreCatalog event = (DublinCoreCatalog) ((DublinCoreCatalogImpl) template).clone();
        int numZeros = length - Integer.toString(i).length();
        StringBuilder sb = new StringBuilder();
        for (int j = 0; j < numZeros; j++) {
            sb.append(0);
        }
        sb.append(i);
        event.set(DublinCore.PROPERTY_TITLE,
                template.getFirst(DublinCore.PROPERTY_TITLE) + " " + sb.toString());

        DublinCoreValue eventTime = EncodingSchemeUtils
                .encodePeriod(new DCMIPeriod(d, new Date(d.getTime() + duration)), Precision.Second);
        event.set(DublinCore.PROPERTY_TEMPORAL, eventTime);
        events.add(event);
        i++;
    }
    return events;
}

From source file:com.landenlabs.all_devtool.SystemFragment.java

public void updateList() {
    // Time today = new Time(Time.getCurrentTimezone());
    // today.setToNow();
    // today.format(" %H:%M:%S")
    Date dt = new Date();
    m_titleTime.setText(m_timeFormat.format(dt));

    boolean expandAll = m_list.isEmpty();
    m_list.clear();//from w ww .  jav a  2s.  c  o m

    // Swap colors
    int color = m_rowColor1;
    m_rowColor1 = m_rowColor2;
    m_rowColor2 = color;

    ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);

    try {
        String androidIDStr = Settings.Secure.getString(getContext().getContentResolver(),
                Settings.Secure.ANDROID_ID);
        addBuild("Android ID", androidIDStr);

        try {
            AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getContext());
            final String adIdStr = adInfo.getId();
            final boolean isLAT = adInfo.isLimitAdTrackingEnabled();
            addBuild("Ad ID", adIdStr);
        } catch (IOException e) {
            // Unrecoverable error connecting to Google Play services (e.g.,
            // the old version of the service doesn't support getting AdvertisingId).
        } catch (GooglePlayServicesNotAvailableException e) {
            // Google Play services is not available entirely.
        }

        /*
        try {
        InstanceID instanceID = InstanceID.getInstance(getContext());
        if (instanceID != null) {
            // Requires a Google Developer project ID.
            String authorizedEntity = "<need to make this on google developer site>";
            instanceID.getToken(authorizedEntity, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            addBuild("Instance ID", instanceID.getId());
        }
        } catch (Exception ex) {
        }
        */

        ConfigurationInfo info = actMgr.getDeviceConfigurationInfo();
        addBuild("OpenGL", info.getGlEsVersion());
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    try {
        long heapSize = Debug.getNativeHeapSize();
        // long maxHeap = Runtime.getRuntime().maxMemory();

        // ConfigurationInfo cfgInfo = actMgr.getDeviceConfigurationInfo();
        int largHeapMb = actMgr.getLargeMemoryClass();
        int heapMb = actMgr.getMemoryClass();

        MemoryInfo memInfo = new MemoryInfo();
        actMgr.getMemoryInfo(memInfo);

        final String sFmtMB = "%.2f MB";
        Map<String, String> listStr = new TreeMap<String, String>();
        listStr.put("Mem Available (now)", String.format(sFmtMB, (double) memInfo.availMem / MB));
        listStr.put("Mem LowWhenOnlyAvail", String.format(sFmtMB, (double) memInfo.threshold / MB));
        if (Build.VERSION.SDK_INT >= 16) {
            listStr.put("Mem Installed", String.format(sFmtMB, (double) memInfo.totalMem / MB));
        }
        listStr.put("Heap (this app)", String.format(sFmtMB, (double) heapSize / MB));
        listStr.put("HeapMax (default)", String.format(sFmtMB, (double) heapMb));
        listStr.put("HeapMax (large)", String.format(sFmtMB, (double) largHeapMb));
        addBuild("Memory...", listStr);
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    try {
        List<ProcessErrorStateInfo> procErrList = actMgr.getProcessesInErrorState();
        int errCnt = (procErrList == null ? 0 : procErrList.size());
        procErrList = null;

        // List<RunningAppProcessInfo> procList = actMgr.getRunningAppProcesses();
        int procCnt = actMgr.getRunningAppProcesses().size();
        int srvCnt = actMgr.getRunningServices(100).size();

        Map<String, String> listStr = new TreeMap<String, String>();
        listStr.put("#Processes", String.valueOf(procCnt));
        listStr.put("#Proc With Err", String.valueOf(errCnt));
        listStr.put("#Services", String.valueOf(srvCnt));
        // Requires special permission
        //   int taskCnt = actMgr.getRunningTasks(100).size();
        //   listStr.put("#Tasks",  String.valueOf(taskCnt));
        addBuild("Processes...", listStr);
    } catch (Exception ex) {
        m_log.e("System-Processes %s", ex.getMessage());
    }

    try {
        Map<String, String> listStr = new LinkedHashMap<String, String>();
        listStr.put("LargeIconDensity", String.valueOf(actMgr.getLauncherLargeIconDensity()));
        listStr.put("LargeIconSize", String.valueOf(actMgr.getLauncherLargeIconSize()));
        putIf(listStr, "isRunningInTestHarness", "Yes", ActivityManager.isRunningInTestHarness());
        putIf(listStr, "isUserAMonkey", "Yes", ActivityManager.isUserAMonkey());
        addBuild("Misc...", listStr);
    } catch (Exception ex) {
        m_log.e("System-Misc %s", ex.getMessage());
    }

    // --------------- Locale / Timezone -------------
    try {
        Locale ourLocale = Locale.getDefault();
        Date m_date = new Date();
        TimeZone tz = TimeZone.getDefault();

        Map<String, String> localeListStr = new LinkedHashMap<String, String>();

        localeListStr.put("Locale Name", ourLocale.getDisplayName());
        localeListStr.put(" Variant", ourLocale.getVariant());
        localeListStr.put(" Country", ourLocale.getCountry());
        localeListStr.put(" Country ISO", ourLocale.getISO3Country());
        localeListStr.put(" Language", ourLocale.getLanguage());
        localeListStr.put(" Language ISO", ourLocale.getISO3Language());
        localeListStr.put(" Language Dsp", ourLocale.getDisplayLanguage());

        localeListStr.put("TimeZoneID", tz.getID());
        localeListStr.put(" DayLightSavings", tz.useDaylightTime() ? "Yes" : "No");
        localeListStr.put(" In DLS", tz.inDaylightTime(m_date) ? "Yes" : "No");
        localeListStr.put(" Short Name", tz.getDisplayName(false, TimeZone.SHORT, ourLocale));
        localeListStr.put(" Long Name", tz.getDisplayName(false, TimeZone.LONG, ourLocale));

        addBuild("Locale TZ...", localeListStr);
    } catch (Exception ex) {
        m_log.e("Locale/TZ %s", ex.getMessage());
    }

    // --------------- Location Services -------------
    try {
        Map<String, String> listStr = new LinkedHashMap<String, String>();

        final LocationManager locMgr = (LocationManager) getActivity()
                .getSystemService(Context.LOCATION_SERVICE);

        GpsStatus gpsStatus = locMgr.getGpsStatus(null);
        if (gpsStatus != null) {
            listStr.put("Sec ToGetGPS", String.valueOf(gpsStatus.getTimeToFirstFix()));

            Iterable<GpsSatellite> satellites = gpsStatus.getSatellites();
            Iterator<GpsSatellite> sat = satellites.iterator();
            while (sat.hasNext()) {
                GpsSatellite satellite = sat.next();

                putIf(listStr,
                        String.format("Azm:%.0f, Elev:%.0f", satellite.getAzimuth(), satellite.getElevation()),
                        String.format("%.2f Snr", satellite.getSnr()), satellite.usedInFix());
            }
        }

        Location location = null;
        if (ActivityCompat.checkSelfPermission(getContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(getContext(),
                        Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

            location = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (null == location)
                location = locMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (null == location)
                location = locMgr.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
        }

        if (null != location) {
            listStr.put(location.getProvider() + " lat,lng",
                    String.format("%.3f, %.3f", location.getLatitude(), location.getLongitude()));
        }
        if (listStr.size() != 0) {
            List<String> gpsProviders = locMgr.getAllProviders();
            int idx = 1;
            for (String providerName : gpsProviders) {
                LocationProvider provider = locMgr.getProvider(providerName);
                if (null != provider) {
                    listStr.put(providerName,
                            (locMgr.isProviderEnabled(providerName) ? "On " : "Off ")
                                    + String.format("Accuracy:%d Pwr:%d", provider.getAccuracy(),
                                            provider.getPowerRequirement()));
                }
            }
            addBuild("GPS...", listStr);
        } else
            addBuild("GPS", "Off");
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    // --------------- Application Info -------------
    ApplicationInfo appInfo = getActivity().getApplicationInfo();
    if (null != appInfo) {
        Map<String, String> appList = new LinkedHashMap<String, String>();
        try {
            appList.put("ProcName", appInfo.processName);
            appList.put("PkgName", appInfo.packageName);
            appList.put("DataDir", appInfo.dataDir);
            appList.put("SrcDir", appInfo.sourceDir);
            //    appList.put("PkgResDir", getActivity().getPackageResourcePath());
            //     appList.put("PkgCodeDir", getActivity().getPackageCodePath());
            String[] dbList = getActivity().databaseList();
            if (dbList != null && dbList.length != 0)
                appList.put("DataBase", dbList[0]);
            // getActivity().getComponentName().

        } catch (Exception ex) {
        }
        addBuild("AppInfo...", appList);
    }

    // --------------- Account Services -------------
    final AccountManager accMgr = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
    if (null != accMgr) {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        try {
            for (Account account : accMgr.getAccounts()) {
                strList.put(account.name, account.type);
            }
        } catch (Exception ex) {
            m_log.e(ex.getMessage());
        }
        addBuild("Accounts...", strList);
    }

    // --------------- Package Features -------------
    PackageManager pm = getActivity().getPackageManager();
    FeatureInfo[] features = pm.getSystemAvailableFeatures();
    if (features != null) {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        for (FeatureInfo featureInfo : features) {
            strList.put(featureInfo.name, "");
        }
        addBuild("Features...", strList);
    }

    // --------------- Sensor Services -------------
    final SensorManager senMgr = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
    if (null != senMgr) {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        // Sensor accelerometer = senMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        // senMgr.registerListener(foo, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        List<Sensor> listSensor = senMgr.getSensorList(Sensor.TYPE_ALL);
        try {
            for (Sensor sensor : listSensor) {
                strList.put(sensor.getName(), sensor.getVendor());
            }
        } catch (Exception ex) {
            m_log.e(ex.getMessage());
        }
        addBuild("Sensors...", strList);
    }

    try {
        if (Build.VERSION.SDK_INT >= 17) {
            final UserManager userMgr = (UserManager) getActivity().getSystemService(Context.USER_SERVICE);
            if (null != userMgr) {
                try {
                    addBuild("UserName", userMgr.getUserName());
                } catch (Exception ex) {
                    m_log.e(ex.getMessage());
                }
            }
        }
    } catch (Exception ex) {
    }

    try {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        int screenTimeout = Settings.System.getInt(getActivity().getContentResolver(),
                Settings.System.SCREEN_OFF_TIMEOUT);
        strList.put("ScreenTimeOut", String.valueOf(screenTimeout / 1000));
        int rotate = Settings.System.getInt(getActivity().getContentResolver(),
                Settings.System.ACCELEROMETER_ROTATION);
        strList.put("RotateEnabled", String.valueOf(rotate));
        if (Build.VERSION.SDK_INT >= 17) {
            // Global added in API 17
            int adb = Settings.Global.getInt(getActivity().getContentResolver(), Settings.Global.ADB_ENABLED);
            strList.put("AdbEnabled", String.valueOf(adb));
        }
        addBuild("Settings...", strList);
    } catch (Exception ex) {
    }

    if (expandAll) {
        // updateList();
        int count = m_list.size();
        for (int position = 0; position < count; position++)
            m_listView.expandGroup(position);
    }

    m_adapter.notifyDataSetChanged();
}

From source file:org.sakaiproject.portal.charon.SkinnableCharonPortal.java

public void includeBottom(PortalRenderContext rcontext) {
    if (rcontext.uses(INCLUDE_BOTTOM)) {
        String thisUser = SessionManager.getCurrentSessionUserId();

        //Get user preferences
        PreferencesService preferencesService = (PreferencesService) ComponentManager
                .get(PreferencesService.class);

        Preferences prefs = preferencesService.getPreferences(thisUser);

        boolean showServerTime = ServerConfigurationService.getBoolean("portal.show.time", true);
        if (showServerTime) {
            rcontext.put("showServerTime", "true");
            Calendar now = Calendar.getInstance();
            Date nowDate = new Date(now.getTimeInMillis());

            //first set server date and time
            TimeZone serverTz = TimeZone.getDefault();
            now.setTimeZone(serverTz);//from w  ww  .ja  v a  2s.c om

            rcontext.put("serverTzDisplay",
                    serverTz.getDisplayName(serverTz.inDaylightTime(nowDate), TimeZone.SHORT));

            rcontext.put("serverTzGMTOffset", String.valueOf(
                    now.getTimeInMillis() + now.get(Calendar.ZONE_OFFSET) + now.get(Calendar.DST_OFFSET)));

            //provide the user's preferred timezone information if it is different

            //Get the Properties object that holds user's TimeZone preferences 
            ResourceProperties tzprops = prefs.getProperties(TimeService.APPLICATION_ID);

            //Get the ID of the timezone using the timezone key.
            //Default to 'localTimeZone' (server timezone?)
            String preferredTzId = (String) tzprops.get(TimeService.TIMEZONE_KEY);

            if (preferredTzId != null && !preferredTzId.equals(serverTz.getID())) {
                TimeZone preferredTz = TimeZone.getTimeZone(preferredTzId);

                now.setTimeZone(preferredTz);

                rcontext.put("showPreferredTzTime", "true");

                //now set up the portal information
                rcontext.put("preferredTzDisplay",
                        preferredTz.getDisplayName(preferredTz.inDaylightTime(nowDate), TimeZone.SHORT));

                rcontext.put("preferredTzGMTOffset", String.valueOf(
                        now.getTimeInMillis() + now.get(Calendar.ZONE_OFFSET) + now.get(Calendar.DST_OFFSET)));
            } else {
                rcontext.put("showPreferredTzTime", "false");
            }
        }

        rcontext.put("pagepopup", false);

        String copyright = ServerConfigurationService.getString("bottom.copyrighttext");

        /**
         * Replace keyword in copyright message from sakai.properties 
         * with the server's current year to auto-update of Copyright end date 
         */
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
        String currentServerYear = simpleDateFormat.format(new Date());
        copyright = copyright.replaceAll(SERVER_COPYRIGHT_CURRENT_YEAR_KEYWORD, currentServerYear);

        String service = ServerConfigurationService.getString("ui.service", "Sakai");
        String serviceVersion = ServerConfigurationService.getString("version.service", "?");
        String sakaiVersion = ServerConfigurationService.getString("version.sakai", "?");
        String server = ServerConfigurationService.getServerId();
        String[] bottomNav = ServerConfigurationService.getStrings("bottomnav");
        String[] poweredByUrl = ServerConfigurationService.getStrings("powered.url");
        String[] poweredByImage = ServerConfigurationService.getStrings("powered.img");
        String[] poweredByAltText = ServerConfigurationService.getStrings("powered.alt");

        {
            List<Object> l = new ArrayList<Object>();
            if ((bottomNav != null) && (bottomNav.length > 0)) {
                for (int i = 0; i < bottomNav.length; i++) {
                    l.add(bottomNav[i]);
                }
            }
            rcontext.put("bottomNav", l);
        }

        boolean neoChatAvailable = ServerConfigurationService.getBoolean("portal.neochat", true)
                && chatHelper.checkChatPermitted(thisUser);

        rcontext.put("neoChat", neoChatAvailable);
        rcontext.put("portalChatPollInterval",
                ServerConfigurationService.getInt("portal.chat.pollInterval", 5000));
        rcontext.put("neoAvatar", ServerConfigurationService.getBoolean("portal.neoavatar", true));
        rcontext.put("neoChatVideo", ServerConfigurationService.getBoolean("portal.chat.video", true));
        rcontext.put("portalVideoChatTimeout",
                ServerConfigurationService.getInt("portal.chat.video.timeout", 25));

        if (sakaiTutorialEnabled && thisUser != null) {
            if (!("1".equals(prefs.getProperties().getProperty("sakaiTutorialFlag")))) {
                rcontext.put("tutorial", true);
                //now save this in the user's prefefences so we don't show it again
                PreferencesEdit preferences = null;
                SecurityAdvisor secAdv = null;
                try {
                    secAdv = new SecurityAdvisor() {
                        @Override
                        public SecurityAdvice isAllowed(String userId, String function, String reference) {
                            if ("prefs.add".equals(function) || "prefs.upd".equals(function)) {
                                return SecurityAdvice.ALLOWED;
                            }
                            return null;
                        }
                    };
                    securityService.pushAdvisor(secAdv);

                    try {
                        preferences = preferencesService.edit(thisUser);
                    } catch (IdUnusedException ex1) {
                        try {
                            preferences = preferencesService.add(thisUser);
                        } catch (IdUsedException ex2) {
                            M_log.error(ex2);
                        } catch (PermissionException ex3) {
                            M_log.error(ex3);
                        }
                    }
                    if (preferences != null) {
                        ResourcePropertiesEdit props = preferences.getPropertiesEdit();
                        props.addProperty("sakaiTutorialFlag", "1");
                        preferencesService.commit(preferences);
                    }
                } catch (Exception e1) {
                    M_log.error(e1);
                } finally {
                    if (secAdv != null) {
                        securityService.popAdvisor(secAdv);
                    }
                }
            }
        }
        // rcontext.put("bottomNavSitNewWindow",
        // Web.escapeHtml(rb.getString("site_newwindow")));

        if ((poweredByUrl != null) && (poweredByImage != null) && (poweredByAltText != null)
                && (poweredByUrl.length == poweredByImage.length)
                && (poweredByUrl.length == poweredByAltText.length)) {
            {
                List<Object> l = new ArrayList<Object>();
                for (int i = 0; i < poweredByUrl.length; i++) {
                    Map<String, Object> m = new HashMap<String, Object>();
                    m.put("poweredByUrl", poweredByUrl[i]);
                    m.put("poweredByImage", poweredByImage[i]);
                    m.put("poweredByAltText", poweredByAltText[i]);
                    l.add(m);
                }
                rcontext.put("bottomNavPoweredBy", l);

            }
        } else {
            List<Object> l = new ArrayList<Object>();
            Map<String, Object> m = new HashMap<String, Object>();
            m.put("poweredByUrl", "http://sakaiproject.org");
            m.put("poweredByImage", "/library/image/sakai_powered.gif");
            m.put("poweredByAltText", "Powered by Sakai");
            l.add(m);
            rcontext.put("bottomNavPoweredBy", l);
        }

        rcontext.put("bottomNavService", service);
        rcontext.put("bottomNavCopyright", copyright);
        rcontext.put("bottomNavServiceVersion", serviceVersion);
        rcontext.put("bottomNavSakaiVersion", sakaiVersion);
        rcontext.put("bottomNavServer", server);

        // SAK-25931 - Do not remove this from session here - removal is done by /direct
        Session s = SessionManager.getCurrentSession();
        String userWarning = (String) s.getAttribute("userWarning");
        rcontext.put("userWarning", new Boolean(StringUtils.isNotEmpty(userWarning)));

        if (ServerConfigurationService.getBoolean("pasystem.enabled", false)) {
            PASystem paSystem = (PASystem) ComponentManager.get(PASystem.class);
            rcontext.put("paSystemEnabled", true);
            rcontext.put("paSystem", paSystem);
        }
    }
}