Example usage for java.util TimeZone getDefault

List of usage examples for java.util TimeZone getDefault

Introduction

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

Prototype

public static TimeZone getDefault() 

Source Link

Document

Gets the default TimeZone of the Java virtual machine.

Usage

From source file:net.sourceforge.eclipsetrader.opentick.Feed.java

public void snapshot() {
    SimpleDateFormat usDateTimeParser = new SimpleDateFormat("MM/dd/yyyy h:mma");
    SimpleDateFormat usDateParser = new SimpleDateFormat("MM/dd/yyyy");
    SimpleDateFormat usTimeParser = new SimpleDateFormat("h:mma");
    NumberFormat numberFormat = NumberFormat.getInstance(Locale.US);

    // Builds the url for quotes download
    String host = "quote.yahoo.com";
    StringBuffer url = new StringBuffer("http://" + host + "/download/javasoft.beans?symbols=");
    for (Iterator iter = subscribedSecurities.iterator(); iter.hasNext();) {
        Security security = (Security) iter.next();
        url = url.append(security.getCode() + "+");
    }// w w w.  j  a  v  a  2  s  . c  om
    if (url.charAt(url.length() - 1) == '+')
        url.deleteCharAt(url.length() - 1);
    url.append("&format=sl1d1t1c1ohgvbap");

    // Read the last prices
    String line = "";
    try {
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        BundleContext context = OpenTickPlugin.getDefault().getBundle().getBundleContext();
        ServiceReference reference = context.getServiceReference(IProxyService.class.getName());
        if (reference != null) {
            IProxyService proxy = (IProxyService) context.getService(reference);
            IProxyData data = proxy.getProxyDataForHost(host, IProxyData.HTTP_PROXY_TYPE);
            if (data != null) {
                if (data.getHost() != null)
                    client.getHostConfiguration().setProxy(data.getHost(), data.getPort());
                if (data.isRequiresAuthentication())
                    client.getState().setProxyCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(data.getUserId(), data.getPassword()));
            }
        }

        HttpMethod method = new GetMethod(url.toString());
        method.setFollowRedirects(true);
        client.executeMethod(method);

        BufferedReader in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
        while ((line = in.readLine()) != null) {
            String[] item = line.split(",");
            if (line.indexOf(";") != -1)
                item = line.split(";");

            Double open = null, high = null, low = null, close = null;
            Quote quote = new Quote();

            // 2 = Date
            // 3 = Time
            try {
                GregorianCalendar c = new GregorianCalendar(TimeZone.getTimeZone("EST"), Locale.US);
                usDateTimeParser.setTimeZone(c.getTimeZone());
                usDateParser.setTimeZone(c.getTimeZone());
                usTimeParser.setTimeZone(c.getTimeZone());

                String date = stripQuotes(item[2]);
                if (date.indexOf("N/A") != -1)
                    date = usDateParser.format(Calendar.getInstance().getTime());
                String time = stripQuotes(item[3]);
                if (time.indexOf("N/A") != -1)
                    time = usTimeParser.format(Calendar.getInstance().getTime());
                c.setTime(usDateTimeParser.parse(date + " " + time));
                c.setTimeZone(TimeZone.getDefault());
                quote.setDate(c.getTime());
            } catch (Exception e) {
                System.out.println(e.getMessage() + ": " + line);
            }
            // 1 = Last price or N/A
            if (item[1].equalsIgnoreCase("N/A") == false)
                quote.setLast(numberFormat.parse(item[1]).doubleValue());
            // 4 = Change
            // 5 = Open
            if (item[5].equalsIgnoreCase("N/A") == false)
                open = new Double(numberFormat.parse(item[5]).doubleValue());
            // 6 = Maximum
            if (item[6].equalsIgnoreCase("N/A") == false)
                high = new Double(numberFormat.parse(item[6]).doubleValue());
            // 7 = Minimum
            if (item[7].equalsIgnoreCase("N/A") == false)
                low = new Double(numberFormat.parse(item[7]).doubleValue());
            // 8 = Volume
            if (item[8].equalsIgnoreCase("N/A") == false)
                quote.setVolume(numberFormat.parse(item[8]).intValue());
            // 9 = Bid Price
            if (item[9].equalsIgnoreCase("N/A") == false)
                quote.setBid(numberFormat.parse(item[9]).doubleValue());
            // 10 = Ask Price
            if (item[10].equalsIgnoreCase("N/A") == false)
                quote.setAsk(numberFormat.parse(item[10]).doubleValue());
            // 11 = Close Price
            if (item[11].equalsIgnoreCase("N/A") == false)
                close = new Double(numberFormat.parse(item[11]).doubleValue());

            // 0 = Code
            String symbol = stripQuotes(item[0]);
            for (Iterator iter = subscribedSecurities.iterator(); iter.hasNext();) {
                Security security = (Security) iter.next();
                if (symbol.equalsIgnoreCase(security.getCode()))
                    security.setQuote(quote, open, high, low, close);
            }
        }
        in.close();
    } catch (Exception e) {
        System.out.println(e.getMessage() + ": " + line);
        e.printStackTrace();
    }
}

From source file:org.jfree.data.time.WeekTest.java

/**
 * Some checks for the getLastMillisecond() method.
 */// ww w . j a v a  2 s.c o m
@Test
public void testGetLastMillisecond() {
    Locale saved = Locale.getDefault();
    Locale.setDefault(Locale.UK);
    TimeZone savedZone = TimeZone.getDefault();
    TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
    Week w = new Week(31, 1970);
    assertEquals(18485999999L, w.getLastMillisecond());
    Locale.setDefault(saved);
    TimeZone.setDefault(savedZone);
}

From source file:com.rogchen.common.xml.UtilDateTime.java

/**
 *  ?  //from  www  .  j  ava  2s.c  o m
 *
 * @param stamp
 * @param daysLater
 * @param weeksLater
 * @return
 */
public static Timestamp getWeekStart(Timestamp stamp, int daysLater, int weeksLater) {
    return getWeekStart(stamp, daysLater, weeksLater, TimeZone.getDefault(), Locale.getDefault());
}

From source file:com.openerp.support.calendar.OECalendar.java

/**
 * Creating own OpenERP Mobile calendar upon Mobile device
 * /*from  w ww  . j a v  a  2s  .  c  o m*/
 * @param account
 *            : for which OpenERP calendar created
 * @return long : the OpenERP Mobile calendar_id
 */
public long createCalendar(Account account) {
    cr = context.getContentResolver();
    values = new ContentValues();
    values.put(Calendars.ACCOUNT_NAME, account.name);
    values.put(CalendarContract.Calendars.ACCOUNT_TYPE, account.type);
    values.put(Calendars.NAME, account.name);
    values.put(Calendars.CALENDAR_DISPLAY_NAME, account.name);
    values.put(Calendars.CALENDAR_COLOR, Color.parseColor("#cc0000"));
    values.put(Calendars.CALENDAR_ACCESS_LEVEL, Calendars.CAL_ACCESS_OWNER);
    values.put(Calendars.OWNER_ACCOUNT, account.name);
    values.put(Calendars.SYNC_EVENTS, 1);
    values.put(Calendars.VISIBLE, 1);
    values.put(CalendarContract.Calendars.CALENDAR_TIME_ZONE, TimeZone.getDefault().getID());
    creationUri = asSyncAdapter(Calendars.CONTENT_URI, account.name, account.type);
    uri = cr.insert(creationUri, values);
    created_Calendar_id = Long.parseLong(uri.getLastPathSegment());
    return created_Calendar_id;
}

From source file:org.openmrs.module.atomfeed.AtomFeedUtilTest.java

/**
 * @see AtomFeedUtil#dateToRFC3339(Date)
 * @verifies convert date to rfc//  w w w. j  ava2s  .c  o m
 */
@Test
public void dateToRFC3339_shouldConvertDateToRfc() throws Exception {
    TimeZone tz = TimeZone.getDefault();
    System.out.println("timezone: " + tz.getDisplayName());
    try {
        TimeZone.setDefault(TimeZone.getTimeZone("Europe/Helsinki"));
        String expectedOutput = "2012-05-08T22:39:54+03:00";
        Date date = new Date(1336505994083l);
        Assert.assertEquals(expectedOutput, AtomFeedUtil.dateToRFC3339(date));
    } finally {
        TimeZone.setDefault(tz); // reset back to what it was
    }
}

From source file:com.rogchen.common.xml.UtilDateTime.java

/**
 *  ?  ?/*from w ww . j  a va  2  s  . c om*/
 *
 * @param stamp
 * @return
 */
public static Timestamp getWeekEnd(Timestamp stamp) {
    return getWeekEnd(stamp, TimeZone.getDefault(), Locale.getDefault());
}

From source file:at.alladin.rmbt.android.util.InformationCollector.java

public static JSONObject fillBasicInfo(JSONObject object, Context ctx) throws JSONException {
    object.put("plattform", PLATTFORM_NAME);
    object.put("os_version",
            android.os.Build.VERSION.RELEASE + "(" + android.os.Build.VERSION.INCREMENTAL + ")");
    object.put("api_level", String.valueOf(android.os.Build.VERSION.SDK_INT));
    object.put("device", android.os.Build.DEVICE);
    object.put("model", android.os.Build.MODEL);
    object.put("product", android.os.Build.PRODUCT);
    object.put("language", Locale.getDefault().getLanguage());
    object.put("timezone", TimeZone.getDefault().getID());
    object.put("softwareRevision", RevisionHelper.getVerboseRevision());
    PackageInfo pInfo = getPackageInfo(ctx);
    if (pInfo != null) {
        object.put("softwareVersionCode", pInfo.versionCode);
        object.put("softwareVersionName", pInfo.versionName);
    }/*from   w  ww.  ja v  a  2s  . c  o  m*/
    object.put("type", at.alladin.rmbt.android.util.Config.RMBT_CLIENT_TYPE);

    if (BASIC_INFORMATION_INCLUDE_LOCATION) {
        Location loc = GeoLocation.getLastKnownLocation(ctx);
        if (loc != null) {
            JSONObject locationJson = new JSONObject();
            locationJson.put("lat", loc.getLatitude());
            locationJson.put("long", loc.getLongitude());
            locationJson.put("provider", loc.getProvider());
            if (loc.hasSpeed())
                locationJson.put("speed", loc.getSpeed());
            if (loc.hasAltitude())
                locationJson.put("altitude", loc.getAltitude());
            locationJson.put("age", System.currentTimeMillis() - loc.getTime()); //getElapsedRealtimeNanos() would be better, but require higher API-level
            if (loc.hasAccuracy())
                locationJson.put("accuracy", loc.getAccuracy());
            if (loc.hasSpeed())
                locationJson.put("speed", loc.getSpeed());
            /*
             *  would require API level 18
            if (loc.isFromMockProvider())
               locationJson.put("mock",loc.isFromMockProvider());
            */
            object.put("location", locationJson);
        }
    }

    InformationCollector infoCollector = null;

    if (ctx instanceof RMBTMainActivity) {
        Fragment curFragment = ((RMBTMainActivity) ctx).getCurrentFragment();
        if (curFragment != null) {
            if (curFragment instanceof RMBTMainMenuFragment) {
                infoCollector = ((RMBTMainMenuFragment) curFragment).getInformationCollector();
            }
        }
    }

    if (BASIC_INFORMATION_INCLUDE_LAST_SIGNAL_ITEM && (infoCollector != null)) {
        SignalItem signalItem = infoCollector.getLastSignalItem();
        if (signalItem != null) {
            object.put("last_signal_item", signalItem.toJson());
        } else {
            object.put("last_signal_item", JSONObject.NULL);
        }
    }

    return object;
}

From source file:com.robin.utilities.Utilities.java

/**
 * Gives a time stamp in the format of 'YYMMddHHmmss'.
 * @return The time stamp string./*ww  w  . j av a2  s.  c  o  m*/
 */
public String getTimeStamp() {
    return dateToString(now(Calendar.SECOND), "yyMMddHHmmss", TimeZone.getDefault());
}

From source file:morphy.user.SocketChannelUserSession.java

public void send(String message) {
    try {/*from w  w w  . j a va2  s .c om*/
        /* this logic block should be commented out to get rid of multiple-login implementation. */
        if (multipleLoginsParent != null) {
            List<SocketChannelUserSession> list = multipleLoginsParent.multipleLogins;
            multipleLoginsParent.multipleLogins = null;
            multipleLoginsParent.send(message);
            multipleLoginsParent.multipleLogins = list;
        } else {
            if (multipleLogins != null) {
                for (SocketChannelUserSession sess : multipleLogins) {
                    if (sess != null)
                        sess.send(message);
                }
            }
        }

        if (isConnected()) {
            String prompt = "fics% ";
            HashMap<String, String> map = getUser().getUserVars().getVariables();
            if (map.containsKey("prompt") && map.containsKey("ptime") && map.containsKey("tzone")) {
                prompt = map.get("prompt");
                boolean useptime = map.get("ptime").equals("1");
                if (useptime) {
                    Date d = new Date();
                    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("HH:mm");
                    String tzone = getUser().getUserVars().getVariables().get("tzone").toUpperCase();
                    TimeZone tz = TimeZone.getDefault();
                    if (tzone.equals("SERVER"))
                        tzone = tz.getDisplayName(tz.inDaylightTime(d), TimeZone.SHORT);
                    sdf.setTimeZone(TimeZoneUtils.getTimeZone(tzone));
                    prompt = sdf.format(d) + "_" + prompt;
                }
            }

            ByteBuffer buffer = BufferUtils.createBuffer(
                    SocketConnectionService.getInstance().formatMessage(this, message + "\n" + prompt + " "));
            System.out.println((message + "\n\r" + prompt + " ").replace("\n", "\\n").replace("\r", "\\r"));
            try {
                channel.write(buffer);
            } catch (java.io.IOException e) {
                Morphy.getInstance().onError("IOException while trying to write to channel.", e);
            }
        } else {
            if (LOG.isInfoEnabled()) {
                LOG.info("Tried to send message to a logged off user " + user.getUserName() + " " + message);
            }
            disconnect();
        }
    } catch (Throwable t) {
        if (LOG.isErrorEnabled())
            LOG.error("Error sending message to user " + user.getUserName() + " " + message, t);
        disconnect();
    }
}

From source file:com.kubotaku.android.openweathermap.lib.WeatherParser.java

private static void parseForecastDateTime(WeatherInfo info, JSONObject object) {
    try {/* w w  w  .  j ava 2  s .co m*/
        if (object.has(KEY_DT)) {
            // received data's unit is sec, so convert unit to millisecond.
            long time = object.getLong(KEY_DT) * 1000;
            info.setTime(time);

            TimeZone tz = TimeZone.getDefault();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd kk:mm");
            sdf.setTimeZone(tz);
            Date date = new Date(time);
            String forecastDate = sdf.format(date);
            info.setForecastDate(forecastDate);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}