Java Code Examples for org.apache.wicket.Session

The following are top voted examples for showing how to use org.apache.wicket.Session. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: gitplex-mit   File: RequestOverviewPage.java   Source Code and License 7 votes vote down vote up
private WebMarkupContainer newManageContainer() {
	WebMarkupContainer container = new WebMarkupContainer("manage");
	container.setVisible(SecurityUtils.canModify(getPullRequest()));
	container.add(new Link<Void>("synchronize") {

		@Override
		public void onClick() {
			GitPlex.getInstance(PullRequestManager.class).check(getPullRequest());
			Session.get().success("Pull request is synchronized");
		}
		
	});
	container.add(new Link<Void>("delete") {

		@Override
		public void onClick() {
			PullRequest request = getPullRequest();
			GitPlex.getInstance(PullRequestManager.class).delete(request);
			Session.get().success("Pull request #" + request.getNumber() + " is deleted");
			setResponsePage(RequestListPage.class, RequestListPage.paramsOf(getProject()));
		}
		
	}.add(new ConfirmOnClick("Do you really want to delete this pull request?")));
	return container;
}
 
Example 2
Project: engerek   File: Utf8BundleStringResourceLoader.java   Source Code and License 7 votes vote down vote up
@Override
public String loadStringResource(Component component, String key, Locale locale, String style, String variation) {
    if (locale == null) {
        locale = Session.exists() ? Session.get().getLocale() : Locale.getDefault();
    }

    ResourceBundle.Control control = new UTF8Control();
    try {
        return ResourceBundle.getBundle(bundleName, locale, control).getString(key);
    } catch (MissingResourceException ex) {
        try {
            return ResourceBundle.getBundle(bundleName, locale,
                    Thread.currentThread().getContextClassLoader(), control).getString(key);
        } catch (MissingResourceException ex2) {
            return null;
        }
    }
}
 
Example 3
Project: vlo-curation   File: PermalinkServiceImpl.java   Source Code and License 7 votes vote down vote up
@Override
public String getUrlString(Class<? extends Page> pageClass, QueryFacetsSelection selection, SolrDocument document) {
    final PageParameters params = new PageParameters();
    if (selection != null) {
        params.mergeWith(paramsConverter.toParameters(selection));
    }

    if (document != null) {
        params.add(VloWebAppParameters.DOCUMENT_ID, document.getFirstValue(FacetConstants.FIELD_ID));
    }

    final String style = Session.get().getStyle();
    if (style != null) {
        params.add(VloWebAppParameters.THEME, style);
    }

    final CharSequence url = RequestCycle.get().urlFor(pageClass, params);
    final String absoluteUrl = RequestCycle.get().getUrlRenderer().renderFullUrl(Url.parse(url));
    return absoluteUrl;
}
 
Example 4
Project: vlo-curation   File: AllFacetValuesPage.java   Source Code and License 7 votes vote down vote up
public AllFacetValuesPage(PageParameters params) {
    super(params);

    this.selectionModel = Model.of(parametersConverter.fromParameters(params));
    final StringValue facetValue = params.get(SELECTED_FACET_PARAM);
    if (facetValue.isEmpty()) {
        Session.get().error("No facet provided for all values page");
        throw new RestartResponseException(new FacetedSearchPage(selectionModel));
    }

    final String facet = facetParamMapper.getFacet(facetValue.toString());

    if (vloConfig.getFacetsInSearch().contains(facet)) {
        // create a new model so that all values will be retrieved
        setModel(new FacetFieldModel(facet, facetFieldsService, selectionModel)); // gets all facet values
    }
    if (getModelObject() == null) {
        Session.get().error(String.format("Facet '%s' could not be found", facet));
        ErrorPage.triggerErrorPage(ErrorPage.ErrorType.PAGE_NOT_FOUND, params);
    }

    addComponents();
}
 
Example 5
Project: vlo-curation   File: VloBasePage.java   Source Code and License 7 votes vote down vote up
/**
 * Sets the theme from the page parameters if applicable. An present but
 * empty theme value will reset the theme (by unsetting the style).
 *
 * @param parameters page parameters to process
 * @see VloWebAppParameters#THEME
 * @see Session#setStyle(java.lang.String)
 */
private void processTheme(PageParameters parameters) {
    final StringValue themeValue = parameters.get(VloWebAppParameters.THEME);
    if (!themeValue.isNull()) {
        if (themeValue.isEmpty()) {
            // empty string resets theme
            logger.debug("Resetting theme");
            Session.get().setStyle(null);
        } else {
            // theme found, set it as style in the session
            final String theme = themeValue.toString().toLowerCase();
            logger.debug("Setting theme to {}", theme);
            Session.get().setStyle(theme);
        }

        /*
         * Remove theme parameter to prevent it from interfering with 
         * further processing, specifically the parameters check in 
         * the simple page search
         */
        parameters.remove(VloWebAppParameters.THEME, themeValue.toString());
    }
}
 
Example 6
Project: Unicorn   File: NotificationPage.java   Source Code and License 7 votes vote down vote up
public NotificationPage() {
	super();

	// Create the modal window.
	this.addNotificationModal = new AddNotificationModal("addNotificationModal", this);
	this.add(this.addNotificationModal);

	// add notificationList
	if (((AuthenticatedSession) Session.get()).getUser() != null) {
		// logged in users see their notifications
		final NotificationList notificationList = new NotificationList("notificationList", this);
		notificationList.setOutputMarkupId(true);
		this.add(notificationList);
	} else {
		final Label notificationListLabel = new Label("notificationList", "Log in to check your notifications.");
		notificationListLabel.setOutputMarkupId(true);
		this.add(notificationListLabel);
	}

	this.form = new Form<Void>("form");
	this.form.add(this.addAddButton());
	this.form.add(this.addDeleteAllButton());
	this.add(this.form);

	this.addNotificationRules();
}
 
Example 7
Project: Unicorn   File: LoginPage.java   Source Code and License 7 votes vote down vote up
private void buildMainLayout() {
	this.loginForm = new WarnOnExitForm("loginForm");

	this.emailInput = new TextField<String>("emailInput", Model.of(""));
	this.loginForm.add(this.emailInput);

	this.passwordInput = new PasswordTextField("passwordInput", Model.of(""));
	this.loginForm.add(this.passwordInput);

	this.addLoginButton();
	this.addRegisterLink();

	this.add(this.loginForm);

	this.logoutForm = new Form<Object>("logoutForm");

	this.addLogoutButton();

	this.add(this.logoutForm);

	if (((AuthenticatedSession) Session.get()).getUser() != null) {
		this.loginForm.setVisible(false);
	} else {
		this.logoutForm.setVisible(false);
	}
}
 
Example 8
Project: u-qasar.platform   File: UQasarRedirectWithoutLoginStrategy.java   Source Code and License 6 votes vote down vote up
@Override
public <T extends IRequestableComponent> boolean isInstantiationAuthorized(Class<T> componentClass) {
	// if it's not a wicket page --> allow
	if (!Page.class.isAssignableFrom(componentClass)) {
		return true;
	}

	// if it's a page that does not require authentication --> allow
	for (Class<? extends WebPage> clazz : PAGES_WO_AUTH_REQ) {
		if (clazz.isAssignableFrom(componentClass)) {
			return true;
		}
	}

	// if it's any other wicket page and user is not logged in -->
	// redirect to login page
	if (!((UQSession) Session.get()).isAuthenticated()) {
		throw new RestartResponseAtInterceptPageException(LoginPage.class);
	}
	return true;
}
 
Example 9
Project: owsi-core-parent   File: CorePageInstanceLinkGenerator.java   Source Code and License 6 votes vote down vote up
protected Page getValidPageInstance() throws LinkInvalidTargetRuntimeException {
	Page pageInstance = pageInstanceModel.getObject();
	if (pageInstance == null) {
		throw new LinkInvalidTargetRuntimeException("The target page instance was null");
	}
	
	Class<? extends Page> validPageClass = getValidExpectedPageClass(pageInstance);
	
	if (validPageClass == null) {
		throw new LinkInvalidTargetRuntimeException("The target page instance '" + pageInstance + "' had unexpected type :"
				+ " got " + pageInstance.getClass().getName() + ", "
				+ "expected one of " + Joiner.on(", ").join(Collections2.transform(expectedPageClassModels, GET_NAME_FROM_CLASS_MODEL_FUNCTION)));
	}
	
	if (! bypassPermissions) {
		if (!Session.get().getAuthorizationStrategy().isActionAuthorized(pageInstance, Page.RENDER)) {
			throw new LinkInvalidTargetRuntimeException("The rendering of the target page instance '" + pageInstance
					+ "' was not authorized.");
		}
	}
	
	return pageInstance;
}
 
Example 10
Project: owsi-core-parent   File: AbstractGenericItemListPanel.java   Source Code and License 6 votes vote down vote up
protected MarkupContainer getDeleteLink(String id, final IModel<? extends T> itemModel) {
	return AjaxConfirmLink.<T>build()
			.title(getDeleteConfirmationTitleModel(itemModel))
			.content(getDeleteConfirmationTextModel(itemModel))
			.yes(getDeleteConfirmationYesLabelModel(itemModel))
			.no(getDeleteConfirmationNoLabelModel(itemModel))
			.onClick(new AbstractAjaxAction() {
				private static final long serialVersionUID = 1L;
				@Override
				public void execute(AjaxRequestTarget target) {
					try {
						doDeleteItem(itemModel);
						Session.get().success(getString("common.delete.success"));
					} catch (Exception e) {
						Session.get().error(getString("common.delete.error"));
					}
					target.add(getPage());
					dataProvider.detach();
					FeedbackUtils.refreshFeedback(target, getPage());
				}
			})
			.create(id, ReadOnlyModel.of(itemModel));
}
 
Example 11
Project: owsi-core-parent   File: LinkBreadCrumbElementPanel.java   Source Code and License 6 votes vote down vote up
public LinkBreadCrumbElementPanel(String id, BreadCrumbElement breadCrumbElement, BreadCrumbMarkupTagRenderingBehavior renderingBehavior) {
	super(id, breadCrumbElement.getLabelModel());
	
	Link<Void> breadCrumbLink = new BookmarkablePageLink<Void>("breadCrumbElementLink", breadCrumbElement.getPageClass(),
			breadCrumbElement.getPageParameters()) {
		private static final long serialVersionUID = 1L;

		@Override
		protected void onConfigure() {
			super.onConfigure();
			
			setVisible(Session.get().getAuthorizationStrategy().isInstantiationAuthorized(getPageClass()));
		}
	};
	breadCrumbLink.setBody(getModel());
	breadCrumbLink.add(renderingBehavior);
	add(breadCrumbLink);
	
	add(
			Condition.componentVisible(breadCrumbLink).thenShowInternal()
	);
}
 
Example 12
Project: webanno   File: LoginPage.java   Source Code and License 6 votes vote down vote up
private void setDefaultResponsePageIfNecessary()
{
    // This does not work because it was Spring Security that intercepted the access, not
    // Wicket continueToOriginalDestination();

    String redirectUrl = getRedirectUrl();
    
    if (redirectUrl == null || redirectUrl.contains(".IBehaviorListener.")
            || redirectUrl.contains("-logoutPanel-")) {
        log.debug("Redirecting to welcome page");
        setResponsePage(getApplication().getHomePage());
    }
    else {
        log.debug("Redirecting to saved URL: [{}]", redirectUrl);
        if (isNotBlank(form.urlfragment) && form.urlfragment.startsWith("!")) {
            Url url = Url.parse("http://dummy?" + form.urlfragment.substring(1));
            UrlRequestParametersAdapter adapter = new UrlRequestParametersAdapter(url);
            LinkedHashMap<String, StringValue> params = new LinkedHashMap<>();
            for (String name : adapter.getParameterNames()) {
                params.put(name, adapter.getParameterValue(name));
            }
            Session.get().setMetaData(SessionMetaData.LOGIN_URL_FRAGMENT_PARAMS, params);
        }
        throw new NonResettingRestartException(redirectUrl);
    }
}
 
Example 13
Project: webanno   File: AnnotationPage.java   Source Code and License 6 votes vote down vote up
public AnnotationPage()
{
    super();
    LOG.debug("Setting up annotation page without parameters");
    commonInit();
    
    Map<String, StringValue> fragmentParameters = Session.get()
            .getMetaData(SessionMetaData.LOGIN_URL_FRAGMENT_PARAMS);
    if (fragmentParameters != null) {
        // Clear the URL fragment parameters - we only use them once!
        Session.get().setMetaData(SessionMetaData.LOGIN_URL_FRAGMENT_PARAMS, null);
        
        StringValue project = fragmentParameters.get(PAGE_PARAM_PROJECT_ID);
        StringValue document = fragmentParameters.get(PAGE_PARAM_DOCUMENT_ID);
        StringValue focus = fragmentParameters.get(PAGE_PARAM_FOCUS);
        
        handleParameters(null, project, document, focus, false);
    }
}
 
Example 14
Project: WicketRedisSession   File: RedisSessionStore.java   Source Code and License 6 votes vote down vote up
@Override
public void bind(Request request, Session newSession)
{
	if (getAttribute(request, Session.SESSION_ATTRIBUTE_NAME) != newSession)
	{
		// call template method
		onBind(request, newSession);
		for (BindListener listener : getBindListeners())
		{
			listener.bindingSession(request, newSession);
		}

		HttpSession httpSession = getHttpSession(request, false);

		if (httpSession != null)
		{
			// register an unbinding listener for cleaning up
			String applicationKey = Application.get().getName();
			httpSession.setAttribute("Wicket:SessionUnbindingListener-" + applicationKey,
				new SessionBindingListener(applicationKey, newSession));
		}
		// register the session object itself
		setAttribute(request, Session.SESSION_ATTRIBUTE_NAME, newSession);
	}
}
 
Example 15
Project: ontopia   File: SignInPage.java   Source Code and License 6 votes vote down vote up
public SignInPage(PageParameters params) {
super(params);
    
add(new StartPageHeaderPanel("header"));
add(new FooterPanel("footer"));

   add(new Label("title", new ResourceModel("page.title.signin")));

   add(new Label("message", new AbstractReadOnlyModel<String>() {
       @Override
       public String getObject() {
         OntopolySession session = (OntopolySession)Session.findOrCreate();
         return session.getSignInMessage();
       }
     }));
   add(new SignInForm("form"));
 }
 
Example 16
Project: ontopia   File: LockPanel.java   Source Code and License 6 votes vote down vote up
protected boolean acquireLock() {
  // create lock id and lock key
  OntopolySession session = (OntopolySession)Session.get();
  String lockerId = session.getLockerId(getRequest());
  LockManager.Lock lock = session.lock((Topic)getDefaultModelObject(), lockerId);
  this.lockedBy = lock.getLockedBy();
  this.lockedAt = new Date(lock.getLockTime()).toString();
  this.lockKey = lock.getLockKey();
  if (!lock.ownedBy(lockerId)) {
    this.lockedByOther = true;
    //! System.out.println("Got lock: false: " + lock);
    return false;
  } else {
    //! System.out.println("Got lock: true" + lock);
    return true;
  }
}
 
Example 17
Project: u-qasar.platform   File: PlatformSettingsAddEditPage.java   Source Code and License 6 votes vote down vote up
/**
 * Save adapter settings, show message to the user and redirect to the adapter list
 * 
 * @param target
 */
private void save(AjaxRequestTarget target) {

    // Persist the adapter settings
    saveSettings();

    // success message has to be associated to session so that it is shown
    // in the global feedback panel
    Session.get().success(new StringResourceModel("saved.message", this, Model.of(platformSettings)).getString());
    // redirect to adapter list page
    setResponsePage(
        PlatformSettingsPage.class,
        new PageParameters().set(MESSAGE_PARAM,
            new StringResourceModel("saved.message", this, Model.of(platformSettings)).getString()).set(LEVEL_PARAM,
            FeedbackMessage.SUCCESS));
}
 
Example 18
Project: hippo   File: BlankStaticDropdownSelectionFieldValidator.java   Source Code and License 5 votes vote down vote up
private IModel<String> getViolationMessageTemplate() {
    return new ResourceBundleModel(
        VALIDATORS_TRANSLATION_KEY,
        VIOLATION_MESSAGE_TEMPLATE_KEY,
        Session.get().getLocale()
    );
}
 
Example 19
Project: gitplex-mit   File: NewProjectPage.java   Source Code and License 5 votes vote down vote up
@Override
protected void onInitialize() {
	super.onInitialize();
	
	Project project = new Project();
	
	BeanEditor<?> editor = BeanContext.editBean("editor", project);
	
	Form<?> form = new Form<Void>("form") {

		@Override
		protected void onSubmit() {
			super.onSubmit();
			
			ProjectManager projectManager = GitPlex.getInstance(ProjectManager.class);
			Project projectWithSameName = projectManager.find(project.getName());
			if (projectWithSameName != null) {
				editor.getErrorContext(new PathSegment.Property("name"))
						.addError("This name has already been used by another project");
			} else {
				projectManager.save(project, null);
				Session.get().success("New project created");
				setResponsePage(ProjectBlobPage.class, ProjectBlobPage.paramsOf(project));
			}
		}
		
	};
	form.add(editor);
	
	add(form);
}
 
Example 20
Project: gitplex-mit   File: CommitMessageTransformPage.java   Source Code and License 5 votes vote down vote up
@Override
protected void onInitialize() {
	super.onInitialize();
	
	Form<?> form = new Form<Void>("commitMessageTransformSetting") {

		@Override
		protected void onSubmit() {
			super.onSubmit();
			GitPlex.getInstance(ProjectManager.class).save(getProject());
			Session.get().success("Commit message transform setting is updated");
		}
		
	};
	form.add(new ReflectionPropertyEditor("editor", new PropertyDescriptor(Project.class, "commitMessageTransformSetting"), new IModel<Serializable>() {

		@Override
		public void detach() {
		}

		@Override
		public Serializable getObject() {
			return getProject().getCommitMessageTransformSetting();
		}

		@Override
		public void setObject(Serializable object) {
			getProject().setCommitMessageTransformSetting((CommitMessageTransformSetting) object);
		}

	}));

	add(form);
}
 
Example 21
Project: gitplex-mit   File: PasswordEditPage.java   Source Code and License 5 votes vote down vote up
@Override
protected void onInitialize() {
	super.onInitialize();
	
	PasswordEditBean bean = new PasswordEditBean();
	
	Set<String> excludedProperties = new HashSet<>();
	
	// in case administrator changes password we do not ask for old password
	if (SecurityUtils.isAdministrator()) 
		excludedProperties.add("oldPassword");
	
	Form<?> form = new Form<Void>("form") {

		@Override
		protected void onSubmit() {
			super.onSubmit();
			getUser().setPassword(AppLoader.getInstance(PasswordService.class).encryptPassword(bean.getNewPassword()));
			GitPlex.getInstance(UserManager.class).save(getUser(), null);
			Session.get().success("Password has been changed");

			bean.setOldPassword(null);
			replace(BeanContext.editBean("editor", bean, excludedProperties));
		}

	};
	add(form);
	
	form.add(BeanContext.editBean("editor", bean, excludedProperties));
}
 
Example 22
Project: cas-playground   File: ExamplePage.java   Source Code and License 5 votes vote down vote up
@Override
protected void onInitialize() {
    super.onInitialize();
    Form form1 = new Form("form1") {
        @Override
        protected void onSubmit() {
            success("Success");
            Session.get().invalidateNow();
        }
    };
    form1.add(new FeedbackPanel("feedback", new ComponentFeedbackMessageFilter(form1)));
    add(form1);
    WebMarkupContainer c = new WebMarkupContainer("cont");
    c.setOutputMarkupId(true);
    Form form2 = new Form("form2");
    form2.add(new FeedbackPanel("feedback", new ComponentFeedbackMessageFilter(form2)));
    form2.add(new AjaxSubmitLink("submit") {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            super.onSubmit(target, form);
            form.success("Ajax success");
            target.add(form2);
        }
    });
    c.add(form2);
    add(c);
}
 
Example 23
Project: engerek   File: LookupPropertyModel.java   Source Code and License 5 votes vote down vote up
@Override
public void setObject(T object) {
    final String expression = propertyExpression();

    PropertyResolverConverter prc = new PropertyResolverConverter(Application.get().getConverterLocator(),
            Session.get().getLocale());

    if (object instanceof String) {
        String label = (String) object;
        String key;

        if (StringUtils.isBlank(label)) {
            PropertyResolver.setValue(expression, getInnermostModelOrObject(), null, prc);
        } else {
            if (!isStrict || lookupTable == null) { // set default value from input and overwrite later if key is found
                PropertyResolver.setValue(expression, getInnermostModelOrObject(), label, prc);
            }
            if (lookupTable != null) {
             for (LookupTableRowType row : lookupTable.getRow()) {
                 if (label.equals(WebComponentUtil.getOrigStringFromPoly(row.getLabel()))) {
                     key = row.getKey();
                     PropertyResolver.setValue(expression, getInnermostModelOrObject(), key, prc);
                     if (isSupportsDisplayName()) {
                     	PropertyResolver.setValue("displayName", getInnermostModelOrObject(), label, prc);
                     }
                 }
             }
            }
        }
    } else if (object == null) {
        PropertyResolver.setValue(expression, getInnermostModelOrObject(), object, prc);
    }
}
 
Example 24
Project: engerek   File: SecurityContextAwareCallable.java   Source Code and License 5 votes vote down vote up
protected void setupContext(Application application, Session session) {
	if (!Application.exists() && application != null) {
		ThreadContext.setApplication(application);
	}
	if (!Session.exists() && session != null) {
		ThreadContext.setSession(session);
	}
}
 
Example 25
Project: engerek   File: MainMenuPanel.java   Source Code and License 5 votes vote down vote up
private void menuItemPerformed(MenuItem menu) {
	LOGGER.trace("menuItemPerformed: {}", menu);

    IPageFactory pFactory = Session.get().getPageFactory();
    WebPage page = pFactory.newPage(menu.getPageClass(), menu.getParams());
    if (!(page instanceof PageBase)) {
        setResponsePage(page);
        return;
    }

    PageBase pageBase = (PageBase) page;

    // IMPORTANT: we need to re-bundle the name to a new models
    // that will not be connected to the old page reference
    // otherwise the old page will somehow remain in the memory
    // I have no idea how it could do that and especially how
    // several old pages can remain in memory. But if the model
    // is not re-bundled here then the page size grows and never
    // falls.
    MainMenuItem mainMenuItem = getModelObject();
    String name = mainMenuItem.getNameModel().getObject();
    Breadcrumb bc = new Breadcrumb(new Model<>(name));
    bc.setIcon(new Model<>(mainMenuItem.getIconClass()));
    pageBase.addBreadcrumb(bc);

    List<MenuItem> items = mainMenuItem.getItems();
    if (!items.isEmpty() && mainMenuItem.isInsertDefaultBackBreadcrumb()) {
        MenuItem first = items.get(0);

        IModel<String> nameModel = first.getNameModel();
        BreadcrumbPageClass invisibleBc = new BreadcrumbPageClass(new Model<>(nameModel.getObject()), first.getPageClass(),
                first.getParams());
        invisibleBc.setVisible(false);
        pageBase.addBreadcrumb(invisibleBc);
    }

    setResponsePage(page);
}
 
Example 26
Project: engerek   File: BreadcrumbPageClass.java   Source Code and License 5 votes vote down vote up
@Override
public WebPage redirect() {
    IPageFactory pFactory = Session.get().getPageFactory();
    if (parameters == null) {
        return pFactory.newPage(page);
    } else {
        return pFactory.newPage(page, parameters);
    }
}
 
Example 27
Project: engerek   File: WebComponentUtil.java   Source Code and License 5 votes vote down vote up
public static String formatDate(String format, Date date) {
	if (date == null) {
		return null;
	}

	if (StringUtils.isEmpty(format)) {
		format = "EEEE, d. MMM yyyy HH:mm:ss";
	}
	Locale locale = Session.get().getLocale();
	if (locale == null) {
		locale = Locale.US;
	}
	SimpleDateFormat dateFormat = new SimpleDateFormat(format, locale);
	return dateFormat.format(date);
}
 
Example 28
Project: engerek   File: WebComponentUtil.java   Source Code and License 5 votes vote down vote up
public static Locale getCurrentLocale() {
	Locale locale = Session.get().getLocale();
	if (locale == null) {
		locale = Locale.getDefault();
	}
	return locale;
}
 
Example 29
Project: vlo-curation   File: ConvertedFieldValueModel.java   Source Code and License 5 votes vote down vote up
@Override
public String getObject() {
    final IConverter<String> converter = VloWicketApplication.get().getFieldValueConverterProvider().getConverter(field);
    if (converter == null) {
        logger.warn("No converter for field {}", field);
        return valueModel.getObject();
    } else {
        return converter.convertToString(valueModel.getObject(), Session.get().getLocale());
    }
}
 
Example 30
Project: vlo-curation   File: FormattedStringModel.java   Source Code and License 5 votes vote down vote up
@Override
public String getObject() {
    final String value = valueModel.getObject();
    if (value == null) {
        return null;
    } else {
        return String.format(Session.get().getLocale(), formattingModel.getObject(), value);
    }
}
 
Example 31
Project: vlo-curation   File: FacetFieldValuesProvider.java   Source Code and License 5 votes vote down vote up
protected Locale getLocale() {
    try {
        final Session session = Session.get();
        if (session != null) {
            return session.getLocale();
        }
    } catch (WicketRuntimeException ex) {
        logger.info("No session available, falling back to JVM default locale");
    }
    return Locale.getDefault();
}
 
Example 32
Project: ecpcrm   File: EcpCrmApplication.java   Source Code and License 5 votes vote down vote up
@Override
public Session newSession(final Request request, final Response response) {
    if(!DEMO_MODE_USING_CREDENTIALS_AS_QUERYARGS) {
        return super.newSession(request, response);
    } 
    
    // else demo mode
    final AuthenticatedWebSessionForIsis s = (AuthenticatedWebSessionForIsis) super.newSession(request, response);
    final org.apache.wicket.util.string.StringValue user = request.getRequestParameters().getParameterValue("user");
    final org.apache.wicket.util.string.StringValue password = request.getRequestParameters().getParameterValue("pass");
    s.signIn(user.toString(), password.toString());
    return s;
}
 
Example 33
Project: singular-server   File: AbstractFormPage.java   Source Code and License 5 votes vote down vote up
protected String getUserDisplayName() {
    Session session = Session.get();
    if (session instanceof SingularSession) {
        return SingularSession.get().getUserDetails().getDisplayName();
    }
    return "";
}
 
Example 34
Project: singular-server   File: Menu.java   Source Code and License 5 votes vote down vote up
protected List<ModuleEntity> getSelectedCategoryOrAll() {
    if (SingularSession.exists() && Session.get() instanceof SingularSession) {
        final ModuleEntity categoriaSelecionada = SingularSession.get().getCategoriaSelecionada();
        if (categoriaSelecionada == null && menuService != null) {
            return menuService.getCategories();
        } else {
            return Collections.singletonList(categoriaSelecionada);
        }
    }
    return Collections.emptyList();
}
 
Example 35
Project: Unicorn   File: BPMNTreeTableExpansion.java   Source Code and License 5 votes vote down vote up
public static BPMNTreeTableExpansion get() {
	BPMNTreeTableExpansion expansion = Session.get().getMetaData(BPMNTreeTableExpansion.KEY);
	if (expansion == null) {
		expansion = new BPMNTreeTableExpansion();
		Session.get().setMetaData(BPMNTreeTableExpansion.KEY, expansion);
	}
	return expansion;
}
 
Example 36
Project: Unicorn   File: NotificationPage.java   Source Code and License 5 votes vote down vote up
@Override
protected List<Notification> load() {
	// get User
	final EapUser user = ((AuthenticatedSession) Session.get()).getUser();
	if (user == null) {
		return new ArrayList<Notification>();
	}
	// get Notifications
	final List<Notification> notifications = Notification.findUnseenForUser(user);
	if (notifications == null) {
		return new ArrayList<Notification>();
	}
	return notifications;
}
 
Example 37
Project: Unicorn   File: ProcessInstanceMonitoringTreeTableExpansion.java   Source Code and License 5 votes vote down vote up
public static ProcessInstanceMonitoringTreeTableExpansion get() {
	ProcessInstanceMonitoringTreeTableExpansion expansion = Session.get().getMetaData(ProcessInstanceMonitoringTreeTableExpansion.KEY);
	if (expansion == null) {
		expansion = new ProcessInstanceMonitoringTreeTableExpansion();
		Session.get().setMetaData(ProcessInstanceMonitoringTreeTableExpansion.KEY, expansion);
	}
	return expansion;
}
 
Example 38
Project: Unicorn   File: ProcessInstanceMonitoringTreeTableExpansionModel.java   Source Code and License 5 votes vote down vote up
public static ProcessInstanceMonitoringTreeTableExpansion get() {
	ProcessInstanceMonitoringTreeTableExpansion expansion = Session.get().getMetaData(ProcessInstanceMonitoringTreeTableExpansionModel.KEY);
	if (expansion == null) {
		expansion = new ProcessInstanceMonitoringTreeTableExpansion();
		Session.get().setMetaData(ProcessInstanceMonitoringTreeTableExpansionModel.KEY, expansion);
	}
	return expansion;
}
 
Example 39
Project: Unicorn   File: ProcessAnalysingTreeTableExpansion.java   Source Code and License 5 votes vote down vote up
public static ProcessAnalysingTreeTableExpansion get() {
	ProcessAnalysingTreeTableExpansion expansion = Session.get().getMetaData(ProcessAnalysingTreeTableExpansion.KEY);
	if (expansion == null) {
		expansion = new ProcessAnalysingTreeTableExpansion();
		Session.get().setMetaData(ProcessAnalysingTreeTableExpansion.KEY, expansion);
	}
	return expansion;
}
 
Example 40
Project: Unicorn   File: ProcessAnalysingTreeTableExpansionModel.java   Source Code and License 5 votes vote down vote up
public static ProcessAnalysingTreeTableExpansion get() {
	ProcessAnalysingTreeTableExpansion expansion = Session.get().getMetaData(ProcessAnalysingTreeTableExpansionModel.KEY);
	if (expansion == null) {
		expansion = new ProcessAnalysingTreeTableExpansion();
		Session.get().setMetaData(ProcessAnalysingTreeTableExpansionModel.KEY, expansion);
	}
	return expansion;
}
 
Example 41
Project: Unicorn   File: AbstractEapPage.java   Source Code and License 5 votes vote down vote up
/**
 * Constructor for the {@link AbstractEapPage}. This page constructs the
 * Bootstrap Navbar, adds a feedback panel for status information and the
 * footer.
 */
@SuppressWarnings("unchecked")
public AbstractEapPage() {
	// TODO: richtige URL?!
	// add(new FaviconLink("favicon", "favicon.ico"));

	if (((AuthenticatedSession) Session.get()).getUser() != null) {
		this.logInString = ((AuthenticatedSession) Session.get()).getUser().getName();
	} else {
		this.logInString = "Sign In";
	}

	final Navbar navbar = new Navbar("eapNavBar");
	navbar.fluid();
	navbar.brandName(Model.of(""));
	// TODO: Remove also in backend
	navbar.addComponents(NavbarComponents.transform(Navbar.ComponentPosition.LEFT, new NavbarButton<MainPage>(MainPage.class, Model.of("Home")).setIconType(IconType.home), this.newImportDropDownButton(), this.newProcessingDropDownButton(), new NavbarButton<EventRepository>(EventRepository.class, Model.of("Event Repository")).setIconType(IconType.book), this.newQueriesDropDownButton(), newMonitoringDropDownButton(), new NavbarButton<NotificationPage>(NotificationPage.class, Model.of("Notifications")).setIconType(IconType.envelope), new NavbarButton<Export>(Export.class, Model.of("Export")).setIconType(IconType.download)) // ,
			// newEventProducerDropDownButton())
	);

	navbar.addComponents(NavbarComponents.transform(Navbar.ComponentPosition.RIGHT, new NavbarButton<MainPage>(LoginPage.class, Model.of(this.logInString)).setIconType(IconType.user)));

	this.add(navbar);
	this.addFeedbackPanel();

	// Label footer = new Label("footer", new PropertyModel<String>(this,
	// "footer"));
	// footer.setEscapeModelStrings(false);
	// add(footer);
}
 
Example 42
Project: Unicorn   File: SimulationTreeTableExpansion.java   Source Code and License 5 votes vote down vote up
public static SimulationTreeTableExpansion get() {
	SimulationTreeTableExpansion expansion = Session.get().getMetaData(SimulationTreeTableExpansion.KEY);
	if (expansion == null) {
		expansion = new SimulationTreeTableExpansion();
		Session.get().setMetaData(SimulationTreeTableExpansion.KEY, expansion);
	}
	return expansion;
}
 
Example 43
Project: Unicorn   File: UNICORNApplication.java   Source Code and License 5 votes vote down vote up
/**
 * Initializes the authorization strategy for the web application. Pages,
 * which implement the {@link AuthenticatedWebPage} interface, are only
 * accessible for authenticated users.
 */
private void setAuthorizationStrategy() {
	this.getSecuritySettings().setAuthorizationStrategy(new IAuthorizationStrategy() {

		@Override
		public boolean isActionAuthorized(final Component component, final Action action) {
			// authorize everything
			return true;
		}

		@Override
		public <T extends IRequestableComponent> boolean isInstantiationAuthorized(final Class<T> componentClass) {
			// Check if the new Page requires authentication
			// (implements the marker interface)
			if (AuthenticatedWebPage.class.isAssignableFrom(componentClass)) {
				// Is user signed in?
				if (((AuthenticatedSession) Session.get()).isSignedIn()) {
					// okay to proceed
					return true;
				}

				// Intercept the request, but remember the target
				// for later.
				// Invoke Component.continueToOriginalDestination()
				// after successful logon to
				// continue with the target remembered.

				throw new RestartResponseAtInterceptPageException(LoginPage.class);
			}

			// okay to proceed
			return true;
		}
	});
}
 
Example 44
Project: Unicorn   File: TreeExpansion.java   Source Code and License 5 votes vote down vote up
public static TreeExpansion get() {
	TreeExpansion expansion = Session.get().getMetaData(TreeExpansion.KEY);
	if (expansion == null) {
		expansion = new TreeExpansion();
		Session.get().setMetaData(TreeExpansion.KEY, expansion);
	}
	return expansion;
}
 
Example 45
Project: Unicorn   File: LabelTreeExpansion.java   Source Code and License 5 votes vote down vote up
public LabelTreeExpansion<T> get() {
	LabelTreeExpansion<T> expansion = Session.get().getMetaData(this.KEY);
	if (expansion == null) {
		expansion = new LabelTreeExpansion<T>();
		Session.get().setMetaData(this.KEY, expansion);
	}
	return expansion;
}
 
Example 46
Project: Unicorn   File: AttributeTreeExpansion.java   Source Code and License 5 votes vote down vote up
public static AttributeTreeExpansion get() {
	AttributeTreeExpansion expansion = Session.get().getMetaData(AttributeTreeExpansion.KEY);
	if (expansion == null) {
		expansion = new AttributeTreeExpansion();
		Session.get().setMetaData(AttributeTreeExpansion.KEY, expansion);
	}
	return expansion;
}
 
Example 47
Project: owsi-core-parent   File: NotificationDemoEntry.java   Source Code and License 5 votes vote down vote up
protected final <E extends GenericEntity<Long, ?>> E getFirstInRange(Class<E> clazz, Range<Long> range, Predicate<E> predicate) {
	E entity = getFirstWithId(clazz, ContiguousSet.create(range, DiscreteDomain.longs()), predicate);
	
	if (entity != null) {
		return entity;
	} else {
		LOGGER.error("A demo object is missing for demo " + Classes.simpleName(getClass()));
		Session.get().error(Localizer.get().getString("console.notifications.demo.noDataAvailable", null));
		
		throw ConsoleNotificationDemoIndexPage.linkDescriptor().newRestartResponseException();
	}
}
 
Example 48
Project: owsi-core-parent   File: ZIndexTestModalPopupPanel.java   Source Code and License 5 votes vote down vote up
@Override
protected Component createBody(String wicketId) {
	DelegatedMarkupPanel body = new DelegatedMarkupPanel(wicketId, ZIndexTestModalPopupPanel.class);
	
	// Actuellement, le popover se retrouve derrière le popup car il n'a pas de z-index et que les modal
	// ont un z-index par défaut de 150.
	
	// Popover
	WebMarkupContainer popoverInformation = new WebMarkupContainer("popoverInformation");
	popoverInformation.setOutputMarkupId(true);
	body.add(popoverInformation);
	
	WebMarkupContainer popoverLabel = new WebMarkupContainer("popoverLabel");
	BootstrapPopoverOptions popoverOptions = new BootstrapPopoverOptions();
	popoverOptions.setTitleText(new ResourceModel("widgets.modal.zIndexTest.popover.title").getObject());
	popoverOptions.setContentComponent(popoverInformation);
	popoverOptions.setHtml(true);
	popoverLabel.add(new BootstrapPopoverBehavior(popoverOptions));
	popoverLabel.add(new ClassAttributeAppender(Model.of("popover-btn")));
	body.add(popoverLabel);
	
	body.add(new UserAutocompleteAjaxComponent("autocomplete", new GenericEntityModel<Long, User>(null)));
	
	body.add(new AjaxLink<Void>("feedbackTest") {
		private static final long serialVersionUID = 1L;
		
		@Override
		public void onClick(AjaxRequestTarget target) {
			Session.get().warn(getString("widgets.modal.zIndexTest.feedbackTest.warn"));
			FeedbackUtils.refreshFeedback(target, getPage());
		}
	});
	
	return body;
}
 
Example 49
Project: owsi-core-parent   File: RendererServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public final String localize(final Enum<?> enumValue, final String prefix, final String suffix, final Locale locale) {
	try (ITearDownHandle handle = context().open()) {
		return EnumRenderer.with(prefix, suffix)
				.render(enumValue, locale != null ? locale : Session.get().getLocale());
	}
}
 
Example 50
Project: owsi-core-parent   File: RendererServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public final <T> String localize(final Class<T> clazz, final T value, final Locale locale) {
	try (ITearDownHandle handle = context().open()) {
		return Application.get().getConverterLocator().getConverter(clazz)
				.convertToString(value, locale != null ? locale : Session.get().getLocale());
	}
}
 
Example 51
Project: owsi-core-parent   File: CoreWicketAuthenticatedApplication.java   Source Code and License 5 votes vote down vote up
@Override
public Session newSession(Request request, Response response) {
	try {
		return webSessionClassRef.get().getDeclaredConstructor(Request.class).newInstance(request); // NOSONAR
	} catch (RuntimeException | InstantiationException | IllegalAccessException
			| InvocationTargetException | NoSuchMethodException e) {
		throw new WicketRuntimeException("Unable to instantiate web session " +
			webSessionClassRef.get(), e);
	}
}
 
Example 52
Project: owsi-core-parent   File: CorePageLinkDescriptorImpl.java   Source Code and License 5 votes vote down vote up
protected Class<? extends Page> getValidPageClass() throws LinkInvalidTargetRuntimeException {
	Class<? extends Page> pageClass = pageClassModel.getObject();
	if (pageClass == null) {
		throw new LinkInvalidTargetRuntimeException("The target page of this ILinkDescriptor was null");
	}
	if (! bypassPermissions) {
		if (!Session.get().getAuthorizationStrategy().isInstantiationAuthorized(pageClass)) {
			throw new LinkInvalidTargetRuntimeException("The instantiation of the target page class '" + pageClass
					+ "' was not authorized when trying to render the URL.");
		}
	}
	return pageClass;
}
 
Example 53
Project: owsi-core-parent   File: CorePageLinkDescriptorImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void extractSafely(PageParameters parameters, IPageLinkGenerator fallbackLink, String errorMessage)
		throws RestartResponseException {
	try {
		extract(parameters);
	} catch (RuntimeException | LinkParameterSerializedFormValidationException |
			LinkParameterModelValidationException e) {
		EXTRACTOR_INTERFACE_LOGGER.error("Error while extracting page parameters", e);
		if (StringUtils.hasText(errorMessage)) {
			Session.get().error(errorMessage);
		}
		throw fallbackLink.newRestartResponseException();
	}
}
 
Example 54
Project: owsi-core-parent   File: CorePageLinkDescriptorImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void checkModelsSafely(IPageLinkGenerator fallbackLink, String errorMessage) {
	try {
		checkModels();
	} catch (RuntimeException | LinkParameterModelValidationException e) {
		EXTRACTOR_INTERFACE_LOGGER.error("Error while extracting page parameters", e);
		if (StringUtils.hasText(errorMessage)) {
			Session.get().error(errorMessage);
		}
		throw fallbackLink.newRestartResponseException();
	}
}
 
Example 55
Project: owsi-core-parent   File: CorePageInstanceLinkGenerator.java   Source Code and License 5 votes vote down vote up
@Override
public boolean isAccessible() {
	Page pageInstance = pageInstanceModel.getObject();
	if (pageInstance == null) {
		return false;
	}
	Class<? extends Page> validPageClass = getValidExpectedPageClass(pageInstance);
	if (validPageClass == null) {
		return false;
	}
	return Session.get().getAuthorizationStrategy().isActionAuthorized(pageInstance, Page.RENDER);
}
 
Example 56
Project: owsi-core-parent   File: GenericEntityRendererToChoiceRenderer.java   Source Code and License 5 votes vote down vote up
public static <E extends GenericEntity<?, ?>>
		AbstractGenericEntityChoiceRenderer<E> of(final Renderer<E> renderer) {
	return new AbstractGenericEntityChoiceRenderer<E>() {
		private static final long serialVersionUID = 1L;
		@Override
		public Object getDisplayValue(E value) {
			return renderer.render(value, Session.get().getLocale());
		}
	};
}
 
Example 57
Project: owsi-core-parent   File: GenericEntityRendererToChoiceRenderer.java   Source Code and License 5 votes vote down vote up
public static <E extends GenericEntity<?, ?>>
		AbstractGenericEntityChoiceRenderer<E> ofWildcardRenderer(final Renderer<? super E> renderer) {
	return new AbstractGenericEntityChoiceRenderer<E>() {
		private static final long serialVersionUID = 1L;
		@Override
		public Object getDisplayValue(E value) {
			return renderer.render(value, Session.get().getLocale());
		}
	};
}
 
Example 58
Project: owsi-core-parent   File: BooleanDropDownSingleChoice.java   Source Code and License 5 votes vote down vote up
@Override
public Object getDisplayValue(Boolean object) {
	if (StringUtils.hasText(prefix)) {
		return BooleanRenderer.withPrefix(prefix).render(object, Session.get().getLocale());
	} else {
		return BooleanRenderer.get().render(object, Session.get().getLocale());
	}
}
 
Example 59
Project: owsi-core-parent   File: EnumDropDownSingleChoice.java   Source Code and License 5 votes vote down vote up
@Override
public Object getDisplayValue(E object) {
	// This converter adds the enum value as a model parameter when rendering the resource key, which
	// enables the rendering of properties of the enum value
	// (DateEnum.TOMORROW being rendered as "Tomorrow (${date})" with DateEnum implementing getDate(), for instance).
	return EnumRenderer.get().render(object, Session.get().getLocale());
}
 
Example 60
Project: owsi-core-parent   File: AbstractNotificationContentDescriptorFactory.java   Source Code and License 5 votes vote down vote up
private Locale getDefaultLocale() {
	if (Session.exists()) {
		return Session.get().getLocale();
	} else {
		return propertyService.get(SpringPropertyIds.DEFAULT_LOCALE);
	}
}