com.vaadin.flow.component.UI.getSession()方法的使用及代码示例

x33g5p2x  于2022-02-01 转载在 其他  
字(10.0k)|赞(0)|评价(0)|浏览(335)

本文整理了Java中com.vaadin.flow.component.UI.getSession()方法的一些代码示例,展示了UI.getSession()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。UI.getSession()方法的具体详情如下:
包路径:com.vaadin.flow.component.UI
类名称:UI
方法名:getSession

UI.getSession介绍

[英]Gets the VaadinSession to which this UI is attached.

The method will return null if the UI is not currently attached to a VaadinSession.

Getting a null value is often a problem in constructors of regular components and in the initializers of custom composite components. A standard workaround is to use VaadinSession#getCurrent() to retrieve the application instance that the current request relates to. Another way is to move the problematic initialization to #onAttach(AttachEvent), as described in the documentation of the method.
[中]获取此UI附加到的会话。
如果UI当前未连接到会话,则该方法将返回null。
在常规组件的构造函数和自定义复合组件的初始值设定项中,获取空值通常是一个问题。标准的解决方法是使用VaadinSession#getCurrent()检索当前请求所涉及的应用程序实例。另一种方法是将有问题的初始化移到#onAttach(AttachEvent),如方法文档中所述。

代码示例

代码示例来源:origin: com.vaadin/flow-server

/**
 * Gets the session the component is attached to.
 *
 * @return the session this component is attached to
 */
public VaadinSession getSession() {
  return getUI().getSession();
}

代码示例来源:origin: vaadin/spring

@Override
public void run() {
  // We can acquire the lock after the request started this thread is processed
  // Needed to make sure that this is sent as a push message
  Lock lockInstance = ui.getSession().getLockInstance();
  lockInstance.lock();
  lockInstance.unlock();
  ui.access(() -> execute(ui));
}

代码示例来源:origin: com.vaadin/flow-server

/**
 * Sets current instances for the UI and all related classes. The previously
 * defined values can be restored by passing the returned map to
 * {@link #restoreInstances(Map)}.
 *
 *
 * @param ui
 *            The UI
 * @return A map containing the old values of the instances that this method
 *         updated.
 */
public static Map<Class<?>, CurrentInstance> setCurrent(UI ui) {
  Map<Class<?>, CurrentInstance> old = setCurrent(ui.getSession());
  old.put(UI.class, doSet(UI.class, ui));
  return old;
}

代码示例来源:origin: com.vaadin/flow-server

/**
 * Gets the instantiator to use for the given UI.
 *
 * @param ui
 *            the attached UI for which to find an instantiator, not
 *            <code>null</code>
 * @return the instantiator, not <code>null</code>
 */
static Instantiator get(UI ui) {
  assert ui != null;
  VaadinSession session = ui.getSession();
  assert session != null;
  return session.getService().getInstantiator();
}

代码示例来源:origin: appreciated/vaadin-app-layout

public void setLayoutToSession() {
  UI.getCurrent().getSession().setAttribute(SESSION_ATTRIBUTE_APP_LAYOUT, appLayout);
}

代码示例来源:origin: appreciated/vaadin-app-layout

public static AppLayout getCurrent() {
  return (AppLayout) UI.getCurrent().getSession().getAttribute(SESSION_ATTRIBUTE_APP_LAYOUT);
}

代码示例来源:origin: com.vaadin/flow-server

/**
 * Adds an initialized UI to this session.
 *
 * @param ui
 *         the initialized UI to add.
 */
public void addUI(UI ui) {
  checkHasLock();
  if (ui.getUIId() == -1) {
    throw new IllegalArgumentException(
        "Can not add an UI that has not been initialized.");
  }
  if (ui.getSession() != this) {
    throw new IllegalArgumentException(
        "The UI belongs to a different session");
  }
  uIs.put(ui.getUIId(), ui);
}

代码示例来源:origin: com.vaadin/flow-server

/**
 * Adds the performance timing data (used by TestBench 3) to the UIDL
 * response.
 */
private JsonValue createPerformanceData(UI ui) {
  JsonArray timings = Json.createArray();
  timings.set(0, ui.getSession().getCumulativeRequestDuration());
  timings.set(1, ui.getSession().getLastRequestDuration());
  return timings;
}

代码示例来源:origin: com.vaadin/flow-server

private VaadinSession getSession() {
  NodeOwner owner = getNode().getOwner();
  assert owner instanceof StateTree;
  return ((StateTree) owner).getUI().getSession();
}

代码示例来源:origin: com.vaadin/flow-server

private void handleInvocationData(UI ui, JsonObject invocationJson) {
  String type = invocationJson.getString(JsonConstants.RPC_TYPE);
  RpcInvocationHandler handler = getInvocationHandlers().get(type);
  if (handler == null) {
    throw new IllegalArgumentException(
        "Unsupported event type: " + type);
  }
  try {
    Optional<Runnable> handle = handler.handle(ui, invocationJson);
    assert !handle.isPresent() : "RPC handler "
        + handler.getClass().getName()
        + " returned a Runnable even though it shouldn't";
  } catch (Exception e) {
    ui.getSession().getErrorHandler().error(new ErrorEvent(e));
  }
}

代码示例来源:origin: com.vaadin/flow-server

@Override
  public void handleError(Exception exception) {
    try {
      if (command instanceof ErrorHandlingCommand) {
        ErrorHandlingCommand errorHandlingCommand = (ErrorHandlingCommand) command;
        errorHandlingCommand.handleError(exception);
      } else {
        getSession().getErrorHandler()
            .error(new ErrorEvent(exception));
      }
    } catch (Exception e) {
      getLogger().error(e.getMessage(), e);
    }
  }
});

代码示例来源:origin: com.vaadin/flow-server

/**
 * Sets the navigation {@code handler} and the navigation {@code event}
 * for this action.
 *
 * @param handler
 *            the navigation handler
 * @param event
 *            the navigation event
 */
public void setReferences(NavigationHandler handler,
    NavigationEvent event) {
  if (event != null) {
    event.getUI().getSession().hasLock();
  } else {
    assert UI.getCurrent() != null
        && UI.getCurrent().getSession().hasLock();
  }
  this.handler = handler;
  this.event = event;
}

代码示例来源:origin: vaadin/spring

@Override
  public void run() {
    // We can acquire the lock after the request started this thread is processed
    // Needed to make sure that this is sent as a push message
    Lock lockInstance = ui.getSession().getLockInstance();
    lockInstance.lock();
    lockInstance.unlock();
    ui.access(() -> {
      Paragraph world = new Paragraph("World");
      world.setId("world");
      add(world);
    });
  }
}

代码示例来源:origin: com.vaadin/flow-server

/**
   * Resumes the page transition associated with the postponed event.
   */
  public void proceed() {
    BeforeLeaveEvent.this.continueNavigationAction = null;
    if (handler != null && event != null) {
      if (!event.getUI().getSession().hasLock()) {
        throw new IllegalStateException(
            "The method 'proceed' may not be called without the session lock. "
                + "Use UI.access() to execute any UI related code from a separate thread properly");
      }
      handler.handle(event);
      setReferences(null, null);
    }
  }
}

代码示例来源:origin: com.vaadin/flow-server

/**
 * Creates a new bootstrap resolver based on the given request and
 * session.
 *
 * @param ui
 *            the ui to resolve for
 */
protected BootstrapUriResolver(UI ui) {
  servletPathToContextRoot = ui.getInternals()
      .getContextRootRelativePath();
  VaadinSession session = ui.getSession();
  DeploymentConfiguration config = session.getConfiguration();
  if (session.getBrowser().isEs6Supported()) {
    frontendRootUrl = config.getEs6FrontendPrefix();
  } else {
    frontendRootUrl = config.getEs5FrontendPrefix();
  }
  assert frontendRootUrl.endsWith("/");
  assert servletPathToContextRoot.endsWith("/");
}

代码示例来源:origin: com.vaadin/flow-server

private void accessSynchronously(Command command,
    SerializableRunnable detachHandler) {
  Map<Class<?>, CurrentInstance> old = null;
  VaadinSession session = getSession();
  if (session == null) {
    handleAccessDetach(detachHandler);
    return;
  }
  VaadinService.verifyNoOtherSessionLocked(session);
  session.lock();
  try {
    if (getSession() == null) {
      // UI was detached after fetching the session but before we
      // acquired the lock.
      handleAccessDetach(detachHandler);
      return;
    }
    old = CurrentInstance.setCurrent(this);
    command.execute();
  } finally {
    session.unlock();
    if (old != null) {
      CurrentInstance.restoreInstances(old);
    }
  }
}

代码示例来源:origin: com.vaadin/flow-server

@Override
public int setErrorParameter(BeforeEnterEvent event,
    ErrorParameter<NotFoundException> parameter) {
  String path = event.getLocation().getPath();
  String additionalInfo = "";
  if (parameter.hasCustomMessage()) {
    additionalInfo = "Reason: " + parameter.getCustomMessage();
  }
  boolean productionMode = event.getUI().getSession().getConfiguration()
      .isProductionMode();
  String template = getErrorHtml(productionMode);
  template = template.replace("{{path}}", path);
  template = template.replace("{{additionalInfo}}", additionalInfo);
  if (template.contains("{{routes}}")) {
    template = template.replace("{{routes}}", getRoutes(event));
  }
  getElement().appendChild(new Html(template).getElement());
  return HttpServletResponse.SC_NOT_FOUND;
}

代码示例来源:origin: com.vaadin/flow-server

/**
 * Generates the initial UIDL message which is included in the initial
 * bootstrap page.
 *
 * @param ui
 *            the UI for which the UIDL should be generated
 * @return a JSON object with the initial UIDL message
 */
protected static JsonObject getInitialUidl(UI ui) {
  JsonObject json = new UidlWriter().createUidl(ui, false);
  VaadinSession session = ui.getSession();
  if (session.getConfiguration().isXsrfProtectionEnabled()) {
    writeSecurityKeyUIDL(json, session);
  }
  writePushIdUIDL(json, session);
  if (getLogger().isDebugEnabled()) {
    getLogger().debug("Initial UIDL: {}", json.asString());
  }
  return json;
}

代码示例来源:origin: com.vaadin/flow-server

@Override
public void setPushMode(PushMode pushMode) {
  if (pushMode == null) {
    throw new IllegalArgumentException("Push mode cannot be null");
  }
  VaadinSession session = ui.getSession();
  if (session == null) {
    throw new UIDetachedException(
        "Cannot set the push mode for a detached UI");
  }
  session.checkHasLock();
  if (pushMode.isEnabled()
      && !session.getService().ensurePushAvailable()) {
    throw new IllegalStateException(
        "Push is not available. See previous log messages for more information.");
  }
  PushMode oldMode = getPushConfigurationMap().getPushMode();
  if (oldMode != pushMode) {
    getPushConfigurationMap().setPushMode(pushMode);
    if (!oldMode.isEnabled() && pushMode.isEnabled()) {
      // The push connection is initially in a disconnected state;
      // the client will establish the connection
      ui.getInternals()
        .setPushConnection(pushConnectionFactory.apply(ui));
    }
    // Nothing to do here if disabling push;
    // the client will close the connection
  }
}

代码示例来源:origin: com.holon-platform.vaadin/holon-vaadin-flow

@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() + "]");
        }
      }
    }
  });
}

相关文章