Example usage for org.apache.wicket Application get

List of usage examples for org.apache.wicket Application get

Introduction

In this page you can find the example usage for org.apache.wicket Application get.

Prototype

public static Application get() 

Source Link

Document

Get Application for current thread.

Usage

From source file:org.onexus.ui.api.OnexusWebApplication.java

License:Apache License

public static OnexusWebApplication get() {
    return (OnexusWebApplication) Application.get();
}

From source file:org.onexus.website.api.WebsiteApplication.java

License:Apache License

public static WebsiteApplication get() {
    return (WebsiteApplication) Application.get();
}

From source file:org.opensingular.form.wicket.panel.SUploadProgressBar.java

License:Apache License

@Override
protected ResourceResponse newResourceResponse(final Attributes attributes) {
    // Determine encoding
    final String encoding = Application.get().getRequestCycleSettings().getResponseRequestEncoding();

    ResourceResponse response = new ResourceResponse();
    response.setContentType("text/html; charset=" + encoding);
    response.setCacheDuration(Duration.NONE);

    final String status = getStatus(attributes);
    response.setWriteCallback(new WriteCallback() {
        @Override/*  www. j ava2 s.  c  o  m*/
        public void writeData(final Attributes attributes) {
            attributes.getResponse().write("<html><body>|");
            attributes.getResponse().write(status);
            attributes.getResponse().write("|</body></html>");
        }
    });

    return response;
}

From source file:org.opensingular.lib.wicket.util.bootstrap.layout.TemplatePanel.java

License:Apache License

@Override
protected IMarkupSourcingStrategy newMarkupSourcingStrategy() {
    return new PanelMarkupSourcingStrategy(false) {
        @Override/* ww  w. j ava 2  s.c o  m*/
        public IMarkupFragment getMarkup(MarkupContainer parent, Component child) {
            // corrige o problema de encoding
            StringResourceStream stringResourceStream = new StringResourceStream(
                    "<wicket:panel>" + getTemplateFunction().apply(TemplatePanel.this) + "</wicket:panel>",
                    "text/html");
            stringResourceStream.setCharset(Charset.forName(
                    Optional.ofNullable(Application.get().getMarkupSettings().getDefaultMarkupEncoding())
                            .orElse(StandardCharsets.UTF_8.name())));

            MarkupParser markupParser = new MarkupParser(new MarkupResourceStream(stringResourceStream));
            markupParser.setWicketNamespace(MarkupParser.WICKET);
            Markup markup;
            try {
                markup = markupParser.parse();
            } catch (Exception e) {
                throw SingularUtil.propagate(e);
            }

            // If child == null, than return the markup fragment starting
            // with <wicket:panel>
            if (child == null) {
                return markup;
            }

            // Copiado da superclasse. buscando markup do child
            IMarkupFragment associatedMarkup = markup.find(child.getId());
            if (associatedMarkup != null) {
                return associatedMarkup;
            }
            associatedMarkup = searchMarkupInTransparentResolvers(parent, parent.getMarkup(), child);
            if (associatedMarkup != null) {
                return associatedMarkup;
            }
            return findMarkupInAssociatedFileHeader(parent, child);
        }

        @Override
        public void onComponentTagBody(Component component, MarkupStream markupStream, ComponentTag openTag) {
            TemplatePanel.this.onBeforeComponentTagBody(markupStream, openTag);
            super.onComponentTagBody(component, markupStream, openTag);
            TemplatePanel.this.onAfterComponentTagBody(markupStream, openTag);
        }
    };
}

From source file:org.ops4j.pax.wicket.api.InjectorHolder.java

License:Apache License

/**
 * Retrieves the InjectionHolder responsible for the active {@link Application}. Therefore this will only work in an
 * active Wicket context!/*from ww  w.ja  va 2 s  .c  om*/
 */
public static PaxWicketInjector getInjector() {
    String applicationName = Application.get().getApplicationKey();
    PaxWicketInjector injector = null;
    synchronized (instance.injectorMap) {
        injector = instance.injectorMap.get(applicationName);
    }
    if (injector == null) {
        throw new IllegalStateException(
                String.format("No Injector is set for application %s", Application.get().getApplicationKey()));
    }
    return injector;
}

From source file:org.projectforge.web.mobile.AbstractMobilePage.java

License:Open Source License

@Override
public void renderHead(final IHeaderResponse response) {
    super.renderHead(response);
    response.render(JavaScriptReferenceHeaderItem
            .forReference(Application.get().getJavaScriptLibrarySettings().getJQueryReference()));
    response.render(StringHeaderItem.forString(WicketUtils.getCssForFavicon(getUrl("/favicon.ico"))));
    if (WebConfiguration.isDevelopmentMode() == true) {
        response.render(CssReferenceHeaderItem
                .forUrl("mobile/jquery.mobile/jquery.mobile-" + JQUERY_MOBILE_VERSION + ".css"));
    } else {//from  w  ww  .  j  a v  a2s  .com
        response.render(CssReferenceHeaderItem
                .forUrl("mobile/jquery.mobile/jquery.mobile-" + JQUERY_MOBILE_VERSION + ".min.css"));
    }
    response.render(CssReferenceHeaderItem.forUrl("mobile/projectforge.css"));
    response.render(JavaScriptReferenceHeaderItem.forUrl("mobile/jquery.mobile/myconfig.js"));
    if (WebConfiguration.isDevelopmentMode() == true) {
        // response.renderJavaScriptReference("mobile/jquery.mobile/myconfig.js");
        response.render(JavaScriptReferenceHeaderItem
                .forUrl("mobile/jquery.mobile/jquery.mobile-" + JQUERY_MOBILE_VERSION + ".js"));
    } else {
        // response.renderJavaScriptReference("mobile/jquery.mobile/myconfig.js");
        response.render(JavaScriptReferenceHeaderItem
                .forUrl("mobile/jquery.mobile/jquery.mobile-" + JQUERY_MOBILE_VERSION + ".min.js"));
    }
}

From source file:org.projectforge.web.wicket.WicketApplication.java

License:Open Source License

@Override
protected void init() {
    super.init();
    // Own error page for deployment mode and UserException and AccessException.
    getRequestCycleListeners().add(new AbstractRequestCycleListener() {
        /**//ww  w.j  a  v  a2 s . co m
         * Log only non ProjectForge exceptions.
         * @see org.apache.wicket.request.cycle.AbstractRequestCycleListener#onException(org.apache.wicket.request.cycle.RequestCycle,
         *      java.lang.Exception)
         */
        @Override
        public IRequestHandler onException(final RequestCycle cycle, final Exception ex) {
            // in case of expired session, please redirect to home page
            if (ex instanceof PageExpiredException) {
                return new RenderPageRequestHandler(new PageProvider(getHomePage()));
            }
            final Throwable rootCause = ExceptionHelper.getRootCause(ex);
            // log.error(rootCause.getMessage(), ex);
            // if (rootCause instanceof ProjectForgeException == false) {
            // return super.onException(cycle, ex);
            // }
            // return null;
            if (isDevelopmentSystem() == true) {
                log.error(ex.getMessage(), ex);
                if (rootCause instanceof SQLException) {
                    SQLException next = (SQLException) rootCause;
                    while ((next = next.getNextException()) != null) {
                        log.error(next.getMessage(), next);
                    }
                }
                return super.onException(cycle, ex);
            } else {
                // Show always this error page in production mode:
                return new RenderPageRequestHandler(new PageProvider(new ErrorPage(ex)));
            }
        }
    });

    getApplicationSettings().setDefaultMaximumUploadSize(Bytes.megabytes(100));
    getMarkupSettings().setDefaultMarkupEncoding("utf-8");
    final MyAuthorizationStrategy authStrategy = new MyAuthorizationStrategy();
    getSecuritySettings().setAuthorizationStrategy(authStrategy);
    getSecuritySettings().setUnauthorizedComponentInstantiationListener(authStrategy);
    // Prepend the resource bundle for overwriting some Wicket default localizations (such as StringValidator.*)
    getResourceSettings().getStringResourceLoaders().add(new BundleStringResourceLoader(RESOURCE_BUNDLE_NAME));
    getResourceSettings().setThrowExceptionOnMissingResource(false); // Don't throw MissingResourceException for missing i18n keys.
    getApplicationSettings().setPageExpiredErrorPage(PageExpiredPage.class); // Don't show expired page.
    // getSessionSettings().setMaxPageMaps(20); // Map up to 20 pages per session (default is 5).
    getComponentInstantiationListeners().add(new SpringComponentInjector(this));
    getApplicationSettings().setInternalErrorPage(ErrorPage.class);
    // getRequestCycleSettings().setGatherExtendedBrowserInfo(true); // For getting browser width and height.

    // Select2:
    // final ApplicationSettings select2Settings = ApplicationSettings.get();
    // select2Settings.setIncludeJavascript(false);

    final XmlWebApplicationContext webApplicationContext = (XmlWebApplicationContext) WebApplicationContextUtils
            .getWebApplicationContext(getServletContext());
    final ConfigurableListableBeanFactory beanFactory = webApplicationContext.getBeanFactory();
    beanFactory.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
    final LocalSessionFactoryBean localSessionFactoryBean = (LocalSessionFactoryBean) beanFactory
            .getBean("&sessionFactory");

    // if ("true".equals(System.getProperty(SYSTEM_PROPERTY_HSQLDB_18_UPDATE)) == true) {
    // try {
    // log.info("Send SHUTDOWN COMPACT to upgrade data-base version:");
    // final DataSource dataSource = (DataSource)beanFactory.getBean("dataSource");
    // dataSource.getConnection().createStatement().execute("SHUTDOWN COMPACT");
    // log.fatal("************ PLEASE RESTART APPLICATION NOW FOR PROPER INSTALLATION !!!!!!!!!!!!!! ************");
    // return;
    // } catch (final SQLException ex) {
    // log.fatal("Data-base SHUTDOWN COMPACT failed: " + ex.getMessage());
    // }
    // }
    final org.hibernate.cfg.Configuration hibernateConfiguration = localSessionFactoryBean.getConfiguration();
    HibernateUtils.setConfiguration(hibernateConfiguration);
    final ServletContext servletContext = getServletContext();
    final String configContextPath = configXml.getServletContextPath();
    String contextPath;
    if (StringUtils.isBlank(configContextPath) == true) {
        contextPath = servletContext.getContextPath();
        configXml.setServletContextPath(contextPath);
    } else {
        contextPath = configContextPath;
    }
    log.info("Using servlet context path: " + contextPath);
    if (configuration.getBeanFactory() == null) {
        configuration.setBeanFactory(beanFactory);
    }
    configuration.setConfigurationDao(configurationDao);
    SystemInfoCache.internalInitialize(systemInfoCache);
    WicketUtils.setContextPath(contextPath);
    UserFilter.initialize(userDao, contextPath);
    if (this.wicketApplicationFilter != null) {
        this.wicketApplicationFilter.setApplication(this);
    } else {
        throw new RuntimeException("this.wicketApplicationFilter is null");
    }
    daoRegistry.init();

    final PluginsRegistry pluginsRegistry = PluginsRegistry.instance();
    pluginsRegistry.set(beanFactory, getResourceSettings());
    pluginsRegistry.set(systemUpdater);
    pluginsRegistry.initialize();

    for (final Map.Entry<String, Class<? extends WebPage>> mountPage : WebRegistry.instance().getMountPages()
            .entrySet()) {
        final String path = mountPage.getKey();
        final Class<? extends WebPage> pageClass = mountPage.getValue();
        mountPage(path, pageClass);
        mountedPages.put(pageClass, path);
    }
    if (isDevelopmentSystem() == true) {
        if (isStripWicketTags() == true) {
            log.info("Strip Wicket tags also in development mode at default (see context.xml).");
            Application.get().getMarkupSettings().setStripWicketTags(true);
        }
        getDebugSettings().setOutputMarkupContainerClassName(true);
    }
    log.info("Default TimeZone is: " + TimeZone.getDefault());
    if ("UTC".equals(TimeZone.getDefault().getID()) == false) {
        for (final String str : UTC_RECOMMENDED) {
            log.fatal(str);
        }
        for (final String str : UTC_RECOMMENDED) {
            System.err.println(str);
        }
    }
    log.info("user.timezone is: " + System.getProperty("user.timezone"));
    cronSetup.initialize();
    log.info(AppVersion.APP_ID + " " + AppVersion.NUMBER + " (" + AppVersion.RELEASE_TIMESTAMP
            + ") initialized.");

    PFUserContext.setUser(DatabaseUpdateDao.__internalGetSystemAdminPseudoUser()); // Logon admin user.
    if (systemUpdater.isUpdated() == false) {
        // Force redirection to update page:
        UserFilter.setUpdateRequiredFirst(true);
    }
    PFUserContext.setUser(null);
    UserXmlPreferencesCache.setInternalInstance(userXmlPreferencesCache);
    LoginHandler loginHandler;
    if (StringUtils.isNotBlank(configXml.getLoginHandlerClass()) == true) {
        loginHandler = (LoginHandler) BeanHelper.newInstance(configXml.getLoginHandlerClass());
    } else {
        loginHandler = new LoginDefaultHandler();
    }
    if (loginHandler == null) {
        log.error("Can't load login handler '" + configXml.getLoginHandlerClass()
                + "'. No login will be possible!");
    } else {
        loginHandler.initialize();
        Login.getInstance().setLoginHandler(loginHandler);
    }
    try {
        StorageClient.getInstance(); // Initialize storage
    } catch (final Exception ex) {
        log.error(ex.getMessage(), ex);
    }
    getPageSettings().setRecreateMountedPagesAfterExpiry(false);

    // initialize ical4j to be more "relaxed"
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION, true);

    // initialize styles compiler
    try {
        final LessWicketApplicationInstantiator lessInstantiator = new LessWicketApplicationInstantiator(this,
                "styles", "projectforge.less", "projectforge.css");
        lessInstantiator.instantiate();
    } catch (final Exception e) {
        log.error("Unable to instantiate wicket less compiler", e);
    }
}

From source file:org.projectforge.web.wicket.WicketApplicationFilter.java

License:Open Source License

public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    // Sollte eigentlich immer NULL ergeben, aber man weiss nie ...
    final Application previousOne = (Application.exists() == true) ? Application.get() : null;
    org.apache.wicket.ThreadContext.setApplication(this.application);
    try {//from  ww  w .j a  v  a2 s . c o m
        chain.doFilter(request, response);
    } finally {
        if (previousOne != null) {
            org.apache.wicket.ThreadContext.setApplication(previousOne);
        } else {
            org.apache.wicket.ThreadContext.setApplication(null);
        }
    }
}

From source file:org.sakaiproject.scorm.ui.ContentPackageResourceMountStrategy.java

License:Educational Community License

@Override
protected String urlDecode(String value) {
    try {//  ww w.  j a  v  a 2  s . c  o m
        value = URLDecoder.decode(value,
                Application.get().getRequestCycleSettings().getResponseRequestEncoding());
    } catch (UnsupportedEncodingException ex) {
        log.error("error decoding parameter", ex);
    }
    return value;
}

From source file:org.sakaiproject.scorm.ui.ContentPackageResourceMountStrategy.java

License:Educational Community License

@Override
protected String urlEncode(String string) {
    try {//w  ww  .j a v a 2  s . c om
        return URLEncoder.encode(string,
                Application.get().getRequestCycleSettings().getResponseRequestEncoding());
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage(), e);
        return string;
    }

}