Example usage for org.joda.time DateTime withZone

List of usage examples for org.joda.time DateTime withZone

Introduction

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

Prototype

public DateTime withZone(DateTimeZone newZone) 

Source Link

Document

Returns a copy of this datetime with a different time zone, preserving the millisecond instant.

Usage

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

License:Open Source License

/**
 * Constructor/*from  w  w  w.j a  va 2 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:be.nielsbril.clicket.app.viewmodels.ParkFragmentViewModel.java

private void loadCurrentSession() {
    ApiHelper.subscribe(//from   www  . j a va2 s. c  om
            ClicketInstance.getClicketserviceInstance().activeSession(AuthHelper.getAuthToken(mContext)),
            new Action1<SessionSingleResult>() {
                @Override
                public void call(SessionSingleResult sessionSingleResult) {
                    if (sessionSingleResult != null && sessionSingleResult.isSuccess()) {
                        Session session = sessionSingleResult.getData();
                        setSession(session);
                        startButton(false);
                        stopButton(true);
                        DateTime start = new DateTime(getSession().getStarted_on());
                        start = start.withZone(dateTimeZone);
                        setStarted_on(start.toString(dateTimeFormatter));
                        setStopped_on("n.a.");
                        setZone(getSession().getZone_id().getName() + " (" + getSession().getStreet() + ")");
                        setCar(getSession().getCar_id().getName() + " ("
                                + getSession().getCar_id().getLicense_plate() + ")");
                        setCost(0);
                    } else {
                        noCurrentSession();
                    }
                }
            });
}

From source file:be.nielsbril.clicket.app.viewmodels.ParkFragmentViewModel.java

private void startSession() {
    ApiHelper.subscribe(//w  ww.j a  v a 2  s  .  com
            ClicketInstance.getClicketserviceInstance().startSession(Double.toString(mLocation.getLatitude()),
                    Double.toString(mLocation.getLongitude()), mId, AuthHelper.getAuthToken(mContext)),
            new Action1<SessionSingleResult>() {
                @Override
                public void call(SessionSingleResult sessionSingleResult) {
                    if (sessionSingleResult != null && sessionSingleResult.isSuccess()) {
                        setSession(sessionSingleResult.getData());
                        startButton(false);
                        stopButton(true);
                        DateTime start = new DateTime(getSession().getStarted_on());
                        start = start.withZone(dateTimeZone);
                        setStarted_on(start.toString(dateTimeFormatter));
                        setStopped_on("n.a.");
                        setZone(getSession().getZone_id().getName() + " (" + getSession().getStreet() + ")");
                        setCar(getSession().getCar_id().getName() + " ("
                                + getSession().getCar_id().getLicense_plate() + ")");
                        setCost(0);
                    } else {
                        showSnackbar("Error when starting session: zone not found, Clicket won't work here");
                    }
                }
            });
}

From source file:be.nielsbril.clicket.app.viewmodels.ParkFragmentViewModel.java

private void stop() {
    ApiHelper.subscribe(ClicketInstance.getClicketserviceInstance().stopSession(getSession().get_id(),
            AuthHelper.getAuthToken(mContext)), new Action1<SessionStopResult>() {
                @Override/* www. j  av  a 2 s  .  c  o  m*/
                public void call(SessionStopResult sessionStopResult) {
                    if (sessionStopResult != null && sessionStopResult.isSuccess()) {
                        setSession(null);
                        startButton(true);
                        stopButton(false);
                        DateTime stop = new DateTime(sessionStopResult.getData().getSession().getStopped_on());
                        stop = stop.withZone(dateTimeZone);
                        setStopped_on(stop.toString(dateTimeFormatter));
                        setCost(sessionStopResult.getData().getInfo().getPrice().getTotal());
                        showSnackbar(
                                "Stopped your session. You parked for "
                                        + Utils.roundToDecimals(
                                                sessionStopResult.getData().getInfo().getPrice().getTotal(), 2)
                                        + ".");
                        updateUser();
                    } else {
                        showSnackbar("Error when stopping session");
                    }
                }
            });
}

From source file:ching.icecreaming.action.ResourceDescriptors.java

License:Open Source License

@Action(value = "resource-descriptors", results = { @Result(name = "success", location = "json.jsp") })
public String execute() throws Exception {
    int int1 = 401, int0 = 0;
    String string1 = null;//from  w  w w  .j a va2s .c  om
    URL url1 = null;
    URI uri1 = null;
    HttpGet httpGet1 = null;
    HttpResponse httpResponse1 = null;
    HttpEntity httpEntity1 = null;
    HttpPost httpPost1 = null;
    HttpHost httpHost1 = null;
    DefaultHttpClient httpClient1 = null;
    File file1 = null;
    InputStream inputStream1 = null;
    OutputStream outputStream1 = null;
    BeanComparator beanComparator1 = null;
    List<Map<String, Object>> list1 = null, list2 = null;
    Map<String, Object> map1 = null;
    Object object1 = null;
    int toIndex = rows * page;
    int fromIndex = toIndex - rows;
    GridModel1 jsonObject1 = null;
    Gson gson = null;
    Long long1 = -1L;
    java.util.Date date1 = null;
    URIBuilder uriBuilder1 = null;
    Node node1 = null;
    Element element1 = null;
    NodeList nodeList1 = null;
    Document document1 = null;
    DocumentBuilder documentBuilder1 = null;
    DocumentBuilderFactory documentBuilderFactory1 = null;
    org.joda.time.DateTime dateTime1 = null, dateTime2 = null;

    try {
        if (StringUtils.isNotEmpty(sid) && StringUtils.isNotEmpty(uid) && StringUtils.isNotEmpty(pid)) {
            sid = new String(Base64.decodeBase64(sid.getBytes()));
            uid = new String(Base64.decodeBase64(uid.getBytes()));
            pid = new String(Base64.decodeBase64(pid.getBytes()));
            httpClient1 = new DefaultHttpClient();
            url1 = new URL(sid);
            uriBuilder1 = new URIBuilder(sid);
            uriBuilder1.setParameter("j_username", uid);
            uriBuilder1.setParameter("j_password", pid);
            uriBuilder1.setPath(url1.getPath() + "/rest/resources" + urlString);
            uriBuilder1.setUserInfo(uid, pid);
            uri1 = uriBuilder1.build();
            httpGet1 = new HttpGet(uri1);
            httpResponse1 = httpClient1.execute(httpGet1);
            int1 = httpResponse1.getStatusLine().getStatusCode();
            if (int1 == HttpStatus.SC_OK) {
                httpEntity1 = httpResponse1.getEntity();
                inputStream1 = httpResponse1.getEntity().getContent();
                if (inputStream1 != null) {
                    documentBuilderFactory1 = DocumentBuilderFactory.newInstance();
                    documentBuilder1 = documentBuilderFactory1.newDocumentBuilder();
                    document1 = documentBuilder1.parse(inputStream1);
                    document1.getDocumentElement().normalize();
                    nodeList1 = document1.getElementsByTagName("resourceDescriptor");
                    int1 = nodeList1.getLength();
                    list1 = new ArrayList<Map<String, Object>>();
                    for (int0 = 0; int0 < int1; int0++) {
                        node1 = nodeList1.item(int0);
                        if (node1.getNodeType() == Node.ELEMENT_NODE) {
                            element1 = (Element) node1;
                            map1 = new HashMap<String, Object>();
                            map1.put("wsType", element1.getAttribute("wsType"));
                            map1.put("uriString", element1.getAttribute("uriString"));
                            string1 = getTagValue("label", element1);
                            map1.put("label1", StringUtils.defaultString(string1));
                            string1 = getTagValue("description", element1);
                            map1.put("description", StringUtils.defaultString(string1));
                            string1 = getTagValue("creationDate", element1);
                            long1 = (string1 == null) ? -1L
                                    : NumberUtils.toLong(StringUtils.trim(string1), -1L);
                            if (long1 > 0) {
                                if (StringUtils.isNotBlank(timeZone1)) {
                                    dateTime1 = new org.joda.time.DateTime(long1);
                                    dateTime2 = dateTime1.withZone(DateTimeZone.forID(timeZone1));
                                    date1 = dateTime2.toLocalDateTime().toDate();
                                } else {
                                    date1 = new java.util.Date(long1);
                                }
                            } else {
                                date1 = null;
                            }
                            map1.put("creationDate", date1);
                            map1.put("type1", getText(element1.getAttribute("wsType")));
                            list1.add(map1);
                        }
                    }
                }
                EntityUtils.consume(httpEntity1);
            }
        }
    } catch (UnsupportedEncodingException | URISyntaxException | ParserConfigurationException
            | SAXException exception1) {
        exception1.printStackTrace();
        return ERROR;
    } catch (org.apache.http.conn.HttpHostConnectException | java.net.NoRouteToHostException
            | java.net.MalformedURLException | java.net.UnknownHostException exception1) {
        exception1.printStackTrace();
        return ERROR;
    } catch (IOException exception1) {
        httpGet1.abort();
        exception1.printStackTrace();
        return ERROR;
    } finally {
        if (httpClient1 != null)
            httpClient1.getConnectionManager().shutdown();
        if (list1 != null) {
            records = list1.size();
            if (list1.size() > 0) {
                if (StringUtils.isNotEmpty(sidx)) {
                    if (StringUtils.equals(sord, "desc")) {
                        beanComparator1 = new BeanComparator(sidx,
                                new ReverseComparator(new ComparableComparator()));
                    } else {
                        beanComparator1 = new BeanComparator(sidx);
                    }
                    Collections.sort(list1, beanComparator1);
                }
                if (StringUtils.isNotBlank(searchField) && StringUtils.isNotEmpty(searchOper)) {
                    Iterator iterator1 = list1.iterator();
                    while (iterator1.hasNext()) {
                        map1 = (Map<String, Object>) iterator1.next();
                        for (Map.Entry<String, Object> entry1 : map1.entrySet()) {
                            if (StringUtils.equals(entry1.getKey(), searchField)) {
                                object1 = entry1.getValue();
                                if (searchFilter(searchField, searchOper, searchString, object1))
                                    iterator1.remove();
                                break;
                            }
                        }
                    }
                    records = list1.size();
                }
                if (toIndex > records)
                    toIndex = records;
                if (fromIndex > toIndex) {
                    fromIndex = toIndex - rows;
                    if (fromIndex < 0)
                        fromIndex = 0;
                }
                if (list1.size() > 0 && fromIndex >= 0 && toIndex <= list1.size() && fromIndex <= toIndex)
                    list2 = list1.subList(fromIndex, toIndex);

            }
            total = (int) Math.ceil((double) records / (double) rows);
            if (page > total)
                page = total;
            jsonObject1 = new GridModel1(rows, page, sord, sidx, searchField, searchString, searchOper, total,
                    records, id, list2);
            gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss.SSS").create();
            jsonData = gson.toJson(jsonObject1);
        }
        IOUtils.closeQuietly(inputStream1);
    }
    return SUCCESS;
}

From source file:cmg.org.monitor.app.schedule.MailServiceScheduler.java

License:Open Source License

/**
 * Do schedule./*from   w  ww .  j  a v a2s .  co m*/
 */
public void doSchedule() {
    // BEGIN LOG
    UtilityDAO utilDAO = new UtilityDaoImpl();
    long start = System.currentTimeMillis();
    logger.log(Level.INFO, MonitorUtil.parseTime(start, true) + " -> START: Scheduled send alert mail ...");
    String currentZone = utilDAO.getCurrentTimeZone();
    DateTime dtStart = new DateTime(start);
    dtStart = dtStart.withZone(DateTimeZone.forID(currentZone));
    // BEGIN LOG
    String alertName = MonitorConstant.ALERTSTORE_DEFAULT_NAME + ": "
            + dtStart.toString(DateTimeFormat.forPattern(MonitorConstant.SYSTEM_DATE_FORMAT));
    SystemAccountDAO accountDao = new SystemAccountDaoImpl();
    SystemDAO sysDAO = new SystemDaoImpl();
    AlertDao alertDAO = new AlertDaoImpl();
    ArrayList<SystemMonitor> systems = sysDAO.listSystemsFromMemcache(false);

    MailMonitorDAO mailDAO = new MailMonitorDaoImpl();

    SystemGroupDAO groupDao = new SystemGroupDaoImpl();
    if (systems != null && systems.size() > 0) {
        ArrayList<UserMonitor> listUsers = utilDAO.listAllUsers();
        if (listUsers != null && listUsers.size() > 0) {
            for (UserMonitor user : listUsers) {
                for (SystemMonitor sys : systems) {
                    try {
                        SystemGroup gr = groupDao.getByName(sys.getGroupEmail());
                        if (gr != null) {
                            if (user.checkGroup(gr.getId())) {
                                user.addSystem(sys);
                            }
                        }
                    } catch (Exception e) {
                        logger.log(Level.WARNING, "Error: " + e.getMessage());
                    }
                }
            }

            for (UserMonitor user : listUsers) {
                if (user.getSystems() != null && user.getSystems().size() > 0) {
                    for (Object tempSys : user.getSystems()) {
                        AlertStoreMonitor alertstore = alertDAO.getLastestAlertStore((SystemMonitor) tempSys);
                        if (alertstore != null) {
                            alertstore.setName(alertName);
                            alertstore.setTimeStamp(new Date(start));
                            NotifyMonitor notify = null;
                            try {
                                notify = sysDAO.getNotifyOption(((SystemMonitor) tempSys).getCode());
                            } catch (Exception e) {
                            }
                            if (notify == null) {
                                notify = new NotifyMonitor();
                            }
                            alertstore.fixAlertList(notify);
                            if (alertstore.getAlerts().size() > 0) {
                                user.addAlertStore(alertstore);
                            }
                        }
                    }
                }
            }
        }
        List<GoogleAccount> googleAccs = null;
        try {
            googleAccs = accountDao.listAllGoogleAccount();
        } catch (Exception e1) {
            logger.log(Level.WARNING, "Error: " + e1.getMessage());
        }
        if (listUsers != null && listUsers.size() > 0 && googleAccs != null && googleAccs.size() > 0) {
            for (UserMonitor user : listUsers) {
                if (user.getUser().getDomain().equalsIgnoreCase(SystemUser.THIRD_PARTY_USER)) {
                    if (user.getStores() != null && user.getStores().size() > 0) {
                        MailConfigMonitor config = mailDAO.getMailConfig(user.getId());
                        MailService mailService = new MailService();
                        try {
                            String content = mailService.parseContent(user.getStores(), config);
                            MailAsync mailUtil = new MailAsync(new String[] { user.getId() }, alertName,
                                    content);
                            mailUtil.run();
                            logger.log(Level.INFO, "send mail" + content);
                        } catch (Exception e) {
                            logger.log(Level.INFO, "Can not send mail" + e.getMessage());
                        }

                    }
                }

            }

            for (GoogleAccount gAcc : googleAccs) {
                MailService mailService = new MailService(gAcc);
                for (UserMonitor user : listUsers) {
                    if (user.getUser().getDomain().equalsIgnoreCase(gAcc.getDomain())) {
                        if (user.getStores() != null && user.getStores().size() > 0) {
                            MailConfigMonitor config = mailDAO.getMailConfig(user.getId());
                            try {
                                String content = mailService.parseContent(user.getStores(), config);
                                mailService.sendMail(alertName, content, config);
                                logger.log(Level.INFO, "send mail" + content);
                            } catch (Exception e) {
                                logger.log(Level.INFO, "Can not send mail" + e.getMessage());
                            }

                        }
                    }

                }
            }
            for (SystemMonitor sys : systems) {
                AlertStoreMonitor store = alertDAO.getLastestAlertStore(sys);
                alertDAO.putAlertStore(store);
                alertDAO.clearTempStore(sys);
            }

        }
        for (SystemMonitor sys : systems) {
            AlertStoreMonitor asm = alertDAO.getLastestAlertStore(sys);
            if (asm == null) {
                asm = new AlertStoreMonitor();
            }
            asm.setCpuUsage(sys.getLastestCpuUsage());
            asm.setMemUsage(sys.getLastestMemoryUsage());
            asm.setSysId(sys.getId());
            asm.setName(alertName);
            asm.setTimeStamp(new Date(start));
            alertDAO.putAlertStore(asm);
            alertDAO.clearTempStore(sys);
        }
    } else {
        logger.log(Level.INFO, "NO SYSTEM FOUND");
    }

    /*
     * mailDAO.getMailConfig(maiId); mailService.sendMail(subject, content,
     * mailConfig);
     */

    // END LOG
    long end = System.currentTimeMillis();
    long time = end - start;
    logger.log(Level.INFO, MonitorUtil.parseTime(end, true)
            + " -> END: Scheduled send alert mail. Time executed: " + time + " ms");
    // END LOG

}

From source file:cmg.org.monitor.ext.util.DateTimeUtils.java

License:Open Source License

public static Date convertDateWithZone(Date input) {
    if (currentZone == null) {
        Object obj = MonitorMemcache.get(Key.create(Key.CURRENT_ZONE));
        if (obj != null && obj instanceof String) {
            currentZone = (String) obj;
        } else {//from w  ww . j  a  v a 2  s .co  m
            currentZone = MonitorConstant.DEFAULT_SYSTEM_TIME_ZONE;
        }
    }

    DateTime temp = new DateTime(input);

    return temp.withZone(DateTimeZone.forID(currentZone)).toDate();
}

From source file:cmg.org.monitor.services.GoogleAccountService.java

License:Open Source License

/**
 * Gets the timestamp string./*www  .j ava  2  s  .  co m*/
 *
 * @return the timestamp string
 */
private String getTimestampString() {
    DateTime t = new DateTime(new Date(System.currentTimeMillis()));
    t = t.withZone(DateTimeZone.forID(currentZone));
    return t.toString(DateTimeFormat.forPattern("dd/MM/yyyy hh:mm:ss.SSS"));
}

From source file:com.alliander.osgp.webdevicesimulator.service.OslpChannelHandler.java

License:Open Source License

private static DateTime correctUsageUntilDate(final DateTime dateTimeUntil, final HistoryTermType termType) {
    final DateTime now = new DateTime();
    if (dateTimeUntil.isAfter(now)) {
        if (termType == HistoryTermType.Short) {
            return now.hourOfDay().roundCeilingCopy();
        } else {/*from  ww w.java2s.  c om*/
            return now.withZone(localTimeZone).dayOfWeek().roundCeilingCopy().withZone(DateTimeZone.UTC);
        }
    }

    return dateTimeUntil;
}

From source file:com.barchart.feed.ddf.historical.api.DDF_Query.java

License:BSD License

private final CharSequence renderTime(/* local */DateTime time) {
    if (time == null) {
        time = NULL_TIME;//w  w  w  .java  2 s.com
    }
    if (instrument == null) {
        return time.toString();
    } else {
        final DateTimeZone zone = DateTimeZone.forOffsetMillis((int) (instrument.timeZoneOffset()));
        return time.withZone(zone).toString();
    }
}