下面列出了org.apache.commons.lang3.SerializationException#com.vaadin.flow.component.UI 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void setResourceAttributeSeveralTimes_elementIsNotAttached_elementHasAttribute() {
UI.setCurrent(createUI());
Element element = ElementFactory.createDiv();
String resName = "resource";
StreamResource resource = createEmptyResource(resName);
element.setAttribute("foo", resource);
Assert.assertTrue(element.hasAttribute("foo"));
resName = "resource1";
resource = createEmptyResource(resName);
element.setAttribute("foo", resource);
Assert.assertTrue(element.hasAttribute("foo"));
Assert.assertTrue(element.getAttribute("foo").endsWith(resName));
}
@Test
public void setResourceAttribute_elementIsAttached_setAnotherResource()
throws URISyntaxException {
UI ui = createUI();
UI.setCurrent(ui);
StreamResource resource = createEmptyResource("resource1");
ui.getElement().setAttribute("foo", resource);
String uri = ui.getElement().getAttribute("foo");
Optional<StreamResource> res = ui.getSession().getResourceRegistry()
.getResource(StreamResource.class, new URI(uri));
Assert.assertTrue(res.isPresent());
String resName = "resource2";
ui.getElement().setAttribute("foo", createEmptyResource(resName));
res = ui.getSession().getResourceRegistry()
.getResource(StreamResource.class, new URI(uri));
Assert.assertFalse(res.isPresent());
Assert.assertTrue(ui.getElement().hasAttribute("foo"));
Assert.assertTrue(
ui.getElement().getAttribute("foo").endsWith(resName));
}
/**
* 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);
JsonObject response = new UidlWriter().createUidl(ui, async);
sendMessage("for(;;);[" + response.toJson() + "]");
} catch (Exception e) {
throw new PushException("Push failed", e);
}
}
}
@Test
public void registerEventHandlers_elementsAreAlreadyAttached_setupEvenHandlers() {
UI ui = new TestUI();
Element contentTemplate = new Element(Tag.DIV);
Element templateDataHost = new Element(Tag.SPAN);
attachElements(ui, contentTemplate, templateDataHost);
TestUIInternals internals = (TestUIInternals) ui.getInternals();
Renderer<String> renderer = new Renderer<>();
renderer.setEventHandler("foo", value -> {
});
RendererUtil.registerEventHandlers(renderer, contentTemplate,
templateDataHost, ValueProvider.identity());
assertJSExecutions(ui, internals, contentTemplate, templateDataHost);
}
@Test
public void testAttachDetach_elementMoved_bothEventsTriggered() {
Element body = new UI().getElement();
Element parent = ElementFactory.createDiv();
Element child = ElementFactory.createDiv();
parent.appendChild(child);
body.appendChild(parent);
AtomicBoolean attached = new AtomicBoolean();
AtomicBoolean detached = new AtomicBoolean();
child.addAttachListener(event -> {
attached.set(true);
Assert.assertTrue(detached.get());
});
child.addDetachListener(event -> {
detached.set(true);
Assert.assertFalse(attached.get());
});
body.appendChild(child);
Assert.assertTrue(attached.get());
Assert.assertTrue(detached.get());
}
@Test
public void servletWithEnclosingUI_hasItsNameInConfig() throws Exception {
Class<TestUI.ServletWithEnclosingUi> servlet = TestUI.ServletWithEnclosingUi.class;
Map<String, String> servletConfigParams = new HashMap<>(
new HashMap<>(defaultServletParams));
DeploymentConfiguration config = DeploymentConfigurationFactory
.createDeploymentConfiguration(servlet,
createVaadinConfigMock(servletConfigParams,
Collections.singletonMap(PARAM_TOKEN_FILE,
tokenFile.getPath())));
Class<?> customUiClass = servlet.getEnclosingClass();
assertTrue(String.format(
"Servlet '%s' should have its enclosing class to be UI subclass, but got: '%s'",
customUiClass, servlet),
UI.class.isAssignableFrom(customUiClass));
assertEquals(String.format(
"Expected DeploymentConfiguration for servlet '%s' to have its enclosing UI class",
servlet), customUiClass.getName(), config.getUIClassName());
}
private void assertPushConfigurationForComponent(
Class<? extends Component> annotatedClazz,
Class<? extends PushConnection> pushConnectionType)
throws InvalidRouteConfigurationException {
BootstrapHandler bootstrapHandler = new BootstrapHandler();
VaadinResponse response = mock(VaadinResponse.class);
RouteConfiguration routeConfiguration = RouteConfiguration
.forRegistry(service.getRouteRegistry());
routeConfiguration.update(() -> {
routeConfiguration.getHandledRegistry().clean();
routeConfiguration.setAnnotatedRoute(annotatedClazz);
});
final BootstrapHandler.BootstrapContext context = bootstrapHandler
.createAndInitUI(UI.class, createVaadinRequest(), response,
session);
Push pushAnnotation = annotatedClazz.getAnnotation(Push.class);
Assert.assertNotNull("Should have @Push annotated component",
pushAnnotation);
PushConfiguration pushConfiguration = context.getUI()
.getPushConfiguration();
assertPushConfiguration(pushConfiguration, pushAnnotation);
assertThat(context.getUI().getInternals().getPushConnection(),
instanceOf(pushConnectionType));
}
@Test
public void should_not_initialize_UI_and_add_initialUidl_when_invalid_route()
throws IOException {
deploymentConfiguration.setEagerServerLoad(true);
service.setBootstrapInitialPredicate(request -> {
return request.getPathInfo().equals("/");
});
indexHtmlRequestHandler.synchronizedHandleRequest(session,
createVaadinRequest("/foo"), response);
String indexHtml = responseOutput
.toString(StandardCharsets.UTF_8.name());
Document document = Jsoup.parse(indexHtml);
Elements scripts = document.head().getElementsByTag("script");
Assert.assertEquals(1, scripts.size());
Assert.assertEquals("window.Vaadin = {TypeScript: {}};",
scripts.get(0).childNode(0).toString());
Assert.assertEquals("", scripts.get(0).attr("initial"));
Assert.assertNull(UI.getCurrent());
}
@Override
public boolean synchronizedHandleRequest(VaadinSession session,
VaadinRequest request, VaadinResponse response) throws IOException {
// Find UI class
Class<? extends UI> uiClass = getUIClass(request);
BootstrapContext context = createAndInitUI(uiClass, request, response,
session);
HandlerHelper.setResponseNoCacheHeaders(response::setHeader,
response::setDateHeader);
Document document = pageBuilder.getBootstrapPage(context);
writeBootstrapPage(response, document.outerHtml());
return true;
}
public InitialExtendedClientDetailsView() {
UI.getCurrent().getPage().retrieveExtendedClientDetails(details ->{
addSpan("screenWidth", details.getScreenWidth());
addSpan("screenHeight", details.getScreenHeight());
addSpan("windowInnerWidth",details.getWindowInnerWidth());
addSpan("windowInnerHeight",details.getWindowInnerHeight());
addSpan("bodyClientWidth",details.getBodyClientWidth());
addSpan("bodyClientHeight",details.getBodyClientHeight());
addSpan("timezoneOffset", details.getTimezoneOffset());
addSpan("timeZoneId", details.getTimeZoneId());
addSpan("rawTimezoneOffset", details.getRawTimezoneOffset());
addSpan("DSTSavings", details.getDSTSavings());
addSpan("DSTInEffect", details.isDSTInEffect());
addSpan("currentDate", details.getCurrentDate());
addSpan("touchDevice", details.isTouchDevice());
addSpan("devicePixelRatio", details.getDevicePixelRatio());
addSpan("windowName", details.getWindowName());
});
}
/**
* Finds the {@link UI} that belongs to the provided request. This is
* generally only supported for UIDL requests as other request types are not
* related to any particular UI or have the UI information encoded in a
* non-standard way. The returned UI is also set as the current UI (
* {@link UI#setCurrent(UI)}).
*
* @param request
* the request for which a UI is desired
* @return the UI belonging to the request or null if no UI is found
*/
public UI findUI(VaadinRequest request) {
// getForSession asserts that the lock is held
VaadinSession session = loadSession(request.getWrappedSession());
// Get UI id from the request
String uiIdString = request
.getParameter(ApplicationConstants.UI_ID_PARAMETER);
UI ui = null;
if (uiIdString != null && session != null) {
int uiId = Integer.parseInt(uiIdString);
ui = session.getUIById(uiId);
}
UI.setCurrent(ui);
return ui;
}
@Test
public void servletWithNoEnclosingUI_hasDefaultUiInConfig()
throws Exception {
Class<NoSettings> servlet = NoSettings.class;
Map<String, String> servletConfigParams = new HashMap<>(
defaultServletParams);
DeploymentConfiguration config = DeploymentConfigurationFactory
.createDeploymentConfiguration(servlet, createVaadinConfigMock(
servletConfigParams, emptyMap()));
Class<?> notUiClass = servlet.getEnclosingClass();
assertFalse(String.format(
"Servlet '%s' should not have its enclosing class to be UI subclass, but got: '%s'",
notUiClass, servlet), UI.class.isAssignableFrom(notUiClass));
assertEquals(String.format(
"Expected DeploymentConfiguration for servlet '%s' to have its enclosing UI class",
servlet), UI.class.getName(), config.getUIClassName());
}
public CustomScrollCallbacksView() {
viewName.setId("view");
log.setId("log");
log.getStyle().set("white-space", "pre");
UI.getCurrent().getPage().executeJs(
"window.Vaadin.Flow.setScrollPosition = function(xAndY) { $0.textContent += JSON.stringify(xAndY) + '\\n' }",
log);
UI.getCurrent().getPage().executeJs(
"window.Vaadin.Flow.getScrollPosition = function() { return [42, -window.pageYOffset] }");
RouterLink navigate = new RouterLink("Navigate",
CustomScrollCallbacksView.class, "navigated");
navigate.setId("navigate");
Anchor back = new Anchor("javascript:history.go(-1)", "Back");
back.setId("back");
add(viewName, log, new Span("Scroll down to see navigation actions"),
ScrollView.createSpacerDiv(2000), navigate, back);
}
public RouterLinkView() {
Element bodyElement = getElement();
bodyElement.getStyle().set("margin", "1em");
Element location = ElementFactory.createDiv("no location")
.setAttribute("id", "location");
Element queryParams = ElementFactory.createDiv("no queryParams")
.setAttribute("id", "queryParams");
bodyElement.appendChild(location, new Element("p"));
bodyElement.appendChild(queryParams, new Element("p"));
addLinks();
getPage().getHistory().setHistoryStateChangeHandler(e -> {
location.setText(e.getLocation().getPath());
queryParams.setText(
e.getLocation().getQueryParameters().getQueryString());
if (e.getState().isPresent())
UI.getCurrent().getPage().getHistory().pushState(null,
((JsonObject) e.getState().get()).getString("href"));
});
addImageLink();
}
@Test
public void initModel_sendUpdatableProperties() {
UI ui = UI.getCurrent();
InitModelTemplate template = new InitModelTemplate();
ui.add(template);
ui.getInternals().getStateTree().runExecutionsBeforeClientResponse();
Assert.assertEquals(2, executionOrder.size());
Assert.assertEquals("this.registerUpdatableModelProperties($0, $1)",
executionOrder.get(0));
Serializable[] params = executionParams.get(0);
JsonArray properties = (JsonArray) params[1];
Assert.assertEquals(2, properties.length());
Set<String> props = new HashSet<>();
props.add(properties.get(0).asString());
props.add(properties.get(1).asString());
// all model properties except 'list' which has no getter
Assert.assertTrue(props.contains("message"));
Assert.assertTrue(props.contains("title"));
}
@Test
public void testDetachListener_eventOrder_childFirst() {
Element body = new UI().getElement();
Element parent = ElementFactory.createDiv();
Element child = ElementFactory.createDiv();
parent.appendChild(child);
body.appendChild(parent);
AtomicBoolean parentDetached = new AtomicBoolean();
AtomicBoolean childDetached = new AtomicBoolean();
child.addDetachListener(event -> {
childDetached.set(true);
Assert.assertFalse(parentDetached.get());
});
parent.addDetachListener(event -> {
parentDetached.set(true);
Assert.assertTrue(childDetached.get());
});
body.removeAllChildren();
Assert.assertTrue(parentDetached.get());
Assert.assertTrue(childDetached.get());
}
@Test
public void should_use_client_routing_when_there_is_a_router_call()
throws IOException {
deploymentConfiguration.setEagerServerLoad(true);
indexHtmlRequestHandler.synchronizedHandleRequest(session,
createVaadinRequest("/"), response);
Mockito.verify(session, Mockito.times(1)).setAttribute(SERVER_ROUTING,
Boolean.TRUE);
Mockito.verify(session, Mockito.times(0)).setAttribute(SERVER_ROUTING,
Boolean.FALSE);
((JavaScriptBootstrapUI) UI.getCurrent()).connectClient("foo", "bar",
"/foo");
Mockito.verify(session, Mockito.times(1)).setAttribute(SERVER_ROUTING,
Boolean.FALSE);
}
@Test
public void callFunctionBeforeDetach() {
UI ui = new MockUI();
Element element = ElementFactory.createDiv();
ui.getElement().appendChild(element);
element.callJsFunction("noArgsMethod");
ui.getElement().removeAllChildren();
ui.getInternals().getStateTree().runExecutionsBeforeClientResponse();
List<PendingJavaScriptInvocation> invocations = ui.getInternals()
.dumpPendingJavaScriptInvocations();
Assert.assertTrue(invocations.isEmpty());
}
/**
* Called by the framework to remove an UI instance from the session because
* it has been closed.
*
* @param ui
* the UI to remove
*/
public void removeUI(UI ui) {
checkHasLock();
assert UI.getCurrent() != null : "Current UI cannot be null";
assert ui != null : "Removed UI cannot be null";
assert UI.getCurrent().getUIId() == ui.getUIId() : "UIs don't match";
ui.getInternals().setSession(null);
uIs.remove(ui.getUIId());
}
@Test
public void callFunctionTwoParams() {
UI ui = new MockUI();
Element element = ElementFactory.createDiv();
element.callJsFunction("method", "foo", 123);
ui.getElement().appendChild(element);
ui.getInternals().getStateTree().runExecutionsBeforeClientResponse();
assertPendingJs(ui, "return $0.method($1,$2)", element, "foo", 123);
}
private static SockJSPushConnection getConnectionForUI(UI ui) {
PushConnection pushConnection = ui.getInternals().getPushConnection();
if (pushConnection instanceof SockJSPushConnection) {
return (SockJSPushConnection) pushConnection;
} else {
return null;
}
}
private static UI findUiUsingSocket(PushSocket socket, Collection<UI> uIs) {
for (UI ui : uIs) {
PushConnection pushConnection = ui.getInternals().getPushConnection();
if (pushConnection instanceof SockJSPushConnection &&
((SockJSPushConnection) pushConnection).getSocket() == socket) {
return ui;
}
}
return null;
}
@Test
public void implicitlyDisabledElement_updateIsAllowedBySynchronizeProperty_updateIsDone()
throws Exception {
Element element = ElementFactory.createDiv();
UI ui = new UI();
ui.getElement().appendChild(element);
ui.setEnabled(false);
element.addPropertyChangeListener(TEST_PROPERTY, DUMMY_EVENT, event -> {
}).setDisabledUpdateMode(DisabledUpdateMode.ALWAYS);
sendSynchronizePropertyEvent(element, ui, TEST_PROPERTY, NEW_VALUE);
Assert.assertEquals(NEW_VALUE, element.getPropertyRaw(TEST_PROPERTY));
}
/**
* Needs to be called from the UI Thread.
* @param type
* @param <T>
* @return
*/
public static <T extends Serializable> T get(Class<T> type) {
UIAttributes session = getSession();
UI ui = UI.getCurrent();
if (!session.map.containsKey(UI.getCurrent())) {
session.map.put(ui, new HashMap<>());
}
return (T) session.map.get(ui).get(type);
}
private void runMapSyncTask(UI ui, Runnable runnable) {
try {
runnable.run();
} catch (Throwable throwable) {
ui.getSession().getErrorHandler().error(new ErrorEvent(throwable));
}
}
private static void readUiFromEnclosingClass(
Class<?> systemPropertyBaseClass, Properties initParameters) {
Class<?> enclosingClass = systemPropertyBaseClass.getEnclosingClass();
if (enclosingClass != null
&& UI.class.isAssignableFrom(enclosingClass)) {
initParameters.put(InitParameters.UI_PARAMETER,
enclosingClass.getName());
}
}
private void addComponentHierarchy(UI ui,
Set<Class<? extends Component>> hierarchyStorage,
Component component) {
hierarchyStorage.add(component.getClass());
if (component instanceof Composite) {
addComponentHierarchy(ui, hierarchyStorage,
((Composite<?>) component).getContent());
}
}
/**
* Tests that a UI class can be loaded even if no classloader has been
* provided.
*
* @throws Exception
* if thrown
*/
public void testWithDefaultClassLoader() throws Exception {
VaadinSession application = createStubApplication();
application.setConfiguration(createConfigurationMock());
Class<? extends UI> uiClass = BootstrapHandler
.getUIClass(createRequestMock(getClass().getClassLoader()));
assertEquals(MyUI.class, uiClass);
}
private UI initializeUIForDependenciesTest(UI ui) throws Exception {
mocks = new MockServletServiceSessionSetup();
VaadinSession session = mocks.getSession();
session.lock();
ui.getInternals().setSession(session);
RouteConfiguration routeConfiguration = RouteConfiguration
.forRegistry(ui.getRouter().getRegistry());
routeConfiguration.update(() -> {
routeConfiguration.getHandledRegistry().clean();
routeConfiguration.setAnnotatedRoute(BaseClass.class);
});
for (String type : new String[] { "html", "js", "css" }) {
mocks.getServlet().addServletContextResource("inline." + type,
"inline." + type);
}
HttpServletRequest servletRequestMock = mock(HttpServletRequest.class);
VaadinServletRequest vaadinRequestMock = mock(
VaadinServletRequest.class);
when(vaadinRequestMock.getHttpServletRequest())
.thenReturn(servletRequestMock);
ui.doInit(vaadinRequestMock, 1);
ui.getRouter().initializeUI(ui, vaadinRequestMock);
return ui;
}
@Test
public void setResourceAttribute_elementIsAttached_elementHasAttribute() {
UI ui = createUI();
UI.setCurrent(ui);
String resName = "resource";
StreamResource resource = createEmptyResource(resName);
ui.getElement().setAttribute("foo", resource);
Assert.assertTrue(ui.getElement().hasAttribute("foo"));
Assert.assertTrue(
ui.getElement().getAttribute("foo").endsWith(resName));
}