Search in sources :

Example 6 with IStringResourceLoader

use of org.apache.wicket.resource.loader.IStringResourceLoader in project wicket by apache.

the class Localizer method getStringIgnoreSettings.

/**
 * This is similar to {@link #getString(String, Component, IModel, String)} except that the
 * resource settings are ignored. This allows to to code something like
 *
 * <pre>
 * String option = getLocalizer().getStringIgnoreSettings(getId() + &quot;.null&quot;, this, &quot;&quot;);
 * if (Strings.isEmpty(option))
 * {
 * 	option = getLocalizer().getString(&quot;null&quot;, this, CHOOSE_ONE);
 * }
 * </pre>
 *
 * @param key
 *            The key to obtain the resource for
 * @param component
 *            The component to get the resource for (optional)
 * @param model
 *            The model to use for substitutions in the strings (optional)
 * @param locale
 *            If != null, it'll supersede the component's locale
 * @param style
 *            If != null, it'll supersede the component's style
 * @param defaultValue
 *            The default value (optional)
 * @return The string resource
 */
public String getStringIgnoreSettings(final String key, final Component component, final IModel<?> model, Locale locale, String style, final String defaultValue) {
    boolean addedToPage = false;
    if (component != null) {
        if ((component instanceof Page) || (null != component.findParent(Page.class))) {
            addedToPage = true;
        }
        if (!addedToPage && log.isWarnEnabled()) {
            log.warn("Tried to retrieve a localized string for a component that has not yet been added to the page. " + "This can sometimes lead to an invalid or no localized resource returned. " + "Make sure you are not calling Component#getString() inside your Component's constructor. " + "Offending component: {}", component);
        }
    }
    String cacheKey = null;
    String value;
    // Make sure locale, style and variation have the right values
    String variation = (component != null ? component.getVariation() : null);
    if ((locale == null) && (component != null)) {
        locale = component.getLocale();
    }
    if (locale == null) {
        locale = Session.exists() ? Session.get().getLocale() : Locale.getDefault();
    }
    if ((style == null) && (component != null)) {
        style = component.getStyle();
    }
    if (style == null) {
        style = Session.exists() ? Session.get().getStyle() : null;
    }
    // cache as we can generate an invalid cache key
    if ((cache != null) && ((component == null) || addedToPage)) {
        cacheKey = getCacheKey(key, component, locale, style, variation);
    }
    // Value not found are cached as well (value = null)
    if ((cacheKey != null) && cache.containsKey(cacheKey)) {
        value = getFromCache(cacheKey);
        if (log.isDebugEnabled()) {
            log.debug("Property found in cache: '" + key + "'; Component: '" + (component != null ? component.toString(false) : null) + "'; value: '" + value + '\'');
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Locate property: key: '" + key + "'; Component: '" + (component != null ? component.toString(false) : null) + '\'');
        }
        // Iterate over all registered string resource loaders until the property has been found
        Iterator<IStringResourceLoader> iter = getStringResourceLoaders().iterator();
        value = null;
        while (iter.hasNext() && (value == null)) {
            IStringResourceLoader loader = iter.next();
            value = loader.loadStringResource(component, key, locale, style, variation);
        }
        // Cache the result incl null if not found
        if (cacheKey != null) {
            putIntoCache(cacheKey, value);
        }
        if ((value == null) && log.isDebugEnabled()) {
            log.debug("Property not found; key: '" + key + "'; Component: '" + (component != null ? component.toString(false) : null) + '\'');
        }
    }
    if (value == null) {
        value = defaultValue;
    }
    // then replace the placeholder and we are done
    if (value != null) {
        return substitutePropertyExpressions(component, value, model);
    }
    return null;
}
Also used : IStringResourceLoader(org.apache.wicket.resource.loader.IStringResourceLoader)

Example 7 with IStringResourceLoader

use of org.apache.wicket.resource.loader.IStringResourceLoader in project wicket by apache.

the class ApplicationSettingsTest method testOverrideStringResourceLoaderSetup.

/**
 */
@Test
public void testOverrideStringResourceLoaderSetup() {
    ResourceSettings settings = new ResourceSettings(new MockApplication());
    settings.getStringResourceLoaders().clear();
    settings.getStringResourceLoaders().add(new BundleStringResourceLoader("org.apache.wicket.resource.DummyResources"));
    settings.getStringResourceLoaders().add(new ComponentStringResourceLoader());
    List<IStringResourceLoader> loaders = settings.getStringResourceLoaders();
    Assert.assertEquals("There should be 2 overridden loaders", 2, loaders.size());
    Assert.assertTrue("First loader one should be the bundle one", loaders.get(0) instanceof BundleStringResourceLoader);
    Assert.assertTrue("Second loader should be the component one", loaders.get(1) instanceof ComponentStringResourceLoader);
}
Also used : ComponentStringResourceLoader(org.apache.wicket.resource.loader.ComponentStringResourceLoader) MockApplication(org.apache.wicket.mock.MockApplication) ResourceSettings(org.apache.wicket.settings.ResourceSettings) IStringResourceLoader(org.apache.wicket.resource.loader.IStringResourceLoader) BundleStringResourceLoader(org.apache.wicket.resource.loader.BundleStringResourceLoader) Test(org.junit.Test)

Example 8 with IStringResourceLoader

use of org.apache.wicket.resource.loader.IStringResourceLoader in project wicket by apache.

the class BundleStringResourceLoaderTest method loaderUnknownResources.

/**
 * @see org.apache.wicket.resource.StringResourceLoaderTestBase#testLoaderUnknownResources()
 */
@Override
@Test
public void loaderUnknownResources() {
    IStringResourceLoader loader = new BundleStringResourceLoader("unknown.resource");
    assertNull("Unknown resource should return null", loader.loadStringResource(component.getClass(), "test.string", Locale.getDefault(), null, null));
}
Also used : IStringResourceLoader(org.apache.wicket.resource.loader.IStringResourceLoader) BundleStringResourceLoader(org.apache.wicket.resource.loader.BundleStringResourceLoader) Test(org.junit.Test)

Example 9 with IStringResourceLoader

use of org.apache.wicket.resource.loader.IStringResourceLoader in project wicket by apache.

the class ComponentStringResourceLoaderTest method searchClassHierarchyFromPage.

/**
 */
@Test
public void searchClassHierarchyFromPage() {
    DummySubClassPage p = new DummySubClassPage();
    IStringResourceLoader loader = new ComponentStringResourceLoader();
    assertEquals("Valid resource string should be found", "SubClass Test String", loader.loadStringResource(p.getClass(), "subclass.test.string", Locale.getDefault(), null, null));
    assertEquals("Valid resource string should be found", "Another string", loader.loadStringResource(p.getClass(), "another.test.string", Locale.getDefault(), null, null));
}
Also used : ComponentStringResourceLoader(org.apache.wicket.resource.loader.ComponentStringResourceLoader) IStringResourceLoader(org.apache.wicket.resource.loader.IStringResourceLoader) Test(org.junit.Test)

Example 10 with IStringResourceLoader

use of org.apache.wicket.resource.loader.IStringResourceLoader in project midpoint by Evolveum.

the class MidPointApplication method init.

@Override
public void init() {
    super.init();
    getCspSettings().blocking().disabled();
    getJavaScriptLibrarySettings().setJQueryReference(new PackageResourceReference(MidPointApplication.class, // todo no jquery.js is found
    "../../../../../webjars/AdminLTE/2.4.18/bower_components/jquery/dist/jquery.min.js"));
    getComponentInstantiationListeners().add(new SpringComponentInjector(this, applicationContext, true));
    systemConfigurationChangeDispatcher.registerListener(new DeploymentInformationChangeListener(this));
    SystemConfigurationType config = getSystemConfigurationIfAvailable();
    if (config != null) {
        deploymentInfo = config.getDeploymentInformation();
    }
    ResourceSettings resourceSettings = getResourceSettings();
    resourceSettings.setParentFolderPlaceholder("$-$");
    resourceSettings.setHeaderItemComparator(new PriorityFirstComparator(true));
    SecurePackageResourceGuard guard = (SecurePackageResourceGuard) resourceSettings.getPackageResourceGuard();
    guard.addPattern("+*.woff2");
    List<IStringResourceLoader> resourceLoaders = resourceSettings.getStringResourceLoaders();
    resourceLoaders.add(0, new MidPointStringResourceLoader(localizationService));
    IResourceStreamLocator locator = new CachingResourceStreamLocator(new MidPointResourceStreamLocator(resourceSettings.getResourceFinders()));
    resourceSettings.setResourceStreamLocator(locator);
    resourceSettings.setThrowExceptionOnMissingResource(false);
    getMarkupSettings().setStripWicketTags(true);
    getMarkupSettings().setStripComments(true);
    if (RuntimeConfigurationType.DEVELOPMENT.equals(getConfigurationType())) {
        getDebugSettings().setAjaxDebugModeEnabled(true);
        getDebugSettings().setDevelopmentUtilitiesEnabled(true);
        initializeDevelopmentSerializers();
        mount(new MountedMapper("/inspector", InspectorPage.class, new PageParametersEncoder()));
        mount(new MountedMapper("/liveSession", LiveSessionsPage.class, new PageParametersEncoder()));
        mount(new MountedMapper("/pageStore", PageStorePage.class, new PageParametersEncoder()));
    }
    // pretty url for resources (e.g. images)
    mountFiles(ImgResources.BASE_PATH, ImgResources.class);
    // exception handling an error pages
    ApplicationSettings appSettings = getApplicationSettings();
    appSettings.setAccessDeniedPage(PageError401.class);
    appSettings.setInternalErrorPage(PageError.class);
    appSettings.setPageExpiredErrorPage(PageError.class);
    mount(new MountedMapper(MOUNT_INTERNAL_SERVER_ERROR, PageError.class, new PageParametersEncoder()));
    mount(new MountedMapper(MOUNT_UNAUTHORIZED_ERROR, PageError401.class, new PageParametersEncoder()));
    mount(new MountedMapper(MOUNT_FORBIDEN_ERROR, PageError403.class, new PageParametersEncoder()));
    mount(new MountedMapper(MOUNT_NOT_FOUND_ERROR, PageError404.class, new PageParametersEncoder()));
    mount(new MountedMapper(MOUNT_GONE_ERROR, PageError410.class, new PageParametersEncoder()));
    getRequestCycleListeners().add(new LoggingRequestCycleListener(this));
    getAjaxRequestTargetListeners().add(new AjaxRequestTarget.IListener() {

        @Override
        public void updateAjaxAttributes(AbstractDefaultAjaxBehavior behavior, AjaxRequestAttributes attributes) {
            // check whether behavior will use POST method, if not then don't put CSRF token there
            if (!isPostMethodTypeBehavior(behavior, attributes)) {
                return;
            }
            CsrfToken csrfToken = SecurityUtils.getCsrfToken();
            if (csrfToken == null) {
                return;
            }
            String parameterName = csrfToken.getParameterName();
            String value = csrfToken.getToken();
            attributes.getExtraParameters().put(parameterName, value);
        }
    });
    getSessionListeners().add((ISessionListener) asyncWebProcessManager);
    // descriptor loader, used for customization
    new PageMounter().loadData(this);
    descriptorLoader.loadData();
    if (applicationContext != null) {
        Map<String, MidPointApplicationConfiguration> map = applicationContext.getBeansOfType(MidPointApplicationConfiguration.class);
        if (map != null) {
            map.forEach((key, value) -> value.init(this));
        }
    }
    // for schrodinger selenide library
    initializeSchrodinger();
    ServletContext servletContext = getServletContext();
    if (servletContext != null) {
        taskManager.setWebContextPath(servletContext.getContextPath());
    }
}
Also used : CachingResourceStreamLocator(org.apache.wicket.core.util.resource.locator.caching.CachingResourceStreamLocator) MountedMapper(org.apache.wicket.core.request.mapper.MountedMapper) MidPointResourceStreamLocator(com.evolveum.midpoint.web.util.MidPointResourceStreamLocator) IResourceStreamLocator(org.apache.wicket.core.util.resource.locator.IResourceStreamLocator) InspectorPage(org.apache.wicket.devutils.inspector.InspectorPage) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) PriorityFirstComparator(org.apache.wicket.markup.head.PriorityFirstComparator) MidPointStringResourceLoader(com.evolveum.midpoint.web.util.MidPointStringResourceLoader) AbstractDefaultAjaxBehavior(org.apache.wicket.ajax.AbstractDefaultAjaxBehavior) PackageResourceReference(org.apache.wicket.request.resource.PackageResourceReference) IStringResourceLoader(org.apache.wicket.resource.loader.IStringResourceLoader) ServletContext(javax.servlet.ServletContext) LiveSessionsPage(org.apache.wicket.devutils.inspector.LiveSessionsPage) MidPointApplicationConfiguration(com.evolveum.midpoint.gui.api.util.MidPointApplicationConfiguration) PageStorePage(org.apache.wicket.devutils.pagestore.PageStorePage) CsrfToken(org.springframework.security.web.csrf.CsrfToken) PageMounter(com.evolveum.midpoint.web.application.PageMounter) AjaxRequestTarget(org.apache.wicket.ajax.AjaxRequestTarget) AjaxRequestAttributes(org.apache.wicket.ajax.attributes.AjaxRequestAttributes) ApplicationSettings(org.apache.wicket.settings.ApplicationSettings) SecurePackageResourceGuard(org.apache.wicket.markup.html.SecurePackageResourceGuard) ResourceSettings(org.apache.wicket.settings.ResourceSettings) SystemConfigurationType(com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType) PageParametersEncoder(org.apache.wicket.request.mapper.parameter.PageParametersEncoder) SpringComponentInjector(org.apache.wicket.spring.injection.annot.SpringComponentInjector)

Aggregations

IStringResourceLoader (org.apache.wicket.resource.loader.IStringResourceLoader)10 Test (org.junit.Test)7 ComponentStringResourceLoader (org.apache.wicket.resource.loader.ComponentStringResourceLoader)6 ResourceSettings (org.apache.wicket.settings.ResourceSettings)3 MockApplication (org.apache.wicket.mock.MockApplication)2 BundleStringResourceLoader (org.apache.wicket.resource.loader.BundleStringResourceLoader)2 MidPointApplicationConfiguration (com.evolveum.midpoint.gui.api.util.MidPointApplicationConfiguration)1 PolyString (com.evolveum.midpoint.prism.polystring.PolyString)1 PageMounter (com.evolveum.midpoint.web.application.PageMounter)1 MidPointResourceStreamLocator (com.evolveum.midpoint.web.util.MidPointResourceStreamLocator)1 MidPointStringResourceLoader (com.evolveum.midpoint.web.util.MidPointStringResourceLoader)1 SystemConfigurationType (com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType)1 ArrayList (java.util.ArrayList)1 ServletContext (javax.servlet.ServletContext)1 Component (org.apache.wicket.Component)1 AbstractDefaultAjaxBehavior (org.apache.wicket.ajax.AbstractDefaultAjaxBehavior)1 AjaxRequestTarget (org.apache.wicket.ajax.AjaxRequestTarget)1 AjaxRequestAttributes (org.apache.wicket.ajax.attributes.AjaxRequestAttributes)1 MountedMapper (org.apache.wicket.core.request.mapper.MountedMapper)1 IResourceStreamLocator (org.apache.wicket.core.util.resource.locator.IResourceStreamLocator)1