Example usage for org.joda.time.format DateTimeFormatter withZone

List of usage examples for org.joda.time.format DateTimeFormatter withZone

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormatter withZone.

Prototype

public DateTimeFormatter withZone(DateTimeZone zone) 

Source Link

Document

Returns a new formatter that will use the specified zone in preference to the zone of the printed object, or default zone on a parse.

Usage

From source file:VMwareInventory.java

/**
 * readings//ww w  .j  av  a  2s. c  om
 *
 * gather properties for VMs in requested List and readings.  Populates this.vmMap and this.hostMap
 *
 * @param  vms List<VirtualMachine> 
 * @param  startTime Calendar
 * @param  endTime Calendar
 */
public void readings(List<VirtualMachine> vms, Calendar startTime, Calendar endTime) throws Exception {
    logger.fine(
            "Entering VMwareInventory.readings(List<VirtualMachine> vms, Calendar startTime, Calendar endTime)");
    String[] counterNames = { "cpu.usage.average", "cpu.usagemhz.average", "mem.consumed.average",
            "virtualDisk.read.average", "virtualDisk.write.average", "net.received.average",
            "net.transmitted.average" };
    gatherCounters();
    PerfMetricId cpu_usage = new PerfMetricId();
    cpu_usage.setCounterId(this.counterMap.get("cpu.usage.average"));
    cpu_usage.setInstance("");

    PerfMetricId cpu_usagemhz = new PerfMetricId();
    cpu_usagemhz.setCounterId(this.counterMap.get("cpu.usagemhz.average"));
    cpu_usagemhz.setInstance("");

    PerfMetricId mem = new PerfMetricId();
    mem.setCounterId(this.counterMap.get("mem.consumed.average"));
    mem.setInstance("");

    PerfMetricId vdisk_read = new PerfMetricId();
    vdisk_read.setCounterId(this.counterMap.get("virtualDisk.read.average"));
    vdisk_read.setInstance("*");

    PerfMetricId vdisk_write = new PerfMetricId();
    vdisk_write.setCounterId(this.counterMap.get("virtualDisk.write.average"));
    vdisk_write.setInstance("*");

    PerfMetricId net_recv = new PerfMetricId();
    net_recv.setCounterId(this.counterMap.get("net.received.average"));
    net_recv.setInstance("*");

    PerfMetricId net_trans = new PerfMetricId();
    net_trans.setCounterId(this.counterMap.get("net.transmitted.average"));
    net_trans.setInstance("*");

    List<PerfQuerySpec> qSpecList = new ArrayList<PerfQuerySpec>();
    Iterator it = vms.iterator();
    while (it.hasNext()) {
        PerfQuerySpec qSpec = new PerfQuerySpec();
        VirtualMachine vm = (VirtualMachine) it.next();
        qSpec.setEntity(vm.getMOR());
        qSpec.setFormat("normal");
        qSpec.setIntervalId(300);
        qSpec.setMetricId(new PerfMetricId[] { cpu_usage, cpu_usagemhz, mem, vdisk_read, vdisk_write,
                vdisk_write, net_trans, net_recv });
        qSpec.setStartTime(startTime);
        qSpec.setEndTime(endTime);
        qSpecList.add(qSpec);
    }

    PerformanceManager pm = getPerformanceManager();
    PerfQuerySpec[] pqsArray = qSpecList.toArray(new PerfQuerySpec[qSpecList.size()]);
    logger.info("Start PerformanceManager.queryPerf");
    PerfEntityMetricBase[] pembs = pm.queryPerf(pqsArray);
    logger.info("Finished PerformanceManager.queryPerf");
    logger.info("Start gathering of valid timestamps");
    DateTimeFormatter fmt = ISODateTimeFormat.dateTimeNoMillis();
    String timestamp = fmt.withZone(DateTimeZone.UTC).print(endTime.getTimeInMillis());
    this.tsSet.add(timestamp);
    for (int i = 0; pembs != null && i < pembs.length; i++) {
        if (pembs[i] instanceof PerfEntityMetric) {
            parseValidTimestamps((PerfEntityMetric) pembs[i]);
        }

    }
    // Prepopulate with all timestamps
    String[] ts = this.tsSet.toArray(new String[0]);
    for (String moref : this.vmMap.keySet()) {
        HashMap<String, HashMap<String, Long>> metrics = new HashMap<String, HashMap<String, Long>>();
        for (int i = 0; ts != null && i < ts.length; i++) {
            metrics.put(ts[i], new HashMap<String, Long>());
        }
        this.vmMap.get(moref).put("stats", metrics);
    }
    logger.info("Finished gathering of valid timestamps");
    logger.info("Start parsing metrics");
    for (int i = 0; pembs != null && i < pembs.length; i++) {
        //DEBUG - printPerfMetric(pembs[i]);
        if (pembs[i] instanceof PerfEntityMetric) {
            String vm_mor = pembs[i].getEntity().get_value();
            HashMap<String, HashMap<String, Long>> metrics = parsePerfMetricForVM(vm_mor,
                    (PerfEntityMetric) pembs[i]);
            this.vmMap.get(vm_mor).put("stats", metrics);
            // DEBUG - printMachineReading(vm_mor,metrics);
        }
    }
    logger.info("Finished parsing metrics");
    logger.fine("Exiting VMwareInventory.readings(String startIso8601, String endIso8601)");
}

From source file:VMwareInventory.java

private void parseValidTimestamps(PerfEntityMetric pem) {
    logger.fine("Entering VMwareInventory.readings(String startIso8601, String endIso8601)");
    PerfSampleInfo[] infos = pem.getSampleInfo();
    for (int i = 0; infos != null && i < infos.length; i++) {
        DateTimeFormatter fmt = ISODateTimeFormat.dateTimeNoMillis();
        String timestamp = fmt.withZone(DateTimeZone.UTC).print(infos[i].getTimestamp().getTimeInMillis());
        this.tsSet.add(timestamp);
        logger.finer("parseValidTimestmaps() found " + timestamp);
    }/*from w  ww. ja v  a  2s .  co m*/
    logger.fine(
            "Exiting VMwareInventory.readings(List<VirtualMachine> vms, Calendar startTime, Calendar endTime)");

}

From source file:VMwareInventory.java

private HashMap<String, HashMap<String, Long>> parsePerfMetricForVM(String vm_mor, PerfEntityMetric pem) {
    logger.fine("Entering VMwareInventory.parsePerfMetricForVM(String vm_mor, PerfEntityMetric pem)");
    PerfMetricSeries[] vals = pem.getValue();
    PerfSampleInfo[] infos = pem.getSampleInfo();
    HashMap<String, Object> vm_hash = this.vmMap.get(vm_mor);
    @SuppressWarnings("unchecked")
    HashMap<String, HashMap<String, Long>> metrics = (HashMap<String, HashMap<String, Long>>) vm_hash
            .get("stats");
    // Prepopulate with all timestamps
    String[] ts = this.tsSet.toArray(new String[0]);
    for (int i = 0; ts != null && i < ts.length; i++) {
        metrics.put(ts[i], new HashMap<String, Long>());
    }//ww  w .jav  a  2  s  . c  o  m
    // Fill in metrics gathered
    for (int i = 0; infos != null && i < infos.length; i++) {
        DateTimeFormatter fmt = ISODateTimeFormat.dateTimeNoMillis();
        String timestamp = fmt.withZone(DateTimeZone.UTC).print(infos[i].getTimestamp().getTimeInMillis());
        for (int j = 0; vals != null && j < vals.length; ++j) {
            String counterName = this.counterIdMap.get(vals[j].getId().getCounterId());
            String instanceName = vals[j].getId().getInstance();
            String metricName = counterName;
            if (instanceName.length() > 0) {
                metricName = counterName + "." + instanceName;
            }
            if (vals[j] instanceof PerfMetricIntSeries) {
                PerfMetricIntSeries val = (PerfMetricIntSeries) vals[j];
                long[] longs = val.getValue();
                long value = longs[i];
                metrics.get(timestamp).put(metricName, value);
                logger.finer("parsePerfMetricForVM adding " + timestamp + " " + metricName + " " + value);
            }
        }
    }
    logger.fine("Exiting VMwareInventory.parsePerfMetricForVM(String vm_mor, PerfEntityMetric pem)");
    return (metrics);
}

From source file:com.barchart.feed.ddf.historical.provider.CodecHelper.java

License:BSD License

static long decodeTime(final String string, final Instrument instrument, final DateTimeFormatter format) {
    final DateTimeZone zone = DateTimeZone.forID(instrument.timeZoneName());
    return format.withZone(zone).parseMillis(string);
}

From source file:com.barchart.feed.ddf.historical.provider.CodecHelper.java

License:BSD License

static String encodeTime(final long millisUTC, final Instrument instrument, final DateTimeFormatter format) {
    final DateTimeZone zone = DateTimeZone.forID(instrument.timeZoneName());
    return format.withZone(zone).print(millisUTC);
}

From source file:com.coderoad.automation.common.util.DateUtil.java

License:Open Source License

/**
 * Format to zone./*from  w  w  w.  j  a  va2 s  .c om*/
 * 
 * @param milliseconds the milliseconds
 * @param zone the zone
 * @param pattern the pattern
 * @return the string
 */
public static String formatToZone(Long milliseconds, DateTimeZone zone, String pattern) {

    DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern);
    fmt = fmt.withZone(zone);
    String strDate = fmt.print(new DateTime(milliseconds));
    return strDate;
}

From source file:com.gst.infrastructure.core.service.DateUtils.java

License:Apache License

public static LocalDate parseLocalDate(final String stringDate, final String pattern) {

    try {/*w  w  w.j  a va2 s  .c  o  m*/
        final DateTimeFormatter dateStringFormat = DateTimeFormat.forPattern(pattern);
        dateStringFormat.withZone(getDateTimeZoneOfTenant());
        final DateTime dateTime = dateStringFormat.parseDateTime(stringDate);
        return dateTime.toLocalDate();
    } catch (final IllegalArgumentException e) {
        final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
        final ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.date.pattern",
                "The parameter date (" + stringDate + ") is invalid w.r.t. pattern " + pattern, "date",
                stringDate, pattern);
        dataValidationErrors.add(error);
        throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                "Validation errors exist.", dataValidationErrors);
    }
}

From source file:com.gst.portfolio.savings.service.SavingsAccountWritePlatformServiceJpaRepositoryImpl.java

License:Apache License

@Transactional
@Override//from w  w w  .j  a  v a2 s . c  o m
public void applyChargeDue(final Long savingsAccountChargeId, final Long accountId) {
    // always use current date as transaction date for batch job
    AppUser user = null;

    final LocalDate transactionDate = DateUtils.getLocalDateOfTenant();
    final SavingsAccountCharge savingsAccountCharge = this.savingsAccountChargeRepository
            .findOneWithNotFoundDetection(savingsAccountChargeId, accountId);

    final DateTimeFormatter fmt = DateTimeFormat.forPattern("dd MM yyyy");
    fmt.withZone(DateUtils.getDateTimeZoneOfTenant());

    while (transactionDate.isAfter(savingsAccountCharge.getDueLocalDate())
            && savingsAccountCharge.isNotFullyPaid()) {
        payCharge(savingsAccountCharge, transactionDate, savingsAccountCharge.amoutOutstanding(), fmt, user);
    }
}

From source file:com.hurence.logisland.processor.TimeSeriesCsvLoader.java

License:Apache License

/**
 * CSV reader that waits for a 2 columns csv files with or without a header.
 * If less than 2 columns ==> exception, otherwise, the 3rd and following columns are ignored
 *
 * @param in//from  www . j a v  a2 s. c om
 * @param hasHeader
 * @param inputDatetimeFormat input date format
 * @return
 * @throws IOException
 * @throws IllegalArgumentException
 * @throws ArrayIndexOutOfBoundsException
 */
public static List<Record> load(Reader in, boolean hasHeader, DateTimeFormatter inputDatetimeFormat)
        throws IOException {

    List<Record> records = new ArrayList<>();
    for (CSVRecord record : CSVFormat.DEFAULT.parse(in)) {
        try {
            if (!hasHeader) {
                StandardRecord event = new StandardRecord("sensors");
                event.setField(TIMESTAMP_KEY, FieldType.LONG, inputDatetimeFormat.withZone(DateTimeZone.UTC)
                        .parseDateTime(record.get(0)).getMillis());
                event.setField(VALUE_KEY, FieldType.DOUBLE, Double.parseDouble(record.get(1)));

                records.add(event);
            } else {
                TIMESTAMP_KEY = record.get(0);
                VALUE_KEY = record.get(1);
            }

            hasHeader = false;
        } catch (Exception e) {
            logger.error("Parsing error " + e.getMessage());
            throw new RuntimeException("parsing error", e);
        }
    }

    return records;
}

From source file:com.money.manager.ex.investment.morningstar.MorningstarPriceUpdater.java

License:Open Source License

/**
 * Parse Morningstar response into price information.
 * @param symbol Morningstar symbol// w w  w  . ja  v  a 2s  . c  om
 * @param html Result
 * @return An object containing price details
 */
private PriceDownloadedEvent parse(String symbol, String html) {
    Document doc = Jsoup.parse(html);

    // symbol
    String yahooSymbol = symbolConverter.getYahooSymbol(symbol);

    // price
    String priceString = doc.body().getElementById("last-price-value").text();
    Money price = MoneyFactory.fromString(priceString);
    // currency
    String currency = doc.body().getElementById("curency").text();
    if (currency.equals("GBX")) {
        price = price.divide(100, MoneyFactory.MAX_ALLOWED_PRECISION);
    }

    // date
    String dateString = doc.body().getElementById("asOfDate").text();
    DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/YYYY HH:mm:ss");
    // the time zone is EST
    DateTime date = formatter.withZone(DateTimeZone.forID("America/New_York")).parseDateTime(dateString)
            .withZone(DateTimeZone.forID("Europe/Vienna"));

    // todo: should this be converted to the exchange time?

    return new PriceDownloadedEvent(yahooSymbol, price, date);
}