下面列出了怎么用com.vaadin.server.VaadinSession的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Pushes pending state changes and client RPC calls to the client. If
* {@code isConnected()} is false, defers the push until a connection is
* established.
*
* @param async True if this push asynchronously originates from the server,
* false if it is a response to a client request.
*/
void push(boolean async) {
if (!isConnected()) {
if (async && state != State.RESPONSE_PENDING) {
state = State.PUSH_PENDING;
} else {
state = State.RESPONSE_PENDING;
}
} else {
try {
UI ui = VaadinSession.getCurrent().getUIById(this.uiId);
Writer writer = new StringWriter();
new UidlWriter().write(ui, writer, async);
sendMessage("for(;;);[{" + writer + "}]");
} catch (Exception e) {
throw new PushException("Push failed", e);
}
}
}
@Override
public String getMainDivId(VaadinSession session, VaadinRequest request, Class<? extends UI> uiClass) {
String appId = request.getPathInfo();
if (appId == null || "".equals(appId) || "/".equals(appId)) {
appId = "ROOT";
}
appId = appId.replaceAll("[^a-zA-Z0-9]", "");
// Add hashCode to the end, so that it is still (sort of)
// predictable, but indicates that it should not be used in CSS
// and
// such:
int hashCode = appId.hashCode();
if (hashCode < 0) {
hashCode = -hashCode;
}
appId = appId + "-" + hashCode;
return appId;
}
public void setLocale(Locale locale) {
UserSession session = getConnection().getSession();
if (session != null) {
session.setLocale(locale);
}
AppUI currentUi = AppUI.getCurrent();
// it can be null if we handle request in a custom RequestHandler
if (currentUi != null) {
currentUi.setLocale(locale);
currentUi.updateClientSystemMessages(locale);
}
VaadinSession.getCurrent().setLocale(locale);
for (AppUI ui : getAppUIs()) {
if (ui != currentUi) {
ui.accessSynchronously(() -> {
ui.setLocale(locale);
ui.updateClientSystemMessages(locale);
});
}
}
}
@Override
protected void initExpectations() {
super.initExpectations();
new Expectations() {
{
vaadinSession.getLocale(); result = Locale.ENGLISH; minTimes = 0;
VaadinSession.getCurrent(); result = vaadinSession; minTimes = 0;
vaadinSession.getConverterFactory(); result = new DefaultConverterFactory(); minTimes = 0;
globalConfig.getAvailableLocales(); result = ImmutableMap.of("en", Locale.ENGLISH); minTimes = 0;
AppContext.getProperty("cuba.mainMessagePack"); result = "com.haulmont.cuba.web"; minTimes = 0;
}
};
this.uiComponents = new TestUiComponents(applicationContext);
}
@Override
protected void initExpectations() {
super.initExpectations();
new Expectations() {
{
vaadinSession.getLocale(); result = Locale.ENGLISH; minTimes = 0;
VaadinSession.getCurrent(); result = vaadinSession; minTimes = 0;
vaadinSession.getConverterFactory(); result = new DefaultConverterFactory(); minTimes = 0;
globalConfig.getAvailableLocales(); result = ImmutableMap.of("en", Locale.ENGLISH); minTimes = 0;
AppContext.getProperty("cuba.mainMessagePack"); result = "com.haulmont.cuba.web"; minTimes = 0;
}
};
}
@Override
protected void initExpectations() {
super.initExpectations();
new Expectations() {
{
vaadinSession.getLocale(); result = Locale.ENGLISH; minTimes = 0;
VaadinSession.getCurrent(); result = vaadinSession; minTimes = 0;
vaadinSession.getConverterFactory(); result = new DefaultConverterFactory(); minTimes = 0;
globalConfig.getAvailableLocales(); result = ImmutableMap.of("en", Locale.ENGLISH); minTimes = 0;
AppContext.getProperty("cuba.mainMessagePack"); result = "com.haulmont.cuba.web"; minTimes = 0;
}
};
this.uiComponents = new TestUiComponents(applicationContext);
}
@Override
protected void initExpectations() {
super.initExpectations();
new Expectations() {
{
vaadinSession.getLocale(); result = Locale.ENGLISH; minTimes = 0;
VaadinSession.getCurrent(); result = vaadinSession; minTimes = 0;
vaadinSession.getConverterFactory(); result = new DefaultConverterFactory(); minTimes = 0;
globalConfig.getAvailableLocales(); result = ImmutableMap.of("en", Locale.ENGLISH); minTimes = 0;
AppContext.getProperty("cuba.mainMessagePack"); result = "com.haulmont.cuba.web"; minTimes = 0;
}
};
this.uiComponents = new TestUiComponents(applicationContext);
}
@Override
protected void initExpectations() {
super.initExpectations();
new Expectations() {
{
vaadinSession.getLocale(); result = Locale.ENGLISH; minTimes = 0;
VaadinSession.getCurrent(); result = vaadinSession; minTimes = 0;
vaadinSession.getConverterFactory(); result = new DefaultConverterFactory(); minTimes = 0;
globalConfig.getAvailableLocales(); result = ImmutableMap.of("en", Locale.ENGLISH); minTimes = 0;
AppContext.getProperty("cuba.mainMessagePack"); result = "com.haulmont.cuba.web"; minTimes = 0;
}
};
this.uiComponents = new TestUiComponents(applicationContext);
}
@Override
protected void initExpectations() {
super.initExpectations();
new Expectations() {
{
vaadinSession.getLocale(); result = Locale.ENGLISH; minTimes = 0;
VaadinSession.getCurrent(); result = vaadinSession; minTimes = 0;
globalConfig.getAvailableLocales(); result = ImmutableMap.of("en", Locale.ENGLISH); minTimes = 0;
AppContext.getProperty("cuba.mainMessagePack"); result = "com.haulmont.cuba.web"; minTimes = 0;
}
};
this.uiComponents = new TestUiComponents(applicationContext);
}
@Override
protected void initExpectations() {
super.initExpectations();
new Expectations() {
{
vaadinSession.getLocale(); result = Locale.ENGLISH; minTimes = 0;
VaadinSession.getCurrent(); result = vaadinSession; minTimes = 0;
vaadinSession.getConverterFactory(); result = new DefaultConverterFactory(); minTimes = 0;
globalConfig.getAvailableLocales(); result = ImmutableMap.of("en", Locale.ENGLISH); minTimes = 0;
AppContext.getProperty("cuba.mainMessagePack"); result = "com.haulmont.cuba.web"; minTimes = 0;
}
};
this.uiComponents = new TestUiComponents(applicationContext);
}
@Override
protected void initExpectations() {
super.initExpectations();
new Expectations() {
{
vaadinSession.getLocale(); result = Locale.ENGLISH; minTimes = 0;
VaadinSession.getCurrent(); result = vaadinSession; minTimes = 0;
globalConfig.getAvailableLocales(); result = ImmutableMap.of("en", Locale.ENGLISH); minTimes = 0;
AppContext.getProperty("cuba.mainMessagePack"); result = "com.haulmont.cuba.web"; minTimes = 0;
}
};
this.uiComponents = new TestUiComponents(applicationContext);
}
@Override
protected void initExpectations() {
super.initExpectations();
new Expectations() {
{
vaadinSession.getLocale(); result = Locale.ENGLISH; minTimes = 0;
VaadinSession.getCurrent(); result = vaadinSession; minTimes = 0;
vaadinSession.getConverterFactory(); result = new DefaultConverterFactory(); minTimes = 0;
globalConfig.getAvailableLocales(); result = ImmutableMap.of("en", Locale.ENGLISH); minTimes = 0;
AppContext.getProperty("cuba.mainMessagePack"); result = "com.haulmont.cuba.web"; minTimes = 0;
}
};
this.uiComponents = new TestUiComponents(applicationContext);
}
@Override
public void attach() {
super.attach();
service = createService();
String url = service.getAuthorizationUrl(null);
gplusLoginButton = new Link("Login with Google", new ExternalResource(url));
gplusLoginButton.addStyleName(ValoTheme.LINK_LARGE);
VaadinSession.getCurrent().addRequestHandler(this);
setContent(new MVerticalLayout(gplusLoginButton).alignAll(
Alignment.MIDDLE_CENTER).withFullHeight());
setModal(true);
setWidth("300px");
setHeight("200px");
}
@Override
public boolean synchronizedHandleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response) throws IOException {
response.setContentType("text/css");
byte[] text = generateCss();
response.setCacheTime(-1);
response.setStatus(HttpURLConnection.HTTP_OK);
try (OutputStream stream = response.getOutputStream()) {
response.setContentLength(text.length);
stream.write(text);
}
return true;
}
/**
* {@inheritDoc}
*/
public String getConversationId() {
Integer uiId = null;
UI ui = UI.getCurrent();
if (ui == null) {
UIid id = CurrentInstance.get(UIid.class);
if (id != null) {
uiId = id.getUiId();
}
}
else if (ui != null) {
if (!sessions.containsKey(ui)) {
ui.addDetachListener(this);
sessions.put(ui, VaadinSession.getCurrent().getSession().getId());
}
uiId = ui.getUIId();
}
return uiId != null ? getConversationId(uiId) : null;
}
@Override
public boolean validate(String username, String password) {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
try {
Authentication auth = this.authenticationManager.authenticate(token);
if (auth.isAuthenticated()) {
// execute session authentication strategy
if (this.sessionStrategy != null)
this.sessionStrategy.onAuthentication(auth, VaadinServletService.getCurrentServletRequest(),
VaadinServletService.getCurrentResponse());
SecurityContextHolder.getContext().setAuthentication(auth);
// save request in context session
VaadinSession.getCurrent().getSession().setAttribute(
HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
SecurityContextHolder.getContext());
return true;
}
SecurityContextHolder.clearContext();
return false;
}
catch(AuthenticationException ae) {
SecurityContextHolder.clearContext();
return false;
}
}
private void readUiFromEnclosingClass(JsonObject vaadinConfig) {
Class<?> enclosingClass = getClass().getEnclosingClass();
if (enclosingClass != null && UI.class.isAssignableFrom(enclosingClass)) {
vaadinConfig.put(VaadinSession.UI_PARAMETER, enclosingClass.getName());
}
}
/**
* Call the session's {@link ErrorHandler}, if it has one, with the given
* exception wrapped in an {@link ErrorEvent}.
*/
private void callErrorHandler(VaadinSession session, Exception e) {
try {
ErrorHandler errorHandler = ErrorEvent.findErrorHandler(session);
if (errorHandler != null) {
errorHandler.error(new ErrorEvent(e));
}
} catch (Exception ex) {
// Let's not allow error handling to cause trouble; log fails
logger.warn("ErrorHandler call failed", ex);
}
}
protected WebBrowser getWebBrowserDetails() {
// timezone info is passed only on VaadinSession creation
WebBrowser webBrowser = VaadinSession.getCurrent().getBrowser();
VaadinRequest currentRequest = VaadinService.getCurrentRequest();
// update web browser instance if current request is not null
// it can be null in case of background/async processing of login request
if (currentRequest != null) {
webBrowser.updateRequestDetails(currentRequest);
}
return webBrowser;
}
protected void setSessionInternal(@Nullable ClientUserSession userSession) {
VaadinSession.getCurrent().setAttribute(UserSession.class, userSession);
if (userSession != null) {
AppContext.setSecurityContext(new SecurityContext(userSession));
} else {
AppContext.setSecurityContext(null);
}
}
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
VaadinSession session = VaadinSession.getCurrent();
if (session == null || !session.hasLock()) {
throw new IllegalStateException("Unable to use VaadinSessionScope from non-Vaadin thread");
}
Object object = session.getAttribute(name);
if (object == null) {
object = objectFactory.getObject();
session.setAttribute(name, object);
}
return object;
}
@Override
public Object remove(String name) {
VaadinSession session = VaadinSession.getCurrent();
if (session == null || !session.hasLock()) {
throw new IllegalStateException("Unable to use VaadinSessionScope from non-Vaadin thread");
}
Object bean = session.getAttribute(name);
session.setAttribute(name, null);
return bean;
}
@Override
public String getConversationId() {
if (VaadinSession.getCurrent() == null || !VaadinSession.getCurrent().hasLock()) {
throw new IllegalStateException("Unable to use VaadinSessionScope from non-Vaadin thread");
}
return VaadinSession.getCurrent().getSession().getId();
}
@Override
public SecurityContext get() {
VaadinSession vaadinSession = VaadinSession.getCurrent();
if (vaadinSession != null && vaadinSession.hasLock()) {
return vaadinSession.getAttribute(SecurityContext.class);
}
return super.get();
}
@Override
public void set(SecurityContext securityContext) {
VaadinSession vaadinSession = VaadinSession.getCurrent();
if (vaadinSession != null && vaadinSession.hasLock()) {
vaadinSession.setAttribute(SecurityContext.class, securityContext);
} else {
super.set(securityContext);
}
}
public void clearCache() {
VaadinSession session = VaadinSession.getCurrent();
if (session == null || !session.hasLock()) {
throw new IllegalConcurrentAccessException("Illegal access to settings client from background thread");
}
session.setAttribute(SettingsClient.NAME, null);
}
protected Map<String, Optional<String>> getCache() {
VaadinSession session = VaadinSession.getCurrent();
if (session == null || !session.hasLock()) {
throw new IllegalConcurrentAccessException("Illegal access to settings client from background thread");
}
@SuppressWarnings("unchecked")
Map<String, Optional<String>> settings = (Map<String, Optional<String>>) session.getAttribute(SettingsClient.NAME);
if (settings == null) {
settings = new HashMap<>();
session.setAttribute(SettingsClient.NAME, settings);
}
return settings;
}
public List<AppUI> getAppUIs() {
List<AppUI> list = new ArrayList<>();
for (UI ui : VaadinSession.getCurrent().getUIs()) {
if (ui instanceof AppUI)
list.add((AppUI) ui);
else
log.warn("Invalid UI in the session: {}", ui);
}
return list;
}
/**
* Called when <em>the first</em> UI of the session is initialized.
*/
protected void init(Locale requestLocale) {
VaadinSession vSession = VaadinSession.getCurrent();
vSession.setAttribute(App.class, this);
vSession.setLocale(messageTools.getDefaultLocale());
// set root error handler for all session
vSession.setErrorHandler(event -> {
try {
getExceptionHandlers().handle(event);
getAppLog().log(event);
} catch (Throwable e) {
log.error("Error handling exception\nOriginal exception:\n{}\nException in handlers:\n{}",
ExceptionUtils.getStackTrace(event.getThrowable()), ExceptionUtils.getStackTrace(e)
);
}
});
log.debug("Initializing application");
appLog = new AppLog(webConfig.getAppLogMaxItemsCount(), beanLocator.get(TimeSource.NAME));
connection = createConnection();
exceptionHandlers = new ExceptionHandlers(this, beanLocator);
cookies = new AppCookies();
themeConstants = loadTheme();
// get default locale from config
Locale targetLocale = resolveLocale(requestLocale);
setLocale(targetLocale);
}
/**
* @return Current App instance. Can be invoked anywhere in application code.
* @throws IllegalStateException if no application instance is bound to the current {@link VaadinSession}
*/
public static App getInstance() {
VaadinSession vSession = VaadinSession.getCurrent();
if (vSession == null) {
throw new IllegalStateException("No VaadinSession found");
}
if (!vSession.hasLock()) {
throw new IllegalStateException("VaadinSession is not owned by the current thread");
}
App app = vSession.getAttribute(App.class);
if (app == null) {
throw new IllegalStateException("No App is bound to the current VaadinSession");
}
return app;
}