下面列出了怎么用com.vaadin.server.VaadinRequest的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public String getStaticFileLocation(VaadinRequest request) {
String staticFileLocation;
// if property is defined in configurations, use that
staticFileLocation = getDeploymentConfiguration().getResourcesPath();
if (staticFileLocation != null) {
return staticFileLocation;
}
VertxVaadinRequest vertxRequest = (VertxVaadinRequest) request;
String requestedPath = vertxRequest.getRequest().path()
.substring(
Optional.ofNullable(vertxRequest.getRoutingContext().mountPoint())
.map(String::length).orElse(0)
);
return VaadinServletService.getCancelingRelativePath(requestedPath);
}
@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;
}
/**
* Called to handle the link.
*/
public void handle() {
try {
ExternalLinkContext linkContext = new ExternalLinkContext(requestParams, action, app);
for (LinkHandlerProcessor processor : processors) {
if (processor.canHandle(linkContext)) {
processor.handle(linkContext);
break;
}
}
} finally {
VaadinRequest request = VaadinService.getCurrentRequest();
WrappedSession wrappedSession = request.getWrappedSession();
wrappedSession.removeAttribute(AppUI.LAST_REQUEST_PARAMS_ATTR);
wrappedSession.removeAttribute(AppUI.LAST_REQUEST_ACTION_ATTR);
}
}
@Override
protected void init(VaadinRequest request) {
final VerticalLayout root = new VerticalLayout();
root.setSizeFull();
setContent(root);
final CssLayout navigationBar = new CssLayout();
navigationBar.addStyleName(ValoTheme.LAYOUT_COMPONENT_GROUP);
navigationBar.addComponent(createNavigationButton("UI Scoped View",
UIScopedView.VIEW_NAME));
navigationBar.addComponent(createNavigationButton("View Scoped View",
ViewScopedView.VIEW_NAME));
root.addComponent(navigationBar);
springViewDisplay = new Panel();
springViewDisplay.setSizeFull();
root.addComponent(springViewDisplay);
root.setExpandRatio(springViewDisplay, 1.0f);
}
@Override
public Locale negotiate(List<Locale> supportedLocales,
VaadinRequest vaadinRequest) {
String languages = vaadinRequest.getHeader("Accept-Language");
try {
// Use reflection here, so the code compiles with jdk 1.7
Class<?> languageRange = Class
.forName("java.util.Locale$LanguageRange");
Method parse = languageRange.getMethod("parse", String.class);
Object priorityList = parse.invoke(null, languages);
Method lookup = Locale.class.getMethod("lookup", List.class,
Collection.class);
return (Locale) lookup.invoke(null, priorityList, supportedLocales);
} catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | NoSuchMethodException | SecurityException | InvocationTargetException e) {
throw new RuntimeException(
"Java8LocaleNegotiontionStrategy need java 1.8 or newer.",
e);
}
}
@Override
protected void init(VaadinRequest request) {
AbstractForm<Pojo> form = new AbstractForm<Pojo>(Pojo.class) {
private static final long serialVersionUID = 1251886098275380006L;
IntegerField myInteger = new IntegerField("My Integer");
@Override
protected Component createContent() {
FormLayout layout = new FormLayout(myInteger, getToolbar());
return layout;
}
};
form.setResetHandler((Pojo entity) -> {
form.setEntity(null);
});
form.setEntity(new Pojo());
setContent(form);
}
@Override
protected void init(VaadinRequest request) {
// TODO: remove test-entry into contet
context.put(CONTEXT_LOGIN_USER, "sebastian");
// create
NavigationManager m = new NavigationManager();
m.setMaintainBreadcrumb(true);
TimesheetChangePresenter pres = obtainPresenterFactory(request.getContextPath()).createTimesheetChangePresenter(null);
// Load the july timesheet into the presenter
CouchDbTimesheetService tsService = new CouchDbTimesheetService();
List<Timesheet> tsList = tsService.listAllTimesheet(new HashMap<String, Object>(context));
for (Timesheet ts : tsList) {
if (ts.getMonth() == 7 && ts.getYear() == 2014) {
pres.setTimesheet(ts);
break;
}
}
// TODO: have list presenter before (instead of one)
m.setCurrentComponent((Component) pres.getView().getComponent());
setContent(m);
// and go
pres.startPresenting();
}
@Override
protected void init(VaadinRequest request) {
ganttListener = null;
createGantt();
MenuBar menu = controlsMenuBar();
Panel controls = createControls();
Component wrapper = UriFragmentWrapperFactory.wrapByUriFragment(UI.getCurrent().getPage().getUriFragment(),
gantt);
if (wrapper instanceof GanttListener) {
ganttListener = (GanttListener) wrapper;
}
final VerticalLayout layout = new VerticalLayout();
layout.setStyleName("demoContentLayout");
layout.setMargin(false);
layout.setSizeFull();
layout.addComponent(menu);
layout.addComponent(controls);
layout.addComponent(wrapper);
layout.setExpandRatio(wrapper, 1);
setContent(layout);
}
@Override
public void init(VaadinRequest request) {
logger.info("New Vaadin UI created");
String invitation = request.getParameter("invitation");
logger.info("Invitation: {} of sessions : {}", invitation);
setSizeFull();
GazpachoViewDisplay viewDisplay = new GazpachoViewDisplay();
setContent(viewDisplay);
navigator = new Navigator(this, (ViewDisplay) viewDisplay);
navigator.addProvider(viewProvider);
navigator.setErrorProvider(new GazpachoErrorViewProvider());
if (isUserSignedIn()) {
navigator.navigateTo(QuestionnaireView.NAME);
} else {
navigator.navigateTo(LoginView.NAME);
}
}
@Override
protected void init(VaadinRequest vaadinRequest) {
getPage().setTitle("Root UI");
Table table = new Table("Customer Table");
table.addContainerProperty("firstName", String.class, null);
table.addContainerProperty("lastName", String.class, null);
table.addContainerProperty("id", Long.class, null);
for (Customer c : this.customerRepository.findAll())
table.addItem(new Object[]{c.getFirstName(), c.getLastName(), c.getId()}, c.getId());
table.setSizeFull();
table.setColumnHeader("firstName", "First Name");
table.setColumnHeader("lastName", "First Name");
setContent(table);
}
@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;
}
private static boolean hasPathPrefix(VaadinRequest request, String prefix) {
String pathInfo = request.getPathInfo();
if (pathInfo == null) {
return false;
}
if (!prefix.startsWith("/")) {
prefix = '/' + prefix;
}
if (pathInfo.startsWith(prefix)) {
return true;
}
return false;
}
private String getClientIpAddr(VaadinRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
@Override
protected boolean requestCanCreateSession(VaadinRequest request) {
if (ServletUIInitHandler.isUIInitRequest(request)) {
// This is the first request if you are embedding by writing the
// embedding code yourself
return true;
} else if (isOtherRequest(request)) {
/*
* I.e URIs that are not RPC calls or static (theme) files.
*/
return true;
}
return false;
}
private boolean isOtherRequest(VaadinRequest request) {
// TODO This should be refactored in some way. It should not be
// necessary to check all these types.
return (!ServletPortletHelper.isAppRequest(request)
&& !ServletUIInitHandler.isUIInitRequest(request)
&& !ServletPortletHelper.isFileUploadRequest(request)
&& !ServletPortletHelper.isHeartbeatRequest(request)
&& !ServletPortletHelper.isPublishedFileRequest(request)
&& !ServletPortletHelper.isUIDLRequest(request) && !ServletPortletHelper
.isPushRequest(request));
}
/**
* Gets a relative path you can use to refer to the context root.
*
* @param request the request for which the location should be determined
* @return A relative path to the context root. Never ends with a slash (/).
*/
public static String getContextRootRelativePath(VaadinRequest request) {
VertxVaadinRequest servletRequest = (VertxVaadinRequest) request;
// Generate location from the request by finding how many "../" should
// be added to the servlet path before we get to the context root
String servletPath = "";
String pathInfo = servletRequest.getPathInfo();
if (pathInfo != null && !pathInfo.isEmpty()) {
servletPath += pathInfo;
}
return getCancelingRelativePath(servletPath);
}
@Override
protected void init(VaadinRequest request) {
request.getService().addSessionDestroyListener(e -> {
((SessionTestVerticle) ((VertxVaadinService) e.getService()).getVertx().getOrCreateContext().get("mySelf"))
.registerSessionEvent("Session destroyed");
});
}
private String testLocation(String mountPoint, String pathInfo) {
VertxVaadinService service = mock(VertxVaadinService.class);
HttpServerRequest httpServerRequest = mock(HttpServerRequest.class);
RoutingContext routingContext = mock(RoutingContext.class);
when(routingContext.mountPoint()).thenReturn(mountPoint);
when(routingContext.request()).thenReturn(httpServerRequest);
VaadinRequest req = new VertxVaadinRequest(service, routingContext);
when(httpServerRequest.path()).thenReturn(Optional.ofNullable(mountPoint).orElse("") + pathInfo);
return VertxVaadinService.getContextRootRelativePath(req);
}
@Override
protected void init(VaadinRequest vaadinRequest) {
Page.getCurrent().setTitle("Advanced Netconf Explorer");
addStyleName(ValoTheme.UI_WITH_MENU);
setContent(new RetrieverView(this, vaadinRequest));
addStyleName("loginview");
}
/**
* Init the UI.
*
* @param request the request.
*/
@Override
protected void init(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
layout.setSpacing(true);
setContent(layout);
layout.addComponent(new Label("Hello Vaadin"));
}
/**
* 首页初始化
* @param vaadinRequest
*/
@Override
protected void init(VaadinRequest vaadinRequest) {
VerticalLayout content = new VerticalLayout();
content.addComponent(createTitle());
content.addComponent(createTabSheet());
setContent(content);
}
@Override
protected void refresh(VaadinRequest request) {
super.refresh(request);
boolean sessionIsAlive = true;
Connection connection = app.getConnection();
if (connection.isAuthenticated()) {
// Ping middleware session if connected
log.debug("Ping middleware session");
try {
UserSession session = connection.getSession();
if (session instanceof ClientUserSession
&& ((ClientUserSession) session).isAuthenticated()) {
userSessionService.getUserSession(session.getId());
if (hasAuthenticatedSession()
&& !Objects.equals(userSession, session)) {
setUserSession(session);
}
}
} catch (Exception e) {
sessionIsAlive = false;
app.exceptionHandlers.handle(new com.vaadin.server.ErrorEvent(e));
}
if (sessionIsAlive) {
events.publish(new SessionHeartbeatEvent(app));
}
}
urlChangeHandler.restoreState();
if (sessionIsAlive) {
events.publish(new UIRefreshEvent(this));
}
}
protected void processExternalLink(VaadinRequest request, NavigationState requestedState) {
if (isLinkHandlerRequest(request)) {
processLinkHandlerRequest(request);
} else {
processRequest(requestedState);
}
}
protected boolean isLinkHandlerRequest(VaadinRequest request) {
WrappedSession wrappedSession = request.getWrappedSession();
if (wrappedSession == null) {
return false;
}
String action = (String) wrappedSession.getAttribute(LAST_REQUEST_ACTION_ATTR);
return webConfig.getLinkHandlerActions().contains(action);
}
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 boolean browserHasNewestVersion(VaadinRequest request, long resourceLastModifiedTimestamp) {
if (resourceLastModifiedTimestamp < 1) {
// We do not know when it was modified so the browser cannot have an
// up-to-date version
return false;
}
/*
* The browser can request the resource conditionally using an
* If-Modified-Since header. Check this against the last modification
* time.
*/
try {
// If-Modified-Since represents the timestamp of the version cached
// in the browser
long headerIfModifiedSince = request
.getDateHeader("If-Modified-Since");
if (headerIfModifiedSince >= resourceLastModifiedTimestamp) {
// Browser has this an up-to-date version of the resource
return true;
}
} catch (Exception e) {
// Failed to parse header. Fail silently - the browser does not have
// an up-to-date version in its cache.
}
return false;
}
@Override
public void setUrls(String selectorId, List<String> urls) {
VaadinRequest vaadinRequest = VaadinService.getCurrentRequest();
if (vaadinRequest != null)
vaadinRequest.getWrappedSession().setAttribute(getAttributeName(selectorId), urls);
else {
HttpSession httpSession = getHttpSession();
if (httpSession != null) {
httpSession.setAttribute(getAttributeName(selectorId), urls);
}
}
}
@Override
protected void init(VaadinRequest vaadinRequest) {
final UI currentUI = getCurrent();
final StreamObserver<Chat.ChatMessage> observer = stub.chat(new StreamObserver<Chat.ChatMessageFromServer>() {
@Override
public void onNext(Chat.ChatMessageFromServer chatMessageFromServer) {
currentUI.access(() -> layout.addComponent(new Label(String.format("%s: %s" ,
chatMessageFromServer.getMessage().getFrom() ,
chatMessageFromServer.getMessage().getMessage()))));
}
@Override
public void onError(Throwable throwable) {
logger.log(Level.SEVERE , "gRPC Error" , throwable);
}
@Override
public void onCompleted() {
logger.info("gRPC Call Completed");
}
});
button.addClickListener(e -> {
final String nameValue = name.getValue();
final String messageValue = message.getValue();
observer.onNext(Chat.ChatMessage.newBuilder()
.setFrom(nameValue)
.setMessage(messageValue)
.build());
});
}
@Override
protected void init(final VaadinRequest request) {
HawkbitCommonUtil.initLocalization(this, uiProperties.getLocalization(), i18n);
SpringContextHelper.setContext(context);
params = UriComponentsBuilder.fromUri(Page.getCurrent().getLocation()).build().getQueryParams();
setContent(buildContent());
fillOutUsernameTenantFields();
}
@Override
protected void init(VaadinRequest request) {
super.init(request);
if (!userSession.isLoggedIn()) {
getContent().setVisible(false);
addWindow(loginWindow.get());
}
}