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:org.anodyneos.jse.cron.CronDaemon.java

public CronDaemon(InputSource source) throws JseException {

    Schedule schedule;/*from w ww.ja  va 2 s.  co  m*/

    // parse source
    try {

        JAXBContext jc = JAXBContext.newInstance("org.anodyneos.jse.cron.config");
        Unmarshaller u = jc.createUnmarshaller();
        //Schedule
        Source schemaSource = new StreamSource(Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("org/anodyneos/jse/cron/cron.xsd"));

        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(schemaSource);
        u.setSchema(schema);
        ValidationEventCollector vec = new ValidationEventCollector();
        u.setEventHandler(vec);

        JAXBElement<?> rootElement;
        try {
            rootElement = ((JAXBElement<?>) u.unmarshal(source));
        } catch (UnmarshalException ex) {
            if (!vec.hasEvents()) {
                throw ex;
            } else {
                for (ValidationEvent ve : vec.getEvents()) {
                    ValidationEventLocator vel = ve.getLocator();
                    log.error("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:"
                            + ve.getMessage());
                }
                throw new JseException("Validation failed for source publicId='" + source.getPublicId()
                        + "'; systemId='" + source.getSystemId() + "';");
            }
        }

        schedule = (Schedule) rootElement.getValue();

        if (vec.hasEvents()) {
            for (ValidationEvent ve : vec.getEvents()) {
                ValidationEventLocator vel = ve.getLocator();
                log.warn("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:"
                        + ve.getMessage());
            }
        }

    } catch (JseException e) {
        throw e;
    } catch (Exception e) {
        throw new JseException("Cannot parse " + source + ".", e);
    }

    SpringHelper springHelper = new SpringHelper();

    ////////////////
    //
    // Configure Spring and Create Beans
    //
    ////////////////

    TimeZone defaultTimeZone;

    if (schedule.isSetTimeZone()) {
        defaultTimeZone = getTimeZone(schedule.getTimeZone());
    } else {
        defaultTimeZone = TimeZone.getDefault();
    }

    if (schedule.isSetSpringContext() && schedule.getSpringContext().isSetConfig()) {
        for (Config config : schedule.getSpringContext().getConfig()) {
            springHelper.addXmlClassPathConfigLocation(config.getClassPathResource());
        }
    }

    for (org.anodyneos.jse.cron.config.JobGroup jobGroup : schedule.getJobGroup()) {
        for (Job job : jobGroup.getJob()) {
            if (job.isSetBeanRef()) {
                if (job.isSetBean() || job.isSetClassName()) {
                    throw new JseException("Cannot set bean or class attribute for job when beanRef is set.");
                } // else config ok
            } else {
                if (!job.isSetClassName()) {
                    throw new JseException("must set either class or beanRef for job.");
                }
                GenericBeanDefinition beanDef = new GenericBeanDefinition();
                MutablePropertyValues propertyValues = new MutablePropertyValues();

                if (!job.isSetBean()) {
                    job.setBean(UUID.randomUUID().toString());
                }

                if (springHelper.containsBean(job.getBean())) {
                    throw new JseException(
                            "Bean name already used; overriding not allowed here: " + job.getBean());
                }

                beanDef.setBeanClassName(job.getClassName());

                for (Property prop : job.getProperty()) {
                    String value = null;
                    if (prop.isSetSystemProperty()) {
                        value = System.getProperty(prop.getSystemProperty());
                    }
                    if (null == value) {
                        value = prop.getValue();
                    }

                    propertyValues.addPropertyValue(prop.getName(), value);
                }

                beanDef.setPropertyValues(propertyValues);
                springHelper.registerBean(job.getBean(), beanDef);
                job.setBeanRef(job.getBean());
            }
        }
    }

    springHelper.init();

    ////////////////
    //
    // Configure Timer Services
    //
    ////////////////

    for (org.anodyneos.jse.cron.config.JobGroup jobGroup : schedule.getJobGroup()) {

        String jobGroupName;
        JseTimerService service = new JseTimerService();

        timerServices.add(service);

        if (jobGroup.isSetName()) {
            jobGroupName = jobGroup.getName();
        } else {
            jobGroupName = UUID.randomUUID().toString();
        }

        if (jobGroup.isSetMaxConcurrent()) {
            service.setMaxConcurrent(jobGroup.getMaxConcurrent());
        }

        for (Job job : jobGroup.getJob()) {

            TimeZone jobTimeZone = defaultTimeZone;

            if (job.isSetTimeZone()) {
                jobTimeZone = getTimeZone(job.getTimeZone());
            } else {
                jobTimeZone = defaultTimeZone;
            }

            Object obj;

            Date notBefore = null;
            Date notAfter = null;

            if (job.isSetNotBefore()) {
                notBefore = job.getNotBefore().toGregorianCalendar(jobTimeZone, null, null).getTime();
            }
            if (job.isSetNotAfter()) {
                notAfter = job.getNotAfter().toGregorianCalendar(jobTimeZone, null, null).getTime();
            }

            CronSchedule cs = new CronSchedule(job.getSchedule(), jobTimeZone, job.getMaxIterations(),
                    job.getMaxQueue(), notBefore, notAfter);

            obj = springHelper.getBean(job.getBeanRef());
            log.info("Adding job " + jobGroup.getName() + "/" + job.getName() + " using bean "
                    + job.getBeanRef());
            if (obj instanceof CronJob) {
                ((CronJob) obj).setCronContext(new CronContext(jobGroupName, job.getName(), cs));
            }
            if (obj instanceof JseDateAwareJob) {
                service.createTimer((JseDateAwareJob) obj, cs);
            } else if (obj instanceof Runnable) {
                service.createTimer((Runnable) obj, cs);
            } else {
                throw new JseException("Job must implement Runnable or JseDateAwareJob");
            }
        }
    }
}

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

/**
 * Constructs a new instance, based on the supplied date/time and
 * the default time zone./*from   w w  w .ja  v  a 2  s  . c  o m*/
 *
 * @param time  the time (<code>null</code> not permitted).
 *
 * @see #Minute(Date, TimeZone)
 */
public Minute(Date time) {
    // defer argument checking
    this(time, TimeZone.getDefault(), Locale.getDefault());
}

From source file:com.arantius.tivocommander.Upcoming.java

protected String formatTime(JsonNode item) throws DateInPast {
    String timeIn = item.path("startTime").asText();
    if (timeIn == null) {
        return null;
    }/*w  w w  .  j av a 2 s.c  o  m*/

    Date playTime = Utils.parseDateTimeStr(timeIn);
    if (playTime.before(new Date())) {
        throw new DateInPast();
    }
    SimpleDateFormat dateFormatter = new SimpleDateFormat("EEE M/d hh:mm a", Locale.US);
    dateFormatter.setTimeZone(TimeZone.getDefault());
    return dateFormatter.format(playTime);
}

From source file:at.alladin.rmbt.client.helper.ControlServerConnection.java

/**
 * requests the parameters for the v2 tests
 * @param host/*from ww  w.j  a  v a2 s .c  o m*/
 * @param pathPrefix
 * @param port
 * @param encryption
 * @param geoInfo
 * @param uuid
 * @param clientType
 * @param clientName
 * @param clientVersion
 * @param additionalValues
 * @return
 */
public String requestQoSTestParameters(final String host, final String pathPrefix, final int port,
        final boolean encryption, final ArrayList<String> geoInfo, final String uuid, final String clientType,
        final String clientName, final String clientVersion, final JSONObject additionalValues) {
    clientUUID = uuid;

    hostUri = getUri(encryption, host, pathPrefix, port, Config.RMBT_CONTROL_V2_TESTS);

    System.out.println("Connection to " + hostUri);

    final JSONObject regData = new JSONObject();

    try {
        regData.put("uuid", uuid);
        regData.put("client", clientName);
        regData.put("version", Config.RMBT_VERSION_NUMBER);
        regData.put("type", clientType);
        regData.put("softwareVersion", clientVersion);
        regData.put("softwareRevision", RevisionHelper.getVerboseRevision());
        regData.put("language", Locale.getDefault().getLanguage());
        regData.put("timezone", TimeZone.getDefault().getID());
        regData.put("time", System.currentTimeMillis());

        if (geoInfo != null) {
            final JSONObject locData = new JSONObject();
            locData.put("time", geoInfo.get(0));
            locData.put("lat", geoInfo.get(1));
            locData.put("long", geoInfo.get(2));
            locData.put("accuracy", geoInfo.get(3));
            locData.put("altitude", geoInfo.get(4));
            locData.put("bearing", geoInfo.get(5));
            locData.put("speed", geoInfo.get(6));
            locData.put("provider", geoInfo.get(7));

            regData.accumulate("location", locData);
        }

        addToJSONObject(regData, additionalValues);

    } catch (final JSONException e1) {
        hasError = true;
        errorMsg = "Error gernerating request";
        // e1.printStackTrace();
    }

    // getting JSON string from URL
    final JSONObject response = jParser.sendJSONToUrl(hostUri, regData);

    if (response != null)
        try {
            final JSONArray errorList = response.getJSONArray("error");

            // System.out.println(response.toString(4));

            if (errorList.length() == 0) {

                int testPort = 5233;

                Map<String, Object> testParams = null;
                testParams = JSONParser.toMap(response.getJSONObject("objectives"));

                v2TaskDesc = new ArrayList<TaskDesc>();

                for (Entry<String, Object> e : testParams.entrySet()) {
                    List<HashMap<String, Object>> paramList = (List<HashMap<String, Object>>) e.getValue();
                    for (HashMap<String, Object> params : paramList) {
                        TaskDesc taskDesc = new TaskDesc(testHost, testPort, encryption, testToken, 0, 1, 0,
                                System.nanoTime(), params, e.getKey());
                        v2TaskDesc.add(taskDesc);
                    }
                }
            } else {
                hasError = true;
                for (int i = 0; i < errorList.length(); i++) {
                    if (i > 0)
                        errorMsg += "\n";
                    errorMsg += errorList.getString(i);
                }
            }

            // }
        } catch (final JSONException e) {
            hasError = true;
            errorMsg = "Error parsing server response";
            e.printStackTrace();
        }
    else {
        hasError = true;
        errorMsg = "No response";
    }

    return errorMsg;
}

From source file:com.apptentive.android.sdk.storage.DeviceManager.java

private static Device generateNewDevice(Context context) {
    Device device = new Device();

    // First, get all the information we can load from static resources.
    device.setOsName("Android");
    device.setOsVersion(Build.VERSION.RELEASE);
    device.setOsBuild(Build.VERSION.INCREMENTAL);
    device.setOsApiLevel(String.valueOf(Build.VERSION.SDK_INT));
    device.setManufacturer(Build.MANUFACTURER);
    device.setModel(Build.MODEL);//from   w  ww  .ja v a2s.  co  m
    device.setBoard(Build.BOARD);
    device.setProduct(Build.PRODUCT);
    device.setBrand(Build.BRAND);
    device.setCpu(Build.CPU_ABI);
    device.setDevice(Build.DEVICE);
    device.setUuid(GlobalInfo.androidId);
    device.setBuildType(Build.TYPE);
    device.setBuildId(Build.ID);

    // Second, set the stuff that requires querying system services.
    TelephonyManager tm = ((TelephonyManager) (context.getSystemService(Context.TELEPHONY_SERVICE)));
    device.setCarrier(tm.getSimOperatorName());
    device.setCurrentCarrier(tm.getNetworkOperatorName());
    device.setNetworkType(Constants.networkTypeAsString(tm.getNetworkType()));

    // Finally, use reflection to try loading from APIs that are not available on all Android versions.
    device.setBootloaderVersion(Reflection.getBootloaderVersion());
    device.setRadioVersion(Reflection.getRadioVersion());

    device.setLocaleCountryCode(Locale.getDefault().getCountry());
    device.setLocaleLanguageCode(Locale.getDefault().getLanguage());
    device.setLocaleRaw(Locale.getDefault().toString());
    device.setUtcOffset(String.valueOf((TimeZone.getDefault().getRawOffset() / 1000)));
    return device;
}

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

/**
 * Constructs a new millisecond using the default time zone.
 *
 * @param time  the time./*from  w  ww. ja  v a  2s. c  o  m*/
 *
 * @see #Millisecond(Date, TimeZone, Locale)
 */
public Millisecond(Date time) {
    this(time, TimeZone.getDefault(), Locale.getDefault());
}

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

/**
 * Constructs a new instance, based on the supplied date/time and
 * the default time zone.//from   w ww.ja  v  a 2  s .c om
 *
 * @param time  the date-time (<code>null</code> not permitted).
 *
 * @see #Hour(Date, TimeZone)
 */
public Hour(Date time) {
    // defer argument checking...
    this(time, TimeZone.getDefault(), Locale.getDefault());
}

From source file:org.tolven.analysis.bean.PercentTimeSeriesBean.java

private JFreeChart getChart(String dataSeriesTitle, String targetSeriesTitle, List<MenuData> snapshots,
        Date fromDate, Date toDate, Class<?> intervalUnitClass) {
    TimeSeries dataTimeSeries = new TimeSeries(dataSeriesTitle);
    TimeSeries targetTimeSeries = null;//from   ww  w .ja v  a2 s  .com
    if (targetSeriesTitle != null) {
        targetTimeSeries = new TimeSeries(targetSeriesTitle);
    }
    for (MenuData snapshot : snapshots) {
        Date snapshotDate = snapshot.getDate01();
        long nSnapshotresultsNumerator = snapshot.getLongField("normCount");
        long nSnapshotresultsDenominator = snapshot.getLongField("allCount");
        Double value = null;
        if (nSnapshotresultsDenominator == 0) {
            value = 0d;
        } else {
            value = 1d * nSnapshotresultsNumerator / nSnapshotresultsDenominator;
        }
        RegularTimePeriod regTimePeriod = RegularTimePeriod.createInstance(intervalUnitClass, snapshotDate,
                TimeZone.getDefault());
        dataTimeSeries.addOrUpdate(regTimePeriod, value);
        if (targetTimeSeries != null) {
            Double targetPercent = snapshot.getDoubleField("targetPercent") / 100;
            targetTimeSeries.addOrUpdate(regTimePeriod, targetPercent);
        }
    }
    TimeSeriesCollection timeSeriesCollection = new TimeSeriesCollection();
    timeSeriesCollection.addSeries(dataTimeSeries);
    if (targetTimeSeries != null) {
        timeSeriesCollection.addSeries(targetTimeSeries);
    }
    XYDataset xyDataset = (XYDataset) timeSeriesCollection;
    JFreeChart chart = ChartFactory.createTimeSeriesChart(null, // title
            null, // x-axis label
            null, // y-axis label
            xyDataset, // data
            true, // create legend?
            false, // generate tooltips?
            false // generate URLs?
    );
    chart.setBackgroundPaint(Color.white);
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.BLACK);
    plot.setDomainGridlinesVisible(false);
    XYItemRenderer r = plot.getRenderer();
    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
    renderer.setBaseShapesVisible(true);
    renderer.setBaseShapesFilled(true);
    renderer.setSeriesShape(0, new Ellipse2D.Double(-3, -3, 6, 6));
    renderer.setSeriesPaint(0, Color.BLUE);
    renderer.setSeriesShape(1, new Rectangle2D.Double(-3, -3, 6, 6));
    renderer.setSeriesPaint(1, Color.RED);
    NumberAxis vaxis = (NumberAxis) plot.getRangeAxis();
    vaxis.setAutoRange(true);
    vaxis.setAxisLineVisible(true);
    vaxis.setNumberFormatOverride(NumberFormat.getPercentInstance());
    vaxis.setTickMarksVisible(true);
    DateAxis daxis = (DateAxis) plot.getDomainAxis();
    daxis.setRange(fromDate, toDate);
    if (intervalUnitClass == Month.class) {
        DateFormatSymbols dateFormatSymbols = new DateFormatSymbols();
        dateFormatSymbols
                .setShortMonths(new String[] { "J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D" });
        daxis.setDateFormatOverride(new SimpleDateFormat("MMM", dateFormatSymbols));
    }
    return chart;
}

From source file:at.jku.rdfstats.RDFStatsConfiguration.java

public static RDFStatsConfiguration create(Resource cfg) throws ConfigurationException {
    Model statsModel;/*from  www. j a v  a2 s  . c  om*/
    if (cfg.hasProperty(Config.statsModel)) {
        Resource r = cfg.getProperty(Config.statsModel).getResource();

        try {
            log.info("Opening statistics model...");
            statsModel = Assembler.general.openModel(r);
        } catch (AssemblerException e) {
            throw new ConfigurationException(
                    "Couldn't init statistics model via Jena Assembler. Please check your configuration.", e);
        }
    } else
        statsModel = ModelFactory.createDefaultModel();

    List<String> endpoints = new ArrayList<String>();
    StmtIterator it = cfg.getModel().listStatements(cfg, Config.endpointUri, (RDFNode) null);
    while (it.hasNext())
        endpoints.add(it.nextStatement().getResource().getURI());

    List<String> documentURLs = new ArrayList<String>();
    StmtIterator it2 = cfg.getModel().listStatements(cfg, Config.documentUrl, (RDFNode) null);
    while (it2.hasNext())
        documentURLs.add(it2.nextStatement().getResource().getURI());

    //      boolean classSpecific = (cfg.hasProperty(Configuration.classSpecificHistograms)) ? cfg.getProperty(Configuration.classSpecificHistograms).getBoolean() : DEFAULT_CLASSSPECIFIC;
    Integer prefSize = (cfg.hasProperty(Config.histogramSize)) ? cfg.getProperty(Config.histogramSize).getInt()
            : DEFAULT_PREFSIZE;
    String outFile = (cfg.hasProperty(Config.outputFile)) ? cfg.getProperty(Config.outputFile).getString()
            : DEFAULT_OUTFILE;
    String outFormat = (cfg.hasProperty(Config.outputFormat)) ? cfg.getProperty(Config.outputFormat).getString()
            : DEFAULT_OUTFORMAT;
    Integer strHistMaxLength = (cfg.hasProperty(Config.stringHistMaxLength))
            ? cfg.getProperty(Config.stringHistMaxLength).getInt()
            : DEFAULT_STRHIST_MAXLEN;
    boolean quickMode = (cfg.hasProperty(Config.quickMode)) ? cfg.getProperty(Config.quickMode).getBoolean()
            : DEFAULT_QUICK_MODE;
    TimeZone timeZone = (cfg.hasProperty(Config.defaultTimezone))
            ? TimeZone.getTimeZone(cfg.getProperty(Config.defaultTimezone).getString())
            : TimeZone.getDefault();

    return new RDFStatsConfiguration(statsModel, endpoints, documentURLs,
            //            classSpecific, 
            prefSize, outFile, outFormat, strHistMaxLength, quickMode, timeZone);
}

From source file:gov.nih.nci.cabig.caaers.utils.DateUtils.java

public static String formatDate(Date d, String pattern) {
    return formatDate(d, pattern, TimeZone.getDefault());
}