public void di1() { UI myUI = null; // tag::di1[] Optional<DeviceInfo> deviceInfo = DeviceInfo.get(myUI); // <1> deviceInfo = DeviceInfo.get(); // <2> DeviceInfo info = DeviceInfo.require(); // <3> info.getAcceptHeader(); // <4> info.getUserAgentHeader(); // <5> info.getWindowWidth(); // <6> info.getWindowHeight(); // <7> info.isSmartphone(); // <8> // ... // end::di1[] }
/** * Get the {@link DeviceInfo} for the current UI, throwing a {@link IllegalStateException} if not available. * @return The {@link DeviceInfo} for the current UI * @throws IllegalStateException If a DeviceInfo for current UI is not available */ static DeviceInfo require() { return get().orElseThrow(() -> new IllegalStateException("A DeviceInfo for current UI is not available")); }
@Override public void serviceInit(ServiceInitEvent event) { // Session event.getSource().addSessionInitListener(e -> { // DeviceInfo registry is available if (e.getSession().getAttribute(DeviceInfoRegistry.class) == null) { e.getSession().setAttribute(DeviceInfoRegistry.class, new DefaultDeviceInfoRegistry()); } }); // UI init event.getSource().addUIInitListener(e -> { if (e.getUI().getSession() != null) { // configure DeviceInfo final DeviceInfoRegistry registry = e.getUI().getSession().getAttribute(DeviceInfoRegistry.class); if (registry != null && !registry.hasDeviceInfo(e.getUI())) { final VaadinRequest request = VaadinRequest.getCurrent(); if (request != null) { registry.setDeviceInfo(e.getUI(), DeviceInfo.create(e.getUI(), request)); // log LOGGER.debug(() -> "A DeviceInfo was configured for UI with id [" + e.getUI().getUIId() + "]"); } } } }); }
/** * Get the {@link DeviceInfo} for the current UI, if available. * @return Optional {@link DeviceInfo} for the current UI */ static Optional<DeviceInfo> get() { final UI ui = UI.getCurrent(); if (ui != null) { return get(ui); } return Optional.empty(); }