下面列出了怎么用com.vaadin.server.WebBrowser的API类实例代码及写法,或者点击链接到github查看源代码。
protected void updateFooterVisibility(String style) {
Page page = Page.getCurrent();
if (page == null) {
return;
}
WebBrowser webBrowser = page.getWebBrowser();
boolean isPredefinedStyle = style.equals(BORDERLESS_STYLE)
|| style.equals(NO_HORIZONTAL_LINES_STYLE)
|| style.equals(NO_VERTICAL_LINES_STYLE);
if (webBrowser.isSafari()
&& isPredefinedStyle
&& grid.getFooterRowCount() > 0
&& grid.isFooterVisible()) {
((CubaEnhancedGrid) grid).updateFooterVisibility();
}
}
/**
* Get browser time zone or fixed time zone if configured
*
* @return TimeZone
*/
public static TimeZone getBrowserTimeZone() {
if (!StringUtils.isEmpty(fixedTimeZoneProperty)) {
return TimeZone.getTimeZone(fixedTimeZoneProperty);
}
final WebBrowser webBrowser = com.vaadin.server.Page.getCurrent().getWebBrowser();
final String[] timeZones = TimeZone.getAvailableIDs(webBrowser.getRawTimezoneOffset());
TimeZone tz = TimeZone.getDefault();
for (final String string : timeZones) {
final TimeZone t = TimeZone.getTimeZone(string);
if (t.getRawOffset() == webBrowser.getRawTimezoneOffset()) {
tz = t;
}
}
return tz;
}
public AboutWindow() {
MHorizontalLayout content = new MHorizontalLayout().withMargin(true).withFullWidth();
this.setContent(content);
Image about = new Image("", new ExternalResource(StorageUtils.generateAssetRelativeLink(WebResourceIds._about)));
MVerticalLayout rightPanel = new MVerticalLayout();
ELabel versionLbl = ELabel.h2(String.format("MyCollab Community Edition %s", Version.getVersion())).withFullWidth();
ELabel javaNameLbl = new ELabel(String.format("%s, %s", System.getProperty("java.vm.name"),
System.getProperty("java.runtime.version"))).withFullWidth();
Label homeFolderLbl = new Label("Home folder: " + AppContextUtil.getSpringBean(ServerConfiguration.class).getHomeDir().getAbsolutePath());
WebBrowser browser = Page.getCurrent().getWebBrowser();
ELabel osLbl = new ELabel(String.format("%s, %s", System.getProperty("os.name"), browser.getBrowserApplication())).withFullWidth();
Div licenseDiv = new Div().appendChild(new Text("Powered by: "))
.appendChild(new A("https://www.mycollab.com")
.appendText("MyCollab")).appendChild(new Text(". Open source under GPL license"));
ELabel licenseLbl = ELabel.html(licenseDiv.write()).withFullWidth();
Label copyRightLbl = ELabel.html(String.format("© %s - %s MyCollab Ltd. All rights reserved", "2011",
LocalDate.now().getYear() + "")).withFullWidth();
rightPanel.with(versionLbl, javaNameLbl, osLbl, homeFolderLbl, licenseLbl, copyRightLbl).withAlign(copyRightLbl, Alignment.BOTTOM_LEFT);
content.with(about, rightPanel).expand(rightPanel);
}
protected String makeClientInfo() {
// timezone info is passed only on VaadinSession creation
WebBrowser webBrowser = getWebBrowserDetails();
//noinspection UnnecessaryLocalVariable
String serverInfo = String.format("Web (%s:%s/%s) %s",
globalConfig.getWebHostName(),
globalConfig.getWebPort(),
globalConfig.getWebContextName(),
webBrowser.getBrowserApplication());
return serverInfo;
}
protected TimeZone detectTimeZone() {
WebBrowser webBrowser = getWebBrowserDetails();
int offset = webBrowser.getTimezoneOffset() / 1000 / 60;
char sign = offset >= 0 ? '+' : '-';
int absOffset = Math.abs(offset);
String hours = StringUtils.leftPad(String.valueOf(absOffset / 60), 2, '0');
String minutes = StringUtils.leftPad(String.valueOf(absOffset % 60), 2, '0');
return TimeZone.getTimeZone("GMT" + sign + hours + minutes);
}
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 isMobileDevice() {
WebBrowser browser = AppUI.getCurrent()
.getPage()
.getWebBrowser();
return browser.getScreenWidth() < 500
|| browser.getScreenHeight() < 800;
}
@Override
public void attach() {
super.attach();
WebBrowser webBrowser = Page.getCurrent().getWebBrowser();
if (webBrowser.isIE() || webBrowser.isEdge()) {
CubaImageObjectFitPolyfillExtension.get(getUI());
}
}
protected void initLayout() {
container = new CubaCssActionsLayout();
container.setPrimaryStyleName(LAYOUT_STYLENAME);
container.setWidth(100, Unit.PERCENTAGE);
field.setWidth(100, Unit.PERCENTAGE);
Page current = Page.getCurrent();
if (current != null) {
WebBrowser browser = current.getWebBrowser();
if (browser != null
&& browser.isSafari()) {
inputWrapper = new CssLayout();
inputWrapper.setWidth(100, Unit.PERCENTAGE);
inputWrapper.setPrimaryStyleName("safari-input-wrap");
inputWrapper.addComponent(field);
container.addComponent(inputWrapper);
} else {
container.addComponent(field);
}
} else {
container.addComponent(field);
}
setFocusDelegate((Focusable) field);
}
/**
* Returns the ctrl or meta modifier depending on the platform.
*
* @return on mac return
* {@link com.vaadin.event.ShortcutAction.ModifierKey#META} other
* platform return
* {@link com.vaadin.event.ShortcutAction.ModifierKey#CTRL}
*/
public static int getCtrlOrMetaModifier() {
final WebBrowser webBrowser = Page.getCurrent().getWebBrowser();
if (webBrowser.isMacOSX()) {
return ShortcutAction.ModifierKey.META;
}
return ShortcutAction.ModifierKey.CTRL;
}
@Override
protected void init(final VaadinRequest request) {
VaadinSession.getCurrent().setErrorHandler(new UiInstanceErrorHandler(this));
setSizeFull();
springNavigator.addView(CRLF_REPLACEMENT, mainView);
setNavigator(springNavigator);
final Page currentPage = Page.getCurrent();
final String requestUrl = currentPage.getLocation().toString();
final String language = request.getLocale().getLanguage();
final UserConfiguration userConfiguration = configurationManager.getUserConfiguration(requestUrl, language);
currentPage.setTitle(userConfiguration.getAgency().getAgencyName() + ":" + userConfiguration.getPortal().getPortalName() + ":" + userConfiguration.getLanguage().getLanguageName());
if (getSession().getUIs().isEmpty()) {
final WebBrowser webBrowser = currentPage.getWebBrowser();
final CreateApplicationSessionRequest serviceRequest = new CreateApplicationSessionRequest();
serviceRequest.setSessionId(RequestContextHolder.currentRequestAttributes().getSessionId());
final String ipInformation = WebBrowserUtil.getIpInformation(webBrowser);
serviceRequest.setIpInformation(ipInformation);
serviceRequest.setTimeZone(webBrowser.getTimeZoneId());
serviceRequest.setScreenSize(webBrowser.getScreenWidth() + "x" + webBrowser.getScreenHeight());
serviceRequest.setUserAgentInformation(webBrowser.getBrowserApplication());
serviceRequest.setLocale(webBrowser.getLocale().toString());
serviceRequest.setOperatingSystem(WebBrowserUtil.getOperatingSystem(webBrowser));
serviceRequest.setSessionType(ApplicationSessionType.ANONYMOUS);
final ServiceResponse serviceResponse = applicationManager.service(serviceRequest);
LOGGER.info(LOG_INFO_BROWSER_ADDRESS_APPLICATION_SESSION_ID_RESULT,requestUrl.replaceAll(CRLF,CRLF_REPLACEMENT),language.replaceAll(CRLF,CRLF_REPLACEMENT),ipInformation.replaceAll(CRLF,CRLF_REPLACEMENT),webBrowser.getBrowserApplication().replaceAll(CRLF,CRLF_REPLACEMENT),serviceRequest.getSessionId().replaceAll(CRLF,CRLF_REPLACEMENT),serviceResponse.getResult().toString().replaceAll(CRLF,CRLF_REPLACEMENT));
}
}
/**
* Gets the ip information.
*
* @param webBrowser
* the web browser
* @return the ip information
*/
public static String getIpInformation(final WebBrowser webBrowser) {
String ipInformation=webBrowser.getAddress();
final HttpServletRequest httpRequest=((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest();
final String xForwardedForHeader = httpRequest.getHeader(X_FORWARDED_FOR);
if (xForwardedForHeader != null) {
final String[] split = xForwardedForHeader.split(",");
if (split.length != 0) {
ipInformation = split[0];
}
}
return ipInformation;
}
/**
* Gets the ip information null test.
*
* @return the ip information null test
*/
@Test
public void getIpInformationNullTest() {
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(new MockHttpServletRequest("GET", "/path")));
final WebBrowser webBrowser = new WebBrowser();
assertNull(WebBrowserUtil.getIpInformation(webBrowser));
}
/**
* Gets the ip information X forward proxy test.
*
* @return the ip information X forward proxy test
*/
@Test
public void getIpInformationXForwardProxyTest() {
final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/path");
request.addHeader(WebBrowserUtil.X_FORWARDED_FOR, "203.0.113.195, 70.41.3.18, 150.172.238.178");
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
final WebBrowser webBrowser = new WebBrowser();
assertEquals("203.0.113.195",WebBrowserUtil.getIpInformation(webBrowser));
}
/**
* Gets the ip information X forward test.
*
* @return the ip information X forward test
*/
@Test
public void getIpInformationXForwardTest() {
final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/path");
request.addHeader(WebBrowserUtil.X_FORWARDED_FOR, "203.0.113.195");
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
final WebBrowser webBrowser = new WebBrowser();
assertEquals("203.0.113.195",WebBrowserUtil.getIpInformation(webBrowser));
}
protected boolean supportsFileDrops() {
WebBrowser browser = getUI().getPage().getWebBrowser();
if (browser.isChrome()) {
return true;
} else if (browser.isFirefox()) {
return true;
} else if (browser.isSafari()) {
return true;
} else if (browser.isIE() && browser.getBrowserMajorVersion() >= 11) {
return true;
}
return false;
}
@Nullable
@Override
public DeviceInfo getDeviceInfo() {
// per request cache
HttpServletRequest currentServletRequest = VaadinServletService.getCurrentServletRequest();
if (currentServletRequest == null) {
return null;
}
DeviceInfo deviceInfo = (DeviceInfo) currentServletRequest.getAttribute(DeviceInfoProvider.NAME);
if (deviceInfo != null) {
return deviceInfo;
}
Page page = Page.getCurrent();
if (page == null) {
return null;
}
WebBrowser webBrowser = page.getWebBrowser();
DeviceInfo di = new DeviceInfo();
di.setAddress(webBrowser.getAddress());
di.setBrowserApplication(webBrowser.getBrowserApplication());
di.setBrowserMajorVersion(webBrowser.getBrowserMajorVersion());
di.setBrowserMinorVersion(webBrowser.getBrowserMinorVersion());
di.setChrome(webBrowser.isChrome());
di.setChromeFrame(webBrowser.isChromeFrame());
di.setChromeFrameCapable(webBrowser.isChromeFrameCapable());
di.setEdge(webBrowser.isEdge());
di.setFirefox(webBrowser.isFirefox());
di.setOpera(webBrowser.isOpera());
di.setIE(webBrowser.isIE());
di.setSafari(webBrowser.isSafari());
if (webBrowser.isWindows()) {
di.setOperatingSystem(OperatingSystem.WINDOWS);
} else if (webBrowser.isAndroid()) {
di.setOperatingSystem(OperatingSystem.ANDROID);
} else if (webBrowser.isIOS()) {
di.setOperatingSystem(OperatingSystem.IOS);
} else if (webBrowser.isMacOSX()) {
di.setOperatingSystem(OperatingSystem.MACOSX);
} else if (webBrowser.isLinux()) {
di.setOperatingSystem(OperatingSystem.LINUX);
}
di.setIPad(webBrowser.isIPad());
di.setIPhone(webBrowser.isIPhone());
di.setWindowsPhone(webBrowser.isWindowsPhone());
di.setSecureConnection(webBrowser.isSecureConnection());
di.setLocale(webBrowser.getLocale());
di.setScreenHeight(webBrowser.getScreenHeight());
di.setScreenWidth(webBrowser.getScreenWidth());
currentServletRequest.setAttribute(DeviceInfoProvider.NAME, di);
return di;
}
public static boolean browserSupportCopy() {
WebBrowser webBrowser = Page.getCurrent().getWebBrowser();
return !webBrowser.isSafari() && !webBrowser.isIOS() && !webBrowser.isWindowsPhone();
}
protected void setupVaadinUi() {
AutowireCapableBeanFactory injector = getInjector();
app = new DefaultApp();
setThemeConstants(app, new ThemeConstants(new HashMap<>()));
setCookies(app, new AppCookies());
Connection connection = new ConnectionImpl();
injector.autowireBean(connection);
setConnection(app, connection);
VaadinSession vaadinSession = new TestVaadinSession(new WebBrowser(), getLocale());
vaadinSession.setAttribute(App.class, app);
vaadinSession.setAttribute(App.NAME, app);
vaadinSession.setAttribute(Connection.class, connection);
vaadinSession.setAttribute(Connection.NAME, connection);
vaadinSession.setAttribute(UserSession.class, sessionSource.getSession());
VaadinSession.setCurrent(vaadinSession);
injector.autowireBean(app);
ui = new AppUI();
injector.autowireBean(ui);
// setup UI
ConnectorTracker connectorTracker = new TestConnectorTracker(ui);
try {
getDeclaredField(UI.class, "connectorTracker", true)
.set(ui, connectorTracker);
getDeclaredField(UI.class, "session", true)
.set(ui, vaadinSession);
} catch (Exception e) {
throw new RuntimeException("Unable to init Vaadin UI state", e);
}
UI.setCurrent(ui);
VaadinRequest vaadinRequest = new TestVaadinRequest();
ui.getPage().init(vaadinRequest);
initUi(ui, vaadinRequest);
}
public TestVaadinSession(WebBrowser webBrowser, Locale locale) {
super(new VaadinServletService(){});
this.webBrowser = webBrowser;
setLocale(locale);
}
@Override
public WebBrowser getBrowser() {
return webBrowser;
}
private static boolean isUnsupportedBrowser() {
final WebBrowser webBrowser = Page.getCurrent().getWebBrowser();
return webBrowser.isIE() && webBrowser.getBrowserMajorVersion() < 11;
}
@Override
public void enter(ViewChangeEvent event) {
logger.debug("Entering {} view ", QuestionnaireView.NAME);
addStyleName(Reindeer.LAYOUT_BLUE);
addStyleName("questionnaires");
WebBrowser webBrowser = Page.getCurrent().getWebBrowser();
Integer screenWidth = webBrowser.getScreenWidth();
Integer heightWidth = webBrowser.getScreenHeight();
logger.debug("Browser screen settings {} x {}", screenWidth, heightWidth);
if (heightWidth <= 480) {
renderingMode = RenderingMode.QUESTION_BY_QUESTION;
}
// centralLayout.addStyleName("questionnaires");
// new Responsive(centralLayout);
RespondentAccount respondent = (RespondentAccount) VaadinServletService.getCurrentServletRequest()
.getUserPrincipal();
if (respondent.hasPreferredLanguage()) {
preferredLanguage = Language.fromString(respondent.getPreferredLanguage());
} else {
preferredLanguage = Language.fromLocale(webBrowser.getLocale());
}
questionnaireId = respondent.getGrantedquestionnaireIds().iterator().next();
logger.debug("Trying to fetch questionnair identified with id = {} ", questionnaireId);
QuestionnaireDefinitionDTO definition = questionnaireResource.getDefinition(questionnaireId);
sectionInfoVisible = definition.isSectionInfoVisible();
QuestionnairePageDTO page = questionnaireResource.getPage(questionnaireId, renderingMode, preferredLanguage,
NavigationAction.ENTERING);
logger.debug("Displaying page {}/{} with {} questions", page.getMetadata().getNumber(), page.getMetadata()
.getCount(), page.getQuestions().size());
questionsLayout = new VerticalLayout();
update(page);
Label questionnaireTitle = new Label(definition.getLanguageSettings().getTitle());
questionnaireTitle.addStyleName(Reindeer.LABEL_H1);
VerticalLayout mainLayout = new VerticalLayout();
mainLayout.setSizeFull();
mainLayout.setMargin(true);
mainLayout.addComponent(questionnaireTitle);
mainLayout.addComponent(questionsLayout);
// Add the responsive capabilities to the components
Panel centralLayout = new Panel();
centralLayout.setContent(mainLayout);
centralLayout.setSizeFull();
centralLayout.getContent().setSizeUndefined();
Responsive.makeResponsive(questionnaireTitle);
setCompositionRoot(centralLayout);
setSizeFull();
}
/**
* Gets the operating system.
*
* @param webBrowser
* the web browser
* @return the operating system
*/
public static String getOperatingSystem(final WebBrowser webBrowser) {
synchronized (USER_AGENT_ANALYZER) {
final UserAgent userAgent = USER_AGENT_ANALYZER.parse(webBrowser.getBrowserApplication());
return userAgent.getValue(UserAgent.DEVICE_CLASS) + "." +userAgent.getValue(UserAgent.OPERATING_SYSTEM_NAME) +"." + userAgent.getValue(UserAgent.OPERATING_SYSTEM_VERSION);
}
}