Example usage for org.apache.wicket Session exists

List of usage examples for org.apache.wicket Session exists

Introduction

In this page you can find the example usage for org.apache.wicket Session exists.

Prototype

public static boolean exists() 

Source Link

Document

Checks existence of a Session associated with the current thread.

Usage

From source file:at.molindo.wicketutils.utils.MockUtilsTest.java

License:Apache License

@Test
public void withSession() throws Exception {
    DummyApplication testApp = new DummyApplication();
    try {/*from ww  w  .j a v  a 2s  .com*/

        assertFalse(Application.exists());
        assertFalse(Session.exists());
        assertFalse(RequestCycle.get() != null);

        String stringResource = MockUtils.withRequest(testApp, new MockRequestCallback<String>() {

            @Override
            public String call() {
                // some basic testing
                assertTrue(Application.exists());
                assertFalse(Session.exists());
                assertTrue(RequestCycle.get() != null);

                return new StringResourceModel("someResource", (IModel<?>) null, Model.of("default value"))
                        .getString();
            }

        });
        assertEquals("default value", stringResource);

        String url = MockUtils.withRequest(testApp, new MockRequestCallback<String>() {

            @Override
            public String call() {
                return RequestCycle.get().urlFor(HomePage.class, null).toString();
            }

        });
        assertEquals(".", url);

        Locale locale = MockUtils.withRequest(testApp, new IMockRequestCallback<Locale>() {

            @Override
            public void configure(MockRequest request) {
                request.setLocale(Locale.GERMAN);
            }

            @Override
            public Locale call() {
                return Session.get().getLocale();
            }

        });
        assertEquals(Locale.GERMAN, locale);

        assertFalse(Application.exists());
        assertFalse(Session.exists());
        assertFalse(RequestCycle.get() != null);
    } finally {
        testApp.destroy();
    }
}

From source file:com.evolveum.midpoint.web.component.SecurityContextAwareCallable.java

License:Apache License

protected void setupContext(Application application, Session session) {
    if (!Application.exists() && application != null) {
        ThreadContext.setApplication(application);
    }/*from  w  ww. j  a  v a 2s .c  o m*/
    if (!Session.exists() && session != null) {
        ThreadContext.setSession(session);
    }
}

From source file:com.evolveum.midpoint.web.util.MidPointStringResourceLoader.java

License:Apache License

@Override
public String loadStringResource(Component component, String key, Locale locale, String style,
        String variation) {/*from   w w  w .  j  av  a 2 s .c om*/
    if (resourceLoader == null) {
        // Just for tests
        return key;
    }

    if (locale == null) {
        locale = Session.exists() ? Session.get().getLocale() : Locale.getDefault();
    }

    return resourceLoader.translate(key, null, locale);
}

From source file:com.evolveum.midpoint.web.util.Utf8BundleStringResourceLoader.java

License:Apache License

@Override
public String loadStringResource(Component component, String key, Locale locale, String style,
        String variation) {//from w  ww .  ja v a2  s. com
    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;
        }
    }
}

From source file:com.lyndir.lhunath.snaplog.data.object.media.TimeFrame.java

License:Apache License

private DateTimeFormatter getFormatter() {

    if (formatter == null) {
        // Find all the fields to include in the formatter.
        DurationFieldType[] fields = range.toPeriod().getFieldTypes();
        DurationFieldType smallestField = fields[fields.length - 1];
        List<DateTimeFieldType> types = DateUtils.fieldsFrom(DateUtils.convert(smallestField));

        // Build a formatter from the fields.
        formatterBuilder.clear();//from   w  ww . j  a  va2 s  .c om
        for (Iterator<DateTimeFieldType> it = types.iterator(); it.hasNext();) {
            DateTimeFieldType type = it.next();

            formatterBuilder.appendShortText(type);
            if (it.hasNext())
                formatterBuilder.appendLiteral(' ');
        }
        formatter = formatterBuilder.toFormatter();
    }

    // Switch formatter to the active locale.
    Locale locale = Session.exists() ? Session.get().getLocale() : null;
    if (!ObjectUtils.isEqual(locale, formatter.getLocale()))
        formatter = formatter.withLocale(locale);

    return formatter;
}

From source file:com.servoy.j2db.debug.DebugWebClient.java

License:Open Source License

/**
 * @see com.servoy.j2db.server.headlessclient.WebClient#shutDown(boolean)
 *///from w  w w.  j  a v  a2s  .c om
@Override
public void shutDown(boolean force) {
    boolean sessionExists = Session.exists() && (RequestCycle.get() != null);
    if (sessionExists)
        Session.unset(); // avoid session invalidating in super.shutDown - as the current session might be needed when DebugWC is restarted (by next DWC)
    super.shutDown(force);
    if (sessionExists)
        Session.get();

    // null pointers fix when switching between browsers in developer.
    if (force && session != null) {
        try {
            session.invalidate();
        } catch (Exception e) {
            // ignore
        }
    }
}

From source file:com.servoy.j2db.server.headlessclient.CachingKeyInSessionSunJceCryptFactory.java

License:Open Source License

public ICrypt newCrypt() {
    ICrypt crypt = null;/*from w w  w.  ja va  2s.c om*/
    WebClientSession webClientSession = null;
    if (Session.exists()) {
        webClientSession = WebClientSession.get();
        crypt = webClientSession.getCrypt();
    }

    if (crypt == null) {

        WebRequestCycle rc = (WebRequestCycle) RequestCycle.get();

        // get http session, create if necessary
        HttpSession session = rc.getWebRequest().getHttpServletRequest().getSession(true);

        // retrieve or generate encryption key from session
        final String keyAttr = rc.getApplication().getApplicationKey() + "." + getClass().getName();
        String key = (String) session.getAttribute(keyAttr);
        if (key == null) {
            // generate new key
            key = session.getId() + "." + UUID.randomUUID().toString();
            session.setAttribute(keyAttr, key);
        }

        // build the crypt based on session key
        try {
            crypt = new CachingSunJceCrypt(key);
        } catch (GeneralSecurityException e) {

            Debug.error("couldn't generate the crypt class", e);
            return new NoCrypt();
        }

        if (webClientSession != null) {
            webClientSession.setCrypt(crypt);
        }
    }
    return crypt;
}

From source file:com.servoy.j2db.server.headlessclient.FormCssResource.java

License:Open Source License

/**
 * @see org.apache.wicket.Resource#getResourceStream()
 *///w  w  w .  j  a v  a 2  s  .  com
@Override
public IResourceStream getResourceStream() {
    String css = "";
    ValueMap params = getParameters();
    Long time = null;
    if (params.size() == 1) {
        Iterator iterator = params.entrySet().iterator();
        if (iterator.hasNext()) {
            Map.Entry entry = (Entry) iterator.next();
            String solutionName = (String) entry.getKey();
            Pair<String, Long> filterTime = filterTime((String) entry.getValue());
            String formInstanceName = filterTime.getLeft();
            time = filterTime.getRight();

            String solutionAndForm = solutionName + "/" + formInstanceName; //$NON-NLS-1$
            String templateDir = "default"; //$NON-NLS-1$
            IServiceProvider sp = null;
            Solution solution = null;
            Form form = null;
            if (Session.exists()) {
                sp = WebClientSession.get().getWebClient();
                if (sp != null) {
                    IForm fc = ((WebClient) sp).getFormManager().getForm(formInstanceName);
                    if (fc instanceof FormController) {
                        FlattenedSolution clientSolution = sp.getFlattenedSolution();
                        form = clientSolution.getForm(((FormController) fc).getForm().getName());
                    }
                }
                templateDir = WebClientSession.get().getTemplateDirectoryName();
            }

            final String fullpath = "/servoy-webclient/templates/" + templateDir + "/" + solutionAndForm
                    + ".css";
            try {
                URL url = context.getResource(fullpath);
                if (url != null) {
                    return new NullUrlResourceStream(url);
                }
            } catch (Exception e) {
                Debug.error(e);
            }

            try {
                IApplicationServerSingleton as = ApplicationServerRegistry.get();
                RootObjectMetaData sd = as.getLocalRepository().getRootObjectMetaData(solutionName,
                        IRepository.SOLUTIONS);
                if (sd != null) {
                    solution = (Solution) as.getLocalRepository().getActiveRootObject(sd.getRootObjectId());
                    if (form == null) {
                        form = solution.getForm(formInstanceName);
                    }
                }
                if (form != null) {
                    Pair<String, String> formHTMLAndCSS = TemplateGenerator.getFormHTMLAndCSS(solution, form,
                            sp, formInstanceName);
                    css = formHTMLAndCSS.getRight();
                }
            } catch (Exception e) {
                Debug.error(e);
            }
        }
    }
    StringResourceStream stream = new StringResourceStream(css, "text/css"); //$NON-NLS-1$
    stream.setLastModified(time != null ? Time.valueOf(time.longValue()) : null);
    return stream;
}

From source file:com.servoy.j2db.server.headlessclient.MainPage.java

License:Open Source License

public boolean touch(boolean onlyIfNotInUse) {
    boolean touched = false;
    if (Session.exists() && RequestCycle.get() != null) {
        WebClientSession session = WebClientSession.get();
        // all the current locked pages for this request, that wants to lock this one.
        List<Page> touchedPages = session.getTouchedPages();
        touched = touchedPages.contains(this);
        if (!touched) {
            session.wantsToLock(touchedPages, this);

            skipAttach.set(Boolean.TRUE);
            if (onlyIfNotInUse)
                ((WebClientsApplication) getApplication()).getRequestCycleSettings().overrideTimeout(1);
            try {
                session.getPage(getPageMapName(), getPath(), Page.LATEST_VERSION);
                touched = true;//from  w  w  w.j  a va2s  .c om
            } catch (WicketRuntimeException e) {
                // ignore if it is the timeout exception in case we only want to touch if not in use
                if (!onlyIfNotInUse || e.getCause() != null)
                    throw new RuntimeException("Touching page " + getPageMapName() + "/" + getPath()
                            + " couldn't be done in thread: " + Thread.currentThread().getName(), e);
                Debug.trace("Touch page ignored.");
            } finally {
                skipAttach.remove();
                if (onlyIfNotInUse)
                    ((WebClientsApplication) getApplication()).getRequestCycleSettings().restoreTimeout();
            }
        }
    }
    return touched;
}

From source file:com.servoy.j2db.server.headlessclient.SessionClient.java

License:Open Source License

static void onDestroy() {
    try {//from  w w  w  .  j  av a2s.c  o m
        if (wicket_app != null) {
            WebClientsApplication tmp = wicket_app;
            wicket_app = null;
            WicketFilter wicketFilter = tmp.getWicketFilter();
            if (wicketFilter != null) {
                wicketFilter.destroy();
            }
            if (Application.exists() && Application.get() == tmp) {
                Application.unset();
            }

            if (Session.exists() && Session.get() == wicket_session) {
                Session.unset();
            }
        } else {
            wicket_app = null;
            wicket_session = null;
        }
    } catch (Exception e) {
        Debug.error("on destroy", e);
    }
}