List of usage examples for java.util GregorianCalendar getTime
public final Date getTime()
Date
object representing this Calendar
's time value (millisecond offset from the Epoch"). From source file:org.etudes.jforum.view.forum.PostAction.java
private boolean isCategoryAccessibleToSpecialAccessUser(SpecialAccess specialAccess) throws Exception { if (JForumUserUtil.isJForumFacilitator(UserDirectoryService.getCurrentUser().getId()) || SecurityService.isSuperUser()) return true; GregorianCalendar gc = new GregorianCalendar(); Date nowDate = gc.getTime(); /* /*from ww w . j a va 2 s .co m*/ check for category special access. If category special access is available verify the special access start date with current time. If special access is not available verify forum start dates with current time. */ boolean specialAccessUser = false, specialAccessUserAccess = false; if (specialAccess.getStartDate() != null) { if (specialAccess.getStartDate().getTime() > nowDate.getTime()) { specialAccessUserAccess = false; } if (specialAccess.getEndDate() != null) { if ((specialAccess.getEndDate().getTime() > nowDate.getTime())) { specialAccessUserAccess = false; } } specialAccessUserAccess = true; } else { specialAccessUserAccess = true; } this.context.put("specialAccessUserAccess", specialAccessUserAccess); return specialAccessUserAccess; }
From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.SystemPropertiesTests.java
public void testLookupDeserializesCreateAtToDate() throws Throwable { final String responseContent = "{\"id\":\"an id\",\"__createdAt\":\"2000-01-01T07:59:59.000Z\"}"; MobileServiceClient client = null;//from w ww .j av a 2s . c om try { client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext()); } catch (MalformedURLException e) { e.printStackTrace(); } // Add a filter to handle the request and create a new json // object with an id defined client = client.withFilter(getTestFilter(responseContent)); // Create get the MobileService table MobileServiceTable<CreatedAtType> msTable = client.getTable(CreatedAtType.class); try { // Call the lookUp method CreatedAtType entity = msTable.lookUp("an id").get(); // Asserts if (entity == null) { fail("Expected result"); } else { assertTrue(entity instanceof CreatedAtType); GregorianCalendar calendar = new GregorianCalendar(2000, 00, 01, 07, 59, 59); calendar.setTimeZone(TimeZone.getTimeZone("UTC")); assertEquals("an id", entity.Id); assertEquals(calendar.getTime(), entity.CreatedAt); } } catch (Exception exception) { fail(exception.getMessage()); } }
From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.SystemPropertiesTests.java
public void testLookupDeserializesUpdateAtToDate() throws Throwable { final String responseContent = "{\"id\":\"an id\",\"__updatedAt\":\"2000-01-01T07:59:59.000Z\"}"; MobileServiceClient client = null;/*from w w w . j av a 2s .c o m*/ try { client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext()); } catch (MalformedURLException e) { e.printStackTrace(); } // Add a filter to handle the request and create a new json // object with an id defined client = client.withFilter(getTestFilter(responseContent)); // Create get the MobileService table MobileServiceTable<UpdatedAtType> msTable = client.getTable(UpdatedAtType.class); try { // Call the lookUp method UpdatedAtType entity = msTable.lookUp("an id").get(); // Asserts if (entity == null) { fail("Expected result"); } else { assertTrue(entity instanceof UpdatedAtType); GregorianCalendar calendar = new GregorianCalendar(2000, 00, 01, 07, 59, 59); calendar.setTimeZone(TimeZone.getTimeZone("UTC")); assertEquals("an id", entity.Id); assertEquals(calendar.getTime(), entity.UpdatedAt); } } catch (Exception exception) { fail(exception.getMessage()); } }
From source file:com.zimbra.cs.mailbox.calendar.ZRecur.java
public List<Date> expandRecurrenceOverRange(ParsedDateTime dtStart, long rangeStart, long rangeEnd) throws ServiceException { List<Date> toRet = new LinkedList<Date>(); Date rangeStartDate = new Date(rangeStart); // subtract 1000ms (1sec) because the code in the method treats // end time as inclusive while the rangeEnd input argument is // exclusive value Date rangeEndDate = new Date(rangeEnd - 1000); Date dtStartDate = new Date(dtStart.getUtcTime()); Date earliestDate;//from ww w . ja va 2 s . c o m if (dtStartDate.after(rangeStartDate)) earliestDate = dtStartDate; else earliestDate = rangeStartDate; if (mUntil != null) { Date until = mUntil.getDateForRecurUntil(dtStart.getTimeZone()); if (until.before(rangeEndDate)) rangeEndDate = until; } // Set limit of expansion count. int maxInstancesFromConfig = sExpansionLimits.maxInstances; int maxInstancesExpanded; if (maxInstancesFromConfig <= 0) maxInstancesExpanded = mCount; else if (mCount <= 0) maxInstancesExpanded = maxInstancesFromConfig; else maxInstancesExpanded = Math.min(mCount, maxInstancesFromConfig); int numInstancesExpanded = 1; // initially 1 rather than 0 because DTSTART is always included // Set hard limit of expansion time range. (bug 21989) ParsedDateTime earliestDateTime = ParsedDateTime.fromUTCTime(earliestDate.getTime()); Date hardEndDate = getEstimatedEndTime(earliestDateTime); if (hardEndDate.before(rangeEndDate)) rangeEndDate = hardEndDate; if (rangeEndDate.before(earliestDate)) { ZimbraLog.calendar.debug( "Expanding recurrence over range where range end %s is before earliest date %s", DateUtil.formatDate(rangeEndDate), DateUtil.formatDate(earliestDate)); return toRet; } GregorianCalendar cur = dtStart.getCalendarCopy(); int baseMonthDay = cur.get(Calendar.DAY_OF_MONTH); boolean baseIsLeapDay = ((baseMonthDay == 29) && (cur.get(Calendar.MONTH) == Calendar.FEBRUARY)); // until we hit rangeEnd, or we've SAVED count entries: // // gather each set { // // // // curDate forward one INTERVAL // // } // check Set against BYSETPOS & ranges & count // int interval = mInterval; if (interval <= 0) interval = 1; // DTSTART is always part of the expansion, as long as it falls within // the range. if (!dtStartDate.before(earliestDate) && !dtStartDate.after(rangeEndDate)) toRet.add(dtStartDate); int numConsecutiveIterationsWithoutMatchingInstance = 0; boolean pastHardEndTime = false; long numIterations = 0; // track how many times we looped while (!pastHardEndTime && (maxInstancesExpanded <= 0 || numInstancesExpanded < maxInstancesExpanded)) { numIterations++; boolean curIsAtOrAfterEarliestDate = !cur.getTime().before(earliestDate); boolean curIsAfterEndDate = cur.getTime().after(rangeEndDate); List<Calendar> addList = new LinkedList<Calendar>(); switch (mFreq) { case HOURLY: /* * BYSECOND - for each listed second * BYMINUTE - for each listed minute in hour * BYHOUR - match iff in hour list * BYDAY - for each day listed * BYMONTHDAY - only those monthdays * BYYEARDAY - only those yeardays * BYMONTH - only those months */ if (!checkMonthList(cur)) continue; if (!checkYearDayList(cur)) continue; if (!checkMonthDayList(cur)) continue; if (!checkDayList(cur)) continue; if (!checkHourList(cur)) continue; addList.add((Calendar) (cur.clone())); cur.add(Calendar.HOUR_OF_DAY, interval); addList = expandHourList(addList); addList = expandMinuteList(addList); addList = expandSecondList(addList); break; case DAILY: /* * BYSECOND - for each listed second in day * BYMINUTE - for each listed minute in day * BYHOUR - for each listed hour in day * BYDAY - no ordinal allowed, match iff in day list * BYMONTHDAY - only that day * BYYEARDAY - only that day * BYWEEKNO -- YEARLY ONLY * BYMONTH - only that month * * while (count check & until check & rangeEnd check) { * if (byMonth && !month matches) * curDay = set MONTH to matching month * * if (byYearDay && !yearday matches) * curDay = set DAY to next matching yearday * * if (byMonthday && !monthday matches) * curDay = skip to next matching monthday * * if (byDay && !day in list) * curDay = skip to next mathcing byDay * * if (!byHour or FOR EACH HOUR IN HOURLIST) * if (!byMinute or FOR EACH MINUTE IN MINLIST) * if (!bySecond or FOR EACH SECOND IN LIST) * ----add to list--- * * check against BYSETPOS * * curDay+=1 day * } * */ if (!checkMonthList(cur)) continue; if (!checkYearDayList(cur)) continue; if (!checkMonthDayList(cur)) continue; if (!checkDayList(cur)) continue; addList.add((Calendar) (cur.clone())); cur.add(Calendar.DAY_OF_YEAR, interval); addList = expandHourList(addList); addList = expandMinuteList(addList); addList = expandSecondList(addList); break; case WEEKLY: /* * BYSECOND - for every listed second * BYMINUTE - for every listed minute * BYHOUR - for every listed hour * BYDAY - for every listed day * BYMONTHDAY - MAYBE once a month * BYYEARDAY - MAYBE once a year * BYMONTH - iff month matches * * for each (INTERVAL)WEEK{ * if (byMonth && !month matches) * curDay = set MONTH to DtStart in next matching month * * if (byYearDay && !yearday matches) * curDay = set date to next matching yearday * * if (byMonthDay && !monthday matches) * curDay = skip to next matching monthday * * if (!byDay or FOREACH day in list) * if (!byHour or FOREACH hour in list) * if (!byMinute or FOREACH minute in list) * if (!bySecond or FOREACH second in list) * ----add to list---- * * check against BYSETPOS * * curDay += 1 week * } while (count check & until check & rangeEnd check) * */ if (!checkMonthList(cur)) continue; if (!checkYearDayList(cur)) continue; if (!checkMonthDayList(cur)) continue; addList.add((Calendar) (cur.clone())); cur.add(Calendar.WEEK_OF_YEAR, interval); addList = expandDayListForWeekly(addList); addList = expandHourList(addList); addList = expandMinuteList(addList); addList = expandSecondList(addList); break; case MONTHLY: if (!checkMonthList(cur)) continue; if (!checkYearDayList(cur)) continue; addList.add((Calendar) (cur.clone())); cur.set(Calendar.DAY_OF_MONTH, 1); cur.add(Calendar.MONTH, interval); int daysInMonth = cur.getActualMaximum(Calendar.DAY_OF_MONTH); cur.set(Calendar.DAY_OF_MONTH, Math.min(baseMonthDay, daysInMonth)); addList = expandMonthDayList(addList); addList = expandDayListForMonthlyYearly(addList); addList = expandHourList(addList); addList = expandMinuteList(addList); addList = expandSecondList(addList); break; case YEARLY: /* * BYSECOND * BYMINUTE * BYHOUR * BYDAY * BYMONTHDAY * BYYEARDAY * BYWEEKNO - specified week * BYMONTH - once */ if (baseIsLeapDay) { // previously adding a year to a leap day will have rounded down to the 28th. // If this happened, we need to be sure that if we are back in a leap // year, it is back at 29th cur.set(Calendar.DAY_OF_MONTH, cur.getActualMaximum(Calendar.DAY_OF_MONTH)); } if (ignoreYearForRecurrenceExpansion(cur, baseIsLeapDay)) { cur.add(Calendar.YEAR, interval); break; } addList.add((Calendar) (cur.clone())); cur.add(Calendar.YEAR, interval); addList = expandMonthList(addList); addList = expandYearDayList(addList); addList = expandMonthDayList(addList); addList = expandDayListForMonthlyYearly(addList); addList = expandHourList(addList); addList = expandMinuteList(addList); addList = expandSecondList(addList); break; default: // MINUTELY and SECONDLY are intentionally not supported for performance reasons. return toRet; } addList = handleSetPos(addList); boolean noInstanceFound = true; boolean foundInstancePastEndDate = false; // add all the ones that match! for (Calendar addCal : addList) { Date toAdd = addCal.getTime(); // We already counted DTSTART before the main loop, so don't // count it twice. if (toAdd.compareTo(dtStartDate) == 0) { noInstanceFound = false; continue; } // we still have expanded this instance, even if it isn't in our // current date window if (toAdd.after(dtStartDate)) numInstancesExpanded++; if (!toAdd.after(rangeEndDate)) { if (!toAdd.before(earliestDate)) { toRet.add(toAdd); noInstanceFound = false; } } else { foundInstancePastEndDate = true; break; } if (maxInstancesExpanded > 0 && numInstancesExpanded >= maxInstancesExpanded) break; } // Detect invalid rule. If the rule was invalid the current iteration, which is for the current // frequency interval, would have found no matching instance. The next iteration will also find // no matching instance, and there is no need to keep iterating until we go past the hard end // time or COUNT/UNTIL limit. // // However, we have to make an exception for leap year. An yearly rule looking for February 29th // will find no instance in up to 3 consecutive years before finding Feb 29th in the fourth year. // // So the invalid rule detection must look for at least 4 consecutive failed iterations. if (curIsAtOrAfterEarliestDate) { if (noInstanceFound) numConsecutiveIterationsWithoutMatchingInstance++; else numConsecutiveIterationsWithoutMatchingInstance = 0; if (numConsecutiveIterationsWithoutMatchingInstance >= 4) { ZimbraLog.calendar.warn("Invalid recurrence rule: " + toString()); return toRet; } } pastHardEndTime = foundInstancePastEndDate || (noInstanceFound && curIsAfterEndDate); } return toRet; }
From source file:org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager.java
/** * *//*from www .j a v a 2s . c om*/ public boolean doAuthenticate(String userName, Object credential) throws UserStoreException { if (!checkUserNameValid(userName)) { return false; } if (!checkUserPasswordValid(credential)) { return false; } if (UserCoreUtil.isRegistryAnnonymousUser(userName)) { log.error("Anonnymous user trying to login"); return false; } Connection dbConnection = null; ResultSet rs = null; PreparedStatement prepStmt = null; String sqlstmt = null; String password = (String) credential; boolean isAuthed = false; try { dbConnection = getDBConnection(); dbConnection.setAutoCommit(false); if (isCaseSensitiveUsername()) { sqlstmt = realmConfig.getUserStoreProperty(JDBCRealmConstants.SELECT_USER); } else { sqlstmt = realmConfig.getUserStoreProperty(JDBCRealmConstants.SELECT_USER_CASE_INSENSITIVE); } if (log.isDebugEnabled()) { log.debug(sqlstmt); } prepStmt = dbConnection.prepareStatement(sqlstmt); prepStmt.setString(1, userName); if (sqlstmt.contains(UserCoreConstants.UM_TENANT_COLUMN)) { prepStmt.setInt(2, tenantId); } rs = prepStmt.executeQuery(); if (rs.next() == true) { String storedPassword = rs.getString(3); String saltValue = null; if ("true".equalsIgnoreCase( realmConfig.getUserStoreProperty(JDBCRealmConstants.STORE_SALTED_PASSWORDS))) { saltValue = rs.getString(4); } boolean requireChange = rs.getBoolean(5); Timestamp changedTime = rs.getTimestamp(6); GregorianCalendar gc = new GregorianCalendar(); gc.add(GregorianCalendar.HOUR, -24); Date date = gc.getTime(); if (requireChange == true && changedTime.before(date)) { isAuthed = false; } else { password = this.preparePassword(password, saltValue); if ((storedPassword != null) && (storedPassword.equals(password))) { isAuthed = true; } } } } catch (SQLException e) { String msg = "Error occurred while retrieving user authentication info for user : " + userName; if (log.isDebugEnabled()) { log.debug(msg, e); } throw new UserStoreException("Authentication Failure", e); } finally { DatabaseUtil.closeAllConnections(dbConnection, rs, prepStmt); } if (log.isDebugEnabled()) { log.debug("User " + userName + " login attempt. Login success :: " + isAuthed); } return isAuthed; }
From source file:org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager.java
/** * *//*www . j a v a2 s. co m*/ public Date getPasswordExpirationTime(String userName) throws UserStoreException { if (userName != null && userName.contains(CarbonConstants.DOMAIN_SEPARATOR)) { return super.getPasswordExpirationTime(userName); } Connection dbConnection = null; ResultSet rs = null; PreparedStatement prepStmt = null; String sqlstmt = null; Date date = null; try { dbConnection = getDBConnection(); dbConnection.setAutoCommit(false); if (isCaseSensitiveUsername()) { sqlstmt = realmConfig.getUserStoreProperty(JDBCRealmConstants.SELECT_USER); } else { sqlstmt = realmConfig.getUserStoreProperty(JDBCRealmConstants.SELECT_USER_CASE_INSENSITIVE); } if (log.isDebugEnabled()) { log.debug(sqlstmt); } prepStmt = dbConnection.prepareStatement(sqlstmt); prepStmt.setString(1, userName); if (sqlstmt.contains(UserCoreConstants.UM_TENANT_COLUMN)) { prepStmt.setInt(2, tenantId); } rs = prepStmt.executeQuery(); if (rs.next() == true) { boolean requireChange = rs.getBoolean(5); Timestamp changedTime = rs.getTimestamp(6); if (requireChange) { GregorianCalendar gc = new GregorianCalendar(); gc.setTime(changedTime); gc.add(GregorianCalendar.HOUR, 24); date = gc.getTime(); } } } catch (SQLException e) { String msg = "Error occurred while retrieving password expiration time for user : " + userName; if (log.isDebugEnabled()) { log.debug(msg, e); } throw new UserStoreException(msg, e); } finally { DatabaseUtil.closeAllConnections(dbConnection, rs, prepStmt); } return date; }
From source file:org.etudes.jforum.view.forum.PostAction.java
public void list() throws Exception { int topicId = this.request.getIntParameter("topic_id"); try {/* w w w . j a v a 2 s . c o m*/ if (logger.isDebugEnabled()) { logger.debug("Entering list()..."); logger.debug("Listing posts for topic id = " + topicId); } if (topicId <= 0) { if (logger.isWarnEnabled()) { logger.warn("topic " + topicId + " has id <= 0"); } this.topicNotFound(); return; } int count = SakaiSystemGlobals.getIntValue(ConfigKeys.POST_PER_PAGE); int startFrom = ViewCommon.getStartPage(); JForumPostService jforumPostService = (JForumPostService) ComponentManager .get("org.etudes.api.app.jforum.JForumPostService"); List<org.etudes.api.app.jforum.Post> posts = null; try { posts = jforumPostService.getTopicPosts(topicId, startFrom, count, UserDirectoryService.getCurrentUser().getId()); } catch (JForumAccessException e) { this.context.put("errorMessage", I18n.getMessage("User.NotAuthorized")); this.setTemplateName(TemplateKeys.USER_NOT_AUTHORIZED); return; } org.etudes.api.app.jforum.Topic topic = null; if (posts.isEmpty()) { try { topic = jforumPostService.getTopic(topicId, UserDirectoryService.getCurrentUser().getId()); } catch (JForumAccessException e) { this.context.put("errorMessage", I18n.getMessage("User.NotAuthorized")); this.setTemplateName(TemplateKeys.USER_NOT_AUTHORIZED); return; } } else { topic = posts.get(0).getTopic(); } if (topic == null) { if (logger.isErrorEnabled()) { logger.error("topic with id " + topicId + " not found"); } this.topicNotFound(); return; } org.etudes.api.app.jforum.Forum forum = null; forum = topic.getForum(); boolean gradeForum = (forum.getGradeType() == Forum.GRADE_BY_FORUM); this.context.put("gradeForum", gradeForum); boolean gradeTopic = (forum.getGradeType() == Forum.GRADE_BY_TOPIC) && topic.isGradeTopic(); this.context.put("gradeTopic", gradeTopic); org.etudes.api.app.jforum.Category category = forum.getCategory(); boolean gradeCategory = category.isGradable(); this.context.put("gradeCategory", gradeCategory); this.context.put("topic", topic); this.context.put("forum", forum); this.context.put("category", category); boolean isfacilitator = JForumUserUtil.isJForumFacilitator( UserDirectoryService.getCurrentUser().getId()) || SecurityService.isSuperUser(); if (!isfacilitator && gradeTopic && topic.getBlocked()) { this.context.put("errorMessage", I18n.getMessage("User.NotAuthorized")); this.setTemplateName(TemplateKeys.USER_NOT_AUTHORIZED); return; } List<Integer> facilitatorsList = new ArrayList<Integer>(); if (gradeForum || gradeTopic || gradeCategory) { this.context.put("facilitators", facilitatorsList); } if (posts.size() > 0) { JForumSecurityService jforumSecurityService = (JForumSecurityService) ComponentManager .get("org.etudes.api.app.jforum.JForumSecurityService"); boolean facilitator = false; for (org.etudes.api.app.jforum.Post post : posts) { facilitator = false; facilitator = jforumSecurityService.isJForumFacilitator( ToolManager.getCurrentPlacement().getContext(), post.getPostedBy().getSakaiUserId()); if (facilitator) { facilitatorsList.add(post.getPostedBy().getId()); } } } this.context.put("posts", posts); this.context.put("attachmentsEnabled", true); this.context.put("canDownloadAttachments", true); this.context.put("canRemove", isfacilitator); this.context.put("canEdit", isfacilitator); this.context.put("isAdmin", isfacilitator); this.context.put("watching", jforumPostService.isUserSubscribedToTopic(topicId, UserDirectoryService.getCurrentUser().getId())); // Topic Status this.context.put("STATUS_LOCKED", new Integer(Topic.STATUS_LOCKED)); this.context.put("STATUS_UNLOCKED", new Integer(Topic.STATUS_UNLOCKED)); // Pagination int totalPosts = jforumPostService.getTotalPosts(topic.getId()); ViewCommon.contextToPagination(startFrom, totalPosts, count); GregorianCalendar gc = new GregorianCalendar(); this.context.put("nowDate", gc.getTime()); Date lastVisitDate = SessionFacade.getUserSession().getLastVisit(); this.context.put("lastVisit", lastVisitDate); JForumUserService jforumUserService = (JForumUserService) ComponentManager .get("org.etudes.api.app.jforum.JForumUserService"); org.etudes.api.app.jforum.User user = jforumUserService .getBySakaiUserId(UserDirectoryService.getCurrentUser().getId()); Date markAllReadTime = jforumUserService.getMarkAllReadTime(category.getContext(), user.getId()); Date compareDate = null; //Date UserTopicMarkTime = jforumPostService.getUserTopicMarkTime(topic.getId(), UserDirectoryService.getCurrentUser().getId()); org.etudes.api.app.jforum.Topic topicUserMarkTime = jforumPostService .getUserTopicMarkTime(topic.getId(), UserDirectoryService.getCurrentUser().getId()); Date userTopicMarkTime = null; if (topicUserMarkTime != null) { userTopicMarkTime = topicUserMarkTime.getTime(); } if ((markAllReadTime == null) && (userTopicMarkTime == null)) { compareDate = null; } else { /*if (markAllReadTime == null) { compareDate = UserTopicMarkTime; } if (UserTopicMarkTime == null) { compareDate = markAllReadTime; }*/ if ((markAllReadTime != null) && (userTopicMarkTime != null)) { if (markAllReadTime.getTime() > userTopicMarkTime.getTime()) { compareDate = markAllReadTime; } else { compareDate = userTopicMarkTime; } } else if ((markAllReadTime == null) && (userTopicMarkTime != null)) { compareDate = userTopicMarkTime; } else if ((markAllReadTime != null) && (userTopicMarkTime == null)) { compareDate = markAllReadTime; } } if (compareDate != null) { this.context.put("compareDate", compareDate); } this.context.put("sju", new JForumUserUtil()); JForumCategoryService jforumCategoryService = (JForumCategoryService) ComponentManager .get("org.etudes.api.app.jforum.JForumCategoryService"); List<org.etudes.api.app.jforum.Category> categories = jforumCategoryService .getUserContextCategories(category.getContext(), UserDirectoryService.getCurrentUser().getId()); this.context.put("allCategories", categories); // Set the topic status as read jforumPostService.markTopicRead(topic.getId(), UserDirectoryService.getCurrentUser().getId(), new Date(), true); // 12/17/2012 - To fix chrome loading of youtube video's immediately after posting(chrome issue - Refused to execute a JavaScript script. Source code of script found within request.) this.response.setIntHeader("X-XSS-Protection", 0); this.setTemplateName(TemplateKeys.POSTS_LIST); } catch (Exception e) { if (logger.isErrorEnabled()) { logger.error(e.toString(), e); } throw e; /*if (topicId > 0) { org.etudes.api.app.jforum.Topic topic = null; try { JForumPostService jforumPostService = (JForumPostService)ComponentManager.get("org.etudes.api.app.jforum.JForumPostService"); topic = jforumPostService.getTopic(topicId, UserDirectoryService.getCurrentUser().getId()); } catch (JForumAccessException e1) { this.context.put("errorMessage", I18n.getMessage("User.NotAuthorized")); this.setTemplateName(TemplateKeys.USER_NOT_AUTHORIZED); return; } if (topic != null) { org.etudes.api.app.jforum.Forum forum = topic.getForum(); if (forum != null) { String path = this.request.getContextPath() +"/forums/show/"+ forum.getId() + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION); JForum.setRedirect(path); } } }*/ } }
From source file:org.obm.icalendar.Ical4jHelper.java
private void appendRecurence(Event event, CalendarComponent component) { EventRecurrence er = new EventRecurrence(); RRule rrule = (RRule) component.getProperty(Property.RRULE); EnumSet<RecurrenceDay> recurrenceDays = EnumSet.noneOf(RecurrenceDay.class); if (rrule != null) { Recur recur = rrule.getRecur();/* w w w. j ava2s . c o m*/ String frequency = recur.getFrequency(); if (Recur.WEEKLY.equals(frequency) || Recur.DAILY.equals(frequency)) { for (Object ob : recur.getDayList()) { recurrenceDays.add(weekDayToRecurrenceDay((WeekDay) ob)); } if (Recur.WEEKLY.equals(frequency) && recurrenceDays.isEmpty()) { GregorianCalendar cal = getEventStartCalendar(event); WeekDay eventStartWeekDay = WeekDay.getDay(cal.get(GregorianCalendar.DAY_OF_WEEK)); recurrenceDays.add(WEEK_DAY_TO_RECURRENCE_DAY.get(eventStartWeekDay)); } } er.setDays(new RecurrenceDays(recurrenceDays)); er.setEnd(recur.getUntil()); er.setFrequence(Math.max(recur.getInterval(), 1)); // getInterval() returns -1 if no interval is defined if (er.getDays().isEmpty()) { if (Recur.DAILY.equals(frequency)) { er.setKind(RecurrenceKind.daily); } else if (Recur.WEEKLY.equals(frequency)) { er.setKind(RecurrenceKind.weekly); } else if (Recur.MONTHLY.equals(frequency)) { WeekDayList wdl = recur.getDayList(); if (wdl.size() > 0) { WeekDay day = (WeekDay) wdl.get(0); GregorianCalendar cal = getEventStartCalendar(event); er.setKind(RecurrenceKind.monthlybyday); cal.set(GregorianCalendar.DAY_OF_WEEK, WeekDay.getCalendarDay(day)); cal.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, day.getOffset()); event.setStartDate(cal.getTime()); } else { er.setKind(RecurrenceKind.monthlybydate); } } else if (Recur.YEARLY.equals(frequency)) { er.setKind(RecurrenceKind.yearly); } } else { er.setKind(RecurrenceKind.weekly); } } event.setRecurrence(er); appendNegativeExceptions(event, component.getProperties(Property.EXDATE)); }
From source file:com.flexive.tests.embedded.persistence.ValueTest.java
@Test public void valueTest() throws Exception { GregorianCalendar gc_multi_date = new GregorianCalendar(1940, 11, 22); GregorianCalendar gc_multi_date2 = new GregorianCalendar(1997, 9, 21); GregorianCalendar gc_single_date = new GregorianCalendar(1974, 0, 12); GregorianCalendar gc_single_date2 = new GregorianCalendar(1974, 3, 17); GregorianCalendar gc_multi_datetime = new GregorianCalendar(1940, 11, 22, 3, 30, 20); GregorianCalendar gc_multi_datetime2 = new GregorianCalendar(1997, 9, 21, 7, 40, 30); GregorianCalendar gc_single_datetime = new GregorianCalendar(1974, 0, 12, 4, 35, 45); GregorianCalendar gc_single_datetime2 = new GregorianCalendar(1974, 3, 17, 14, 30, 15); String s_single = "ABC"; String s_multi = "DEF"; String s_single_big = RandomStringUtils.randomAlphanumeric(50000); String s_multi_big = RandomStringUtils.randomAlphanumeric(50000); File testFile = new File("test.file"); if (!testFile.exists()) testFile = new File("src/framework/testresources/image/Exif.JPG"); if (!testFile.exists()) return;/*from w ww. j a v a 2 s. co m*/ FileInputStream fis = new FileInputStream(testFile); long time = System.currentTimeMillis(); BinaryDescriptor binary = new BinaryDescriptor(testFile.getName(), testFile.length(), fis); System.out.println("size: " + binary.getSize() + " time: " + (System.currentTimeMillis() - time)); System.out.println("==valueTest== Handle received for " + binary.getName() + ": " + binary.getHandle()); fis.close(); TestData[] data = { new TestData<FxHTML>(FxDataType.HTML, new FxHTML(false, s_single).setTidyHTML(true), new FxHTML(true, s_multi)), new TestData<FxString>(FxDataType.String1024, new FxString(false, s_single), new FxString(true, s_multi)), new TestData<FxString>(FxDataType.Text, new FxString(false, s_single_big), new FxString(true, s_multi_big)), new TestData<FxNumber>(FxDataType.Number, new FxNumber(false, Integer.MAX_VALUE), new FxNumber(true, Integer.MIN_VALUE)), new TestData<FxLargeNumber>(FxDataType.LargeNumber, new FxLargeNumber(false, Long.MAX_VALUE), new FxLargeNumber(true, Long.MIN_VALUE)), new TestData<FxFloat>(FxDataType.Float, new FxFloat(false, 123213213213.2222221f), new FxFloat(true, 1f)), new TestData<FxDouble>(FxDataType.Double, new FxDouble(false, 0.000000000000001d), new FxDouble(true, 1d)), new TestData<FxBoolean>(FxDataType.Boolean, new FxBoolean(false, true), new FxBoolean(true, false)), new TestData<FxDate>(FxDataType.Date, new FxDate(false, gc_single_date.getTime()), new FxDate(true, gc_multi_date.getTime())), new TestData<FxDateTime>(FxDataType.DateTime, new FxDateTime(false, gc_single_datetime.getTime()), new FxDateTime(true, gc_multi_datetime.getTime())), new TestData<FxDateRange>(FxDataType.DateRange, new FxDateRange(false, new DateRange(gc_single_date.getTime(), gc_single_date2.getTime())), new FxDateRange(true, new DateRange(gc_multi_date.getTime(), gc_multi_date2.getTime()))), new TestData<FxDateTimeRange>(FxDataType.DateTimeRange, new FxDateTimeRange(false, new DateRange(gc_single_datetime.getTime(), gc_single_datetime2.getTime())), new FxDateTimeRange(true, new DateRange(gc_multi_datetime.getTime(), gc_multi_datetime2.getTime()))), new TestData<FxBinary>(FxDataType.Binary, new FxBinary(false, binary), new FxBinary(true, binary)), new TestData<FxReference>(FxDataType.Reference, new FxReference(false, new ReferencedContent(RPK1)), new FxReference(true, new ReferencedContent(RPK1))) }; FxType testType; StringBuilder sbErr = new StringBuilder(100); for (TestData test : data) { try { System.out.println("Testing " + test.dataType.name() + " ..."); test.testConsistency(); createProperty(test.dataType); testType = CacheAdmin.getEnvironment().getType(TYPE_NAME); FxContent content = co.initialize(testType.getId()); content.setValue("/VTS" + test.dataType.name() + "[1]", test._single.copy()); // content.getPropertyData("/VT" + test.dataType.name() + "[1]").createNew(FxPropertyData.POSITION_BOTTOM); content.setValue("/VTM" + test.dataType.name() + "[1]", test._multi.copy().setValueData(43)); FxPK pk = co.save(content); FxContent loaded = co.load(pk); FxValue loadedSingle = loaded.getPropertyData("/VTS" + test.dataType.name() + "[1]").getValue(); FxValue loadedMulti = loaded.getPropertyData("/VTM" + test.dataType.name() + "[1]").getValue(); test.testSingleValue(loadedSingle); test.testMultiValue(loadedMulti); Assert.assertEquals((int) loadedSingle.getValueData(), 42); Assert.assertEquals((int) loadedMulti.getValueData(), 43); pk = co.save(loaded); loaded = co.load(pk); loadedSingle = loaded.getPropertyData("/VTS" + test.dataType.name() + "[1]").getValue(); loadedMulti = loaded.getPropertyData("/VTM" + test.dataType.name() + "[1]").getValue(); test.testSingleValue(loadedSingle); test.testMultiValue(loadedMulti); Assert.assertEquals((int) loadedSingle.getValueData(), 42); Assert.assertEquals((int) loadedMulti.getValueData(), 43); co.remove(pk); if (test.dataType == FxDataType.Reference) { //additional tests content = co.initialize(testType.getId()); content.setValue("/VTM" + test.dataType.name() + "[1]", new FxReference(true, new ReferencedContent(RPK1))); try { //set to a new pk content.setValue("/VTS" + test.dataType.name() + "[1]", new FxReference(false, new ReferencedContent(new FxPK()))); co.save(content); //expected to fail Assert.fail("Invalid PK (new) for a reference should fail!"); } catch (Exception e) { //expected } try { //set to a non existing pk content.setValue("/VTS" + test.dataType.name() + "[1]", new FxReference(false, new ReferencedContent(new FxPK(123456)))); co.save(content); //expected to fail Assert.fail("Invalid PK (non existant) for a reference should fail!"); } catch (Exception e) { //expected } try { //set to an existing pk, but wrong type content.setValue("/VTS" + test.dataType.name() + "[1]", new FxReference(false, new ReferencedContent(RPK2))); co.save(content); //expected to fail Assert.fail("Invalid PK (wrong type) for a reference should fail!"); } catch (Exception e) { //expected } try { //set to an existing pk, but wrong type content.setValue("/VTS" + test.dataType.name() + "[1]", RPK1); co.save(content); //expected to work } catch (Exception e) { e.printStackTrace(); Assert.fail("Correct PK for a reference should not fail!"); //expected } } } catch (Throwable e) { sbErr.append("Failed DataType: [").append(test.dataType.name()).append("] with: ") .append(e.getMessage()).append("\n"); e.printStackTrace(); } finally { try { removeProperty(test.dataType); } catch (Exception e) { LOG.warn("Failed to remove property", e); } } } if (sbErr.length() > 0) Assert.fail(sbErr.toString()); }
From source file:de.innovationgate.wga.server.api.WGA.java
/** * Modifies a date by adding/substracting a certain timespan * This is a utility method for simple modifications to dates without the use of {@link Calendar} objects. it returns a new {@link Date} object which represents the date of the parameter "date" plus/minus a given timespan. * In order to add a timespan one is first to choose which time unit to use via argument "unit" and then the amount of units to add via argument "amount". In order to substract a timespan from the date a negative amount value is to be used. * The unit is determined by the date string character that would be used by {@link SimpleDateFormat} for the time unit: * <ul>/*w w w.j a v a 2s . c om*/ * <li> d" or "D" - Day * <li> "M" - Month * <li> "w" or "W" - Week * <li> "y" - Year * <li> "H" or "h" - Hour * <li> "m" - Minute * <li> "s" - Second * <li> "S" - Millisecond * <ul> * @param date Date to modify * @param unit Modify unit. See table above. * @param amount Amount of date units to add to the date. Specify negative amounts to substract. * @return The modified date * @throws WGAServerException */ public Date modifyDate(Date date, String unit, int amount) throws WGException { int field; switch (unit.charAt(0)) { case 'd': case 'D': field = GregorianCalendar.DAY_OF_MONTH; break; case 'M': field = GregorianCalendar.MONTH; break; case 'w': case 'W': field = GregorianCalendar.WEEK_OF_YEAR; break; case 'y': field = GregorianCalendar.YEAR; break; case 'H': case 'h': field = GregorianCalendar.HOUR; break; case 'm': field = GregorianCalendar.MINUTE; break; case 's': field = GregorianCalendar.SECOND; break; case 'S': field = GregorianCalendar.MILLISECOND; break; default: throw new WGAServerException("Unknown date field literal: " + unit); } GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); cal.add(field, amount); return cal.getTime(); }