List of usage examples for org.apache.wicket.util.time Duration minutes
public static Duration minutes(final int minutes)
Duration
based on minutes. From source file:ApplicationJettyRunner.java
License:Apache License
public static void main(final String[] args) { final int sessionTimeout = (int) Duration.minutes(1).seconds();// set timeout to 30min(60sec // */* www . j a v a 2 s . c o m*/ // 30min=1800sec)... System.setProperty("wicket.configuration", "development"); final String projectname = "wicket-application-template"; final File projectDirectory = PathFinder.getProjectDirectory(); final File webapp; if (projectDirectory.getAbsolutePath().endsWith(projectname)) { webapp = PathFinder.getRelativePath(projectDirectory, "src", "main", "webapp"); } else { webapp = PathFinder.getRelativePath(projectDirectory, projectname, "src", "main", "webapp"); } final File logfile = new File(projectDirectory, "application.log"); if (logfile.exists()) { try { DeleteFileExtensions.delete(logfile); } catch (final IOException e) { Logger.getRootLogger().error("logfile could not deleted.", e); } } final String absolutePathFromLogfile = logfile.getAbsolutePath(); final String filterPath = "/*"; // Add a file appender to the logger programatically LoggerExtensions.addFileAppender(Logger.getRootLogger(), LoggerExtensions.newFileAppender(absolutePathFromLogfile)); final ContextHandlerCollection contexts = new ContextHandlerCollection(); final ServletContextHandler servletContextHandler = ServletContextHandlerFactory .getNewServletContextHandler(ServletContextHandlerConfiguration.builder().parent(contexts) .filterHolderConfiguration(FilterHolderConfiguration.builder() .filterClass(WicketFilter.class).filterPath(filterPath) .initParameter(WicketFilter.FILTER_MAPPING_PARAM, filterPath) .initParameter(ContextParamWebApplicationFactory.APP_CLASS_PARAM, WicketApplication.class.getName()) .build()) .servletHolderConfiguration(ServletHolderConfiguration.builder() .servletClass(DefaultServlet.class).pathSpec(filterPath).build()) .contextPath("/").webapp(webapp).maxInactiveInterval(sessionTimeout).filterPath(filterPath) .build()); final DeploymentManager deployer = DeploymentManagerFactory.newDeploymentManager(contexts, webapp.getAbsolutePath(), null); final Jetty9RunConfiguration config = newJetty9RunConfiguration(servletContextHandler, contexts, deployer); final Server server = new Server(); Jetty9Runner.runServletContextHandler(server, config); }
From source file:com.gitblit.wicket.pages.BasePage.java
License:Apache License
/** * Sets the last-modified header field and the expires field. * * @param when/* w ww. j av a 2 s . co m*/ */ protected final void setLastModified(Date when) { if (when == null) { return; } if (when.before(app().getBootDate())) { // last-modified can not be before the Gitblit boot date // this helps ensure that pages are properly refreshed after a // server config change when = app().getBootDate(); } int expires = app().settings().getInteger(Keys.web.pageCacheExpires, 0); WebResponse response = (WebResponse) getResponse(); response.setLastModifiedTime(Time.valueOf(when)); response.addHeader("Expires", String.valueOf(System.currentTimeMillis() + Duration.minutes(expires).getMilliseconds())); }
From source file:com.tysanclan.site.projectewok.pages.member.admin.SiteWideNotificationPage.java
License:Open Source License
public SiteWideNotificationPage(User user) { super("Site Wide Notification"); if (!getUser().equals(roleService.getSteward())) { throw new RestartResponseAtInterceptPageException(AccessDeniedPage.class); }/*from w w w .j a va 2 s .c om*/ final TextField<String> messageField = new TextField<String>("message", new Model<String>("")); messageField.setRequired(true); final DropDownChoice<Category> categorySelect = new DropDownChoice<Category>("category", new Model<Category>(Category.INFO), Arrays.asList(Category.values())); categorySelect.setNullValid(false); categorySelect.setRequired(true); String[] durations = new String[DurationTypes.values().length]; int i = 0; for (DurationTypes t : DurationTypes.values()) { durations[i++] = t.getDescriptor(); } final DropDownChoice<String> durationTypeSelect = new DropDownChoice<String>("durationType", new Model<String>("minutes"), Arrays.asList(durations)); durationTypeSelect.setNullValid(false); durationTypeSelect.setRequired(true); final TextField<Integer> durationField = new TextField<Integer>("duration", new Model<Integer>(1), Integer.class); durationField.add(RangeValidator.minimum(1)); durationField.setRequired(true); Form<SiteWideNotification> notificationForm = new Form<SiteWideNotification>("notificationForm") { private static final long serialVersionUID = 1L; /** * @see org.apache.wicket.markup.html.form.Form#onSubmit() */ @Override protected void onSubmit() { String message = messageField.getModelObject(); Category category = categorySelect.getModelObject(); String durationType = durationTypeSelect.getModelObject(); Integer durationAmount = durationField.getModelObject(); Duration d = Duration.minutes(1); for (DurationTypes t : DurationTypes.values()) { if (t.getDescriptor().equals(durationType)) { d = t.getDuration(durationAmount); } } SiteWideNotification not = new SiteWideNotification(category, message, d); TysanApplication.get().notify(not); setResponsePage(new OverviewPage()); } }; notificationForm.add(messageField); notificationForm.add(categorySelect); notificationForm.add(durationTypeSelect); notificationForm.add(durationField); add(notificationForm); }
From source file:de.alpharogroup.wicket.components.examples.StartComponentExamples.java
License:Apache License
private static void startWicketApplication( final ConfigurationPropertiesResolver configurationPropertiesResolver) { String runtimeConfigurationType; runtimeConfigurationType = "development"; // runtimeConfigurationType = "deployment"; final String projectName = "jaulp.wicket.components.examples"; final File projectDirectory = PathFinder.getProjectDirectory(); final File webapp = Jetty9Runner.getWebappDirectory(projectDirectory, projectName); final File logFile = Jetty9Runner.getLogFile(projectDirectory, "application.log"); final StartConfig startConfig = StartConfig.builder().applicationName(WicketApplication.class.getName()) .contextPath("/").filterPath("/*").httpPort(configurationPropertiesResolver.getHttpPort()) .httpsPort(configurationPropertiesResolver.getHttpsPort()).keyStorePassword("wicket") .keyStorePathResource("/keystore").projectDirectory(projectDirectory).projectName(projectName) .runtimeConfigurationType(runtimeConfigurationType) .sessionTimeout((int) Duration.minutes(1).seconds()).webapp(webapp).logFile(logFile) .absolutePathFromLogfile(logFile.getAbsolutePath()).build(); WicketJetty9Runner.run(startConfig); }
From source file:de.tudarmstadt.ukp.csniper.webapp.WicketApplication.java
License:Apache License
@Override public void init() { addResourceReplacement(WiQueryCoreThemeResourceReference.get(), theme); if (!isInitialized) { super.init(); getRequestCycleSettings().setTimeout(Duration.minutes(10)); getComponentInstantiationListeners().add(new SpringComponentInjector(this)); CompoundAuthorizationStrategy autr = new CompoundAuthorizationStrategy(); autr.add(new AnnotationsRoleAuthorizationStrategy(this)); autr.add(new MetaDataRoleAuthorizationStrategy(this)); getSecuritySettings().setAuthorizationStrategy(autr); mountPage("/login.html", getSignInPageClass()); mountPage("/analysis.html", AnalysisPage.class); mountPage("/evaluation.html", EvaluationPage.class); mountPage("/project.html", ProjectPage.class); mountPage("/type.html", AnnotationTypePage.class); mountPage("/statistics.html", StatisticsPage.class); mountPage("/statistics2.html", StatisticsPage2.class); // mountPage("/export.html", ExportPage.class); mountPage("/search.html", SearchPage.class); mountPage("/welcome.html", getHomePage()); // mountPage("/exportHtml.html", ExportHtmlPage.class); mountPage("/users.html", ManageUsersPage.class); isInitialized = true;/*from w w w . j a v a 2s . co m*/ } }
From source file:gr.abiss.calipso.wicket.CalipsoApplication.java
License:Open Source License
@Override public void init() { super.init(); // DEVELOPMENT or DEPLOYMENT RuntimeConfigurationType configurationType = this.getConfigurationType(); if (RuntimeConfigurationType.DEVELOPMENT.equals(configurationType)) { logger.info("You are in DEVELOPMENT mode"); // getResourceSettings().setResourcePollFrequency(Duration.ONE_SECOND); // getDebugSettings().setComponentUseCheck(true); getResourceSettings().setResourcePollFrequency(null); getDebugSettings().setComponentUseCheck(false); // getDebugSettings().setSerializeSessionAttributes(true); // getMarkupSettings().setStripWicketTags(false); // getExceptionSettings().setUnexpectedExceptionDisplay( // UnexpectedExceptionDisplay.SHOW_EXCEPTION_PAGE); // getAjaxSettings().setAjaxDebugModeEnabled(true); } else if (RuntimeConfigurationType.DEPLOYMENT.equals(configurationType)) { getResourceSettings().setResourcePollFrequency(null); getDebugSettings().setComponentUseCheck(false); // getDebugSettings().setSerializeSessionAttributes(false); // getMarkupSettings().setStripWicketTags(true); // getExceptionSettings().setUnexpectedExceptionDisplay( // UnexpectedExceptionDisplay.SHOW_INTERNAL_ERROR_PAGE); // getAjaxSettings().setAjaxDebugModeEnabled(false); }//from www. j a va 2s . com // initialize velocity try { Velocity.init(); if (logger.isInfoEnabled()) { logger.info("Initialized Velocity engine"); } } catch (Exception e) { // TODO Auto-generated catch block logger.error("Failed to initialize velocity engine", e); } // Set custom page for internal errors getApplicationSettings().setInternalErrorPage(CalipsoErrorPage.class); // don't break down on missing resources getResourceSettings().setThrowExceptionOnMissingResource(false); // Redirect to PageExpiredError Page if current page is expired getApplicationSettings().setPageExpiredErrorPage(CalipsoPageExpiredErrorPage.class); // get hold of spring managed service layer (see BasePage, BasePanel etc // for how it is used) ServletContext sc = getServletContext(); applicationContext = WebApplicationContextUtils.getWebApplicationContext(sc); calipsoService = (CalipsoService) applicationContext.getBean("calipsoService"); calipsoPropertiesEditor = new CalipsoPropertiesEditor(); // check if acegi-cas authentication is being used, get reference to // object to be used // by wicket authentication to redirect to right pages for login / // logout try { calipsoCasProxyTicketValidator = (CalipsoCasProxyTicketValidator) applicationContext .getBean("casProxyTicketValidator"); logger.info("casProxyTicketValidator retrieved from application context: " + calipsoCasProxyTicketValidator); } catch (NoSuchBeanDefinitionException nsbde) { logger.info( "casProxyTicketValidator not found in application context, CAS single-sign-on is not being used"); } // delegate wicket i18n support to spring i18n getResourceSettings().getStringResourceLoaders().add(new IStringResourceLoader() { @Override public String loadStringResource(Class<?> clazz, String key, Locale locale, String style, String variation) { return applicationContext.getMessage(key, null, null, locale); } @Override public String loadStringResource(Component component, String key, Locale locale, String style, String variation) { return applicationContext.getMessage(key, null, null, locale); } }); // add DB i18n resources getResourceSettings().getStringResourceLoaders().add(new IStringResourceLoader() { @Override public String loadStringResource(Class<?> clazz, String key, Locale locale, String style, String variation) { if (StringUtils.isNotBlank(locale.getVariant())) { // always ignore the variant locale = new Locale(locale.getLanguage(), locale.getCountry()); } String lang = locale.getLanguage(); I18nStringResource resource = CalipsoApplication.this.calipsoService .loadI18nStringResource(new I18nStringIdentifier(key, lang)); if (resource == null && !lang.equalsIgnoreCase("en")) { resource = CalipsoApplication.this.calipsoService .loadI18nStringResource(new I18nStringIdentifier(key, "en")); } return resource != null ? resource.getValue() : null; } @Override public String loadStringResource(Component component, String key, Locale locale, String style, String variation) { locale = component == null ? Session.get().getLocale() : component.getLocale(); if (StringUtils.isNotBlank(locale.getVariant())) { // always ignore the variant locale = new Locale(locale.getLanguage(), locale.getCountry()); } String lang = locale.getLanguage(); I18nStringResource resource = CalipsoApplication.this.calipsoService .loadI18nStringResource(new I18nStringIdentifier(key, lang)); if (resource == null && !lang.equalsIgnoreCase("en")) { resource = CalipsoApplication.this.calipsoService .loadI18nStringResource(new I18nStringIdentifier(key, "en")); } return resource != null ? resource.getValue() : null; } }); // cache resources. resource cache is cleared when creating/updating a space getResourceSettings().getLocalizer().setEnableCache(true); getSecuritySettings().setAuthorizationStrategy(new IAuthorizationStrategy() { @Override public boolean isActionAuthorized(Component c, Action a) { return true; } @Override public boolean isInstantiationAuthorized(Class clazz) { if (BasePage.class.isAssignableFrom(clazz)) { if (((CalipsoSession) Session.get()).isAuthenticated()) { return true; } if (calipsoCasProxyTicketValidator != null) { // attempt CAS authentication // ========================== // logger.debug("checking if context contains CAS authentication"); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && authentication.isAuthenticated()) { // logger.debug("security context contains CAS authentication, initializing session"); ((CalipsoSession) Session.get()).setUser((User) authentication.getPrincipal()); return true; } } // attempt remember-me auto login // ========================== if (attemptRememberMeAutoLogin()) { return true; } // attempt *anonymous* guest access if there are // spaces that allow it if (((CalipsoSession) Session.get()).getUser() == null) { List<Space> anonymousSpaces = getCalipso().findSpacesWhereAnonymousAllowed(); if (anonymousSpaces.size() > 0) { // logger.debug("Found "+anonymousSpaces.size() // + // " anonymousSpaces allowing ANONYMOUS access, initializing anonymous user"); User guestUser = new User();//getCalipso().loadUser(2); guestUser.setLoginName("guest"); guestUser.setName("Anonymous"); guestUser.setLastname("Guest"); guestUser.setLocale(Session.get().getLocale().getLanguage()); getCalipso().initImplicitRoles(guestUser, anonymousSpaces, RoleType.ANONYMOUS); // store user in session ((CalipsoSession) Session.get()).setUser(guestUser); return true; } else { if (logger.isDebugEnabled()) { // logger.debug("Found no public spaces."); } } } // allow registration if (clazz.equals(RegisterUserFormPage.class)) { return true; } // not authenticated, go to login page // logger.debug("not authenticated, forcing login, page requested was " // + clazz.getName()); if (calipsoCasProxyTicketValidator != null) { String serviceUrl = calipsoCasProxyTicketValidator.getLoginUrl(); // .getServiceProperties().getService(); String loginUrl = calipsoCasProxyTicketValidator.getLoginUrl(); // logger.debug("cas authentication: service URL: " // + serviceUrl); String redirectUrl = loginUrl + "?service=" + serviceUrl; // logger.debug("attempting to redirect to: " + // redirectUrl); throw new RestartResponseAtInterceptPageException(new RedirectPage(redirectUrl)); } else { throw new RestartResponseAtInterceptPageException(LoginPage.class); } } return true; } }); // TODO: create friendly URLs for all created pages // friendly URLs for selected pages if (calipsoCasProxyTicketValidator != null) { mountPage("/login", CasLoginPage.class); } else { mountPage("/login", LoginPage.class); } mountPage("/register", RegisterAnonymousUserFormPage.class); mountPage("/logout", LogoutPage.class); mountPage("/svn", SvnStatsPage.class); mountPage("/test", TestPage.class); mountPage("/casError", CasLoginErrorPage.class); mountPage("/item/", ItemViewPage.class); mountPage("/item/${itemId}", ItemViewPage.class); mountPage("/itemreport/", ItemTemplateViewPage.class); mountPage("/newItem/${spaceCode}", NewItemPage.class); // MixedParamUrlCodingStrategy newItemUrls = new MixedParamUrlCodingStrategy( // "/newItem", // NewItemPage.class, // new String[]{"spaceCode"} // ); // mount(newItemUrls); //fix for tinyMCE bug, see https://github.com/wicketstuff/core/issues/113 SecurePackageResourceGuard guard = (SecurePackageResourceGuard) getResourceSettings() .getPackageResourceGuard(); guard.addPattern("+*.htm"); this.getRequestCycleSettings().setTimeout(Duration.minutes(6)); this.getPageSettings().setVersionPagesByDefault(true); this.getExceptionSettings().setThreadDumpStrategy(ThreadDumpStrategy.THREAD_HOLDING_LOCK); }
From source file:hsa.awp.admingui.view.CampaignListPanel.java
License:Open Source License
/** * Constructor with {@link Panel}ID./*from w ww. j a v a2s . c om*/ * * @param id the id of the {@link Panel}. */ public CampaignListPanel(String id) { super(id); Form<Object> sortChoiceForm = new Form<Object>("campaignList.sortChoices"); add(sortChoiceForm); LinkedList<String> sortFieldChoices = new LinkedList<String>(); sortFieldChoices.addAll(SortChoice.names()); LinkedList<String> sortDirectionChoices = new LinkedList<String>(); sortDirectionChoices.add(ascending); sortDirectionChoices.add(descending); final DropDownChoice<String> sortFields = new DropDownChoice<String>("campaignList.sortFields", new Model<String>(ascending), sortFieldChoices); sortFields.setOutputMarkupId(true); sortChoiceForm.add(sortFields); final DropDownChoice<String> sortDirections = new DropDownChoice<String>("CampaignList.sortDirections", new Model<String>(SortChoice.NAME.name), sortDirectionChoices); sortDirections.setOutputMarkupId(true); sortChoiceForm.add(sortDirections); sortFields.add(new AjaxFormComponentUpdatingBehavior("onchange") { /** * unique serialization id. */ private static final long serialVersionUID = 1L; @Override protected void onUpdate(AjaxRequestTarget target) { boolean asc = false; if (sortDirections.getModelObject() != null && sortDirections.getModelObject().equals(ascending)) { asc = false; } sort(SortChoice.choiceByName(sortFields.getModelObject()), asc); target.addComponent(campaignListMarkupContainer); } }); sortDirections.add(new AjaxFormComponentUpdatingBehavior("onchange") { /** * unique serialization id. */ private static final long serialVersionUID = 1L; @Override protected void onUpdate(AjaxRequestTarget target) { boolean asc = false; if (sortDirections.getModelObject() != null && sortDirections.getModelObject().equals(ascending)) { asc = false; } sort(SortChoice.choiceByName(sortFields.getModelObject()), asc); target.addComponent(campaignListMarkupContainer); } }); campaigns = controller.getCampaignsByMandator(getSession()); ListActiveCampaignsPanel activeCampaigns = new ListActiveCampaignsPanel("campaignList.activeCampaigns"); activeCampaigns.add(new AjaxSelfUpdatingTimerBehavior(Duration.minutes(5d))); add(activeCampaigns); final SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy HH:mm"); campaignList = new PageableListView<Campaign>("campaignList", campaigns, pagesize) { /** * unique identifier. */ private static final long serialVersionUID = 5446468946546848946L; @Override protected void populateItem(final ListItem<Campaign> item) { Campaign campaign = item.getModelObject(); Label state = new Label("campaignState"); String stateString; if (campaign.isRunning()) { stateString = "running"; } else if (campaign.isTerminated()) { stateString = "terminated"; } else { stateString = "notYetStarted"; } state.add(new AttributeAppender("class", new Model<String>(stateString), " ")); item.add(state); item.add(new Label("startShow", format.format(item.getModelObject().getStartShow().getTime()))); item.add(new Label("endShow", format.format(item.getModelObject().getEndShow().getTime()))); item.add(new Label("campaignName", item.getModelObject().getName())); item.add(createEditLink(item)); item.add(createDetailLink(item)); AbstractDeleteLink<Campaign> deleteLink = new AbstractDeleteLink<Campaign>("deleteLink", item.getModelObject()) { @Override public void modifyItem(Campaign campaign) { controller.deleteCampaign(campaign); setResponsePage(new OnePanelPage(new CampaignListPanel(OnePanelPage.getPanelIdOne()))); } }; deleteLink.setVisible(!(item.getModelObject().getAppliedProcedures().size() > 0)); item.add(deleteLink); } private Link<AlterCampaignPanel> createEditLink(final ListItem<Campaign> item) { Link<AlterCampaignPanel> alterCampaign = new Link<AlterCampaignPanel>("campaignLink", new PropertyModel<AlterCampaignPanel>(AlterCampaignPanel.class, "alterCampaign")) { /** * unique serialization id. */ private static final long serialVersionUID = -5466954901705080742L; @Override public void onClick() { setResponsePage(new OnePanelPage(new AlterCampaignPanel(OnePanelPage.getPanelIdOne(), item.getModelObject().getId()))); } }; AccessUtil.allowRender(alterCampaign, "editCampaign"); return alterCampaign; } private Link<CampaignDetailPanel> createDetailLink(final ListItem<Campaign> item) { Link<CampaignDetailPanel> campDetail; campDetail = new Link<CampaignDetailPanel>("eventList", new PropertyModel<CampaignDetailPanel>(CampaignDetailPanel.class, "eventList")) { /** * unique serialization id. */ private static final long serialVersionUID = -5466954901732080742L; @Override public void onClick() { setResponsePage(new OnePanelPage(new CampaignDetailPanel(OnePanelPage.getPanelIdOne(), item.getModelObject().getId()))); } }; return campDetail; } }; campaignList.setOutputMarkupId(true); sort(SortChoice.NAME, true); campaignListMarkupContainer = new WebMarkupContainer("campaignList.listContainer"); campaignListMarkupContainer.add(campaignList); campaignListMarkupContainer.setOutputMarkupId(true); PagingNavigation navigation = new PagingNavigation("campaignList.navigation", campaignList); navigation.setOutputMarkupId(true); campaignListMarkupContainer.add(navigation); if (campaignList.getModelObject().size() < pagesize) { navigation.setVisible(false); } add(campaignListMarkupContainer); add(feedbackPanel); }
From source file:hsa.awp.admingui.view.EventDetailPanel.java
License:Open Source License
/** * Creates a new tab with more information about the {@link Event}. * * @return tab for information/*from w w w . j a va 2 s .com*/ */ private ITab tabEventDetails() { return new AbstractTab(new Model<String>(DETAIL)) { /** * unique serialization id. */ private static final long serialVersionUID = 1L; @Override public Panel getPanel(String arg0) { Panel panel = new TabEventDetailPanel(arg0); panel.add(new AjaxSelfUpdatingTimerBehavior(Duration.minutes(5d))); AccessUtil.allowRender(panel, "viewEventDetails"); return panel; } }; }
From source file:hsa.awp.admingui.view.EventDetailPanel.java
License:Open Source License
/** * Creates a new tab for {@link ConfirmedRegistration}s. * * @return tab for {@link ConfirmedRegistration}s. *//*from ww w.ja v a 2 s . c o m*/ private ITab tabEventConfirmedRegistrations() { return new AbstractTab(new Model<String>(REGISTRATIONS)) { /** * unique serialization id. */ private static final long serialVersionUID = -3145454617649443969L; @Override public Panel getPanel(String arg0) { Panel panel = new TabEventConfirmedRegistrationsPanel(arg0); panel.add(new AjaxSelfUpdatingTimerBehavior(Duration.minutes(5d))); AccessUtil.allowRender(panel, "editEventDetails"); return panel; } }; }
From source file:hsa.awp.admingui.view.EventDetailPanel.java
License:Open Source License
/** * Tab including more information about all associated {@link PriorityList}s. * * @return tab containing {@link PriorityList}s. *//* w ww .ja v a 2 s .c om*/ private ITab tabEventPriorityLists() { return new AbstractTab(new Model<String>(PRIORITYLISTS)) { /** * unique serialization id. */ private static final long serialVersionUID = -5460290314327872731L; @Override public Panel getPanel(String arg0) { Panel panel = new TabEventPriorityListPanel(arg0); panel.add(new AjaxSelfUpdatingTimerBehavior(Duration.minutes(5d))); AccessUtil.allowRender(panel, "editEventDetails"); return panel; } }; }