Example usage for org.apache.wicket.core.util.resource.locator IResourceStreamLocator locate

List of usage examples for org.apache.wicket.core.util.resource.locator IResourceStreamLocator locate

Introduction

In this page you can find the example usage for org.apache.wicket.core.util.resource.locator IResourceStreamLocator locate.

Prototype

IResourceStream locate(Class<?> clazz, String path);

Source Link

Document

Locate a resource, given a path and class.

Usage

From source file:com.swordlord.gozer.util.ResourceLoader.java

License:Open Source License

/**
 * Loads a resource using the {@link Application}s
 * {@link IResourceStreamLocator}./* ww  w  .  j a va2  s.co m*/
 * 
 * @param application
 *            The application
 * @param filename
 *            The normalized name/path of the file to load (after being
 *            passed to {@link #prepareFileName(String)})
 * @param clazz
 *            The class loader for delegating the loading of the resource
 * @return The input stream
 * @throws IOException
 *             If no such resource could be found
 */
private static InputStream loadResource0(Application application, String filename, Class clazz)
        throws IOException {
    final IResourceStreamLocator locator = application.getResourceSettings().getResourceStreamLocator();
    final IResourceStream resource = locator.locate(clazz, filename);
    if (resource == null) {
        throw new IOException("Error while loading " + filename + " from classpath - no such entry found");
    }
    try {
        return resource.getInputStream();
    } catch (ResourceStreamNotFoundException e) {
        throw new IOException("Error while loading " + filename + " from classpath", e);
    }
}

From source file:org.hippoecm.frontend.editor.builder.PreviewClusterConfig.java

License:Apache License

protected String getPluginConfigEditorClass(String pluginClass) {
    if (pluginClass == null) {
        return null;
    }// w  w w  . j av  a 2  s.  co  m
    try {
        Class<?> clazz = Class.forName(pluginClass);
        if (AbstractFieldPlugin.class.isAssignableFrom(clazz)) {
            return FieldPluginEditorPlugin.class.getName();
        } else if (MixinLoaderPlugin.class.isAssignableFrom(clazz)) {
            return MixinLoaderPluginEditorPlugin.class.getName();
        } else if (ListViewPlugin.class.isAssignableFrom(clazz)) {
            return ListViewPluginEditorPlugin.class.getName();
        } else if (RenderPlugin.class.isAssignableFrom(clazz)) {
            return RenderPluginEditorPlugin.class.getName();
        }
    } catch (ClassNotFoundException ex) {
        IResourceSettings resourceSettings = Application.get().getResourceSettings();
        IResourceStreamLocator locator = resourceSettings.getResourceStreamLocator();
        IResourceStream stream = locator.locate(null, pluginClass.replace('.', '/') + ".html");
        if (stream == null) {
            String message = ex.getClass().getName() + ": " + ex.getMessage();
            log.error(message, ex);
        } else {
            return LayoutPluginEditorPlugin.class.getName();
        }
    }
    return null;
}

From source file:org.hippoecm.frontend.Main.java

License:Apache License

@Override
protected void init() {
    super.init();

    addRequestCycleListeners();/*from www.ja v  a2 s.  c  o m*/

    registerSessionListeners();

    getPageSettings().setVersionPagesByDefault(false);
    //        getPageSettings().setAutomaticMultiWindowSupport(false);

    //        getSessionSettings().setPageMapEvictionStrategy(new LeastRecentlyAccessedEvictionStrategy(1));

    getApplicationSettings().setPageExpiredErrorPage(PageExpiredErrorPage.class);
    try {
        String cfgParam = getConfigurationParameter(MAXUPLOAD_PARAM, null);
        if (cfgParam != null && cfgParam.trim().length() > 0) {
            getApplicationSettings().setDefaultMaximumUploadSize(Bytes.valueOf(cfgParam));
        }
    } catch (StringValueConversionException ex) {
        log.warn("Unable to parse number as specified by " + MAXUPLOAD_PARAM, ex);
    }
    final IClassResolver originalResolver = getApplicationSettings().getClassResolver();
    getApplicationSettings().setClassResolver(new IClassResolver() {

        @Override
        public Class resolveClass(String name) throws ClassNotFoundException {
            if (Session.exists()) {
                UserSession session = UserSession.get();
                ClassLoader loader = session.getClassLoader();
                if (loader != null) {
                    return session.getClassLoader().loadClass(name);
                }
            }
            return originalResolver.resolveClass(name);
        }

        @Override
        public Iterator<URL> getResources(String name) {
            List<URL> resources = new LinkedList<>();
            for (Iterator<URL> iter = originalResolver.getResources(name); iter.hasNext();) {
                resources.add(iter.next());
            }
            if (Session.exists()) {
                UserSession session = UserSession.get();
                ClassLoader loader = session.getClassLoader();
                if (loader != null) {
                    try {
                        for (Enumeration<URL> resourceEnum = session.getClassLoader()
                                .getResources(name); resourceEnum.hasMoreElements();) {
                            resources.add(resourceEnum.nextElement());
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            return resources.iterator();
        }

        @Override
        public ClassLoader getClassLoader() {
            return Main.class.getClassLoader();
        }
    });

    final IResourceSettings resourceSettings = getResourceSettings();

    // replace current loaders with own list, starting with component-specific
    List<IStringResourceLoader> loaders = resourceSettings.getStringResourceLoaders();
    loaders.add(new ClassFromKeyStringResourceLoader());
    loaders.add(new IStringResourceLoader() {

        @Override
        public String loadStringResource(final Class<?> clazz, final String key, final Locale locale,
                final String style, final String variation) {
            return null;
        }

        @Override
        public String loadStringResource(final Component component, String key, final Locale locale,
                final String style, final String variation) {
            if (key.contains(",")) {
                key = key.substring(0, key.lastIndexOf(','));
                return resourceSettings.getLocalizer().getStringIgnoreSettings(key, component, null, locale,
                        style, variation);
            }
            return null;
        }
    });

    if (RuntimeConfigurationType.DEVELOPMENT.equals(getConfigurationType())) {
        resourceSettings.setCachingStrategy(new NoOpResourceCachingStrategy());
    } else {
        resourceSettings.setCachingStrategy(
                new FilenameWithVersionResourceCachingStrategy(new LastModifiedResourceVersion()));
    }

    mount(new MountMapper("binaries", new IMountedRequestMapper() {

        @Override
        public IRequestHandler mapRequest(final Request request, final MountParameters mountParams) {
            String path = Strings.join("/", request.getUrl().getSegments());
            try {
                javax.jcr.Session subSession = UserSession.get().getJcrSession();
                Node node = ((HippoWorkspace) subSession.getWorkspace()).getHierarchyResolver()
                        .getNode(subSession.getRootNode(), path);
                // YUCK: no exception!
                if (node == null) {
                    log.info("no binary found at " + path);
                } else {
                    if (node.isNodeType(HippoNodeType.NT_DOCUMENT)) {
                        node = (Node) JcrHelper.getPrimaryItem(node);
                    }
                    return new JcrResourceRequestHandler(node);
                }
            } catch (PathNotFoundException e) {
                log.info("binary not found " + e.getMessage());
            } catch (javax.jcr.LoginException ex) {
                log.warn(ex.getMessage());
            } catch (RepositoryException ex) {
                log.error(ex.getMessage());
            }
            return null;
        }

        @Override
        public int getCompatibilityScore(final Request request) {
            return 1;
        }

        @Override
        public Mount mapHandler(final IRequestHandler requestHandler) {
            return null;
        }
    }));

    String applicationName = getPluginApplicationName();

    if (PLUGIN_APPLICATION_VALUE_CMS.equals(applicationName)) {

        // the following is only applicable and needed for the CMS application, not the Console

        /*
         * HST SAML kind of authentication handler needed for Template Composer integration
         *
         */
        cmsContextService = (CmsInternalCmsContextService) HippoServiceRegistry
                .getService(CmsContextService.class);
        if (cmsContextService == null) {
            cmsContextServiceImpl = new CmsContextServiceImpl();
            cmsContextService = cmsContextServiceImpl;
            HippoServiceRegistry.registerService(cmsContextServiceImpl,
                    new Class[] { CmsContextService.class, CmsInternalCmsContextService.class });
        }
        mount(new MountMapper("auth", new IMountedRequestMapper() {

            @Override
            public IRequestHandler mapRequest(final Request request, final MountParameters mountParams) {

                IRequestHandler requestTarget = new RenderPageRequestHandler(
                        new PageProvider(getHomePage(), null), RedirectPolicy.AUTO_REDIRECT);

                IRequestParameters requestParameters = request.getRequestParameters();
                final List<StringValue> cmsCSIDParams = requestParameters.getParameterValues("cmsCSID");
                final List<StringValue> destinationPathParams = requestParameters
                        .getParameterValues("destinationPath");
                final String destinationPath = destinationPathParams != null && !destinationPathParams.isEmpty()
                        ? destinationPathParams.get(0).toString()
                        : null;

                PluginUserSession userSession = (PluginUserSession) Session.get();
                final UserCredentials userCredentials = userSession.getUserCredentials();

                HttpSession httpSession = ((ServletWebRequest) request).getContainerRequest().getSession();
                final CmsSessionContext cmsSessionContext = CmsSessionContext.getContext(httpSession);

                if (destinationPath != null && destinationPath.startsWith("/")
                        && (cmsSessionContext != null || userCredentials != null)) {

                    requestTarget = new IRequestHandler() {

                        @Override
                        public void respond(IRequestCycle requestCycle) {
                            String destinationUrl = RequestUtils.getFarthestUrlPrefix(request)
                                    + destinationPath;
                            WebResponse response = (WebResponse) RequestCycle.get().getResponse();
                            String cmsCSID = cmsCSIDParams == null ? null
                                    : cmsCSIDParams.get(0) == null ? null : cmsCSIDParams.get(0).toString();
                            if (!cmsContextService.getId().equals(cmsCSID)) {
                                // redirect to destinationURL and include marker that it is a retry. This way
                                // the destination can choose to not redirect for SSO handshake again if it still does not
                                // have a key
                                if (destinationUrl.contains("?")) {
                                    response.sendRedirect(destinationUrl + "&retry");
                                } else {
                                    response.sendRedirect(destinationUrl + "?retry");
                                }
                                return;
                            }
                            String cmsSessionContextId = cmsSessionContext != null ? cmsSessionContext.getId()
                                    : null;
                            if (cmsSessionContextId == null) {
                                CmsSessionContext newCmsSessionContext = cmsContextService.create(httpSession);
                                CmsSessionUtil.populateCmsSessionContext(cmsContextService,
                                        newCmsSessionContext, userSession);
                                cmsSessionContextId = newCmsSessionContext.getId();

                            }
                            if (destinationUrl.contains("?")) {
                                response.sendRedirect(destinationUrl + "&cmsCSID=" + cmsContextService.getId()
                                        + "&cmsSCID=" + cmsSessionContextId);
                            } else {
                                response.sendRedirect(destinationUrl + "?cmsCSID=" + cmsContextService.getId()
                                        + "&cmsSCID=" + cmsSessionContextId);
                            }
                        }

                        @Override
                        public void detach(IRequestCycle requestCycle) {
                            //Nothing to detach.
                        }
                    };
                }
                return requestTarget;
            }

            @Override
            public int getCompatibilityScore(final Request request) {
                return 0;
            }

            @Override
            public Mount mapHandler(final IRequestHandler requestHandler) {
                return null;
            }
        }));
    }

    // caching resource stream locator implementation that allows the class argument to be null.
    final IResourceStreamLocator resourceStreamLocator = resourceSettings.getResourceStreamLocator();
    resourceSettings.setResourceStreamLocator(new IResourceStreamLocator() {
        @Override
        public IResourceStream locate(Class<?> clazz, final String path) {
            if (clazz == null) {
                clazz = CACHING_RESOURCE_STREAM_LOCATOR_CLASS;
            }
            return resourceStreamLocator.locate(clazz, path);
        }

        @Override
        public IResourceStream locate(Class<?> clazz, final String path, final String style,
                final String variation, final Locale locale, final String extension, final boolean strict) {
            if (clazz == null) {
                clazz = CACHING_RESOURCE_STREAM_LOCATOR_CLASS;
            }
            return resourceStreamLocator.locate(clazz, path, style, variation, locale, extension, strict);
        }

        @Override
        public IResourceNameIterator newResourceNameIterator(final String path, final Locale locale,
                final String style, final String variation, final String extension, final boolean strict) {
            return resourceStreamLocator.newResourceNameIterator(path, locale, style, variation, extension,
                    strict);
        }
    });

    if (RuntimeConfigurationType.DEVELOPMENT.equals(getConfigurationType())) {
        // disable cache
        resourceSettings.getLocalizer().setEnableCache(false);

        final long timeout = NumberUtils.toLong(
                getConfigurationParameter(DEVELOPMENT_REQUEST_TIMEOUT_PARAM, null),
                DEFAULT_DEVELOPMENT_REQUEST_TIMEOUT_MS);

        if (timeout > 0L) {
            log.info("Setting wicket request timeout to {} ms.", timeout);
            getRequestCycleSettings().setTimeout(Duration.milliseconds(timeout));
        }

        // render comments with component class names
        getDebugSettings().setOutputMarkupContainerClassName(true);

        // do not render Wicket-specific markup since it can break CSS
        getMarkupSettings().setStripWicketTags(true);
    } else {
        // don't serialize pages for performance
        setPageManagerProvider(new DefaultPageManagerProvider(this) {

            @Override
            protected IPageStore newPageStore(final IDataStore dataStore) {
                return new AmnesicPageStore();
            }
        });

        // don't throw on missing resource
        resourceSettings.setThrowExceptionOnMissingResource(false);

        // don't show exception page
        getExceptionSettings().setUnexpectedExceptionDisplay(IExceptionSettings.SHOW_NO_EXCEPTION_PAGE);

        final long timeout = NumberUtils
                .toLong(getConfigurationParameter(DEPLOYMENT_REQUEST_TIMEOUT_PARAM, null));

        if (timeout > 0L) {
            log.info("Setting wicket request timeout to {} ms.", timeout);
            getRequestCycleSettings().setTimeout(Duration.milliseconds(timeout));
        }
    }

    String outputWicketpaths = obtainOutputWicketPathsParameter();

    if (outputWicketpaths != null && "true".equalsIgnoreCase(outputWicketpaths)) {
        getDebugSettings().setOutputComponentPath(true);
    }

    final IContextProvider<AjaxRequestTarget, Page> ajaxRequestTargetProvider = getAjaxRequestTargetProvider();
    setAjaxRequestTargetProvider(context -> new PluginRequestTarget(ajaxRequestTargetProvider.get(context)));

    setPageRendererProvider(new IPageRendererProvider() {

        @Override
        public PageRenderer get(final RenderPageRequestHandler context) {
            return new WebPageRenderer(context) {

                @Override
                protected BufferedWebResponse renderPage(final Url targetUrl, final RequestCycle requestCycle) {
                    IRequestHandler scheduled = requestCycle.getRequestHandlerScheduledAfterCurrent();
                    if (scheduled == null) {
                        IRequestablePage page = getPage();
                        if (page instanceof Home) {
                            Home home = (Home) page;
                            home.processEvents();
                            home.render(null);
                        }
                    }
                    return super.renderPage(targetUrl, requestCycle);
                }
            };
        }
    });

    // don't allow public access to any package resource (empty whitelist) by default
    resourceSettings.setPackageResourceGuard(new WhitelistedClassesResourceGuard());

    if (log.isInfoEnabled()) {
        log.info("Hippo CMS application " + applicationName + " has started");
    }
}

From source file:org.hippoecm.frontend.plugin.impl.PluginFactory.java

License:Apache License

public IPlugin createPlugin(PluginContext context, IPluginConfig config) {
    String className = config.getString(IPlugin.CLASSNAME);
    IPlugin plugin = null;/*  w  w w.j  av  a  2s . c  o m*/
    String message = null;
    if (className == null) {
        message = "No plugin classname configured, please set plugin configuration parameter "
                + IPlugin.CLASSNAME;
    } else {
        className = className.trim();
        ClassLoader loader = UserSession.get().getClassLoader();
        if (loader == null) {
            log.info("Unable to retrieve repository classloader, falling back to default classloader.");
            loader = getClass().getClassLoader();
        }
        try {
            @SuppressWarnings("unchecked")
            Class<? extends IPlugin> clazz = (Class<? extends IPlugin>) Class.forName(className, true, loader);
            Class<?>[] formalArgs = new Class[] { IPluginContext.class, IPluginConfig.class };
            Constructor<? extends IPlugin> constructor = clazz.getConstructor(formalArgs);
            Object[] actualArgs = new Object[] { context, config };
            plugin = constructor.newInstance(actualArgs);

        } catch (ClassNotFoundException e) {
            IResourceSettings resourceSettings = Application.get().getResourceSettings();
            IResourceStreamLocator locator = resourceSettings.getResourceStreamLocator();
            IResourceStream stream = locator.locate(null, className.replace('.', '/') + ".html");
            if (stream != null) {
                plugin = new LayoutPlugin(context, config, stream);
            } else {
                message = e.getClass().getName() + ": " + e.getMessage();
                log.error(message, e);
            }

        } catch (InvocationTargetException e) {
            if (e.getTargetException() instanceof RestartResponseException) {
                throw (RestartResponseException) e.getTargetException();
            }
            message = e.getTargetException().getClass().getName() + ": " + e.getTargetException().getMessage();
            log.error(message, e);
        } catch (Exception e) {
            message = e.getClass().getName() + ": " + e.getMessage();
            log.error(message, e);
        }
    }
    if (plugin == null && message != null) {
        message += "\nFailed to instantiate plugin class '" + className + "' for wicket id '"
                + config.getString(RenderService.WICKET_ID) + "' in plugin '" + config.getName() + "' ("
                + config + ")";

        // reset context, i.e. unregister everything that was registered so far
        context.reset();

        if (config.getString(RenderService.WICKET_ID) != null) {
            IPluginConfig errorConfig = new JavaPluginConfig();
            errorConfig.put(ErrorPlugin.ERROR_MESSAGE, message);
            errorConfig.put(RenderService.WICKET_ID, config.getString(RenderService.WICKET_ID));
            plugin = new ErrorPlugin(context, errorConfig);
        } else {
            log.error(message);
        }
    }
    return plugin;
}