Example usage for java.util Calendar setTimeZone

List of usage examples for java.util Calendar setTimeZone

Introduction

In this page you can find the example usage for java.util Calendar setTimeZone.

Prototype

public void setTimeZone(TimeZone value) 

Source Link

Document

Sets the time zone with the given time zone value.

Usage

From source file:de.uhh.l2g.dao.VideoDao.java

/**
 * Creates the popular video list./*from   www.j av a  2s. co  m*/
 */
@SuppressWarnings("unchecked")
public void createPopularVideoList() {
    List<Video> returnList = new ArrayList<Video>();
    JdbcTemplate jdbst = new JdbcTemplate(this.getDataSource());
    String sqlquery = "SELECT v.id, v.title, v.tags, v.lectureseriesId, v.ownerId, v.producerId, v.containerFormat, v.filename, v.resolution, v.duration, v.hostId, v.textId, v.filesize, v.generationDate, v.openAccess, v.downloadLink, v.metadataId, v.surl, v.hits, v.uploadDate, v.permittedToSegment, v.facilityId, v.citation2go FROM video v WHERE v.openAccess=1 AND v.hits > 20 ORDER BY hits DESC ";
    returnList = jdbst.query(sqlquery, new VideoRowMapper());

    JdbcTemplate delete = new JdbcTemplate(this.getDataSource());
    delete.update("DELETE FROM videohitlist");

    Calendar calendar = new GregorianCalendar();
    calendar.setTimeZone(TimeZone.getTimeZone("CET"));
    long msnow = calendar.getTimeInMillis();

    Date d1 = new Date();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH-mm");

    for (Video v : returnList) {
        try {
            d1 = df.parse(v.getGenerationDate());
            long ms1 = d1.getTime();
            int hits = v.getHits();
            long timeinms = msnow - ms1;

            // Durschnittswerte berechnen

            //Berechne alter des Videos in...
            long days = timeinms / (1000 * 60 * 60 * 24); //...Tagen
            long week = timeinms / (1000 * 60 * 60 * 24 * 7); //...Wochen
            long month = timeinms / 2628000000l; //....Monaten
            long year = timeinms / (2628000000l * 12l); //....Jahren

            //Berechne die Hits pro...
            int clicksperday = calcHitsPro(days, hits);
            int clicksperweek = calcHitsPro(week, hits);
            int clickspermonth = calcHitsPro(month, hits);
            int clicksperyear = calcHitsPro(year, hits);

            createOneHit(v.getId(), clicksperday, clicksperweek, clickspermonth, clicksperyear);
        } catch (ParseException e) {
            System.out.println("Simple Date Parsen Error!!");
        }
    }

}

From source file:com.concursive.connect.web.modules.calendar.utils.CalendarView.java

/**
 * Constructs the calendar and returns a String object with the HTML
 *
 * @return The HTML value//from w ww .j a v a  2 s  .co  m
 */
public String getHtml(String contextPath) {
    StringBuffer html = new StringBuffer();

    //Begin the whole table
    html.append("<table class='calendarContainer'>" + "<tr><td>");

    //Space at top to match
    if (headerSpace) {
        html.append("<table width=\"100%\" align=\"center\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">"
                + "<tr><td>&nbsp;</td></tr>" + "</table>");
    }

    String monthArrowPrev = "";
    String monthArrowNext = "";

    //If popup, then use small formats of each class
    String tableWidth = "100%";
    String pre = "";
    if (popup) {
        pre = "small";
        tableWidth = "155";
    } else if (frontPageView) {
        tableWidth = "auto";
    }
    //Display Calendar
    html.append("<table height=\"100%\" width='" + tableWidth + "' " + borderSize + cellSpacing + cellPadding
            + " class='" + pre + "calendar' id='calendarTable'>" + "<tr height=\"4%\">");

    //Display Previous Month Arrow
    if (popup) {
        monthArrowPrev = "<INPUT TYPE=\"IMAGE\" NAME=\"prev\" ALIGN=\"MIDDLE\" SRC=\"" + contextPath
                + "/images/calendar/prev_arrow.png\">";
        monthArrowNext = "<INPUT TYPE=\"IMAGE\" NAME=\"next\" ALIGN=\"MIDDLE\" SRC=\"" + contextPath
                + "/images/calendar/next_arrow.png\">";
        if (monthArrows) {
            html.append("<th class='" + pre + "monthArrowPrev'>" + monthArrowPrev + "</th>");
        }

        //Display Current Month name
        if (monthArrows) {
            html.append("<th colspan='5' ");
        } else {
            html.append("<th colspan='7' ");
        }
        html.append("class='" + pre + "monthName'");
        html.append("><strong>" + StringUtils.toHtml(this.getMonthName(cal)) + " " + this.getYear(cal)
                + "</strong></th>");
        //Display Next Month Arrow
        if (monthArrows) {
            html.append("<th class='" + pre + "monthArrowNext'>" + monthArrowNext + "</th>");
        }
    } else {
        if (monthArrows) {
            int prevMonth = calPrev.get(Calendar.MONTH) + 1;
            String previousLink = calPrev.get(Calendar.YEAR) + "-" + (prevMonth < 10 ? "0" : "") + prevMonth;

            int nextMonth = calNext.get(Calendar.MONTH) + 1;
            String nextLink = calNext.get(Calendar.YEAR) + "-" + (nextMonth < 10 ? "0" : "") + nextMonth;
            html.append("<th colspan='8' ");
            html.append("class='" + pre + "monthName'");
            html.append(">" + "<a href=\"javascript:goToMonth('" + previousLink
                    + "');\"><img ALIGN=\"MIDDLE\" border=\"0\" src=\"" + contextPath
                    + "/images/calendar/prev_arrow.png\" /></a> " + "<strong>"
                    + StringUtils.toHtml(this.getMonthName(cal)) + " " + this.getYear(cal) + "</strong>"
                    + " <a href=\"javascript:goToMonth('" + nextLink
                    + "');\"><img ALIGN=\"MIDDLE\" border=\"0\" src=\"" + contextPath
                    + "/images/calendar/next_arrow.png\" /></a>" + "</th>");
        } else {
            html.append("<th colspan=\"8\">");
            html.append(getHtmlMonthSelect());
            html.append("&nbsp;");
            html.append(getHtmlYearSelect());
            html.append("&nbsp;");
            Calendar tmp = Calendar.getInstance(locale);
            tmp.set(Calendar.HOUR, 0);
            tmp.set(Calendar.MINUTE, 0);
            tmp.set(Calendar.SECOND, 0);
            tmp.set(Calendar.MILLISECOND, 0);
            if (timeZone != null) {
                tmp.setTimeZone(timeZone);
            }
            html.append("<a href=\"javascript:showToDaysEvents('" + (tmp.get(Calendar.MONTH) + 1) + "','"
                    + tmp.get(Calendar.DATE) + "','" + tmp.get(Calendar.YEAR) + "');\">Today</a>");
            html.append("</th>");
        }
    }
    html.append("</tr>");

    //Display the Days of the Week names
    html.append("<tr height=\"4%\">");
    if (!popup) {
        html.append("<td width=\"4\" class=\"row1\"><font style=\"visibility:hidden\">n</font></td>");
    }

    // Use locale...
    int firstDayOfWeek = cal.getFirstDayOfWeek();
    for (int i = firstDayOfWeek; i < firstDayOfWeek + 7; i++) {
        html.append("<td width=\"14%\" class='" + pre + "weekName'>");
        if (popup || frontPageView) {
            html.append(StringUtils.toHtml(this.getDayName(i, true)));
        } else {
            html.append(StringUtils.toHtml(this.getDayName(i, false)));
        }
        html.append("</td>");
    }
    html.append("</tr>");
    int startCellPrev = this.getStartCell(calPrev);
    int endCellPrev = this.getEndCell(calPrev);

    int startCell = this.getStartCell(cal);
    int endCell = this.getEndCell(cal);

    int thisDay = 1;
    String tdClass = "";
    for (int cellNo = 0; cellNo < this.getNumberOfCells(); cellNo++) {
        boolean prevMonth = false;
        boolean nextMonth = false;
        boolean mainMonth = false;
        int displayDay = 0;
        int displayMonth = 0;
        int displayYear = 0;
        if (cellNo < startCell) {
            //The previous month
            displayMonth = calPrev.get(Calendar.MONTH) + 1;
            displayYear = calPrev.get(Calendar.YEAR);
            displayDay = (endCellPrev - startCell + 2 + cellNo - startCellPrev);
            prevMonth = true;
        } else if (cellNo > endCell) {
            //The next month
            displayMonth = calNext.get(Calendar.MONTH) + 1;
            displayYear = calNext.get(Calendar.YEAR);
            if (endCell + 1 == cellNo) {
                thisDay = 1;
            }
            displayDay = thisDay;
            nextMonth = true;
            thisDay++;
        } else {
            //The main month
            mainMonth = true;
            displayMonth = cal.get(Calendar.MONTH) + 1;
            displayYear = cal.get(Calendar.YEAR);
            displayDay = thisDay;
            thisDay++;
        }

        if (cellNo % 7 == 0) {
            tdClass = "";
            html.append("<tr");
            if (!popup) {
                if (calendarInfo.getCalendarView().equalsIgnoreCase("week")) {
                    if (displayMonth == calendarInfo.getStartMonthOfWeek()
                            && displayDay == calendarInfo.getStartDayOfWeek()) {
                        html.append(" class=\"selectedWeek\" ");
                        tdClass = "selectedDay";
                    }
                }
            }
            html.append(">");
        }
        if (!popup && (cellNo % 7 == 0)) {
            html.append("<td valign='top' width=\"4\" class=\"weekSelector\" name=\"weekSelector\">");
            String weekSelectedArrow = "<a href=\"javascript:showWeekEvents('" + displayYear + "','"
                    + displayMonth + "','" + displayDay + "')\">" + "<img ALIGN=\"MIDDLE\" src=\"" + contextPath
                    + "/images/control.png\" border=\"0\" onclick=\"javascript:switchTableClass(this,'selectedWeek','row');\"></a>";
            html.append(weekSelectedArrow);
            html.append("</td>");
        }

        html.append("<td valign='top'");
        if (!smallView) {
            if (!frontPageView) {
                html.append(" height='70'");
            } else {
                html.append(" height='35'");
            }
        }
        if (!popup) {
            html.append(" onclick=\"javascript:showDayEvents('" + displayYear + "','" + displayMonth + "','"
                    + displayDay + "');javascript:switchTableClass(this,'selectedDay','cell');\"");
            if (calendarInfo.getCalendarView().equalsIgnoreCase("day")) {
                tdClass = "";
                if (displayMonth == calendarInfo.getMonthSelected()
                        && displayDay == calendarInfo.getDaySelected()) {
                    tdClass = "selectedDay";
                }
            }
        }

        if (prevMonth) {
            //The previous month
            if (this.isCurrentDay(calPrev, displayDay)) {
                html.append(" id='today' class='"
                        + ((tdClass.equalsIgnoreCase("")) ? pre + "today'" : tdClass + "'") + " name='" + pre
                        + "today' >");
            } else {
                html.append(" class='" + ((tdClass.equalsIgnoreCase("")) ? pre + "noday'" : tdClass + "'")
                        + " name='" + pre + "noday' >");
            }
        } else if (nextMonth) {
            if (this.isCurrentDay(calNext, displayDay)) {
                html.append(" id='today' class='"
                        + ((tdClass.equalsIgnoreCase("")) ? pre + "today'" : tdClass + "'") + " name='" + pre
                        + "today' >");
            } else {
                html.append(" class='" + ((tdClass.equalsIgnoreCase("")) ? pre + "noday'" : tdClass + "'")
                        + " name='" + pre + "noday' >");
            }
        } else {
            //The main main
            if (this.isCurrentDay(cal, displayDay)) {
                html.append(" id='today' class='"
                        + ((tdClass.equalsIgnoreCase("")) ? pre + "today'" : tdClass + "'") + " name='" + pre
                        + "today' >");
            } else {
                html.append(" class='" + ((tdClass.equalsIgnoreCase("")) ? pre + "day'" : tdClass + "'")
                        + " name='" + pre + "day' >");
            }
        }
        // end if block
        //Display the day in the appropriate link color
        if (popup) {
            //Popup calendar
            CalendarEventList highlightEvent = eventList
                    .get(displayMonth + "/" + displayDay + "/" + displayYear);
            String dateColor = "" + displayDay;
            if (highlightEvent != null && highlightEvent.containsKey("highlight")) {
                dateColor = "<font color=#FF0000>" + displayDay + "</font>";
            } else if (!mainMonth) {
                dateColor = "<font color=#888888>" + displayDay + "</font>";
            }
            html.append("<a href=\"javascript:returnDate(" + displayDay + ", " + displayMonth + ", "
                    + displayYear + ");\"" + ">" + dateColor + "</a>");
        } else {
            //Event calendar
            String dateColor = "" + displayDay;
            if (!mainMonth) {
                dateColor = "<font color=#888888>" + displayDay + "</font>";
            }
            html.append("<a href=\"javascript:showDayEvents('" + displayYear + "','" + displayMonth + "','"
                    + displayDay + "');\">" + dateColor + "</a>");

            if (this.isHoliday(String.valueOf(displayMonth), String.valueOf(displayDay),
                    String.valueOf(displayYear))) {
                html.append(CalendarEvent.getIcon("holiday", contextPath) + "<font color=\"blue\"><br />");
            }

            //get all events categories and respective counts.
            HashMap events = this.getEventList(String.valueOf(displayMonth), String.valueOf(displayDay),
                    String.valueOf(displayYear));

            if (events.size() > 0) {
                html.append(
                        "<table width=\"12%\" align=\"center\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\" class=\"dayIcon\">");
                for (int i = 0; i < Array.getLength(CalendarEventList.EVENT_TYPES); i++) {
                    String eventType = CalendarEventList.EVENT_TYPES[i];
                    if (events.containsKey(eventType)) {
                        if (!eventType.equals(CalendarEventList.EVENT_TYPES[7])) {
                            Object eventObj = events.get(eventType);
                            // use reflection to call the size method on the event list object
                            String eventSize = (String) ObjectUtils.getObject(eventObj, "sizeString");
                            if (!eventSize.equals("0")) {
                                html.append("<tr><td>" + CalendarEvent.getIcon(eventType, contextPath)
                                        + "</td><td> " + eventSize + "</td></tr>");
                            }
                        }
                    }
                }
                html.append("</table>");
            }
            //end of events display.
        }
        html.append("</td>");
        if ((cellNo + 1) % 7 == 0) {
            html.append("</tr>");
        }
        // end check for end of row
    }
    // end for-loop

    html.append("</table></td></tr>");
    html.append("</table>");

    //Display a link that selects today
    if (popup) {
        Calendar tmp = Calendar.getInstance(locale);
        tmp.set(Calendar.HOUR, 0);
        tmp.set(Calendar.MINUTE, 0);
        tmp.set(Calendar.SECOND, 0);
        tmp.set(Calendar.MILLISECOND, 0);
        if (timeZone != null) {
            tmp.setTimeZone(timeZone);
        }
        int displayMonth = tmp.get(Calendar.MONTH) + 1;
        int displayYear = tmp.get(Calendar.YEAR);
        int displayDay = tmp.get(Calendar.DAY_OF_MONTH);
        html.append("<p class=\"smallfooter\">Today: " + "<a href=\"javascript:returnDate(" + displayDay + ", "
                + displayMonth + ", " + displayYear + ");\"" + ">" + this.getToday() + "</p>");
        html.append("<input type=\"hidden\" name=\"year\" value=\"" + cal.get(Calendar.YEAR) + "\">");
        html.append("<input type=\"hidden\" name=\"month\" value=\"" + (cal.get(Calendar.MONTH) + 1) + "\">");
    }
    html.append("<input type=\"hidden\" name=\"day\" value=\"" + (cal.get(Calendar.DATE)) + "\">");
    return html.toString();
}

From source file:DateFormatUtils.java

/**
 * <p>Formats a <code>Calendar</code> object into the
 * supplied <code>StringBuffer</code>.</p>
 * //from   ww  w.  j  a v  a2 s. c om
 * @param calendar  the calendar to format
 * @param buf  the buffer to format into
 * @return the specified string buffer
 */
public StringBuffer format(Calendar calendar, StringBuffer buf) {
    if (mTimeZoneForced) {
        calendar = (Calendar) calendar.clone();
        calendar.setTimeZone(mTimeZone);
    }
    return applyRules(calendar, buf);
}

From source file:info.magnolia.module.admininterface.SaveHandlerImpl.java

/**
 * Get the value for saving in jcr//  ww w  .j  a  va2s  .co  m
 * @param valueStr string representation of the value
 * @param type type of the value
 * @return the value
 */
public Value getValue(String valueStr, int type) {

    ValueFactory valueFactory = null;

    HierarchyManager hm = MgnlContext.getHierarchyManager(this.getRepository());
    try {
        valueFactory = hm.getWorkspace().getSession().getValueFactory();
    } catch (RepositoryException e) {
        throw new NestableRuntimeException(e);
    }

    Value value = null;
    if (type == PropertyType.STRING) {
        value = valueFactory.createValue(valueStr);
    } else if (type == PropertyType.BOOLEAN) {
        value = valueFactory.createValue(BooleanUtils.toBoolean(valueStr));
    } else if (type == PropertyType.DOUBLE) {
        try {
            value = valueFactory.createValue(Double.parseDouble(valueStr));
        } catch (NumberFormatException e) {
            value = valueFactory.createValue(0d);
        }
    } else if (type == PropertyType.LONG) {
        try {
            value = valueFactory.createValue(Long.parseLong(valueStr));
        } catch (NumberFormatException e) {
            value = valueFactory.createValue(0L);
        }
    } else if (type == PropertyType.DATE) {
        try {
            Calendar date = new GregorianCalendar();
            try {
                String newDateAndTime = valueStr;
                String[] dateAndTimeTokens = newDateAndTime.split("T"); //$NON-NLS-1$
                String newDate = dateAndTimeTokens[0];
                String[] dateTokens = newDate.split("-"); //$NON-NLS-1$
                int hour = 0;
                int minute = 0;
                int second = 0;
                int year = Integer.parseInt(dateTokens[0]);
                int month = Integer.parseInt(dateTokens[1]) - 1;
                int day = Integer.parseInt(dateTokens[2]);
                if (dateAndTimeTokens.length > 1) {
                    String newTime = dateAndTimeTokens[1];
                    String[] timeTokens = newTime.split(":"); //$NON-NLS-1$
                    hour = Integer.parseInt(timeTokens[0]);
                    minute = Integer.parseInt(timeTokens[1]);
                    second = Integer.parseInt(timeTokens[2]);
                }
                date.set(year, month, day, hour, minute, second);
                // this is used in the searching
                date.set(Calendar.MILLISECOND, 0);
                date.setTimeZone(TimeZone.getTimeZone("GMT"));
            }
            // todo time zone??
            catch (Exception e) {
                // ignore, it sets the current date / time
            }
            value = valueFactory.createValue(date);
        } catch (Exception e) {
            if (log.isDebugEnabled())
                log.debug("Exception caught: " + e.getMessage(), e); //$NON-NLS-1$
        }
    } else if (type == PropertyType.REFERENCE) {
        try {
            Node referencedNode = hm.getWorkspace().getSession().getNodeByUUID(valueStr);

            value = valueFactory.createValue(referencedNode);
        } catch (RepositoryException re) {
            if (log.isDebugEnabled())
                log.debug("Cannot retrieve the referenced node by UUID: " + valueStr, re);
        }
    }

    return value;
}

From source file:org.apache.axis2.databinding.utils.ConverterUtil.java

/**
 * Code from Axis1 code base Note - We only follow the convention in the latest schema spec
 *
 * @param source//from  w w w  .  ja  va  2 s  .c o m
 * @return Returns Calendar.
 */
public static Calendar convertToDateTime(String source) {

    if ((source == null) || source.trim().equals("")) {
        return null;
    }
    source = source.trim();
    // the lexical representation of the date time as follows
    // '-'? yyyy '-' mm '-' dd 'T' hh ':' mm ':' ss ('.' s+)? (zzzzzz)?
    Date date = null;
    Calendar calendar = Calendar.getInstance();
    calendar.clear();
    calendar.setLenient(false);

    if (source.startsWith("-")) {
        source = source.substring(1);
        calendar.set(Calendar.ERA, GregorianCalendar.BC);
    }

    int year = 0;
    int month = 0;
    int day = 0;
    int hour = 0;
    int minite = 0;
    int second = 0;
    long miliSecond = 0;
    int timeZoneOffSet = TimeZone.getDefault().getRawOffset();

    if ((source != null) && (source.length() >= 19)) {
        if ((source.charAt(4) != '-') || (source.charAt(7) != '-') || (source.charAt(10) != 'T')
                || (source.charAt(13) != ':') || (source.charAt(16) != ':')) {
            throw new RuntimeException("invalid date format (" + source + ") with out - s at correct place ");
        }
        year = Integer.parseInt(source.substring(0, 4));
        month = Integer.parseInt(source.substring(5, 7));
        day = Integer.parseInt(source.substring(8, 10));
        hour = Integer.parseInt(source.substring(11, 13));
        minite = Integer.parseInt(source.substring(14, 16));
        second = Integer.parseInt(source.substring(17, 19));

        int milliSecondPartLength = 0;

        if (source.length() > 19) {
            String rest = source.substring(19);
            if (rest.startsWith(".")) {
                // i.e this have the ('.'s+) part
                if (rest.endsWith("Z")) {
                    // this is in gmt time zone
                    timeZoneOffSet = 0;
                    calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
                    miliSecond = Integer.parseInt(rest.substring(1, rest.lastIndexOf("Z")));
                    milliSecondPartLength = rest.substring(1, rest.lastIndexOf("Z")).trim().length();
                } else if ((rest.lastIndexOf("+") > 0) || (rest.lastIndexOf("-") > 0)) {
                    // this is given in a general time zione
                    String timeOffSet = null;
                    if (rest.lastIndexOf("+") > 0) {
                        timeOffSet = rest.substring(rest.lastIndexOf("+") + 1);
                        miliSecond = Integer.parseInt(rest.substring(1, rest.lastIndexOf("+")));
                        milliSecondPartLength = rest.substring(1, rest.lastIndexOf("+")).trim().length();
                        // we keep +1 or -1 to finally calculate the value
                        timeZoneOffSet = 1;

                    } else if (rest.lastIndexOf("-") > 0) {
                        timeOffSet = rest.substring(rest.lastIndexOf("-") + 1);
                        miliSecond = Integer.parseInt(rest.substring(1, rest.lastIndexOf("-")));
                        milliSecondPartLength = rest.substring(1, rest.lastIndexOf("-")).trim().length();
                        // we keep +1 or -1 to finally calculate the value
                        timeZoneOffSet = -1;
                    }
                    if (timeOffSet.charAt(2) != ':') {
                        throw new RuntimeException(
                                "invalid time zone format (" + source + ") without : at correct place");
                    }
                    int hours = Integer.parseInt(timeOffSet.substring(0, 2));
                    int minits = Integer.parseInt(timeOffSet.substring(3, 5));
                    timeZoneOffSet = ((hours * 60) + minits) * 60000 * timeZoneOffSet;

                } else {
                    // i.e it does not have time zone
                    miliSecond = Integer.parseInt(rest.substring(1));
                    milliSecondPartLength = rest.substring(1).trim().length();
                }

            } else {
                if (rest.startsWith("Z")) {
                    calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
                    // this is in gmt time zone
                    timeZoneOffSet = 0;
                } else if (rest.startsWith("+") || rest.startsWith("-")) {
                    // this is given in a general time zione
                    if (rest.charAt(3) != ':') {
                        throw new RuntimeException(
                                "invalid time zone format (" + source + ") without : at correct place");
                    }
                    int hours = Integer.parseInt(rest.substring(1, 3));
                    int minits = Integer.parseInt(rest.substring(4, 6));
                    timeZoneOffSet = ((hours * 60) + minits) * 60000;
                    if (rest.startsWith("-")) {
                        timeZoneOffSet = timeZoneOffSet * -1;
                    }
                } else {
                    throw new NumberFormatException("in valid time zone attribute");
                }
            }
        }
        calendar.set(Calendar.YEAR, year);
        // xml month is started from 1 and calendar month is started from 0
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, day);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minite);
        calendar.set(Calendar.SECOND, second);
        if (milliSecondPartLength != 3) {
            // milisecond part represenst the fraction of the second so we have to
            // find the fraction and multiply it by 1000. So if milisecond part
            // has three digits nothing required
            miliSecond = miliSecond * 1000;
            for (int i = 0; i < milliSecondPartLength; i++) {
                miliSecond = miliSecond / 10;
            }
        }
        calendar.set(Calendar.MILLISECOND, (int) miliSecond);
        calendar.set(Calendar.ZONE_OFFSET, timeZoneOffSet);
        // set the day light offset only if the time zone is present
        if (source.length() > 19) {
            calendar.set(Calendar.DST_OFFSET, 0);
        }

    } else {
        throw new NumberFormatException("date string can not be less than 19 characters");
    }

    return calendar;
}

From source file:org.betaconceptframework.astroboa.test.model.query.parser.CriterionParserTest.java

/**
 * If provided value is a valid ISO8601 date then equivalent calendar is returned
 * //from  ww w . j a  v a  2  s  . c  o  m
 * @param value
 * @return
 * @throws ParseException 
 */
private Calendar checkIfValueIsISO8601Date(String value) {

    if (StringUtils.isBlank(value)) {
        return null;
    }

    Calendar date = null;

    try {
        Matcher dateTimeMatcher = ISO8601Pattern.matcher(value);

        if (dateTimeMatcher.matches()) {

            StringBuilder pattern = new StringBuilder("yyyy-MM-dd'T'HH:mm:ss");
            String timeZoneId = null;
            //We must decide which pattern to use
            //At this point this is the minimum

            //Group 7 corresponds to milli seconds
            if (dateTimeMatcher.groupCount() >= 7 && dateTimeMatcher.group(7) != null) {
                pattern.append(".SSS");
            }
            if (dateTimeMatcher.groupCount() >= 8 && dateTimeMatcher.group(8) != null) {
                if (!"Z".equals(dateTimeMatcher.group(8))) {
                    //Keep UTC info to look for time zone when Calendar object will be created, 
                    //as SimpleDateformat which is used in DateUtils
                    //cannot handle time zone designator
                    timeZoneId = "GMT" + dateTimeMatcher.group(8);
                    value = value.replace(dateTimeMatcher.group(8), "");
                } else {
                    timeZoneId = "GMT";
                    value = value.replace("Z", "");
                }
            }

            date = (Calendar) DateUtils.fromString(value, pattern.toString());

            if (timeZoneId != null) {
                //Now that date is found we should define its TimeZone
                TimeZone timeZone = TimeZone.getTimeZone(timeZoneId);
                if (!timeZone.getID().equals(timeZoneId)) {
                    // Time Zone is not valid
                    throw new CmsException("Invalid time zone in date value " + value);
                }

                date.setTimeZone(timeZone);
            }
        } else {
            //check for simple date
            Matcher dateMatcher = ISO8601DatePattern.matcher(value);

            if (dateMatcher.matches()) {
                date = (Calendar) DateUtils.fromString(value, ISO8601_DATE_FORMAT);
            }
        }

    } catch (Exception e) {
        //Probably not a date value. Ignore exception
        return null;
    }

    return date;

}

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);

            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");
            }//ww  w.ja v a  2 s  .co  m
        }

        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);
        }
    }
}

From source file:org.apache.hadoop.fs.azure.AzureNativeFileSystemStore.java

@Override
public void updateFolderLastModifiedTime(String key, SelfRenewingLease folderLease) throws AzureException {
    final Calendar lastModifiedCalendar = Calendar.getInstance(Utility.LOCALE_US);
    lastModifiedCalendar.setTimeZone(Utility.UTC_ZONE);
    Date lastModified = lastModifiedCalendar.getTime();
    updateFolderLastModifiedTime(key, lastModified, folderLease);
}

From source file:com.concursive.connect.web.portal.PortalUtils.java

public static void populateObject(Object bean, ActionRequest request) {
    String nestedAttribute = "_";

    Enumeration en = request.getParameterNames();
    String paramName = null;//from  w ww.  ja  v  a  2  s  . co m
    while (en.hasMoreElements()) {
        paramName = (String) en.nextElement();

        // a form has been submitted and requested to be auto-populated,
        // so we do that here..going through every element and trying
        // to call a setXXX() method on the bean object passed in for the value
        // of the request parameter currently being checked.
        String[] paramValues = request.getParameterValues(paramName);
        if (paramValues.length > 1) {
            ObjectUtils.setParam(bean, paramName, paramValues, nestedAttribute);
        } else {
            ObjectUtils.setParam(bean, paramName, paramValues[0], nestedAttribute);
        }
    }

    // TODO: currently for ticket and ticket history
    //ObjectUtils.invokeMethod(bean, "setRequestItems", new HttpRequestContext(request));
    // Check for valid user
    User thisUser = (User) request.getAttribute(Constants.REQUEST_USER);
    if (thisUser != null) {
        // Populate date/time fields using the user's timezone and locale
        if (thisUser.getTimeZone() != null) {
            ArrayList timeParams = (ArrayList) ObjectUtils.getObject(bean, "TimeZoneParams");
            if (timeParams != null) {
                Calendar cal = Calendar.getInstance();
                Iterator i = timeParams.iterator();
                while (i.hasNext()) {
                    // The property that can be set
                    String name = (String) i.next();
                    // See if it is in the request
                    String value = request.getParameter(name);
                    if (value != null) {
                        // See if time is in request too
                        String hourValue = request.getParameter(name + "Hour");
                        if (hourValue == null) {
                            // Date fields: 1-1 mapping between HTML field and Java property
                            ObjectUtils.setParam(bean, name,
                                    DateUtils.getUserToServerDateTimeString(
                                            TimeZone.getTimeZone(thisUser.getTimeZone()), DateFormat.SHORT,
                                            DateFormat.LONG, value, thisUser.getLocale()));
                        } else {
                            // Date & Time fields: 4-1 mapping between HTML fields and Java property
                            try {
                                Timestamp timestamp = DatabaseUtils.parseDateToTimestamp(value,
                                        thisUser.getLocale());
                                cal.setTimeInMillis(timestamp.getTime());
                                int hour = Integer.parseInt(hourValue);
                                int minute = Integer.parseInt(request.getParameter(name + "Minute"));
                                String ampmString = request.getParameter(name + "AMPM");
                                if (ampmString != null) {
                                    int ampm = Integer.parseInt(ampmString);
                                    if (ampm == Calendar.AM) {
                                        if (hour == 12) {
                                            hour = 0;
                                        }
                                    } else {
                                        if (hour < 12) {
                                            hour += 12;
                                        }
                                    }
                                }
                                cal.set(Calendar.HOUR_OF_DAY, hour);
                                cal.set(Calendar.MINUTE, minute);
                                cal.setTimeZone(TimeZone.getTimeZone(thisUser.getTimeZone()));
                                ObjectUtils.setParam(bean, name, new Timestamp(cal.getTimeInMillis()));
                            } catch (Exception dateE) {
                            }
                        }
                    }
                }
            }
        }

        // Populate number fields using the user's locale
        if (thisUser.getLocale() != null) {
            ArrayList numberParams = (ArrayList) ObjectUtils.getObject(bean, "NumberParams");
            if (numberParams != null) {
                NumberFormat nf = NumberFormat.getInstance(thisUser.getLocale());
                Iterator i = numberParams.iterator();
                while (i.hasNext()) {
                    // The property that can be set
                    String name = (String) i.next();
                    // See if it is in the request
                    String value = (String) request.getParameter(name);
                    if (value != null && !"".equals(value)) {
                        try {
                            // Parse the value
                            ObjectUtils.setParam(bean, name, nf.parse(value).doubleValue());
                        } catch (Exception e) {
                            //e.printStackTrace(System.out);
                        }
                    }
                }
            }
        }
    }
}

From source file:fr.aliacom.obm.common.calendar.CalendarDaoJdbcImpl.java

@Override
public List<String> findEventTwinKeys(String calendar, Event event, ObmDomain domain) {

    String squery = "SELECT DISTINCT event_id from Event "
            + "INNER JOIN EventLink ON eventlink_event_id=event_id "
            + "INNER JOIN UserEntity ON userentity_entity_id=eventlink_entity_id "
            + "INNER JOIN UserObm ON userobm_id=userentity_user_id "
            + "WHERE event_title=? AND userobm_login=? ";
    if (event.isAllday()) {
        squery += "AND event_date >= ? AND event_date <= ? AND (event_duration >= 86400 OR event_allday) ";
    } else {/* ww w. jav a2s.co m*/
        squery += "AND event_date=? AND event_duration=? ";
    }
    squery += "AND userobm_domain_id=?";

    PreparedStatement query = null;
    Connection con = null;
    ResultSet rs = null;
    List<String> ret = new LinkedList<String>();

    try {
        con = obmHelper.getConnection();
        query = con.prepareStatement(squery);
        int index = 1;
        query.setString(index++, event.getTitle());
        query.setString(index++, calendar);
        if (event.isAllday()) {

            java.util.Calendar dayAfter = java.util.Calendar.getInstance();
            dayAfter.setTimeZone(TimeZone.getTimeZone("GMT"));
            dayAfter.setTimeInMillis(event.getStartDate().getTime());
            dayAfter.add(java.util.Calendar.HOUR_OF_DAY, 11);

            java.util.Calendar dayBefore = java.util.Calendar.getInstance();
            dayBefore.setTimeZone(TimeZone.getTimeZone("GMT"));
            dayBefore.setTimeInMillis(event.getStartDate().getTime());
            dayBefore.add(java.util.Calendar.HOUR_OF_DAY, -11);

            query.setTimestamp(index++, new java.sql.Timestamp(dayBefore.getTimeInMillis()));

            query.setTimestamp(index++, new java.sql.Timestamp(dayAfter.getTimeInMillis()));
        } else {
            query.setTimestamp(index++, new java.sql.Timestamp(event.getStartDate().getTime()));
            query.setInt(index++, event.getDuration());
        }

        if (domain != null) {
            query.setInt(index++, domain.getId());
        }
        rs = query.executeQuery();
        while (rs.next()) {
            ret.add(rs.getString(1));
        }
        logger.info("Found " + ret.size() + " results with title " + event.getTitle() + " date: "
                + event.getStartDate() + " duration: " + event.getDuration() + " domain_id: "
                + (domain != null ? domain.getId() : "null"));
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        obmHelper.cleanup(con, query, rs);
    }
    return ret;
}