diff --git a/flow-client/src/main/java/com/vaadin/client/BrowserInfo.java b/flow-client/src/main/java/com/vaadin/client/BrowserInfo.java index c94f94b6ad2..6d93e73ab12 100644 --- a/flow-client/src/main/java/com/vaadin/client/BrowserInfo.java +++ b/flow-client/src/main/java/com/vaadin/client/BrowserInfo.java @@ -209,8 +209,6 @@ private static native String getBrowserString() return $wnd.navigator.userAgent; }-*/; - - private static native boolean isIos() /*-{ return (/iPad|iPhone|iPod/.test(navigator.platform) || diff --git a/flow-client/src/main/java/com/vaadin/client/Console.java b/flow-client/src/main/java/com/vaadin/client/Console.java index 54dfaeef0e0..773ca14dd0e 100644 --- a/flow-client/src/main/java/com/vaadin/client/Console.java +++ b/flow-client/src/main/java/com/vaadin/client/Console.java @@ -30,7 +30,7 @@ */ public final class Console { private static boolean shouldLogToBrowserConsole; - + @FunctionalInterface // Runnable that can throw private interface DeferWithoutEntryTask { diff --git a/flow-client/src/main/java/com/vaadin/client/DefaultRegistry.java b/flow-client/src/main/java/com/vaadin/client/DefaultRegistry.java index 38f79cf54e8..20b197dc149 100644 --- a/flow-client/src/main/java/com/vaadin/client/DefaultRegistry.java +++ b/flow-client/src/main/java/com/vaadin/client/DefaultRegistry.java @@ -118,9 +118,11 @@ public DefaultRegistry(ApplicationConnection connection, new ReconnectDialogConfiguration(this)); if (!applicationConfiguration.isClientRouting()) { if (applicationConfiguration.isWebComponentMode()) { - set(ScrollPositionHandler.class, new WebComponentScrollHandler()); + set(ScrollPositionHandler.class, + new WebComponentScrollHandler()); } else { - set(ScrollPositionHandler.class, new ScrollPositionHandler(this)); + set(ScrollPositionHandler.class, + new ScrollPositionHandler(this)); } } set(Poller.class, new Poller(this)); diff --git a/flow-client/src/main/java/com/vaadin/client/LitUtils.java b/flow-client/src/main/java/com/vaadin/client/LitUtils.java index 67017edab00..468ddf24882 100644 --- a/flow-client/src/main/java/com/vaadin/client/LitUtils.java +++ b/flow-client/src/main/java/com/vaadin/client/LitUtils.java @@ -19,7 +19,8 @@ import elemental.dom.Node; /** - * Utils class, intended to ease working with LitElement related code on client side. + * Utils class, intended to ease working with LitElement related code on client + * side. * * @author Vaadin Ltd */ diff --git a/flow-client/src/main/java/com/vaadin/client/LoadingIndicator.java b/flow-client/src/main/java/com/vaadin/client/LoadingIndicator.java index 0e15c1ee4e8..022f645d618 100644 --- a/flow-client/src/main/java/com/vaadin/client/LoadingIndicator.java +++ b/flow-client/src/main/java/com/vaadin/client/LoadingIndicator.java @@ -39,59 +39,35 @@ public class LoadingIndicator { private static final String PRIMARY_STYLE_NAME = "v-loading-indicator"; - private static final String DEFAULT_THEMING = "@-webkit-keyframes v-progress-start {" + - "0% {width: 0%;}" + - "100% {width: 50%;}}" + - "@-moz-keyframes v-progress-start {" + - "0% {width: 0%;}" + - "100% {width: 50%;}}" + - "@keyframes v-progress-start {" + - "0% {width: 0%;}" + - "100% {width: 50%;}}" + - "@keyframes v-progress-delay {" + - "0% {width: 50%;}" + - "100% {width: 90%;}}" + - "@keyframes v-progress-wait {" + - "0% {width: 90%;height: 4px;}" + - "3% {width: 91%;height: 7px;}" + - "100% {width: 96%;height: 7px;}}" + - "@-webkit-keyframes v-progress-wait-pulse {" + - "0% {opacity: 1;}" + - "50% {opacity: 0.1;}" + - "100% {opacity: 1;}}" + - "@-moz-keyframes v-progress-wait-pulse {" + - "0% {opacity: 1;}" + - "50% {opacity: 0.1;}" + - "100% {opacity: 1;}}" + - "@keyframes v-progress-wait-pulse {" + - "0% {opacity: 1;}" + - "50% {opacity: 0.1;}" + - "100% {opacity: 1;}}" + - ".v-loading-indicator {" + - "position: fixed !important;" + - "z-index: 99999;" + - "left: 0;" + - "right: auto;" + - "top: 0;" + - "width: 50%;" + - "opacity: 1;" + - "height: 4px;" + - "background-color: var(--lumo-primary-color, var(--material-primary-color, blue));" + - "pointer-events: none;" + - "transition: none;" + - "animation: v-progress-start 1000ms 200ms both;}" + - ".v-loading-indicator[style*=\"none\"] {" + - "display: block !important;" + - "width: 100% !important;" + - "opacity: 0;" + - "animation: none !important;" + - "transition: opacity 500ms 300ms, width 300ms;}" + - ".v-loading-indicator.second {" + - "width: 90%;" + - "animation: v-progress-delay 3.8s forwards;}" + - ".v-loading-indicator.third {" + - "width: 96%;" + - "animation: v-progress-wait 5s forwards, v-progress-wait-pulse 1s 4s infinite backwards;}"; + private static final String DEFAULT_THEMING = "@-webkit-keyframes v-progress-start {" + + "0% {width: 0%;}" + "100% {width: 50%;}}" + + "@-moz-keyframes v-progress-start {" + "0% {width: 0%;}" + + "100% {width: 50%;}}" + "@keyframes v-progress-start {" + + "0% {width: 0%;}" + "100% {width: 50%;}}" + + "@keyframes v-progress-delay {" + "0% {width: 50%;}" + + "100% {width: 90%;}}" + "@keyframes v-progress-wait {" + + "0% {width: 90%;height: 4px;}" + "3% {width: 91%;height: 7px;}" + + "100% {width: 96%;height: 7px;}}" + + "@-webkit-keyframes v-progress-wait-pulse {" + "0% {opacity: 1;}" + + "50% {opacity: 0.1;}" + "100% {opacity: 1;}}" + + "@-moz-keyframes v-progress-wait-pulse {" + "0% {opacity: 1;}" + + "50% {opacity: 0.1;}" + "100% {opacity: 1;}}" + + "@keyframes v-progress-wait-pulse {" + "0% {opacity: 1;}" + + "50% {opacity: 0.1;}" + "100% {opacity: 1;}}" + + ".v-loading-indicator {" + "position: fixed !important;" + + "z-index: 99999;" + "left: 0;" + "right: auto;" + "top: 0;" + + "width: 50%;" + "opacity: 1;" + "height: 4px;" + + "background-color: var(--lumo-primary-color, var(--material-primary-color, blue));" + + "pointer-events: none;" + "transition: none;" + + "animation: v-progress-start 1000ms 200ms both;}" + + ".v-loading-indicator[style*=\"none\"] {" + + "display: block !important;" + "width: 100% !important;" + + "opacity: 0;" + "animation: none !important;" + + "transition: opacity 500ms 300ms, width 300ms;}" + + ".v-loading-indicator.second {" + "width: 90%;" + + "animation: v-progress-delay 3.8s forwards;}" + + ".v-loading-indicator.third {" + "width: 96%;" + + "animation: v-progress-wait 5s forwards, v-progress-wait-pulse 1s 4s infinite backwards;}"; private int firstDelay = LoadingIndicatorConfigurationMap.FIRST_DELAY_DEFAULT; private int secondDelay = LoadingIndicatorConfigurationMap.SECOND_DELAY_DEFAULT; @@ -127,7 +103,7 @@ public void run() { * moves into the "first" state and is shown to the user * * @return The delay (in ms) until moving into the "first" state. Counted - * from when {@link #trigger()} is called. + * from when {@link #trigger()} is called. */ public int getFirstDelay() { return firstDelay; @@ -138,8 +114,8 @@ public int getFirstDelay() { * into the "first" state and is shown to the user * * @param firstDelay - * The delay (in ms) until moving into the "first" state. Counted - * from when {@link #trigger()} is called. + * The delay (in ms) until moving into the "first" state. Counted + * from when {@link #trigger()} is called. */ public void setFirstDelay(int firstDelay) { this.firstDelay = firstDelay; @@ -150,7 +126,7 @@ public void setFirstDelay(int firstDelay) { * moves to its "second" state. * * @return The delay (in ms) until the loading indicator moves into its - * "second" state. Counted from when {@link #trigger()} is called. + * "second" state. Counted from when {@link #trigger()} is called. */ public int getSecondDelay() { return secondDelay; @@ -161,9 +137,9 @@ public int getSecondDelay() { * to its "second" state. * * @param secondDelay - * The delay (in ms) until the loading indicator moves into its - * "second" state. Counted from when {@link #trigger()} is - * called. + * The delay (in ms) until the loading indicator moves into its + * "second" state. Counted from when {@link #trigger()} is + * called. */ public void setSecondDelay(int secondDelay) { this.secondDelay = secondDelay; @@ -174,7 +150,7 @@ public void setSecondDelay(int secondDelay) { * moves to its "third" state. * * @return The delay (in ms) until the loading indicator moves into its - * "third" state. Counted from when {@link #trigger()} is called. + * "third" state. Counted from when {@link #trigger()} is called. */ public int getThirdDelay() { return thirdDelay; @@ -185,9 +161,9 @@ public int getThirdDelay() { * to its "third" state. * * @param thirdDelay - * The delay (in ms) from the event until changing the loading - * indicator into its "third" state. Counted from when - * {@link #trigger()} is called. + * The delay (in ms) from the event until changing the loading + * indicator into its "third" state. Counted from when + * {@link #trigger()} is called. */ public void setThirdDelay(int thirdDelay) { this.thirdDelay = thirdDelay; @@ -272,7 +248,8 @@ public boolean isVisible() { */ public Element getElement() { if (element == null) { - element = Browser.getDocument().querySelector("." + PRIMARY_STYLE_NAME); + element = Browser.getDocument() + .querySelector("." + PRIMARY_STYLE_NAME); setupTheming(); if (element == null) { element = Browser.getDocument().createElement("div"); @@ -283,7 +260,8 @@ public Element getElement() { } private void setupTheming() { - Element styleElement = Browser.getDocument().querySelector("style#css-loading-indicator"); + Element styleElement = Browser.getDocument() + .querySelector("style#css-loading-indicator"); if (styleElement == null) { styleElement = Browser.getDocument().createStyleElement(); styleElement.setAttribute("type", "text/css"); @@ -299,12 +277,14 @@ private void setupTheming() { } /** - * Sets whether the default theming should be applied for the loading indicator or not. + * Sets whether the default theming should be applied for the loading + * indicator or not. *

* Default is {@code true}. * * @param applyDefaultTheme - * {@code true} for applying the default theming, {@code false} for not + * {@code true} for applying the default theming, {@code false} + * for not */ public void setApplyDefaultTheme(boolean applyDefaultTheme) { this.applyDefaultTheme = applyDefaultTheme; @@ -312,11 +292,13 @@ public void setApplyDefaultTheme(boolean applyDefaultTheme) { } /** - * Returns whether the default theming should be applied for the loading indicator or not. + * Returns whether the default theming should be applied for the loading + * indicator or not. *

* Default is {@code true}. * - * @return {@code true} for applying the default theming, {@code false} for not + * @return {@code true} for applying the default theming, {@code false} for + * not */ public boolean isApplyDefaultTheme() { return applyDefaultTheme; diff --git a/flow-client/src/main/java/com/vaadin/client/PolymerUtils.java b/flow-client/src/main/java/com/vaadin/client/PolymerUtils.java index 95e6a180d4b..99564246d81 100644 --- a/flow-client/src/main/java/com/vaadin/client/PolymerUtils.java +++ b/flow-client/src/main/java/com/vaadin/client/PolymerUtils.java @@ -178,8 +178,7 @@ private static void registerChangeHandlers(StateNode node, assert feature instanceof NodeMap : "Received an inconsistent NodeFeature for a node that has a ELEMENT_PROPERTIES feature. It should be NodeMap, but it is: " + feature; NodeMap map = (NodeMap) feature; - registerPropertyChangeHandlers(value, registrations, - map); + registerPropertyChangeHandlers(value, registrations, map); registerPropertyAddHandler(value, registrations, map); } else if (node.hasFeature(NodeFeatures.TEMPLATE_MODELLIST)) { assert feature instanceof NodeList : "Received an inconsistent NodeFeature for a node that has a TEMPLATE_MODELLIST feature. It should be NodeList, but it is: " @@ -205,8 +204,8 @@ private static void registerPropertyAddHandler(JsonValue value, })); } - private static void registerPropertyChangeHandlers( - JsonValue value, JsArray registrations, NodeMap map) { + private static void registerPropertyChangeHandlers(JsonValue value, + JsArray registrations, NodeMap map) { map.forEachProperty((property, propertyName) -> registrations .push(property.addChangeListener( event -> handlePropertyChange(property, value)))); @@ -379,7 +378,7 @@ public static native boolean isPolymerElement(Element htmlNode) /*-{ var isP2Element = (typeof $wnd.Polymer === 'function') && $wnd.Polymer.Element && htmlNode instanceof $wnd.Polymer.Element; var isP3Element = htmlNode.constructor.polymerElementVersion !== undefined; - + return (isP2Element || isP3Element); }-*/; diff --git a/flow-client/src/main/java/com/vaadin/client/PopStateHandler.java b/flow-client/src/main/java/com/vaadin/client/PopStateHandler.java index d5e831d0acf..697a1425431 100644 --- a/flow-client/src/main/java/com/vaadin/client/PopStateHandler.java +++ b/flow-client/src/main/java/com/vaadin/client/PopStateHandler.java @@ -62,8 +62,8 @@ public PopStateHandler(Registry registry) { public void bind() { // track the location and query string (#6107) after the latest response // from server - registry.getRequestResponseTracker().addResponseHandlingEndedHandler( - event -> { + registry.getRequestResponseTracker() + .addResponseHandlingEndedHandler(event -> { pathAfterPreviousResponse = Browser.getWindow() .getLocation().getPathname(); queryAfterPreviousResponse = Browser.getWindow() @@ -85,9 +85,9 @@ private void onPopStateEvent(Event e) { assert pathAfterPreviousResponse != null : "Initial response has not ended before pop state event was triggered"; // don't visit server on pop state events caused by fragment change - boolean requiresServerSideRoundtrip = - !(Objects.equals(path, pathAfterPreviousResponse) - && Objects.equals(query, queryAfterPreviousResponse)); + boolean requiresServerSideRoundtrip = !(Objects.equals(path, + pathAfterPreviousResponse) + && Objects.equals(query, queryAfterPreviousResponse)); registry.getScrollPositionHandler().onPopStateEvent((PopStateEvent) e, requiresServerSideRoundtrip); if (!requiresServerSideRoundtrip) { diff --git a/flow-client/src/main/java/com/vaadin/client/bootstrap/Bootstrapper.java b/flow-client/src/main/java/com/vaadin/client/bootstrap/Bootstrapper.java index a4d250221e7..ef1da01b52b 100644 --- a/flow-client/src/main/java/com/vaadin/client/bootstrap/Bootstrapper.java +++ b/flow-client/src/main/java/com/vaadin/client/bootstrap/Bootstrapper.java @@ -128,8 +128,8 @@ private static void populateApplicationConfiguration( conf.setWebComponentMode(jsoConfiguration .getConfigBoolean(ApplicationConstants.APP_WC_MODE)); - conf.setClientRouting( - jsoConfiguration.getConfigBoolean(ApplicationConstants.CLIENT_ROUTING)); + conf.setClientRouting(jsoConfiguration + .getConfigBoolean(ApplicationConstants.CLIENT_ROUTING)); if (serviceUrl == null) { conf.setServiceUrl(WidgetUtil.getAbsoluteUrl(".")); diff --git a/flow-client/src/main/java/com/vaadin/client/bootstrap/JsoConfiguration.java b/flow-client/src/main/java/com/vaadin/client/bootstrap/JsoConfiguration.java index 7818a1af1b0..ba39997f83d 100644 --- a/flow-client/src/main/java/com/vaadin/client/bootstrap/JsoConfiguration.java +++ b/flow-client/src/main/java/com/vaadin/client/bootstrap/JsoConfiguration.java @@ -105,8 +105,8 @@ public native boolean getConfigBoolean(String name) * * @param name * name of the configuration parameter - * @return integer value of the configuration parameter, or null - * if no value is defined + * @return integer value of the configuration parameter, or + * null if no value is defined */ public native Integer getConfigInteger(String name) /*-{ diff --git a/flow-client/src/main/java/com/vaadin/client/communication/LoadingIndicatorConfigurator.java b/flow-client/src/main/java/com/vaadin/client/communication/LoadingIndicatorConfigurator.java index b885e8c6502..56aae8aa415 100644 --- a/flow-client/src/main/java/com/vaadin/client/communication/LoadingIndicatorConfigurator.java +++ b/flow-client/src/main/java/com/vaadin/client/communication/LoadingIndicatorConfigurator.java @@ -62,8 +62,11 @@ public static void observe(StateNode node, loadingIndicator::setThirdDelay, LoadingIndicatorConfigurationMap.THIRD_DELAY_DEFAULT); - MapProperty defaultThemeProperty = configMap.getProperty(LoadingIndicatorConfigurationMap.DEFAULT_THEME_APPLIED_KEY); - defaultThemeProperty.addChangeListener(event -> loadingIndicator.setApplyDefaultTheme(event.getSource().getValueOrDefault(LoadingIndicatorConfigurationMap.DEFAULT_THEME_APPLIED_DEFAULT))); + MapProperty defaultThemeProperty = configMap.getProperty( + LoadingIndicatorConfigurationMap.DEFAULT_THEME_APPLIED_KEY); + defaultThemeProperty.addChangeListener(event -> loadingIndicator + .setApplyDefaultTheme(event.getSource().getValueOrDefault( + LoadingIndicatorConfigurationMap.DEFAULT_THEME_APPLIED_DEFAULT))); } /** diff --git a/flow-client/src/main/java/com/vaadin/client/communication/MessageHandler.java b/flow-client/src/main/java/com/vaadin/client/communication/MessageHandler.java index 5eb99b164c2..f9a1bbe289e 100644 --- a/flow-client/src/main/java/com/vaadin/client/communication/MessageHandler.java +++ b/flow-client/src/main/java/com/vaadin/client/communication/MessageHandler.java @@ -265,15 +265,15 @@ protected void handleJSON(final ValueMap valueMap) { } /** - * Should only prepare resync after the - * if (locked || !isNextExpectedMessage(serverId)) {...} - * since stateTree.repareForResync() will remove the nodes, - * and if locked is true, it will return without handling - * the message, thus won't adding nodes back. + * Should only prepare resync after the if (locked || + * !isNextExpectedMessage(serverId)) {...} since + * stateTree.repareForResync() will remove the nodes, and if locked is + * true, it will return without handling the message, thus won't adding + * nodes back. * - * This is related to https://github.com/vaadin/flow/issues/8699 - * It seems that the reason is that `connectClient` is removed - * from the rootNode( element) during a resync and not added back. + * This is related to https://github.com/vaadin/flow/issues/8699 It + * seems that the reason is that `connectClient` is removed from the + * rootNode( element) during a resync and not added back. */ if (isResynchronize(valueMap)) { // Unregister all nodes and rebuild the state tree @@ -433,8 +433,7 @@ assert getServerId(valueMap) == -1 registry.getSystemErrorHandler().handleUnrecoverableError( error.getString("caption"), error.getString("message"), - error.getString("details"), - error.getString("url"), + error.getString("details"), error.getString("url"), error.getString("querySelector")); registry.getUILifecycle().setState(UIState.TERMINATED); @@ -564,8 +563,10 @@ private int getExpectedServerId() { } private void forceMessageHandling() { - // Clear previous request if it exists. Otherwise resyncrhonize can trigger - // "Trying to start a new request while another is active" exception and fail. + // Clear previous request if it exists. Otherwise resyncrhonize can + // trigger + // "Trying to start a new request while another is active" exception and + // fail. if (registry.getRequestResponseTracker().hasActiveRequest()) { registry.getRequestResponseTracker().endRequest(); } diff --git a/flow-client/src/main/java/com/vaadin/client/communication/PushConnectionFactory.java b/flow-client/src/main/java/com/vaadin/client/communication/PushConnectionFactory.java index b16d004e0d8..7498ed86331 100644 --- a/flow-client/src/main/java/com/vaadin/client/communication/PushConnectionFactory.java +++ b/flow-client/src/main/java/com/vaadin/client/communication/PushConnectionFactory.java @@ -28,9 +28,11 @@ public interface PushConnectionFactory { /** - * Creates a new {@link PushConnection} instance for the given {@code registry}. + * Creates a new {@link PushConnection} instance for the given + * {@code registry}. * - * @param registry the global registry + * @param registry + * the global registry * @return the push connection instance */ PushConnection create(Registry registry); diff --git a/flow-client/src/main/java/com/vaadin/client/communication/XhrConnection.java b/flow-client/src/main/java/com/vaadin/client/communication/XhrConnection.java index 667cf0993b0..7b5e5ba3e42 100644 --- a/flow-client/src/main/java/com/vaadin/client/communication/XhrConnection.java +++ b/flow-client/src/main/java/com/vaadin/client/communication/XhrConnection.java @@ -189,13 +189,15 @@ protected String getUri() { // the variable in JS scope, breaking strict mode which is // needed for ES6 imports. // See https://github.com/vaadin/flow/pull/6227 - return SharedUtil.addGetParameter( - SharedUtil.addGetParameter( - registry.getApplicationConfiguration().getServiceUrl(), - ApplicationConstants.REQUEST_TYPE_PARAMETER, - ApplicationConstants.REQUEST_TYPE_UIDL), - ApplicationConstants.UI_ID_PARAMETER, - registry.getApplicationConfiguration().getUIId()); + return SharedUtil + .addGetParameter( + SharedUtil.addGetParameter( + registry.getApplicationConfiguration() + .getServiceUrl(), + ApplicationConstants.REQUEST_TYPE_PARAMETER, + ApplicationConstants.REQUEST_TYPE_UIDL), + ApplicationConstants.UI_ID_PARAMETER, + registry.getApplicationConfiguration().getUIId()); } private static native boolean resendRequest(XMLHttpRequest xhr) diff --git a/flow-client/src/main/java/com/vaadin/client/flow/binding/ServerEventObject.java b/flow-client/src/main/java/com/vaadin/client/flow/binding/ServerEventObject.java index f7ceb3c41fe..c40b3a75a62 100644 --- a/flow-client/src/main/java/com/vaadin/client/flow/binding/ServerEventObject.java +++ b/flow-client/src/main/java/com/vaadin/client/flow/binding/ServerEventObject.java @@ -85,11 +85,11 @@ private native void initPromiseHandler() Object.defineProperty(this, name, { value: function(promiseId, success, value) { var promise = this[name].promises[promiseId]; - + // undefined if client-side node was recreated after execution was scheduled if (promise !== undefined) { delete this[name].promises[promiseId]; - + if (success) { // Resolve promise[0](value); diff --git a/flow-client/src/main/java/com/vaadin/client/flow/binding/SimpleElementBindingStrategy.java b/flow-client/src/main/java/com/vaadin/client/flow/binding/SimpleElementBindingStrategy.java index 45bce51055b..59abe8222fe 100644 --- a/flow-client/src/main/java/com/vaadin/client/flow/binding/SimpleElementBindingStrategy.java +++ b/flow-client/src/main/java/com/vaadin/client/flow/binding/SimpleElementBindingStrategy.java @@ -291,9 +291,9 @@ private native void bindPolymerModelProperties(StateNode node, private native void hookUpPolymerElement(StateNode node, Element element) /*-{ var self = this; - + var originalPropertiesChanged = element._propertiesChanged; - + if (originalPropertiesChanged) { element._propertiesChanged = function (currentProps, changedProps, oldProps) { $entry(function () { @@ -302,16 +302,16 @@ private native void hookUpPolymerElement(StateNode node, Element element) originalPropertiesChanged.apply(this, arguments); }; } - - + + var tree = node.@com.vaadin.client.flow.StateNode::getTree()(); - + var originalReady = element.ready; - + element.ready = function (){ originalReady.apply(this, arguments); @com.vaadin.client.PolymerUtils::fireReadyEvent(*)(element); - + // The _propertiesChanged method which is replaced above for the element // doesn't do anything for items in dom-repeat. // Instead it's called with some meaningful info for the dom-repeat element. @@ -320,7 +320,7 @@ private native void hookUpPolymerElement(StateNode node, Element element) // which changes this method for any dom-repeat instance. var replaceDomRepeatPropertyChange = function(){ var domRepeat = element.root.querySelector('dom-repeat'); - + if ( domRepeat ){ // If the dom-repeat element is in the DOM then // this method should not be executed anymore. The logic below will replace @@ -334,12 +334,12 @@ private native void hookUpPolymerElement(StateNode node, Element element) // if dom-repeat is found => replace _propertiesChanged method in the prototype and mark it as replaced. if ( !domRepeat.constructor.prototype.$propChangedModified){ domRepeat.constructor.prototype.$propChangedModified = true; - + var changed = domRepeat.constructor.prototype._propertiesChanged; - + domRepeat.constructor.prototype._propertiesChanged = function(currentProps, changedProps, oldProps){ changed.apply(this, arguments); - + var props = Object.getOwnPropertyNames(changedProps); var items = "items."; var i; @@ -360,7 +360,7 @@ private native void hookUpPolymerElement(StateNode node, Element element) if( currentPropsItem && currentPropsItem.nodeId ){ var nodeId = currentPropsItem.nodeId; var value = currentPropsItem[propertyName]; - + // this is an attempt to find the template element // which is not available as a context in the protype method var host = this.__dataHost; @@ -371,7 +371,7 @@ private native void hookUpPolymerElement(StateNode node, Element element) while( !host.localName || host.__dataHost ){ host = host.__dataHost; } - + $entry(function () { @SimpleElementBindingStrategy::handleListItemPropertyChange(*)(nodeId, host, propertyName, value, tree); })(); @@ -382,7 +382,7 @@ private native void hookUpPolymerElement(StateNode node, Element element) }; } }; - + // dom-repeat doesn't have to be in DOM even if template has it // such situation happens if there is dom-if e.g. which evaluates to false initially. // in this case dom-repeat is not yet in the DOM tree until dom-if becomes true @@ -397,7 +397,7 @@ private native void hookUpPolymerElement(StateNode node, Element element) element.addEventListener('dom-change',replaceDomRepeatPropertyChange); } } - + }-*/; private static void handleListItemPropertyChange(double nodeId, diff --git a/flow-client/src/main/java/com/vaadin/client/flow/collection/JsArray.java b/flow-client/src/main/java/com/vaadin/client/flow/collection/JsArray.java index 1b9bae6eb24..b69de2dc5b6 100644 --- a/flow-client/src/main/java/com/vaadin/client/flow/collection/JsArray.java +++ b/flow-client/src/main/java/com/vaadin/client/flow/collection/JsArray.java @@ -236,15 +236,15 @@ private JsniHelper() { static native int pushArray(JsArray array, JsArray values) - /*-{ - return array.push.apply(array, values); - }-*/; + /*-{ + return array.push.apply(array, values); + }-*/; static native JsArray spliceArray(JsArray array, int index, int remove, JsArray add) - /*-{ - return array.splice.apply(array, [index, remove].concat(add)); - }-*/; + /*-{ + return array.splice.apply(array, [index, remove].concat(add)); + }-*/; static native void clear(JsArray array) /*-{ diff --git a/flow-client/src/main/java/com/vaadin/client/flow/reactive/Reactive.java b/flow-client/src/main/java/com/vaadin/client/flow/reactive/Reactive.java index 83919780d87..5dd003d5bfb 100644 --- a/flow-client/src/main/java/com/vaadin/client/flow/reactive/Reactive.java +++ b/flow-client/src/main/java/com/vaadin/client/flow/reactive/Reactive.java @@ -50,7 +50,7 @@ public class Reactive { private static Computation currentComputation = null; - private static boolean flushing =false; + private static boolean flushing = false; private Reactive() { // Only static stuff in this class @@ -97,7 +97,7 @@ public static void addPostFlushListener(FlushListener postFlushListener) { * @see #addPostFlushListener(FlushListener) */ public static void flush() { - if(flushing) { + if (flushing) { return; } try { @@ -109,14 +109,15 @@ public static void flush() { oldestListener.flush(); } - // Purge one post flush listener, then look if there are new flush + // Purge one post flush listener, then look if there are new + // flush // listeners to purge if (hasPostFlushListeners()) { FlushListener oldestListener = postFlushListeners.remove(0); oldestListener.flush(); } } - }finally { + } finally { flushing = false; } } diff --git a/flow-client/src/main/java/com/vaadin/flow/linker/ClientEngineLinker.java b/flow-client/src/main/java/com/vaadin/flow/linker/ClientEngineLinker.java index f09259dbcc8..af0412d9808 100644 --- a/flow-client/src/main/java/com/vaadin/flow/linker/ClientEngineLinker.java +++ b/flow-client/src/main/java/com/vaadin/flow/linker/ClientEngineLinker.java @@ -158,7 +158,7 @@ protected Collection> doEmitCompilation(TreeLogger logger, @Override protected EmittedArtifact emitSelectionScript(TreeLogger logger, LinkerContext context, ArtifactSet artifacts) - throws UnableToCompleteException { + throws UnableToCompleteException { // Find the single Script result Script result = getScript(logger, artifacts); @@ -298,7 +298,7 @@ protected String getSelectionScriptTemplate(TreeLogger logger, @Override public ArtifactSet link(TreeLogger logger, LinkerContext context, ArtifactSet artifacts, boolean onePermutation) - throws UnableToCompleteException { + throws UnableToCompleteException { ArtifactSet result = super.link(logger, context, artifacts, onePermutation); if (!onePermutation) { @@ -312,7 +312,7 @@ public ArtifactSet link(TreeLogger logger, LinkerContext context, */ private Artifact emitStrongNamePropertyFile(TreeLogger logger, LinkerContext context, ArtifactSet artifacts) - throws UnableToCompleteException { + throws UnableToCompleteException { Script result = getScript(logger, artifacts); String contents = "jsFile=" + getJsFilename(context, result); diff --git a/flow-client/src/test/java/com/vaadin/client/CodeTest.java b/flow-client/src/test/java/com/vaadin/client/CodeTest.java index 99d1a7a53b5..e9374a4e3cc 100644 --- a/flow-client/src/test/java/com/vaadin/client/CodeTest.java +++ b/flow-client/src/test/java/com/vaadin/client/CodeTest.java @@ -82,6 +82,7 @@ public boolean visit(PackageDeclaration node) { packageName = node.getName().toString(); return false; } + @Override public boolean visit(ImportDeclaration node) { imports.add(node.getName().toString()); @@ -93,7 +94,8 @@ public boolean visit(VariableDeclarationStatement node) { for (Object frament : node.fragments()) { if (frament instanceof VariableDeclarationFragment) { VariableDeclarationFragment variableDeclaration = (VariableDeclarationFragment) frament; - Expression expression = variableDeclaration.getInitializer(); + Expression expression = variableDeclaration + .getInitializer(); if (expression instanceof ClassInstanceCreation) { ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation) expression; Class typeClass = getClass(node.getType()); diff --git a/flow-client/src/test/java/com/vaadin/client/flow/TreeChangeProcessorTest.java b/flow-client/src/test/java/com/vaadin/client/flow/TreeChangeProcessorTest.java index b4b3d3aef3c..775c74d68cf 100644 --- a/flow-client/src/test/java/com/vaadin/client/flow/TreeChangeProcessorTest.java +++ b/flow-client/src/test/java/com/vaadin/client/flow/TreeChangeProcessorTest.java @@ -242,8 +242,6 @@ public void poulateListFeature() { Assert.assertEquals(node, updatedNode); } - - @Test public void testPutNodeGetsParent() { StateNode child = new StateNode(2, tree); @@ -267,13 +265,13 @@ public void testNodeChainGetsCorrectParents() { StateNode child = new StateNode(2, tree); tree.registerNode(child); - StateNode subChild = new StateNode(3, tree); tree.registerNode(subChild); child.getList(NodeFeatures.ELEMENT_CHILDREN).add(0, child); JsonObject change = putNodeChange(rootId, ns, myKey, child.getId()); - JsonObject subChange = putNodeChange(child.getId(), ns, myKey, subChild.getId()); + JsonObject subChange = putNodeChange(child.getId(), ns, myKey, + subChild.getId()); StateNode node = TreeChangeProcessor.processChange(tree, change); Assert.assertEquals(tree.getRootNode(), node); @@ -291,7 +289,6 @@ public void testNodeChainGetsCorrectParents() { Assert.assertEquals(child, subChild.getParent()); } - @Test public void testNodeDetachRemovesParent() { StateNode child = new StateNode(2, tree); @@ -308,7 +305,6 @@ public void testNodeDetachRemovesParent() { Assert.assertSame(child, value); Assert.assertEquals(node, child.getParent()); - change = detachChange(child.getId()); TreeChangeProcessor.processChange(tree, change); diff --git a/flow-client/src/test/java/com/vaadin/client/flow/reactive/ReactiveTest.java b/flow-client/src/test/java/com/vaadin/client/flow/reactive/ReactiveTest.java index fff612ed3f9..508ad1aadb1 100644 --- a/flow-client/src/test/java/com/vaadin/client/flow/reactive/ReactiveTest.java +++ b/flow-client/src/test/java/com/vaadin/client/flow/reactive/ReactiveTest.java @@ -175,6 +175,7 @@ public void flushRunning_newFlushIsIgnored() { Reactive.flush(); - Assert.assertEquals(Arrays.asList("flush", "flush2", "postFlush"), order); + Assert.assertEquals(Arrays.asList("flush", "flush2", "postFlush"), + order); } } diff --git a/flow-data/src/main/java/com/vaadin/flow/data/binder/BeanPropertySet.java b/flow-data/src/main/java/com/vaadin/flow/data/binder/BeanPropertySet.java index 305e7cb3cfd..c29d48731c5 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/binder/BeanPropertySet.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/binder/BeanPropertySet.java @@ -146,8 +146,7 @@ private Object writeReplace() { * property definition from the cache. */ return new SerializedPropertyDefinition( - getPropertySet().instanceKey.type, - getName()); + getPropertySet().instanceKey.type, getName()); } @Override @@ -238,8 +237,7 @@ private Object writeReplace() { * property definition from the cache. */ return new SerializedPropertyDefinition( - getPropertySet().instanceKey.type, - getName()); + getPropertySet().instanceKey.type, getName()); } @Override @@ -319,8 +317,7 @@ private BeanPropertySet(InstanceKey instanceKey) { try { definitions = BeanUtil.getBeanPropertyDescriptors(instanceKey.type) - .stream() - .filter(BeanPropertySet::hasNonObjectReadMethod) + .stream().filter(BeanPropertySet::hasNonObjectReadMethod) .map(descriptor -> new BeanPropertyDefinition<>(this, instanceKey.type, descriptor)) .collect(Collectors.toMap(PropertyDefinition::getName, @@ -329,7 +326,7 @@ private BeanPropertySet(InstanceKey instanceKey) { throw new IllegalArgumentException( "Cannot find property descriptors for " + instanceKey.type.getName(), - e); + e); } } @@ -415,8 +412,9 @@ public static PropertySet get(Class beanType) { Objects.requireNonNull(beanType, "Bean type cannot be null"); InstanceKey key = new InstanceKey(beanType, false, 0, null); // Cache the reflection results - return (PropertySet) INSTANCES.computeIfAbsent(key, - ignored -> new BeanPropertySet<>(key)).copy(); + return (PropertySet) INSTANCES + .computeIfAbsent(key, ignored -> new BeanPropertySet<>(key)) + .copy(); } private BeanPropertySet copy() { @@ -444,9 +442,9 @@ public static PropertySet get(Class beanType, InstanceKey key = new InstanceKey(beanType, false, filterDefinition.getMaxNestingDepth(), filterDefinition.getIgnorePackageNamesStartingWith()); - return (PropertySet) INSTANCES.computeIfAbsent(key, - k -> new BeanPropertySet<>(key, checkNestedDefinitions, - filterDefinition)) + return (PropertySet) INSTANCES + .computeIfAbsent(key, k -> new BeanPropertySet<>(key, + checkNestedDefinitions, filterDefinition)) .copy(); } @@ -488,7 +486,7 @@ public static PropertySet get(Class beanType, throw new IllegalArgumentException( "Cannot find property descriptors for " + instanceKey.type.getName(), - e); + e); } } return definition; diff --git a/flow-data/src/main/java/com/vaadin/flow/data/binder/BeanValidationBinder.java b/flow-data/src/main/java/com/vaadin/flow/data/binder/BeanValidationBinder.java index 639a9a0e109..ab241094fa0 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/binder/BeanValidationBinder.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/binder/BeanValidationBinder.java @@ -58,7 +58,7 @@ public class BeanValidationBinder extends Binder { * the bean type to use, not null */ public BeanValidationBinder(Class beanType) { - this(beanType,false); + this(beanType, false); } /** @@ -75,14 +75,15 @@ public BeanValidationBinder(Class beanType) { * @param scanNestedDefinitions * if {@code true}, scan for nested property definitions as well */ - public BeanValidationBinder(Class beanType, boolean scanNestedDefinitions) { + public BeanValidationBinder(Class beanType, + boolean scanNestedDefinitions) { super(beanType, scanNestedDefinitions); if (!BeanUtil.checkBeanValidationAvailable()) { - throw new IllegalStateException( - BeanValidationBinder.class.getSimpleName() - + " cannot be used because a JSR-303 Bean Validation " - + "implementation not found on the classpath or could not be initialized. Use " - + Binder.class.getSimpleName() + " instead"); + throw new IllegalStateException(BeanValidationBinder.class + .getSimpleName() + + " cannot be used because a JSR-303 Bean Validation " + + "implementation not found on the classpath or could not be initialized. Use " + + Binder.class.getSimpleName() + " instead"); } this.beanType = beanType; } diff --git a/flow-data/src/main/java/com/vaadin/flow/data/binder/Binder.java b/flow-data/src/main/java/com/vaadin/flow/data/binder/Binder.java index 28eeb6c7eb4..a860c0ceed5 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/binder/Binder.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/binder/Binder.java @@ -237,10 +237,11 @@ default BindingValidationStatus validate() { public boolean isAsRequiredEnabled(); /** - * Define whether validators are disabled or enabled for this - * specific binding. + * Define whether validators are disabled or enabled for this specific + * binding. * - * @param validatorsDisabled A boolean value. + * @param validatorsDisabled + * A boolean value. */ public void setValidatorsDisabled(boolean validatorsDisabled); @@ -605,9 +606,11 @@ default BindingBuilder withNullRepresentation( TARGET nullRepresentation) { return withConverter( fieldValue -> Objects.equals(fieldValue, nullRepresentation) - ? null : fieldValue, + ? null + : fieldValue, modelValue -> Objects.isNull(modelValue) - ? nullRepresentation : modelValue); + ? nullRepresentation + : modelValue); } /** @@ -891,8 +894,8 @@ public BindingBuilder withValidator( Objects.requireNonNull(validator, "validator cannot be null"); Validator wrappedValidator = ((value, context) -> { - if (getBinder().isValidatorsDisabled() || - (binding != null && binding.isValidatorsDisabled())) { + if (getBinder().isValidatorsDisabled() || (binding != null + && binding.isValidatorsDisabled())) { return ValidationResult.ok(); } else { return validator.apply(value, context); @@ -1872,13 +1875,13 @@ public void writeBean(BEAN bean) throws ValidationException { * {@code null} */ public void writeBeanAsDraft(BEAN bean) { - doWriteDraft(bean, new ArrayList<>(bindings),false); + doWriteDraft(bean, new ArrayList<>(bindings), false); } /** - * Writes successfully converted changes from the bound fields bypassing - * all the Validation or all fields passing conversion if forced = true. - * If the conversion fails, the value written to the bean will be null. + * Writes successfully converted changes from the bound fields bypassing all + * the Validation or all fields passing conversion if forced = true. If the + * conversion fails, the value written to the bean will be null. * * @see #writeBean(Object) * @see #writeBeanIfValid(Object) @@ -1892,7 +1895,7 @@ public void writeBeanAsDraft(BEAN bean) { * disable all Validators during write */ public void writeBeanAsDraft(BEAN bean, boolean forced) { - doWriteDraft(bean, new ArrayList<>(bindings),forced); + doWriteDraft(bean, new ArrayList<>(bindings), forced); } /** @@ -1994,12 +1997,12 @@ private BinderValidationStatus doWriteIfValid(BEAN bean, * disable validators during write if true */ @SuppressWarnings({ "unchecked" }) - private void doWriteDraft(BEAN bean, - Collection> bindings, boolean forced) { + private void doWriteDraft(BEAN bean, Collection> bindings, + boolean forced) { Objects.requireNonNull(bean, "bean cannot be null"); if (!forced) { - bindings.forEach(binding -> ((BindingImpl) binding) + bindings.forEach(binding -> ((BindingImpl) binding) .writeFieldValue(bean)); } else { boolean isDisabled = isValidatorsDisabled(); @@ -2670,7 +2673,8 @@ private Converter createNullRepresentationA Converter nullRepresentationConverter = Converter .from(fieldValue -> fieldValue, modelValue -> Objects.isNull(modelValue) - ? field.getEmptyValue() : modelValue, + ? field.getEmptyValue() + : modelValue, Throwable::getMessage); ConverterDelegate converter = new ConverterDelegate<>( nullRepresentationConverter); @@ -3066,18 +3070,19 @@ public void removeBinding(String propertyName) { } /** - * Control whether validators including bean level validators are - * disabled or enabled globally for this Binder. + * Control whether validators including bean level validators are disabled + * or enabled globally for this Binder. * - * @param validatorsDisabled Boolean value. + * @param validatorsDisabled + * Boolean value. */ public void setValidatorsDisabled(boolean validatorsDisabled) { this.validatorsDisabled = validatorsDisabled; } /** - * Returns if the validators including bean level validators - * are disabled or enabled for this Binder. + * Returns if the validators including bean level validators are disabled or + * enabled for this Binder. * * @return Boolean value */ diff --git a/flow-data/src/main/java/com/vaadin/flow/data/binder/BinderValidationStatus.java b/flow-data/src/main/java/com/vaadin/flow/data/binder/BinderValidationStatus.java index 858acb87bea..36b1fb583bb 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/binder/BinderValidationStatus.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/binder/BinderValidationStatus.java @@ -34,8 +34,8 @@ * Note: if there are any field level validation errors, the bean level * validation is not run. *

- * Use {@link Binder#setValidationStatusHandler(BinderValidationStatusHandler)} to handle - * form level validation status changes. + * Use {@link Binder#setValidationStatusHandler(BinderValidationStatusHandler)} + * to handle form level validation status changes. * * @author Vaadin Ltd * @since 1.0 @@ -94,8 +94,8 @@ public BinderValidationStatus(Binder source, public static BinderValidationStatus createUnresolvedStatus( Binder source) { return new BinderValidationStatus<>(source, - source.getBindings().stream().map( - BindingValidationStatus::createUnresolvedStatus) + source.getBindings().stream() + .map(BindingValidationStatus::createUnresolvedStatus) .collect(Collectors.toList()), Collections.emptyList()); } @@ -117,7 +117,8 @@ public boolean isOk() { */ public boolean hasErrors() { return binderStatuses.stream().anyMatch(ValidationResult::isError) - || bindingStatuses.stream().anyMatch(BindingValidationStatus::isError); + || bindingStatuses.stream() + .anyMatch(BindingValidationStatus::isError); } /** @@ -137,8 +138,8 @@ public Binder getBinder() { public List getValidationErrors() { List errors = new ArrayList<>( getFieldValidationErrors().stream() - .map(s -> s.getResult().get()) - .collect(Collectors.toList())); + .map(s -> s.getResult().get()) + .collect(Collectors.toList())); errors.addAll(getBeanValidationErrors()); return errors; } diff --git a/flow-data/src/main/java/com/vaadin/flow/data/binder/BinderValidationStatusHandler.java b/flow-data/src/main/java/com/vaadin/flow/data/binder/BinderValidationStatusHandler.java index 304b3274aee..e8a8c5612a4 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/binder/BinderValidationStatusHandler.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/binder/BinderValidationStatusHandler.java @@ -27,8 +27,7 @@ *

* error message} for failed field validations. For bean level validation errors * the default handler will display the first error message in - * {@link Binder#setStatusLabel(HasText) status label}, if one has - * been set. + * {@link Binder#setStatusLabel(HasText) status label}, if one has been set. * * @author Vaadin Ltd * @since 1.0 @@ -43,7 +42,7 @@ */ @FunctionalInterface public interface BinderValidationStatusHandler -extends SerializableEventListener { + extends SerializableEventListener { /** * Invoked when the validation status has changed in binder. diff --git a/flow-data/src/main/java/com/vaadin/flow/data/binder/BindingValidationStatusHandler.java b/flow-data/src/main/java/com/vaadin/flow/data/binder/BindingValidationStatusHandler.java index 8065b001922..ce5542a33da 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/binder/BindingValidationStatusHandler.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/binder/BindingValidationStatusHandler.java @@ -35,7 +35,7 @@ */ @FunctionalInterface public interface BindingValidationStatusHandler -extends SerializableEventListener { + extends SerializableEventListener { /** * Invoked when the validation status has changed in a binding. diff --git a/flow-data/src/main/java/com/vaadin/flow/data/binder/ErrorMessageProvider.java b/flow-data/src/main/java/com/vaadin/flow/data/binder/ErrorMessageProvider.java index 371834b07f3..ce596320068 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/binder/ErrorMessageProvider.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/binder/ErrorMessageProvider.java @@ -26,7 +26,7 @@ */ @FunctionalInterface public interface ErrorMessageProvider -extends SerializableFunction { + extends SerializableFunction { /** * Returns a generated error message for given {@code ValueContext}. diff --git a/flow-data/src/main/java/com/vaadin/flow/data/binder/RequiredFieldConfigurator.java b/flow-data/src/main/java/com/vaadin/flow/data/binder/RequiredFieldConfigurator.java index 7ad8d3580f0..69db9851bd7 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/binder/RequiredFieldConfigurator.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/binder/RequiredFieldConfigurator.java @@ -56,8 +56,8 @@ public interface RequiredFieldConfigurator */ RequiredFieldConfigurator NOT_EMPTY = (annotation, binding) -> (annotation.annotationType().equals(NotEmpty.class) - || annotation.annotationType().getName() - .equals("org.hibernate.validator.constraints.NotEmpty")) + || annotation.annotationType().getName().equals( + "org.hibernate.validator.constraints.NotEmpty")) && RequiredFieldConfiguratorUtil.testConvertedDefaultValue( binding, RequiredFieldConfiguratorUtil::hasZeroSize); diff --git a/flow-data/src/main/java/com/vaadin/flow/data/binder/Result.java b/flow-data/src/main/java/com/vaadin/flow/data/binder/Result.java index ecd5fe3866e..df613c2091a 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/binder/Result.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/binder/Result.java @@ -82,7 +82,7 @@ static Result error(String message) { * @return the result of invoking the supplier */ static Result of(SerializableSupplier supplier, - SerializableFunction onError) { + SerializableFunction onError) { Objects.requireNonNull(supplier, "supplier cannot be null"); Objects.requireNonNull(onError, "onError cannot be null"); @@ -133,7 +133,7 @@ default Result map(SerializableFunction mapper) { * the function to call if failure */ void handle(SerializableConsumer ifOk, - SerializableConsumer ifError); + SerializableConsumer ifError); /** * Applies the {@code consumer} if result is not an error. @@ -187,5 +187,5 @@ default void ifError(SerializableConsumer consumer) { */ R getOrThrow( SerializableFunction exceptionProvider) - throws X; + throws X; } diff --git a/flow-data/src/main/java/com/vaadin/flow/data/binder/Setter.java b/flow-data/src/main/java/com/vaadin/flow/data/binder/Setter.java index f180bfc96e7..a4d343afe6a 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/binder/Setter.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/binder/Setter.java @@ -36,7 +36,7 @@ */ @FunctionalInterface public interface Setter -extends BiConsumer, Serializable { + extends BiConsumer, Serializable { /** * Save value to the bean property. diff --git a/flow-data/src/main/java/com/vaadin/flow/data/binder/SimpleResult.java b/flow-data/src/main/java/com/vaadin/flow/data/binder/SimpleResult.java index 6c40e4ff75a..baeaaabed26 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/binder/SimpleResult.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/binder/SimpleResult.java @@ -100,7 +100,7 @@ public String toString() { @Override public R getOrThrow( SerializableFunction exceptionSupplier) - throws X { + throws X { Objects.requireNonNull(exceptionSupplier, "Exception supplier cannot be null"); if (isError()) { diff --git a/flow-data/src/main/java/com/vaadin/flow/data/binder/ValidationException.java b/flow-data/src/main/java/com/vaadin/flow/data/binder/ValidationException.java index d172648845e..de5dd4c9680 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/binder/ValidationException.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/binder/ValidationException.java @@ -62,8 +62,8 @@ public ValidationException( public List getValidationErrors() { List errors = new ArrayList<>( getFieldValidationErrors().stream() - .map(s -> s.getResult().get()) - .collect(Collectors.toList())); + .map(s -> s.getResult().get()) + .collect(Collectors.toList())); errors.addAll(getBeanValidationErrors()); return errors; } diff --git a/flow-data/src/main/java/com/vaadin/flow/data/binder/ValidationResult.java b/flow-data/src/main/java/com/vaadin/flow/data/binder/ValidationResult.java index 1e80be9298b..5e8067bbe6e 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/binder/ValidationResult.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/binder/ValidationResult.java @@ -68,95 +68,94 @@ public Optional getErrorLevel() { } } - /** - * Returns the result message. - *

- * Throws an {@link IllegalStateException} if the result represents success. - * - * @return the error message - * @throws IllegalStateException - * if the result represents success - */ - String getErrorMessage(); + /** + * Returns the result message. + *

+ * Throws an {@link IllegalStateException} if the result represents success. + * + * @return the error message + * @throws IllegalStateException + * if the result represents success + */ + String getErrorMessage(); - /** - * Returns optional error level for this validation result. Error level is - * not present for successful validation results. - *

- * Note: By default {@link ErrorLevel#INFO} and - * {@link ErrorLevel#WARNING} are not considered to be blocking the - * validation and conversion chain. - * - * @see #isError() - * - * @return optional error level; error level is present for validation - * results that have not passed validation - * - */ - Optional getErrorLevel(); + /** + * Returns optional error level for this validation result. Error level is + * not present for successful validation results. + *

+ * Note: By default {@link ErrorLevel#INFO} and + * {@link ErrorLevel#WARNING} are not considered to be blocking the + * validation and conversion chain. + * + * @see #isError() + * + * @return optional error level; error level is present for validation + * results that have not passed validation + * + */ + Optional getErrorLevel(); - /** - * Checks if the result denotes an error. - *

- *Note: By default {@link ErrorLevel#INFO} and - * {@link ErrorLevel#WARNING} are not considered to be errors. - * - * @return true if the result denotes an error, - * false otherwise - */ - default boolean isError() { - ErrorLevel errorLevel = getErrorLevel().orElse(null); - return errorLevel != null && errorLevel != ErrorLevel.INFO - && errorLevel != ErrorLevel.WARNING; - } + /** + * Checks if the result denotes an error. + *

+ * Note: By default {@link ErrorLevel#INFO} and + * {@link ErrorLevel#WARNING} are not considered to be errors. + * + * @return true if the result denotes an error, + * false otherwise + */ + default boolean isError() { + ErrorLevel errorLevel = getErrorLevel().orElse(null); + return errorLevel != null && errorLevel != ErrorLevel.INFO + && errorLevel != ErrorLevel.WARNING; + } - /** - * Returns a successful result. - * - * @return the successful result - */ - static ValidationResult ok() { - return new SimpleValidationResult(null,null); - } + /** + * Returns a successful result. + * + * @return the successful result + */ + static ValidationResult ok() { + return new SimpleValidationResult(null, null); + } - /** - * Creates the validation result which represent an error with the given - * {@code errorMessage}. - * - * @param errorMessage - * error message, not {@code null} - * @return validation result which represent an error with the given - * {@code errorMessage} - * @throws NullPointerException - * if {@code errorMessage} is null - */ - static ValidationResult error(String errorMessage) { - Objects.requireNonNull(errorMessage); - return create(errorMessage, ErrorLevel.ERROR); - } - - /** - * Creates the validation result with the given {@code errorMessage} and - * {@code errorLevel}. Results with {@link ErrorLevel} of {@code INFO} or - * {@code WARNING} are not errors by default. - * - * @see #ok() - * @see #error(String) - * - * @param errorMessage - * error message, not {@code null} - * @param errorLevel - * error level, not {@code null} - * @return validation result with the given {@code errorMessage} and - * {@code errorLevel} - * @throws NullPointerException - * if {@code errorMessage} or {@code errorLevel} is {@code null} - * - */ - static ValidationResult create(String errorMessage, - ErrorLevel errorLevel) { - Objects.requireNonNull(errorMessage); - Objects.requireNonNull(errorLevel); - return new SimpleValidationResult(errorMessage, errorLevel); - } + /** + * Creates the validation result which represent an error with the given + * {@code errorMessage}. + * + * @param errorMessage + * error message, not {@code null} + * @return validation result which represent an error with the given + * {@code errorMessage} + * @throws NullPointerException + * if {@code errorMessage} is null + */ + static ValidationResult error(String errorMessage) { + Objects.requireNonNull(errorMessage); + return create(errorMessage, ErrorLevel.ERROR); + } + + /** + * Creates the validation result with the given {@code errorMessage} and + * {@code errorLevel}. Results with {@link ErrorLevel} of {@code INFO} or + * {@code WARNING} are not errors by default. + * + * @see #ok() + * @see #error(String) + * + * @param errorMessage + * error message, not {@code null} + * @param errorLevel + * error level, not {@code null} + * @return validation result with the given {@code errorMessage} and + * {@code errorLevel} + * @throws NullPointerException + * if {@code errorMessage} or {@code errorLevel} is {@code null} + * + */ + static ValidationResult create(String errorMessage, ErrorLevel errorLevel) { + Objects.requireNonNull(errorMessage); + Objects.requireNonNull(errorLevel); + return new SimpleValidationResult(errorMessage, errorLevel); } +} diff --git a/flow-data/src/main/java/com/vaadin/flow/data/binder/Validator.java b/flow-data/src/main/java/com/vaadin/flow/data/binder/Validator.java index dd5b5c0aa14..363107c5b6a 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/binder/Validator.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/binder/Validator.java @@ -190,8 +190,8 @@ static Validator from(SerializablePredicate guard, errorMessageProvider.apply(context), errorLevel); } } catch (Exception e) { - LoggerFactory.getLogger(Validator.class.getName()).info( - "An exception is thrown during validation", e); + LoggerFactory.getLogger(Validator.class.getName()) + .info("An exception is thrown during validation", e); return ValidationResult.create( errorMessageProvider.apply(context), errorLevel); } diff --git a/flow-data/src/main/java/com/vaadin/flow/data/converter/LocalDateTimeToDateConverter.java b/flow-data/src/main/java/com/vaadin/flow/data/converter/LocalDateTimeToDateConverter.java index 98ee4c756a6..f31d72bd547 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/converter/LocalDateTimeToDateConverter.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/converter/LocalDateTimeToDateConverter.java @@ -31,21 +31,25 @@ * @author Vaadin Ltd * @since 1.0 */ -public class LocalDateTimeToDateConverter implements Converter { +public class LocalDateTimeToDateConverter + implements Converter { private ZoneId zoneId; /** * Creates a new converter using the given time zone. * - * @param zoneId the time zone to use, not null + * @param zoneId + * the time zone to use, not null */ public LocalDateTimeToDateConverter(ZoneId zoneId) { - this.zoneId = Objects.requireNonNull(zoneId, "Zone identifier cannot be null"); + this.zoneId = Objects.requireNonNull(zoneId, + "Zone identifier cannot be null"); } @Override - public Result convertToModel(LocalDateTime localDate, ValueContext context) { + public Result convertToModel(LocalDateTime localDate, + ValueContext context) { if (localDate == null) { return Result.ok(null); } @@ -54,12 +58,14 @@ public Result convertToModel(LocalDateTime localDate, ValueContext context } @Override - public LocalDateTime convertToPresentation(Date date, ValueContext context) { + public LocalDateTime convertToPresentation(Date date, + ValueContext context) { if (date == null) { return null; } - return Instant.ofEpochMilli(date.getTime()).atZone(zoneId).toLocalDateTime(); + return Instant.ofEpochMilli(date.getTime()).atZone(zoneId) + .toLocalDateTime(); } } diff --git a/flow-data/src/main/java/com/vaadin/flow/data/converter/StringToDateConverter.java b/flow-data/src/main/java/com/vaadin/flow/data/converter/StringToDateConverter.java index 26708ae8393..ccc963e8957 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/converter/StringToDateConverter.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/converter/StringToDateConverter.java @@ -40,8 +40,9 @@ public class StringToDateConverter implements Converter { /** - * Returns the format used by {@link #convertToPresentation(Date, ValueContext)} - * and {@link #convertToModel(String, ValueContext)}. + * Returns the format used by + * {@link #convertToPresentation(Date, ValueContext)} and + * {@link #convertToModel(String, ValueContext)}. * * @param locale * The locale to use diff --git a/flow-data/src/main/java/com/vaadin/flow/data/converter/StringToUuidConverter.java b/flow-data/src/main/java/com/vaadin/flow/data/converter/StringToUuidConverter.java index be765e67577..25a081f5552 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/converter/StringToUuidConverter.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/converter/StringToUuidConverter.java @@ -29,8 +29,8 @@ * Leading and trailing white spaces are ignored when converting from a String. *

*

- * The String representation uses the canonical format of 32-characters with a hyphen - * to separate each of five groups of hexadecimal digits as defined in: + * The String representation uses the canonical format of 32-characters with a + * hyphen to separate each of five groups of hexadecimal digits as defined in: * RFC 4122: A Universally Unique IDentifier (UUID) URN Namespace * http://www.ietf.org/rfc/rfc4122.txt *

@@ -44,17 +44,19 @@ public class StringToUuidConverter implements Converter { /** * Constructs a converter for String to UUID and back. * - * @param errorMessage the error message to use if conversion fails + * @param errorMessage + * the error message to use if conversion fails */ public StringToUuidConverter(String errorMessage) { this(ctx -> errorMessage); } /** - * Constructs a new converter instance with the given error message provider. - * Empty strings are converted to null. + * Constructs a new converter instance with the given error message + * provider. Empty strings are converted to null. * - * @param errorMessageProvider the error message provider to use if conversion fails + * @param errorMessageProvider + * the error message provider to use if conversion fails */ public StringToUuidConverter(ErrorMessageProvider errorMessageProvider) { this.errorMessageProvider = errorMessageProvider; @@ -74,11 +76,12 @@ public Result convertToModel(String value, ValueContext context) { try { uuid = UUID.fromString(value); } catch (java.lang.IllegalArgumentException e) { - LoggerFactory.getLogger(StringToUuidConverter.class.getName()).warn( - "Unable to convert String to UUID: " + value, e); + LoggerFactory.getLogger(StringToUuidConverter.class.getName()) + .warn("Unable to convert String to UUID: " + value, e); return Result.error(this.errorMessageProvider.apply(context)); } - return Result.ok(uuid); // Return the UUID object, converted from String. + return Result.ok(uuid); // Return the UUID object, converted from + // String. } @Override @@ -87,7 +90,8 @@ public String convertToPresentation(UUID value, ValueContext context) { return null; } // `java.util.UUID::toString` generates a textual representation of a - // UUID’s 128-bits as in a hexadecimal `String` in 32-character canonical + // UUID’s 128-bits as in a hexadecimal `String` in 32-character + // canonical // format with four hyphens separating groups of digits. // https://docs.oracle.com/javase/10/docs/api/java/util/UUID.html#toString() return value.toString(); diff --git a/flow-data/src/main/java/com/vaadin/flow/data/provider/AbstractDataProvider.java b/flow-data/src/main/java/com/vaadin/flow/data/provider/AbstractDataProvider.java index 7c057eb03bd..3e1c7de8a05 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/provider/AbstractDataProvider.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/provider/AbstractDataProvider.java @@ -45,7 +45,8 @@ public abstract class AbstractDataProvider implements DataProvider { @Override public Registration addDataProviderListener( DataProviderListener listener) { - // Using an anonymous class instead of lambda or method reference to prevent potential + // Using an anonymous class instead of lambda or method reference to + // prevent potential // self reference serialization issues when clients holds a reference // to the Registration instance returned by this method SerializableConsumer consumer = new SerializableConsumer() { diff --git a/flow-data/src/main/java/com/vaadin/flow/data/provider/AbstractListDataView.java b/flow-data/src/main/java/com/vaadin/flow/data/provider/AbstractListDataView.java index 04aadf359a6..4867da08ebd 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/provider/AbstractListDataView.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/provider/AbstractListDataView.java @@ -355,8 +355,8 @@ private void addItemOnTarget(T item, T target, * position towards to target item. */ removeItemIfPresent(item, dataProvider); - itemList.add(insertItemsIndexProvider.apply(getItemIndex(target, - itemList.stream())), item); + itemList.add(insertItemsIndexProvider + .apply(getItemIndex(target, itemList.stream())), item); dataProvider.refreshAll(); } diff --git a/flow-data/src/main/java/com/vaadin/flow/data/provider/DataChangeEvent.java b/flow-data/src/main/java/com/vaadin/flow/data/provider/DataChangeEvent.java index 53766241f0e..0ac13c88317 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/provider/DataChangeEvent.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/provider/DataChangeEvent.java @@ -65,9 +65,11 @@ public DataRefreshEvent(DataProvider source, T item) { * @param item * the updated item, not null * @param refreshChildren - * whether, in hierarchical providers, subelements should be refreshed as well + * whether, in hierarchical providers, subelements should be + * refreshed as well */ - public DataRefreshEvent(DataProvider source, T item, boolean refreshChildren) { + public DataRefreshEvent(DataProvider source, T item, + boolean refreshChildren) { super(source); Objects.requireNonNull(item, "Refreshed item can't be null"); this.item = item; @@ -84,9 +86,11 @@ public T getItem() { } /** - * Gets the a boolean whether the refresh is supposed to be refreshChildren (in hierarchical data providers). + * Gets the a boolean whether the refresh is supposed to be + * refreshChildren (in hierarchical data providers). * - * @return whether, in hierarchical providers, subelements should be refreshed as well + * @return whether, in hierarchical providers, subelements should be + * refreshed as well */ public boolean isRefreshChildren() { return refreshChildren; diff --git a/flow-data/src/main/java/com/vaadin/flow/data/provider/DataCommunicator.java b/flow-data/src/main/java/com/vaadin/flow/data/provider/DataCommunicator.java index b691279457a..7d59db15d55 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/provider/DataCommunicator.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/provider/DataCommunicator.java @@ -126,18 +126,20 @@ public class DataCommunicator implements Serializable { /** * In-memory data provider with no items. *

- * Data Communicator is initialised with this data provider by default - * until a new data provider is assigned with + * Data Communicator is initialised with this data provider by default until + * a new data provider is assigned with * {@link #setDataProvider(DataProvider, Object)}. * - * @param item type + * @param + * item type * * @see AbstractDataView#AbstractDataView(SerializableSupplier, Component) */ - public static final class EmptyDataProvider extends ListDataProvider { + public static final class EmptyDataProvider + extends ListDataProvider { /** - * Create in-memory data provider instance with no items in the - * backed collection. + * Create in-memory data provider instance with no items in the backed + * collection. */ public EmptyDataProvider() { super(new ArrayList<>(0)); @@ -286,9 +288,9 @@ public DataCommunicator(DataGenerator dataGenerator, * @param stateNode * the state node used to communicate for * @param fetchEnabled - * if {@code fetchEnabled} is {@code true} then the data - * provider will be called to fetch the items and/or to get the - * items count until it's set to {@code false} + * if {@code fetchEnabled} is {@code true} then the data provider + * will be called to fetch the items and/or to get the items + * count until it's set to {@code false} */ public DataCommunicator(DataGenerator dataGenerator, ArrayUpdater arrayUpdater, @@ -505,8 +507,8 @@ public boolean isItemActive(T item) { * Gets the item at the given index from the data available to the * component. Data is filtered and sorted the same way as in the component. *

- * Call to the backend is triggered if the item for a requested index is - * not present in the cached active items. + * Call to the backend is triggered if the item for a requested index is not + * present in the cached active items. * * @param index * the index of the item to get @@ -523,22 +525,21 @@ public T getItem(int index) { int activeDataEnd = activeStart + activeKeyOrder.size() - 1; /* * Check if the item on a requested index is already in the cache of - * active items. No matter is this currently a defined or undefined - * mode + * active items. No matter is this currently a defined or undefined mode */ if (index >= activeStart && index <= activeDataEnd) { return getKeyMapper().get(activeKeyOrder.get(index - activeStart)); } else { final int itemCount = getItemCount(); /* - * The exception is thrown if the exact size is used and the data - * is empty, or the index is outside of the item count range, - * because we definitely know the item count from a backend. + * The exception is thrown if the exact size is used and the data is + * empty, or the index is outside of the item count range, because + * we definitely know the item count from a backend. */ if (isDefinedSize()) { if (itemCount == 0) { - throw new IndexOutOfBoundsException(String - .format("Requested index %d on empty data.", index)); + throw new IndexOutOfBoundsException(String.format( + "Requested index %d on empty data.", index)); } else if (index >= itemCount) { throw new IndexOutOfBoundsException(String.format( "Given index %d is outside of the accepted range '0 - %d'", @@ -546,13 +547,12 @@ public T getItem(int index) { } } /* - * In case of undefined size we don't check the empty data or - * the item count, because item count = 0 may mean the - * flush (fetch) action hasn't been made yet. And even - * if the requested index is outside of the item count - * estimation, we can make the request, because the backend can - * have the item on that index (we simply not yet fetched - * this item during the scrolling). + * In case of undefined size we don't check the empty data or the + * item count, because item count = 0 may mean the flush (fetch) + * action hasn't been made yet. And even if the requested index is + * outside of the item count estimation, we can make the request, + * because the backend can have the item on that index (we simply + * not yet fetched this item during the scrolling). */ return (T) getDataProvider().fetch(buildQuery(index, 1)).findFirst() .orElse(null); @@ -955,7 +955,8 @@ protected Stream fetchFromProvider(int offset, int limit) { doFetchFromDataProvider(newOffset, pageSize) .forEach(addItemAndCheckConsumer); page++; - } while (page < pages && fetchedPerPage.getAndSet(0) == pageSize); + } while (page < pages + && fetchedPerPage.getAndSet(0) == pageSize); stream = streamBuilder.build(); } else { @@ -1300,15 +1301,14 @@ private List getJsonItems(Range range) { } private static void withMissing(Range expected, Range actual, - Consumer action) { + Consumer action) { Range[] partition = expected.partitionWith(actual); applyIfNotEmpty(partition[0], action); applyIfNotEmpty(partition[2], action); } - private static void applyIfNotEmpty(Range range, - Consumer action) { + private static void applyIfNotEmpty(Range range, Consumer action) { if (!range.isEmpty()) { action.accept(range); } diff --git a/flow-data/src/main/java/com/vaadin/flow/data/provider/DataKeyMapper.java b/flow-data/src/main/java/com/vaadin/flow/data/provider/DataKeyMapper.java index 8d813025aeb..9a9f952c4d1 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/provider/DataKeyMapper.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/provider/DataKeyMapper.java @@ -93,4 +93,3 @@ public interface DataKeyMapper extends Serializable { */ void setIdentifierGetter(ValueProvider identifierGetter); } - diff --git a/flow-data/src/main/java/com/vaadin/flow/data/provider/DataProvider.java b/flow-data/src/main/java/com/vaadin/flow/data/provider/DataProvider.java index e930a8aa573..56d92900400 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/provider/DataProvider.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/provider/DataProvider.java @@ -113,9 +113,9 @@ public interface DataProvider extends Serializable { * * @see #refreshItem(Object) * - * By default it just does a standard refreshItem, in a hierarchical DataProvider - * it is supposed to refresh all of the children as well in case 'refreshChildren' - * is true. + * By default it just does a standard refreshItem, in a hierarchical + * DataProvider it is supposed to refresh all of the children as well + * in case 'refreshChildren' is true. * * @param item * the item to refresh diff --git a/flow-data/src/main/java/com/vaadin/flow/data/provider/DataView.java b/flow-data/src/main/java/com/vaadin/flow/data/provider/DataView.java index 52d0c0e8280..3ada5feb9a6 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/provider/DataView.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/provider/DataView.java @@ -59,9 +59,9 @@ public interface DataView extends Serializable { *

* For this to work properly, the item must either implement * {@link Object#equals(Object)} and {@link Object#hashCode()} to consider - * both the old and the new item instances to be equal, or alternatively - * use the {@link #setIdentifierProvider(IdentifierProvider)} to set - * an appropriate item's identifier. + * both the old and the new item instances to be equal, or alternatively use + * the {@link #setIdentifierProvider(IdentifierProvider)} to set an + * appropriate item's identifier. *

* This method delegates the update to * {@link DataProvider#refreshItem(Object)}. diff --git a/flow-data/src/main/java/com/vaadin/flow/data/provider/DataViewUtils.java b/flow-data/src/main/java/com/vaadin/flow/data/provider/DataViewUtils.java index 9c7884454a7..38d7b524cca 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/provider/DataViewUtils.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/provider/DataViewUtils.java @@ -85,7 +85,7 @@ public static Optional> getComponentSortComparator * items type */ public static void setComponentFilter(Component component, - SerializablePredicate filter) { + SerializablePredicate filter) { ComponentUtil.setData(component, COMPONENT_IN_MEMORY_FILTER_KEY, filter); } @@ -104,7 +104,7 @@ public static void setComponentFilter(Component component, * items type */ public static void setComponentSortComparator(Component component, - SerializableComparator sortComparator) { + SerializableComparator sortComparator) { ComponentUtil.setData(component, COMPONENT_IN_MEMORY_SORTING_KEY, sortComparator); } diff --git a/flow-data/src/main/java/com/vaadin/flow/data/provider/InMemoryDataProvider.java b/flow-data/src/main/java/com/vaadin/flow/data/provider/InMemoryDataProvider.java index f0ad28dc721..ba077e22f7c 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/provider/InMemoryDataProvider.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/provider/InMemoryDataProvider.java @@ -232,8 +232,7 @@ default void clearFilters() { * @param comparator * a comparator to add, not null */ - default void addSortComparator( - SerializableComparator comparator) { + default void addSortComparator(SerializableComparator comparator) { Objects.requireNonNull(comparator, "Comparator to add cannot be null"); SerializableComparator originalComparator = getSortComparator(); if (originalComparator == null) { @@ -402,8 +401,7 @@ default DataProvider filteringBySubstring( ValueProvider valueProvider, Locale locale) { Objects.requireNonNull(locale, "Locale cannot be null"); return InMemoryDataProviderHelpers.filteringByCaseInsensitiveString( - this, valueProvider, - String::contains, () -> locale); + this, valueProvider, String::contains, () -> locale); } /** @@ -444,8 +442,8 @@ default DataProvider filteringBySubstring( */ default DataProvider filteringByPrefix( ValueProvider valueProvider, Locale locale) { - return InMemoryDataProviderHelpers.filteringByCaseInsensitiveString(this, valueProvider, - String::startsWith, () -> locale); + return InMemoryDataProviderHelpers.filteringByCaseInsensitiveString( + this, valueProvider, String::startsWith, () -> locale); } /** @@ -464,7 +462,8 @@ default DataProvider filteringByPrefix( */ default DataProvider filteringByPrefix( ValueProvider valueProvider) { - return InMemoryDataProviderHelpers.filteringByCaseInsensitiveString(this, valueProvider, - String::startsWith, InMemoryDataProviderHelpers.CURRENT_LOCALE_SUPPLIER); + return InMemoryDataProviderHelpers.filteringByCaseInsensitiveString( + this, valueProvider, String::startsWith, + InMemoryDataProviderHelpers.CURRENT_LOCALE_SUPPLIER); } } diff --git a/flow-data/src/main/java/com/vaadin/flow/data/provider/ItemCountChangeEvent.java b/flow-data/src/main/java/com/vaadin/flow/data/provider/ItemCountChangeEvent.java index 8be0e57ed10..c1c1fed8efc 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/provider/ItemCountChangeEvent.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/provider/ItemCountChangeEvent.java @@ -53,7 +53,8 @@ public class ItemCountChangeEvent * @param itemCountEstimated * whether item count is an estimate */ - public ItemCountChangeEvent(T source, int itemCount, boolean itemCountEstimated) { + public ItemCountChangeEvent(T source, int itemCount, + boolean itemCountEstimated) { super(source, false); this.itemCount = itemCount; this.itemCountEstimated = itemCountEstimated; diff --git a/flow-data/src/main/java/com/vaadin/flow/data/provider/ItemCountChangeListener.java b/flow-data/src/main/java/com/vaadin/flow/data/provider/ItemCountChangeListener.java index 345c8e36e79..4a584d9e36f 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/provider/ItemCountChangeListener.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/provider/ItemCountChangeListener.java @@ -23,12 +23,12 @@ * Items count changes are mostly due to filtering of the data, but can also be * sent for changes in the dataset. *

- * The {@link #itemCountChanged(ItemCountChangeEvent)} will be called - * during the "before client response"-phase, so changes done during the - * server round trip will only receive one event. - * For example, this code will trigger only one + * The {@link #itemCountChanged(ItemCountChangeEvent)} will be called during the + * "before client response"-phase, so changes done during the server round trip + * will only receive one event. For example, this code will trigger only one * {@link #itemCountChanged(ItemCountChangeEvent)} method call, although there * are two methods called which cause the item count change: + * *

  * {@code
  * dataView.addItemCountChangeListener(listener);
@@ -46,7 +46,7 @@ public interface ItemCountChangeListener extends Serializable {
      * Invoked for changes in the data size.
      *
      * @param event
-     *         Component event containing new data size
+     *            Component event containing new data size
      */
     void itemCountChanged(ItemCountChangeEvent event);
 
diff --git a/flow-data/src/main/java/com/vaadin/flow/data/provider/ListDataView.java b/flow-data/src/main/java/com/vaadin/flow/data/provider/ListDataView.java
index 5d080f79bb3..ab8fb0965dd 100644
--- a/flow-data/src/main/java/com/vaadin/flow/data/provider/ListDataView.java
+++ b/flow-data/src/main/java/com/vaadin/flow/data/provider/ListDataView.java
@@ -56,8 +56,8 @@ public interface ListDataView>
     boolean contains(T item);
 
     /**
-     * Get the full item count with filters if any set. As the item count
-     * might change at any point, it is recommended to add a listener with the
+     * Get the full item count with filters if any set. As the item count might
+     * change at any point, it is recommended to add a listener with the
      * {@link #addItemCountChangeListener(ComponentEventListener)} method
      * instead to get notified when the item count has changed.
      *
@@ -99,8 +99,8 @@ public interface ListDataView>
     /**
      * Adds an item to the data list if it is not already present.
      * 

- * The backing {@link List} must be mutable to use this method. Immutable data - * structure will throw an exception. + * The backing {@link List} must be mutable to use this method. Immutable + * data structure will throw an exception. * * @param item * item to add @@ -116,8 +116,8 @@ public interface ListDataView> /** * Adds an item after the given target item. *

- * The backing {@link List} must be mutable to use this method. Immutable data - * structure will throw an exception. + * The backing {@link List} must be mutable to use this method. Immutable + * data structure will throw an exception. *

* If the item is already present in the data provider, then it is moved. *

@@ -140,8 +140,8 @@ public interface ListDataView> /** * Adds an item before the given target item. *

- * The backing {@link List} must be mutable to use this method. Immutable data - * structure will throw an exception. + * The backing {@link List} must be mutable to use this method. Immutable + * data structure will throw an exception. *

* If the item is already present in the data provider, then it is moved. *

@@ -164,8 +164,8 @@ public interface ListDataView> /** * Adds multiple items to the data list. *

- * The backing {@link List} must be mutable to use this method. Immutable data - * structure will throw an exception. + * The backing {@link List} must be mutable to use this method. Immutable + * data structure will throw an exception. *

* Any items that already present in the data provider are moved to the end. * @@ -184,9 +184,9 @@ public interface ListDataView> * Adds multiple items after the given target item. The full collection is * added in order after the target. *

- * The backing {@link List} must be mutable to use this method. Immutable data - * structure will throw an exception. - * Any items that already present in the data provider are moved. + * The backing {@link List} must be mutable to use this method. Immutable + * data structure will throw an exception. Any items that already present in + * the data provider are moved. *

* Note! Item is added to the unfiltered and unsorted List. * @@ -208,8 +208,8 @@ public interface ListDataView> * Adds multiple items before the given target item. The full collection is * added in order before the target. *

- * The backing {@link List} must be mutable to use this method. Immutable data - * structure will throw an exception. + * The backing {@link List} must be mutable to use this method. Immutable + * data structure will throw an exception. *

* Any items that already present in the data provider are moved. *

@@ -232,8 +232,8 @@ public interface ListDataView> /** * Remove an item from the data list. *

- * The backing {@link List} must be mutable to use this method. Immutable data - * structure will throw an exception. + * The backing {@link List} must be mutable to use this method. Immutable + * data structure will throw an exception. * * @param item * item to remove @@ -248,8 +248,8 @@ public interface ListDataView> /** * Remove multiple items from the data list. *

- * The backing {@link List} must be mutable to use this method. Immutable data - * structure will throw an exception. + * The backing {@link List} must be mutable to use this method. Immutable + * data structure will throw an exception. * * @param items * collection of items to remove diff --git a/flow-data/src/main/java/com/vaadin/flow/data/provider/hierarchy/HasHierarchicalDataProvider.java b/flow-data/src/main/java/com/vaadin/flow/data/provider/hierarchy/HasHierarchicalDataProvider.java index 76bde643428..f082df5c815 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/provider/hierarchy/HasHierarchicalDataProvider.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/provider/hierarchy/HasHierarchicalDataProvider.java @@ -177,5 +177,6 @@ public default void setItems(Stream rootItems, * @param hierarchicalDataProvider * the hierarchical data provider to use, not {@code null} */ - void setDataProvider(HierarchicalDataProvider hierarchicalDataProvider); + void setDataProvider( + HierarchicalDataProvider hierarchicalDataProvider); } diff --git a/flow-data/src/main/java/com/vaadin/flow/data/provider/hierarchy/HierarchicalCommunicationController.java b/flow-data/src/main/java/com/vaadin/flow/data/provider/hierarchy/HierarchicalCommunicationController.java index 70928dc6ef5..dad2540fbda 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/provider/hierarchy/HierarchicalCommunicationController.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/provider/hierarchy/HierarchicalCommunicationController.java @@ -261,8 +261,7 @@ private List activate(Range range) { if (mapperHasKey) { // Ensure latest instance from provider is used keyMapper.refresh(bean); - passivatedByUpdate.values() - .forEach(set -> set.remove(key)); + passivatedByUpdate.values().forEach(set -> set.remove(key)); } activeKeys.add(key); }); diff --git a/flow-data/src/main/java/com/vaadin/flow/data/provider/hierarchy/HierarchicalDataCommunicator.java b/flow-data/src/main/java/com/vaadin/flow/data/provider/hierarchy/HierarchicalDataCommunicator.java index 49d97b9524a..b7fe7c29931 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/provider/hierarchy/HierarchicalDataCommunicator.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/provider/hierarchy/HierarchicalDataCommunicator.java @@ -159,18 +159,15 @@ public void reset() { .startUpdate(getHierarchyMapper().getRootSize()); update.enqueue("$connector.ensureHierarchy"); - Collection expandedItems = getHierarchyMapper().getExpandedItems(); + Collection expandedItems = getHierarchyMapper() + .getExpandedItems(); if (!expandedItems.isEmpty()) { - update.enqueue("$connector.expandItems", - expandedItems - .stream() - .map(getKeyMapper()::key) - .map(key -> { - JsonObject json = Json.createObject(); - json.put("key", key); - return json; - }).collect( - JsonUtils.asArray())); + update.enqueue("$connector.expandItems", expandedItems.stream() + .map(getKeyMapper()::key).map(key -> { + JsonObject json = Json.createObject(); + json.put("key", key); + return json; + }).collect(JsonUtils.asArray())); } requestFlush(update); @@ -178,16 +175,19 @@ public void reset() { } @Override - protected void handleDataRefreshEvent(DataChangeEvent.DataRefreshEvent event) { + protected void handleDataRefreshEvent( + DataChangeEvent.DataRefreshEvent event) { if (event.isRefreshChildren()) { T item = event.getItem(); if (isExpanded(item)) { String parentKey = uniqueKeyProviderSupplier.get().apply(item); if (!dataControllers.containsKey(parentKey)) { - setParentRequestedRange(0, mapper.countChildItems(item), item); + setParentRequestedRange(0, mapper.countChildItems(item), + item); } - HierarchicalCommunicationController dataController = dataControllers.get(parentKey); + HierarchicalCommunicationController dataController = dataControllers + .get(parentKey); if (dataController != null) { dataController.setResendEntireRange(true); requestFlush(dataController); diff --git a/flow-data/src/main/java/com/vaadin/flow/data/provider/hierarchy/HierarchyMapper.java b/flow-data/src/main/java/com/vaadin/flow/data/provider/hierarchy/HierarchyMapper.java index 34f6da66a10..4a17db738ab 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/provider/hierarchy/HierarchyMapper.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/provider/hierarchy/HierarchyMapper.java @@ -189,8 +189,8 @@ private boolean doExpand(T item) { * * @param item * the item to collapse - * @return {@code true} if item has been collapsed, - * {@code false} if item is empty or already collapsed + * @return {@code true} if item has been collapsed, {@code false} if item is + * empty or already collapsed */ public boolean collapse(T item) { if (item == null) { @@ -225,7 +225,6 @@ public Range collapse(T item, Integer position) { return removedRows; } - /** * Gets the current in-memory sorting. * @@ -374,10 +373,10 @@ private Stream doFetchDirectChildren(T parent, Range range) { Range actualRange = (range == null) ? Range.withLength(0, Integer.MAX_VALUE) : range; - return getDataProvider().fetchChildren(new HierarchicalQuery( - actualRange.getStart(), actualRange.length(), - getBackEndSorting(), - getInMemorySorting(), getFilter(), parent)); + return getDataProvider() + .fetchChildren(new HierarchicalQuery(actualRange.getStart(), + actualRange.length(), getBackEndSorting(), + getInMemorySorting(), getFilter(), parent)); } /** @@ -573,12 +572,10 @@ private Stream getChildrenStream(T parent, Range range, registerChildren(parent, childList); } } - return combineParentAndChildStreams(parent, - childList.stream(), + return combineParentAndChildStreams(parent, childList.stream(), includeParent); } - /** * Register parent and children items into inner structures. May be * overridden in subclasses. @@ -635,7 +632,7 @@ public boolean hasExpandedItems() { * Returns the expanded items in form of an unmodifiable collection. * * @return an unmodifiable {@code Collection} containing the expanded - * items. + * items. */ public Collection getExpandedItems() { return Collections.unmodifiableCollection(expandedItems.values()); diff --git a/flow-data/src/main/java/com/vaadin/flow/data/provider/hierarchy/TreeDataProvider.java b/flow-data/src/main/java/com/vaadin/flow/data/provider/hierarchy/TreeDataProvider.java index d151c7bfafc..4d8c997bbda 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/provider/hierarchy/TreeDataProvider.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/provider/hierarchy/TreeDataProvider.java @@ -24,7 +24,6 @@ import com.vaadin.flow.function.SerializableComparator; import com.vaadin.flow.function.SerializablePredicate; - /** * An in-memory data provider for listing components that display hierarchical * data. Uses an instance of {@link TreeData} as its source of data. @@ -89,8 +88,8 @@ public int getChildCount( items = treeData.getRootItems().stream(); } - return (int) getFilteredStream(items, - query.getFilter()).skip(query.getOffset()).limit(query.getLimit()).count(); + return (int) getFilteredStream(items, query.getFilter()) + .skip(query.getOffset()).limit(query.getLimit()).count(); } @Override @@ -143,17 +142,16 @@ public void setSortComparator(SerializableComparator comparator) { private Stream getFilteredStream(Stream stream, Optional> queryFilter) { - final Optional> combinedFilter = - filter != null ? - Optional.of(queryFilter.map(filter::and).orElse(filter)) : - queryFilter; - return combinedFilter - .map(f -> stream.filter(element -> flatten(element).anyMatch(f))) - .orElse(stream); + final Optional> combinedFilter = filter != null + ? Optional.of(queryFilter.map(filter::and).orElse(filter)) + : queryFilter; + return combinedFilter.map( + f -> stream.filter(element -> flatten(element).anyMatch(f))) + .orElse(stream); } private Stream flatten(T element) { - return Stream.concat(Stream.of(element), - getTreeData().getChildren(element).stream().flatMap(this::flatten)); + return Stream.concat(Stream.of(element), getTreeData() + .getChildren(element).stream().flatMap(this::flatten)); } } diff --git a/flow-data/src/main/java/com/vaadin/flow/data/renderer/BasicRenderer.java b/flow-data/src/main/java/com/vaadin/flow/data/renderer/BasicRenderer.java index 3e3573aae95..4dcb9e9f224 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/renderer/BasicRenderer.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/renderer/BasicRenderer.java @@ -81,17 +81,16 @@ public Rendering render(Element container, private void setupTemplate(Element owner, SimpleValueRendering rendering, DataKeyMapper keyMapper) { - /* - * setupTemplateWhenAttached does some setup that will be needed by - * generateData. To ensure the setup has completed before it is needed, - * we forego the general convention of using beforeClientResponse to - * guard the action against duplicate invocation. This is not a big - * problem in this case since setupTemplateWhenAttached only sets - * properties but doesn't execute any JS. - */ - owner.getNode() - .runWhenAttached(ui -> setupTemplateWhenAttached(owner, - rendering, keyMapper)); + /* + * setupTemplateWhenAttached does some setup that will be needed by + * generateData. To ensure the setup has completed before it is needed, + * we forego the general convention of using beforeClientResponse to + * guard the action against duplicate invocation. This is not a big + * problem in this case since setupTemplateWhenAttached only sets + * properties but doesn't execute any JS. + */ + owner.getNode().runWhenAttached( + ui -> setupTemplateWhenAttached(owner, rendering, keyMapper)); } private void setupTemplateWhenAttached(Element owner, diff --git a/flow-data/src/main/java/com/vaadin/flow/data/renderer/ComponentRenderer.java b/flow-data/src/main/java/com/vaadin/flow/data/renderer/ComponentRenderer.java index a479e22a557..8477c23899f 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/renderer/ComponentRenderer.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/renderer/ComponentRenderer.java @@ -165,10 +165,8 @@ public Rendering render(Element container, * problem in this case since setupTemplateWhenAttached only sets * properties but doesn't execute any JS. */ - container.getNode() - .runWhenAttached(ui -> setupTemplateWhenAttached( - ui, container, rendering, - keyMapper)); + container.getNode().runWhenAttached(ui -> setupTemplateWhenAttached(ui, + container, rendering, keyMapper)); return rendering; } diff --git a/flow-data/src/main/java/com/vaadin/flow/data/renderer/NumberRenderer.java b/flow-data/src/main/java/com/vaadin/flow/data/renderer/NumberRenderer.java index e06fee0c1fc..61dce44a129 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/renderer/NumberRenderer.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/renderer/NumberRenderer.java @@ -31,8 +31,7 @@ * the type of the input item, from which the number is extracted * */ -public class NumberRenderer - extends BasicRenderer { +public class NumberRenderer extends BasicRenderer { private Locale locale; private NumberFormat numberFormat; diff --git a/flow-data/src/main/java/com/vaadin/flow/data/renderer/TemplateRenderer.java b/flow-data/src/main/java/com/vaadin/flow/data/renderer/TemplateRenderer.java index 16a8ce3353e..d8976169ba8 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/renderer/TemplateRenderer.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/renderer/TemplateRenderer.java @@ -75,10 +75,10 @@ public static TemplateRenderer of(String template) { private static void warnIfClassOrStyleWithoutDollar(String template) { if (hasClassOrStyleWithoutDollar(template)) { - LoggerFactory.getLogger(TemplateRenderer.class) - .warn("Bindings for 'class' and 'style' need a $ prefix (e.g. 'class$=\"[[item.className]]\"') to use an attribute binding instead of a property binding." + LoggerFactory.getLogger(TemplateRenderer.class).warn( + "Bindings for 'class' and 'style' need a $ prefix (e.g. 'class$=\"[[item.className]]\"') to use an attribute binding instead of a property binding." + " Apparent omission detected in the template '{}'", - template); + template); } } diff --git a/flow-data/src/main/java/com/vaadin/flow/data/value/ValueChangeMode.java b/flow-data/src/main/java/com/vaadin/flow/data/value/ValueChangeMode.java index dd6ad0cdec8..be6ba5f8130 100644 --- a/flow-data/src/main/java/com/vaadin/flow/data/value/ValueChangeMode.java +++ b/flow-data/src/main/java/com/vaadin/flow/data/value/ValueChangeMode.java @@ -44,8 +44,8 @@ public enum ValueChangeMode { LAZY, /** - * Syncs the value at defined intervals - * as long as the value changes from one event to the next. + * Syncs the value at defined intervals as long as the value changes from + * one event to the next. */ TIMEOUT, @@ -72,8 +72,8 @@ public enum ValueChangeMode { /** * Gets the name of the event associated with the given mode. If the mode is * null, then null is returned. If the mode is {@link #EAGER}, - * {@link #LAZY}, or {@link #TIMEOUT}, - * then the provided immediate event name is returned. + * {@link #LAZY}, or {@link #TIMEOUT}, then the provided immediate event + * name is returned. * * @see HasValueChangeMode#setValueChangeMode(ValueChangeMode) * @see AbstractSinglePropertyField#setSynchronizedEvent(String) @@ -81,11 +81,12 @@ public enum ValueChangeMode { * @param mode * the value change mode * @param immediateEventName - * the name of the event that is fired immediately on value change + * the name of the event that is fired immediately on value + * change * @return the event name */ public static String eventForMode(ValueChangeMode mode, - String immediateEventName) { + String immediateEventName) { if (mode == null) { return null; } @@ -106,41 +107,41 @@ public static String eventForMode(ValueChangeMode mode, } /** - * Applies the value change timeout of the given mode on the registration - * of the DOM event listener that synchronizes. - * It has any effect only for {@link #LAZY}, or {@link #TIMEOUT}. - + * Applies the value change timeout of the given mode on the registration of + * the DOM event listener that synchronizes. It has any effect only for + * {@link #LAZY}, or {@link #TIMEOUT}. + * * @see HasValueChangeMode#getValueChangeTimeout() * @see AbstractSinglePropertyField#getSynchronizationRegistration() * * @param mode * the value change mode * @param timeout - * Value change timeout in milliseconds. - * 0 means timeout is disabled, - * so the change mode will behave like {@link #EAGER} + * Value change timeout in milliseconds. 0 means + * timeout is disabled, so the change mode will behave like + * {@link #EAGER} * @param registration * The registration of the DOM event listener that synchronizes. */ public static void applyChangeTimeout(ValueChangeMode mode, int timeout, - DomListenerRegistration registration) { + DomListenerRegistration registration) { if (mode == null || registration == null) { return; } switch (mode) { - case LAZY: - registration.debounce(timeout); - break; - case TIMEOUT: - registration.throttle(timeout); - break; - case EAGER: - case ON_BLUR: - case ON_CHANGE: - break; - default: - throwModeNotSupported(mode); + case LAZY: + registration.debounce(timeout); + break; + case TIMEOUT: + registration.throttle(timeout); + break; + case EAGER: + case ON_BLUR: + case ON_CHANGE: + break; + default: + throwModeNotSupported(mode); } } diff --git a/flow-data/src/test/java/com/vaadin/flow/data/binder/BeanPropertySetTest.java b/flow-data/src/test/java/com/vaadin/flow/data/binder/BeanPropertySetTest.java index 95a835e8a7a..717b929ecc9 100644 --- a/flow-data/src/test/java/com/vaadin/flow/data/binder/BeanPropertySetTest.java +++ b/flow-data/src/test/java/com/vaadin/flow/data/binder/BeanPropertySetTest.java @@ -162,7 +162,8 @@ public void testSerializeDeserialize_nestedPropertyDefinition() PropertyDefinition definition = BeanPropertySet .get(com.vaadin.flow.tests.data.bean.Person.class, true, PropertyFilterDefinition.getDefaultFilter()) - .getProperty("address.postalCode").orElseThrow(AssertionFailedError::new); + .getProperty("address.postalCode") + .orElseThrow(AssertionFailedError::new); PropertyDefinition deserializedDefinition = ClassesSerializableUtils .serializeAndDeserialize(definition); diff --git a/flow-data/src/test/java/com/vaadin/flow/data/binder/BinderTest.java b/flow-data/src/test/java/com/vaadin/flow/data/binder/BinderTest.java index da8690c9d75..ff982449183 100644 --- a/flow-data/src/test/java/com/vaadin/flow/data/binder/BinderTest.java +++ b/flow-data/src/test/java/com/vaadin/flow/data/binder/BinderTest.java @@ -340,15 +340,13 @@ public void save_bound_beanAsDraft_setBean() { private void do_test_save_bound_beanAsDraft(boolean setBean) { Binder binder = new Binder<>(); - binder.forField(nameField) - .withValidator((value,context) -> { - if (value.equals("Mike")) { - return ValidationResult.ok(); - } else { - return ValidationResult.error("value must be Mike"); - } - }) - .bind(Person::getFirstName, Person::setFirstName); + binder.forField(nameField).withValidator((value, context) -> { + if (value.equals("Mike")) { + return ValidationResult.ok(); + } else { + return ValidationResult.error("value must be Mike"); + } + }).bind(Person::getFirstName, Person::setFirstName); binder.forField(ageField) .withConverter(new StringToIntegerConverter("")) .bind(Person::getAge, Person::setAge); @@ -375,20 +373,22 @@ private void do_test_save_bound_beanAsDraft(boolean setBean) { // fails assertEquals(age, person.getAge()); - binder.writeBeanAsDraft(person,true); + binder.writeBeanAsDraft(person, true); // name is now written despite validation as write was forced assertEquals(fieldValue, person.getFirstName()); } @Test - public void save_bound_bean_disable_validation_binding() throws ValidationException { + public void save_bound_bean_disable_validation_binding() + throws ValidationException { Binder binder = new Binder<>(); Binding nameBinding = binder.forField(nameField) - .withValidator((value,context) -> { - if (value.equals("Mike")) return ValidationResult.ok(); - else return ValidationResult.error("value must be Mike"); - }) - .bind(Person::getFirstName, Person::setFirstName); + .withValidator((value, context) -> { + if (value.equals("Mike")) + return ValidationResult.ok(); + else + return ValidationResult.error("value must be Mike"); + }).bind(Person::getFirstName, Person::setFirstName); binder.forField(ageField) .withConverter(new StringToIntegerConverter("")) .bind(Person::getAge, Person::setAge); @@ -412,14 +412,15 @@ public void save_bound_bean_disable_validation_binding() throws ValidationExcept } @Test - public void save_bound_bean_disable_validation_binder() throws ValidationException { + public void save_bound_bean_disable_validation_binder() + throws ValidationException { Binder binder = new Binder<>(); - binder.forField(nameField) - .withValidator((value,context) -> { - if (value.equals("Mike")) return ValidationResult.ok(); - else return ValidationResult.error("value must be Mike"); - }) - .bind(Person::getFirstName, Person::setFirstName); + binder.forField(nameField).withValidator((value, context) -> { + if (value.equals("Mike")) + return ValidationResult.ok(); + else + return ValidationResult.error("value must be Mike"); + }).bind(Person::getFirstName, Person::setFirstName); binder.forField(ageField) .withConverter(new StringToIntegerConverter("")) .bind(Person::getAge, Person::setAge); @@ -615,13 +616,15 @@ public void setRequired_withErrorMessage_fieldGetsRequiredIndicatorAndValidator( TestTextField textField = new TestTextField(); assertFalse(textField.isRequiredIndicatorVisible()); - BindingBuilder bindingBuilder = binder.forField(textField); + BindingBuilder bindingBuilder = binder + .forField(textField); assertFalse(textField.isRequiredIndicatorVisible()); bindingBuilder.asRequired("foobar"); assertTrue(textField.isRequiredIndicatorVisible()); - Binding binding = bindingBuilder.bind(Person::getFirstName, Person::setFirstName); + Binding binding = bindingBuilder + .bind(Person::getFirstName, Person::setFirstName); binder.setBean(item); assertThat(textField.getErrorMessage(), isEmptyString()); @@ -642,12 +645,15 @@ public void setRequired_withErrorMessage_fieldGetsRequiredIndicatorAndValidator( public void settingAsRequiredEnabledFalseWhenNoAsRequired() { TestTextField textField = new TestTextField(); - BindingBuilder bindingBuilder = binder.forField(textField); - Binding binding = bindingBuilder.bind(Person::getFirstName, Person::setFirstName); + BindingBuilder bindingBuilder = binder + .forField(textField); + Binding binding = bindingBuilder + .bind(Person::getFirstName, Person::setFirstName); binder.readBean(item); - // TextField input is not set required, this should trigger IllegalStateExceptipon + // TextField input is not set required, this should trigger + // IllegalStateExceptipon binding.setAsRequiredEnabled(false); } diff --git a/flow-data/src/test/java/com/vaadin/flow/data/binder/UnbindTest.java b/flow-data/src/test/java/com/vaadin/flow/data/binder/UnbindTest.java index e763eadff0d..10a3811a488 100644 --- a/flow-data/src/test/java/com/vaadin/flow/data/binder/UnbindTest.java +++ b/flow-data/src/test/java/com/vaadin/flow/data/binder/UnbindTest.java @@ -5,7 +5,8 @@ import org.junit.Before; import org.junit.Test; -public class UnbindTest extends BinderTestBase, BeanToValidate> { +public class UnbindTest + extends BinderTestBase, BeanToValidate> { @Before public void setUp() { binder = new BeanValidationBinder<>(BeanToValidate.class); @@ -16,7 +17,8 @@ public void setUp() { @Test public void binding_unbind_shouldBeRemovedFromBindings() { - Binder.Binding firstnameBinding = binder.bind(nameField, "firstname"); + Binder.Binding firstnameBinding = binder + .bind(nameField, "firstname"); Assert.assertEquals(1, binder.getBindings().size()); firstnameBinding.unbind(); Assert.assertTrue(binder.getBindings().isEmpty()); @@ -25,22 +27,24 @@ public void binding_unbind_shouldBeRemovedFromBindings() { @Test public void binding_unbindDuringReadBean_shouldBeRemovedFromBindings() { - Binder.Binding firstnameBinding = binder.bind(nameField, "firstname"); - Binder.Binding ageBinding = binder.bind(ageField, "age"); + Binder.Binding firstnameBinding = binder + .bind(nameField, "firstname"); + Binder.Binding ageBinding = binder + .bind(ageField, "age"); Assert.assertEquals(2, binder.getBindings().size()); nameField.addValueChangeListener(event -> { - if(event.getValue().length() > 0) + if (event.getValue().length() > 0) ageBinding.unbind(); - } ); + }); binder.readBean(item); Assert.assertEquals(1, binder.getBindings().size()); Assert.assertNull(ageBinding.getField()); } - @Test public void binding_unbindTwice_shouldBeRemovedFromBindings() { - Binder.Binding firstnameBinding = binder.bind(nameField, "firstname"); + Binder.Binding firstnameBinding = binder + .bind(nameField, "firstname"); Assert.assertEquals(1, binder.getBindings().size()); firstnameBinding.unbind(); firstnameBinding.unbind(); diff --git a/flow-data/src/test/java/com/vaadin/flow/data/binder/testcomponents/TestLabel.java b/flow-data/src/test/java/com/vaadin/flow/data/binder/testcomponents/TestLabel.java index 0cecd9d7d02..c75e8b8f4fc 100644 --- a/flow-data/src/test/java/com/vaadin/flow/data/binder/testcomponents/TestLabel.java +++ b/flow-data/src/test/java/com/vaadin/flow/data/binder/testcomponents/TestLabel.java @@ -24,7 +24,6 @@ import com.vaadin.flow.component.PropertyDescriptors; import com.vaadin.flow.component.Tag; - /* Test label so that we don't depend on the html components. */ @Tag(Tag.LABEL) public class TestLabel extends HtmlContainer { diff --git a/flow-data/src/test/java/com/vaadin/flow/data/provider/AbstractComponentDataViewTest.java b/flow-data/src/test/java/com/vaadin/flow/data/provider/AbstractComponentDataViewTest.java index 87d524f0ea7..e32e39b572f 100644 --- a/flow-data/src/test/java/com/vaadin/flow/data/provider/AbstractComponentDataViewTest.java +++ b/flow-data/src/test/java/com/vaadin/flow/data/provider/AbstractComponentDataViewTest.java @@ -30,11 +30,11 @@ import org.junit.Test; /** - * Abstract test class that contains the common tests for all generic - * data view component's implementations, i.e. which extends - * {@link AbstractDataView} and doesn't contain an in-memory or lazy - * specific API. Concrete implementations of this class should provide a - * particular component to be tested as a {@link HasDataView} implementation. + * Abstract test class that contains the common tests for all generic data view + * component's implementations, i.e. which extends {@link AbstractDataView} and + * doesn't contain an in-memory or lazy specific API. Concrete implementations + * of this class should provide a particular component to be tested as a + * {@link HasDataView} implementation. */ public abstract class AbstractComponentDataViewTest { @@ -62,15 +62,14 @@ public void getItems_noFiltersSet_allItemsObtained() { public void getItems_filtersSet_filteredItemsObtained() { dataProvider.setFilter(item -> item.equals("first")); Assert.assertArrayEquals("Unexpected data set after filtering", - new String[]{"first"}, - dataView.getItems().toArray()); + new String[] { "first" }, dataView.getItems().toArray()); } @Test public void getItems_sortingSet_sortedItemsObtained() { dataProvider.setSortComparator(String::compareToIgnoreCase); Assert.assertArrayEquals("Unexpected items sorting", - new String[]{"first", "last", "middle"}, + new String[] { "first", "last", "middle" }, dataView.getItems().toArray()); } @@ -89,8 +88,7 @@ public void addItemCountChangeListener_fireEvent_listenerNotified() { protected abstract HasDataView> getComponent(); private HasDataView> getVerifiedComponent() { - HasDataView> component = - getComponent(); + HasDataView> component = getComponent(); if (component instanceof Component) { return component; } @@ -130,11 +128,12 @@ public void setValue(String value) { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; Item item = (Item) o; - return id == item.id && - Objects.equals(value, item.value); + return id == item.id && Objects.equals(value, item.value); } @Override diff --git a/flow-data/src/test/java/com/vaadin/flow/data/provider/AbstractDataViewTest.java b/flow-data/src/test/java/com/vaadin/flow/data/provider/AbstractDataViewTest.java index ef1fe790ffa..af4e8cb4b1c 100644 --- a/flow-data/src/test/java/com/vaadin/flow/data/provider/AbstractDataViewTest.java +++ b/flow-data/src/test/java/com/vaadin/flow/data/provider/AbstractDataViewTest.java @@ -43,11 +43,10 @@ public class AbstractDataViewTest { @Before public void init() { - items = new ArrayList<>(Arrays.asList( - new Item(1L, "first", "description1"), - new Item(2L, "middle", "description2"), - new Item(3L, "last", "description3") - )); + items = new ArrayList<>( + Arrays.asList(new Item(1L, "first", "description1"), + new Item(2L, "middle", "description2"), + new Item(3L, "last", "description3"))); dataProvider = DataProvider.ofCollection(items); component = new TestComponent(); dataView = new DataViewImpl(() -> dataProvider, component); @@ -82,15 +81,15 @@ public void addItemCountChangeListener_fireEvent_listenerNotified() { dataView.addItemCountChangeListener( event -> fired.compareAndSet(0, event.getItemCount())); - ComponentUtil - .fireEvent(component, new ItemCountChangeEvent<>(component, 10, false)); + ComponentUtil.fireEvent(component, + new ItemCountChangeEvent<>(component, 10, false)); Assert.assertEquals(10, fired.get()); } /** - * setIdentifierProvider is tested in AbstractListDataView since it - * has the container(T item) method. + * setIdentifierProvider is tested in AbstractListDataView since it has the + * container(T item) method. */ @Tag("test-component") diff --git a/flow-data/src/test/java/com/vaadin/flow/data/provider/AbstractLazyDataViewTest.java b/flow-data/src/test/java/com/vaadin/flow/data/provider/AbstractLazyDataViewTest.java index c0cd7ade38d..4eee4220b80 100644 --- a/flow-data/src/test/java/com/vaadin/flow/data/provider/AbstractLazyDataViewTest.java +++ b/flow-data/src/test/java/com/vaadin/flow/data/provider/AbstractLazyDataViewTest.java @@ -145,7 +145,8 @@ public void addItemCountListener_beforeSettingDataProvider_verificationPassed() // Check that we can add a listener even if no data provider set by // user - dataView.addItemCountChangeListener(event -> {}); + dataView.addItemCountChangeListener(event -> { + }); } @Test(expected = IllegalStateException.class) @@ -369,53 +370,53 @@ public void refreshItem_itemPresentInDataSet_refreshesItem() { Mockito.verify(dataCommunicator).refresh(updatedItem2); } - @Test - public void refreshItem_itemNotPresent_itemNotRefreshed() { - Item item1 = new Item(0L, "value1"); + @Test + public void refreshItem_itemNotPresent_itemNotRefreshed() { + Item item1 = new Item(0L, "value1"); - DataProvider dataProvider = Mockito - .spy(DataProvider.fromCallbacks(query -> { - query.getOffset(); - query.getLimit(); - return Stream.of(item1); - }, query -> 1)); + DataProvider dataProvider = Mockito + .spy(DataProvider.fromCallbacks(query -> { + query.getOffset(); + query.getLimit(); + return Stream.of(item1); + }, query -> 1)); - DataCommunicator dataCommunicator = Mockito - .spy(new DataCommunicator<>((item, jsonObject) -> { - }, arrayUpdater, null, component.getElement().getNode())); + DataCommunicator dataCommunicator = Mockito + .spy(new DataCommunicator<>((item, jsonObject) -> { + }, arrayUpdater, null, component.getElement().getNode())); - dataCommunicator.setDataProvider(dataProvider, null); + dataCommunicator.setDataProvider(dataProvider, null); - AbstractLazyDataView dataView = new AbstractLazyDataView( - dataCommunicator, component) { - }; + AbstractLazyDataView dataView = new AbstractLazyDataView( + dataCommunicator, component) { + }; - Item item2 = new Item(1L, "value1"); - dataView.refreshItem(item1); + Item item2 = new Item(1L, "value1"); + dataView.refreshItem(item1); - // Verify that the refresh request is not promoted to data provider and - // data communicator, because item with id=1 is not found. - Mockito.verify(dataProvider, Mockito.times(0)).refreshItem(item2); - Mockito.verify(dataCommunicator, Mockito.times(0)).refresh(item2); - } + // Verify that the refresh request is not promoted to data provider and + // data communicator, because item with id=1 is not found. + Mockito.verify(dataProvider, Mockito.times(0)).refreshItem(item2); + Mockito.verify(dataCommunicator, Mockito.times(0)).refresh(item2); + } - @Test - public void paged_access_methods_in_query_object() { - Query query; + @Test + public void paged_access_methods_in_query_object() { + Query query; - query = new Query<>(0, 20, null, null, null); - Assert.assertEquals(0L, query.getPage()); - Assert.assertEquals(20, query.getPageSize()); + query = new Query<>(0, 20, null, null, null); + Assert.assertEquals(0L, query.getPage()); + Assert.assertEquals(20, query.getPageSize()); - query = new Query<>(20, 20, null, null, null); - Assert.assertEquals(1L, query.getPage()); - Assert.assertEquals(20, query.getPageSize()); + query = new Query<>(20, 20, null, null, null); + Assert.assertEquals(1L, query.getPage()); + Assert.assertEquals(20, query.getPageSize()); - query = new Query<>(200, 40, null, null, null); - Assert.assertEquals(5L, query.getPage()); - Assert.assertEquals(40, query.getPageSize()); + query = new Query<>(200, 40, null, null, null); + Assert.assertEquals(5L, query.getPage()); + Assert.assertEquals(40, query.getPageSize()); - } + } private void fakeClientCommunication() { ui.getInternals().getStateTree().runExecutionsBeforeClientResponse(); diff --git a/flow-data/src/test/java/com/vaadin/flow/data/provider/AbstractListDataViewListenerTest.java b/flow-data/src/test/java/com/vaadin/flow/data/provider/AbstractListDataViewListenerTest.java index 352a98af30b..fd882590770 100644 --- a/flow-data/src/test/java/com/vaadin/flow/data/provider/AbstractListDataViewListenerTest.java +++ b/flow-data/src/test/java/com/vaadin/flow/data/provider/AbstractListDataViewListenerTest.java @@ -37,8 +37,7 @@ public abstract class AbstractListDataViewListenerTest { @Test public void addItemCountChangeListener_itemsCountChanged_listenersAreNotified() { String[] items = new String[] { "item1", "item2", "item3", "item4" }; - HasListDataView> component = - getVerifiedComponent(); + HasListDataView> component = getVerifiedComponent(); AbstractListDataView dataView = component .setItems(new ArrayList<>(Arrays.asList(items))); @@ -60,17 +59,16 @@ public void addItemCountChangeListener_itemsCountChanged_listenersAreNotified() fakeClientCall(ui); Assert.assertEquals( - "Unexpected number of item count change listener invocations " + - "occurred", 1, invocationCounter.get()); + "Unexpected number of item count change listener invocations " + + "occurred", + 1, invocationCounter.get()); } @Test public void addItemCountChangeListener_itemsCountNotChanged_listenersAreNotNotified() { String[] items = new String[] { "item1", "item2", "item3", "item4" }; - HasListDataView> component = - getVerifiedComponent(); - AbstractListDataView dataView = component - .setItems(items); + HasListDataView> component = getVerifiedComponent(); + AbstractListDataView dataView = component.setItems(items); AtomicBoolean invocationChecker = new AtomicBoolean(false); @@ -96,10 +94,8 @@ public void addItemCountChangeListener_itemsCountNotChanged_listenersAreNotNotif @Test public void addItemCountChangeListener_itemsCountChanged_newItemCountSuppliedInEvent() { String[] items = new String[] { "item1", "item2", "item3", "item4" }; - HasListDataView> component = - getVerifiedComponent(); - AbstractListDataView dataView = component - .setItems(items); + HasListDataView> component = getVerifiedComponent(); + AbstractListDataView dataView = component.setItems(items); AtomicBoolean invocationChecker = new AtomicBoolean(false); diff --git a/flow-data/src/test/java/com/vaadin/flow/data/provider/AbstractListDataViewTest.java b/flow-data/src/test/java/com/vaadin/flow/data/provider/AbstractListDataViewTest.java index 747b1cea976..ddf3dddb6e1 100644 --- a/flow-data/src/test/java/com/vaadin/flow/data/provider/AbstractListDataViewTest.java +++ b/flow-data/src/test/java/com/vaadin/flow/data/provider/AbstractListDataViewTest.java @@ -68,7 +68,8 @@ public void init() { dataView = new ListDataViewImpl(() -> dataProvider, component); itemListDataProvider = DataProvider.ofCollection(getTestItems()); - beanDataView = new ItemListDataView(() -> itemListDataProvider, component); + beanDataView = new ItemListDataView(() -> itemListDataProvider, + component); } @Test @@ -92,8 +93,8 @@ public void getItemCount_noFiltersSet_dataSizeObtained() { @Test public void getItemCount_filtersSet_filteredItemsObtained() { dataProvider.setFilter(item -> item.equals("first")); - Assert.assertEquals("Unexpected item count", - 1, dataView.getItemCount()); + Assert.assertEquals("Unexpected item count", 1, + dataView.getItemCount()); } @Test @@ -190,7 +191,8 @@ public void setSortOrder_sortOrderIsSet_sortedItemsObtained() { @Test public void addSortOrder_twoOrdersAdded_itemsSortedByCompositeOrders() { dataProvider = DataProvider.ofItems("b3", "a1", "a2"); - dataView = new ListDataViewImpl(() -> dataProvider, new TestComponent()); + dataView = new ListDataViewImpl(() -> dataProvider, + new TestComponent()); dataView.addSortOrder((item) -> item.charAt(0), SortDirection.DESCENDING); Assert.assertEquals("Unexpected data set order (order 1)", "b3,a1,a2", @@ -226,69 +228,62 @@ public void contains_itemNotPresentedInDataSet_itemNotFound() { @Test public void setIdentifierProvider_defaultIdentity_equalsIsUsed() { - Assert.assertTrue(beanDataView.contains( - new Item(1L, "value1"))); - Assert.assertFalse(beanDataView.contains( - new Item(1L, "non present"))); - Assert.assertFalse(beanDataView.contains( - new Item(4L, "value1"))); + Assert.assertTrue(beanDataView.contains(new Item(1L, "value1"))); + Assert.assertFalse(beanDataView.contains(new Item(1L, "non present"))); + Assert.assertFalse(beanDataView.contains(new Item(4L, "value1"))); } @Test public void setIdentifierProvider_dataProviderIdentity_getIdIsUsed() { - itemListDataProvider = new AbstractDataViewTest.CustomIdentityItemDataProvider(getTestItems()); + itemListDataProvider = new AbstractDataViewTest.CustomIdentityItemDataProvider( + getTestItems()); - Assert.assertTrue(beanDataView.contains( - new Item(1L, "value1"))); - Assert.assertTrue(beanDataView.contains( - new Item(1L, "non present"))); - Assert.assertFalse(beanDataView.contains( - new Item(4L, "value1"))); + Assert.assertTrue(beanDataView.contains(new Item(1L, "value1"))); + Assert.assertTrue(beanDataView.contains(new Item(1L, "non present"))); + Assert.assertFalse(beanDataView.contains(new Item(4L, "value1"))); } @Test public void setIdentifierProvider_customIdentifierProvider_customIdentifierProviderIsUsed() { beanDataView.setIdentifierProvider(Item::getValue); - Assert.assertTrue(beanDataView.contains( - new Item(1L, "value1"))); - Assert.assertFalse(beanDataView.contains( - new Item(1L, "non present"))); - Assert.assertTrue(beanDataView.contains( - new Item(4L, "value1"))); + Assert.assertTrue(beanDataView.contains(new Item(1L, "value1"))); + Assert.assertFalse(beanDataView.contains(new Item(1L, "non present"))); + Assert.assertTrue(beanDataView.contains(new Item(4L, "value1"))); } @Test public void setIdentifierProvider_dataProviderHasChanged_newDataProviderIsUsed() { - Assert.assertFalse(beanDataView.contains( - new Item(1L, "non present"))); + Assert.assertFalse(beanDataView.contains(new Item(1L, "non present"))); - itemListDataProvider = new AbstractDataViewTest.CustomIdentityItemDataProvider(getTestItems()); + itemListDataProvider = new AbstractDataViewTest.CustomIdentityItemDataProvider( + getTestItems()); - Assert.assertTrue(beanDataView.contains( - new Item(1L, "non present"))); + Assert.assertTrue(beanDataView.contains(new Item(1L, "non present"))); - itemListDataProvider = DataProvider.ofItems(new Item(10L, "description10")); + itemListDataProvider = DataProvider + .ofItems(new Item(10L, "description10")); - Assert.assertFalse(beanDataView.contains( - new Item(1L, "non present"))); - Assert.assertTrue(beanDataView.contains(new Item(10L, "description10"))); + Assert.assertFalse(beanDataView.contains(new Item(1L, "non present"))); + Assert.assertTrue( + beanDataView.contains(new Item(10L, "description10"))); } @Test public void setIdentifierProvider_dataProviderHasChanged_identifierProviderRetained() { - Assert.assertFalse(beanDataView.contains( - new Item(4L, "non present", "descr1"))); + Assert.assertFalse( + beanDataView.contains(new Item(4L, "non present", "descr1"))); beanDataView.setIdentifierProvider(Item::getDescription); - Assert.assertTrue(beanDataView.contains( - new Item(4L, "non present", "descr1"))); + Assert.assertTrue( + beanDataView.contains(new Item(4L, "non present", "descr1"))); - itemListDataProvider = new AbstractDataViewTest.CustomIdentityItemDataProvider(getTestItems()); + itemListDataProvider = new AbstractDataViewTest.CustomIdentityItemDataProvider( + getTestItems()); - Assert.assertTrue(beanDataView.contains( - new Item(4L, "non present", "descr1"))); + Assert.assertTrue( + beanDataView.contains(new Item(4L, "non present", "descr1"))); } @Test @@ -390,8 +385,7 @@ public void addItemBefore_addItemInFilteredDataSet_itemAddedBeforeTheTarget() { dataView.addFilter(item -> !item.equalsIgnoreCase("first")); dataView.addItemBefore("newItem", "last"); - Assert.assertArrayEquals( - new String[] { "middle", "newItem", "last"}, + Assert.assertArrayEquals(new String[] { "middle", "newItem", "last" }, dataView.getItems().toArray(String[]::new)); } @@ -450,8 +444,7 @@ public void addItemAfter_addItemInFilteredDataSet_itemAddedAfterTheTarget() { dataView.addFilter(item -> !item.equalsIgnoreCase("first")); dataView.addItemAfter("newItem", "last"); - Assert.assertArrayEquals( - new String[] { "middle", "last", "newItem"}, + Assert.assertArrayEquals(new String[] { "middle", "last", "newItem" }, dataView.getItems().toArray(String[]::new)); } @@ -557,15 +550,13 @@ public void addItemsAfter_emptyCollectionPassed_dataNotChanged() { dataView.getItems().toArray(String[]::new)); } - @Test public void addItemsAfter_addItemsInFilteredDataSet_itemsAddedAfterTheTarget() { dataView.addFilter(item -> !item.equalsIgnoreCase("first")); - dataView.addItemsAfter(Arrays.asList("newItem1", "newItem2"), - "last"); + dataView.addItemsAfter(Arrays.asList("newItem1", "newItem2"), "last"); Assert.assertArrayEquals( - new String[] { "middle", "last", "newItem1", "newItem2"}, + new String[] { "middle", "last", "newItem1", "newItem2" }, dataView.getItems().toArray(String[]::new)); } @@ -641,11 +632,10 @@ public void addItemsBefore_emptyCollectionPassed_dataNotChanged() { @Test public void addItemsBefore_addItemsInFilteredDataSet_itemsAddedBeforeTheTarget() { dataView.addFilter(item -> !item.equalsIgnoreCase("first")); - dataView.addItemsBefore(Arrays.asList("newItem1", "newItem2"), - "last"); + dataView.addItemsBefore(Arrays.asList("newItem1", "newItem2"), "last"); Assert.assertArrayEquals( - new String[] { "middle", "newItem1", "newItem2", "last"}, + new String[] { "middle", "newItem1", "newItem2", "last" }, dataView.getItems().toArray(String[]::new)); } @@ -691,7 +681,7 @@ public void addItemsAndRemoveItems_noConcurrencyIssues() { dataView.addItemsAfter(Arrays.asList("one", "two"), "newOne"); Assert.assertArrayEquals(new String[] { "newOne", "one", "two", - "newTwo", "newThree", "last" }, + "newTwo", "newThree", "last" }, dataView.getItems().toArray(String[]::new)); } @@ -908,9 +898,9 @@ public void dataViewCreatedAndAPIUsed_beforeSettingDataProvider_verificationPass // hasn't setup any data provider to a component. In the example // below, we just create a data communicator instance but don't call // 'setDataProvider' method. - DataCommunicator dataCommunicator = - new DataCommunicator<>((item, jsonObject) -> { - }, null, null, component.getElement().getNode()); + DataCommunicator dataCommunicator = new DataCommunicator<>( + (item, jsonObject) -> { + }, null, null, component.getElement().getNode()); AbstractListDataView dataView = new AbstractListDataView( dataCommunicator::getDataProvider, component, @@ -920,7 +910,8 @@ public void dataViewCreatedAndAPIUsed_beforeSettingDataProvider_verificationPass // Check that we can add a listener even if not data provider set by // user - dataView.addItemCountChangeListener(event -> {}); + dataView.addItemCountChangeListener(event -> { + }); // Check that the verification is still passed during data view API // usage, because the default data provider is an in-memory one @@ -929,12 +920,11 @@ public void dataViewCreatedAndAPIUsed_beforeSettingDataProvider_verificationPass @Test public void createListDataProviderFromArrayOfItems_addingOneItem_itemCountShouldBeIncreasedByOne() { - ListDataProvider localListDataProvider = DataProvider.ofItems( - new Item(1L, "First"), new Item(2L, "Second") - ); + ListDataProvider localListDataProvider = DataProvider + .ofItems(new Item(1L, "First"), new Item(2L, "Second")); - ListDataView> listDataView = - new ItemListDataView(() -> localListDataProvider, component); + ListDataView> listDataView = new ItemListDataView( + () -> localListDataProvider, component); long itemCount = listDataView.getItemCount(); @@ -946,11 +936,11 @@ public void createListDataProviderFromArrayOfItems_addingOneItem_itemCountShould public void createListDataProviderFromArrayOfItems_removingOneItem_itemCountShouldBeDecreasedByOne() { Item first = new Item(1L, "First"); Item second = new Item(2L, "Second"); - ListDataProvider localListDataProvider = DataProvider.ofItems( - first, second); + ListDataProvider localListDataProvider = DataProvider + .ofItems(first, second); - ListDataView> listDataView = - new ItemListDataView(() -> localListDataProvider, component); + ListDataView> listDataView = new ItemListDataView( + () -> localListDataProvider, component); long itemCount = listDataView.getItemCount(); @@ -1164,8 +1154,8 @@ public void setSortComparator_setDataProviderSorting_bothDataViewAndDataProvider ListDataProvider dataProvider = DataProvider.ofItems( new Item(2L, "bar"), new Item(3L, "foo"), new Item(1L, "bar")); - ItemListDataView listDataView = new ItemListDataView( - () -> dataProvider, component); + ItemListDataView listDataView = new ItemListDataView(() -> dataProvider, + component); listDataView.setSortOrder(Item::getValue, SortDirection.ASCENDING); @@ -1199,13 +1189,11 @@ public void setSortComparator_setDataProviderSorting_bothDataViewAndDataProvider public void setFilterOrSorting_filterOrSortingUpdated_filterOrSortingChangedCallbackInvoked() { Collection items = Arrays.asList("foo", "bar", "baz"); - AtomicReference> filtering = - new AtomicReference<>(); - AtomicReference> sorting = - new AtomicReference<>(); + AtomicReference> filtering = new AtomicReference<>(); + AtomicReference> sorting = new AtomicReference<>(); - ListDataViewImpl listDataView = new ListDataViewImpl(() -> dataProvider, component, - (filter, sort) -> { + ListDataViewImpl listDataView = new ListDataViewImpl(() -> dataProvider, + component, (filter, sort) -> { filtering.set(filter); sorting.set(sort); }); @@ -1213,7 +1201,7 @@ public void setFilterOrSorting_filterOrSortingUpdated_filterOrSortingChangedCall listDataView.setFilter("bar"::equals); Assert.assertNotNull(filtering.get()); - Assert.assertArrayEquals(new String [] {"bar"}, + Assert.assertArrayEquals(new String[] { "bar" }, items.stream().filter(filtering.get()).toArray()); Assert.assertNull(sorting.get()); @@ -1221,7 +1209,7 @@ public void setFilterOrSorting_filterOrSortingUpdated_filterOrSortingChangedCall listDataView.setSortOrder(String::toLowerCase, SortDirection.ASCENDING); Assert.assertNotNull(sorting.get()); Assert.assertNull(filtering.get()); - Assert.assertArrayEquals(new String [] {"bar", "baz", "foo"}, + Assert.assertArrayEquals(new String[] { "bar", "baz", "foo" }, items.stream().sorted(sorting.get()).toArray()); listDataView.setSortComparator(null); @@ -1231,7 +1219,8 @@ public void setFilterOrSorting_filterOrSortingUpdated_filterOrSortingChangedCall @Test public void filterOrSortingChangedCallback_emptyCallbackProvided_throws() { exceptionRule.expect(NullPointerException.class); - exceptionRule.expectMessage("Filter or Sorting Change Callback cannot be empty"); + exceptionRule.expectMessage( + "Filter or Sorting Change Callback cannot be empty"); new ListDataViewImpl(() -> dataProvider, component, null); } @@ -1248,9 +1237,9 @@ public ListDataViewImpl( public ListDataViewImpl( SerializableSupplier> dataProviderSupplier, Component component, - SerializableBiConsumer, - SerializableComparator> filterOrSortingChangedCallback) { - super(dataProviderSupplier, component, filterOrSortingChangedCallback); + SerializableBiConsumer, SerializableComparator> filterOrSortingChangedCallback) { + super(dataProviderSupplier, component, + filterOrSortingChangedCallback); } } @@ -1268,7 +1257,8 @@ public ItemListDataView( SerializableSupplier> dataProviderSupplier, Component component, SerializableBiConsumer, SerializableComparator> filterOrSortingChangedCallback) { - super(dataProviderSupplier, component, filterOrSortingChangedCallback); + super(dataProviderSupplier, component, + filterOrSortingChangedCallback); } } diff --git a/flow-data/src/test/java/com/vaadin/flow/data/provider/DataCommunicatorTest.java b/flow-data/src/test/java/com/vaadin/flow/data/provider/DataCommunicatorTest.java index b74c0518258..d189b02aba0 100644 --- a/flow-data/src/test/java/com/vaadin/flow/data/provider/DataCommunicatorTest.java +++ b/flow-data/src/test/java/com/vaadin/flow/data/provider/DataCommunicatorTest.java @@ -253,8 +253,8 @@ public void dataProviderBreaksContract_limitOrPageSizeAreNotCalled_throw() { expectedException.expect(IllegalStateException.class); expectedException.expectMessage(CoreMatchers.containsString( - "The data provider hasn't ever called getLimit() or " + - "getPageSize()")); + "The data provider hasn't ever called getLimit() or " + + "getPageSize()")); dataCommunicator.fetchFromProvider(0, 1); } @@ -273,7 +273,7 @@ public void dataProviderBreaksContract_offsetOrPageAreNotCalled_throw() { expectedException.expect(IllegalStateException.class); expectedException.expectMessage(CoreMatchers.containsString( - "The data provider hasn't ever called getOffset() or getPage()")); + "The data provider hasn't ever called getOffset() or getPage()")); dataCommunicator.fetchFromProvider(1, 1); } @@ -551,7 +551,8 @@ public void setInitialItemCountEstimateAndIncrease_lessThanRequestedRange_estima @Test public void setInitialItemCountEstimateAndIncrease_requestedItemsMuchHigherThanExactCount_exactCountIsResolvedOnServer() { final int exactSize = 200; - AbstractDataProvider dataProvider = createDataProvider(exactSize); + AbstractDataProvider dataProvider = createDataProvider( + exactSize); dataProvider = Mockito.spy(dataProvider); dataCommunicator.setDataProvider(dataProvider, null); @@ -564,7 +565,8 @@ public void setInitialItemCountEstimateAndIncrease_requestedItemsMuchHigherThanE // if the user scrolls far from the exact size of the backend, // the exact size is resolved on the server side without causing a new - // roundtrip where the client will request items because it received less + // roundtrip where the client will request items because it received + // less // items than expected dataCommunicator.setRequestedRange(900, 100); fakeClientCommunication(); @@ -583,7 +585,8 @@ public void setInitialItemCountEstimateAndIncrease_requestedItemsMuchHigherThanE @Test public void setInitialItemCountEstimateAndIncrease_backendEmpty_noEndlessFlushLoop() { final int exactSize = 0; - AbstractDataProvider dataProvider = createDataProvider(exactSize); + AbstractDataProvider dataProvider = createDataProvider( + exactSize); dataProvider = Mockito.spy(dataProvider); dataCommunicator.setDataProvider(dataProvider, null); @@ -1004,13 +1007,15 @@ public void itemCountChangeEvent_exactSize_correctCountAndIsCountEstimated() { fakeClientCommunication(); Assert.assertNull(cachedEvent.get()); - // creating a new data provider with same exact size -> no new event fired + // creating a new data provider with same exact size -> no new event + // fired dataCommunicator.setDataProvider(createDataProvider(500), null); fakeClientCommunication(); Assert.assertNull(cachedEvent.get()); // new data provider with different size - dataCommunicator.setDataProvider(createDataProvider(exactCount = 1000), null); + dataCommunicator.setDataProvider(createDataProvider(exactCount = 1000), + null); fakeClientCommunication(); event = cachedEvent.getAndSet(null); @@ -1078,7 +1083,8 @@ public void setDefinedSize_rangeEndEqualsAssumedSize_flushRequested() { StateNode stateNode = Mockito.spy(element.getNode()); DataCommunicator dataCommunicator = new DataCommunicator<>( - dataGenerator, arrayUpdater, data -> {}, stateNode); + dataGenerator, arrayUpdater, data -> { + }, stateNode); // the items size returned by this data provider will be 100 dataCommunicator.setDataProvider(createDataProvider(), null); @@ -1112,8 +1118,8 @@ public void pageSize_defaultPageSizeUsed_returnsItemNormally() { @Test public void fetchFromProvider_pageSizeLessThanLimit_multiplePagedQueries() { - AbstractDataProvider dataProvider = - createDataProvider(100); + AbstractDataProvider dataProvider = createDataProvider( + 100); dataProvider = Mockito.spy(dataProvider); dataCommunicator.setPageSize(10); @@ -1124,15 +1130,14 @@ public void fetchFromProvider_pageSizeLessThanLimit_multiplePagedQueries() { ArgumentCaptor queryCaptor = ArgumentCaptor .forClass(Query.class); - Mockito.verify(dataProvider, Mockito.times(3)).fetch( - queryCaptor.capture()); + Mockito.verify(dataProvider, Mockito.times(3)) + .fetch(queryCaptor.capture()); List items = stream.collect(Collectors.toList()); Assert.assertEquals(30, items.size()); - Assert.assertEquals( - IntStream.range(0, 30).mapToObj(Item::new) - .collect(Collectors.toList()), items); + Assert.assertEquals(IntStream.range(0, 30).mapToObj(Item::new) + .collect(Collectors.toList()), items); List allQueries = queryCaptor.getAllValues(); Assert.assertEquals(3, allQueries.size()); @@ -1164,8 +1169,8 @@ public void fetchFromProvider_pageSizeLessThanLimit_multiplePagedQueries() { @Test public void fetchFromProvider_limitEqualsPageSize_singleQuery() { - AbstractDataProvider dataProvider = - createDataProvider(100); + AbstractDataProvider dataProvider = createDataProvider( + 100); dataProvider = Mockito.spy(dataProvider); dataCommunicator.setDataProvider(dataProvider, null); @@ -1179,9 +1184,8 @@ public void fetchFromProvider_limitEqualsPageSize_singleQuery() { List items = stream.collect(Collectors.toList()); Assert.assertEquals(50, items.size()); - Assert.assertEquals( - IntStream.range(0, 50).mapToObj(Item::new) - .collect(Collectors.toList()), items); + Assert.assertEquals(IntStream.range(0, 50).mapToObj(Item::new) + .collect(Collectors.toList()), items); Query query = queryCaptor.getValue(); Assert.assertEquals(0, query.getOffset()); @@ -1192,8 +1196,8 @@ public void fetchFromProvider_limitEqualsPageSize_singleQuery() { @Test public void fetchFromProvider_limitLessThanPageSize_singleQuery() { - AbstractDataProvider dataProvider = - createDataProvider(100); + AbstractDataProvider dataProvider = createDataProvider( + 100); dataProvider = Mockito.spy(dataProvider); dataCommunicator.setDataProvider(dataProvider, null); @@ -1207,9 +1211,8 @@ public void fetchFromProvider_limitLessThanPageSize_singleQuery() { List items = stream.collect(Collectors.toList()); Assert.assertEquals(50, items.size()); - Assert.assertEquals( - IntStream.range(10, 60).mapToObj(Item::new) - .collect(Collectors.toList()), items); + Assert.assertEquals(IntStream.range(10, 60).mapToObj(Item::new) + .collect(Collectors.toList()), items); Query query = queryCaptor.getValue(); Assert.assertEquals(10, query.getOffset()); @@ -1220,8 +1223,8 @@ public void fetchFromProvider_limitLessThanPageSize_singleQuery() { @Test public void fetchFromProvider_disablePaging_singleQueryWithLimit() { - AbstractDataProvider dataProvider = - createDataProvider(200); + AbstractDataProvider dataProvider = createDataProvider( + 200); dataProvider = Mockito.spy(dataProvider); dataCommunicator.setPagingEnabled(false); @@ -1237,9 +1240,8 @@ public void fetchFromProvider_disablePaging_singleQueryWithLimit() { List items = stream.collect(Collectors.toList()); Assert.assertEquals(123, items.size()); - Assert.assertEquals( - IntStream.range(0, 123).mapToObj(Item::new) - .collect(Collectors.toList()), items); + Assert.assertEquals(IntStream.range(0, 123).mapToObj(Item::new) + .collect(Collectors.toList()), items); List allQueries = queryCaptor.getAllValues(); Assert.assertEquals(1, allQueries.size()); @@ -1253,24 +1255,20 @@ public void fetchFromProvider_disablePaging_singleQueryWithLimit() { @Test public void fetchFromProvider_maxLimitValue_pagesCalculatedProperly() { - AbstractDataProvider dataProvider = - createDataProvider(42); - dataProvider = Mockito.spy(dataProvider); + AbstractDataProviderdataProvider=createDataProvider(42);dataProvider=Mockito.spy(dataProvider); - dataCommunicator.setDataProvider(dataProvider, null); - dataCommunicator.setPageSize(2_000_000_000); + dataCommunicator.setDataProvider(dataProvider,null);dataCommunicator.setPageSize(2_000_000_000); // We check the page number calculation does not lead to integer // overflow, and not throw thus - dataCommunicator.fetchFromProvider(0, Integer.MAX_VALUE); + dataCommunicator.fetchFromProvider(0,Integer.MAX_VALUE); - Mockito.verify(dataProvider, Mockito.times(1)) - .fetch(Mockito.any(Query.class)); + Mockito.verify(dataProvider,Mockito.times(1)).fetch(Mockito.any(Query.class)); } @Test public void fetchFromProvider_backendRunsOutOfItems_secondPageRequestSkipped() { - AbstractDataProvider dataProvider = - createDataProvider(42); + AbstractDataProvider dataProvider = createDataProvider( + 42); dataProvider = Mockito.spy(dataProvider); dataCommunicator.setDataProvider(dataProvider, null); @@ -1325,10 +1323,8 @@ public void fetchEnabled_requestRange_fetchIgnored() { fakeClientCommunication(); - Mockito.verify(dataProvider) - .fetch(Mockito.any(Query.class)); - Mockito.verify(dataProvider) - .size(Mockito.any(Query.class)); + Mockito.verify(dataProvider).fetch(Mockito.any(Query.class)); + Mockito.verify(dataProvider).size(Mockito.any(Query.class)); } @Test @@ -1351,8 +1347,7 @@ public void filter_setFilterThroughFilterConsumer_shouldRetainFilterBetweenReque dataCommunicator.setRequestedRange(0, 50); fakeClientCommunication(); - Assert.assertNotNull( - "Filter should be retained after data request", + Assert.assertNotNull("Filter should be retained after data request", dataCommunicator.getFilter()); Assert.assertEquals("Unexpected items count", 2, @@ -1364,8 +1359,7 @@ public void filter_setFilterThroughFilterConsumer_shouldRetainFilterBetweenReque dataCommunicator.setRequestedRange(0, 50); fakeClientCommunication(); - Assert.assertNotNull( - "Filter should be retained after data request", + Assert.assertNotNull("Filter should be retained after data request", dataCommunicator.getFilter()); Assert.assertEquals("Unexpected items count", 1, @@ -1399,8 +1393,8 @@ public void filter_setNotifyOnFilterChange_firesItemChangeEvent() { public void filter_skipNotifyOnFilterChange_doesNotFireItemChangeEvent() { TestComponent testComponent = new TestComponent(element); - testComponent.addItemChangeListener(event -> Assert - .fail("Event triggering not expected")); + testComponent.addItemChangeListener( + event -> Assert.fail("Event triggering not expected")); dataCommunicator.setDataProvider( DataProvider.ofItems(new Item(1), new Item(2), new Item(3)), diff --git a/flow-data/src/test/java/com/vaadin/flow/data/provider/HasLazyDataViewTest.java b/flow-data/src/test/java/com/vaadin/flow/data/provider/HasLazyDataViewTest.java index 4316ec85af0..710078734dc 100644 --- a/flow-data/src/test/java/com/vaadin/flow/data/provider/HasLazyDataViewTest.java +++ b/flow-data/src/test/java/com/vaadin/flow/data/provider/HasLazyDataViewTest.java @@ -12,9 +12,8 @@ public class HasLazyDataViewTest { @Tag("test-component") - private static class TestComponent extends Component - implements HasLazyDataView> { + private static class TestComponent extends Component implements + HasLazyDataView> { private DataCommunicator dataCommunicator; @@ -24,8 +23,9 @@ public TestComponent() { } @Override - public AbstractLazyDataView setItems(BackEndDataProvider dataProvider) { - dataCommunicator.setDataProvider(dataProvider,null); + public AbstractLazyDataView setItems( + BackEndDataProvider dataProvider) { + dataCommunicator.setDataProvider(dataProvider, null); return getLazyDataView(); } @@ -49,14 +49,17 @@ public void setItemsCountCallback_switchesToDefinedSize_throwsOnSizeQuery() { // uses a NOOP count callback that will throw when called testComponent.setItems(query -> Stream.of("foo", "bar", "baz")); - Assert.assertFalse(testComponent.getLazyDataView().getDataCommunicator().isDefinedSize()); + Assert.assertFalse(testComponent.getLazyDataView().getDataCommunicator() + .isDefinedSize()); testComponent.getLazyDataView().setItemCountFromDataProvider(); - Assert.assertTrue(testComponent.getLazyDataView().getDataCommunicator().isDefinedSize()); + Assert.assertTrue(testComponent.getLazyDataView().getDataCommunicator() + .isDefinedSize()); expectedException.expect(IllegalStateException.class); - // to make things fail, just need to call size() which will trigger a size query + // to make things fail, just need to call size() which will trigger a + // size query // // Although we don't have getSize() method for lazy data view, it is // still possible for developer to call getItemCount() from diff --git a/flow-data/src/test/java/com/vaadin/flow/data/provider/hierarchy/HasHierarchicalDataProviderTest.java b/flow-data/src/test/java/com/vaadin/flow/data/provider/hierarchy/HasHierarchicalDataProviderTest.java index e9db3aa0767..b6df4866fb7 100644 --- a/flow-data/src/test/java/com/vaadin/flow/data/provider/hierarchy/HasHierarchicalDataProviderTest.java +++ b/flow-data/src/test/java/com/vaadin/flow/data/provider/hierarchy/HasHierarchicalDataProviderTest.java @@ -72,7 +72,8 @@ public int getItemCountEstimate() { } @Override - public void setItemCountEstimateIncrease(int itemCountEstimateIncrease) { + public void setItemCountEstimateIncrease( + int itemCountEstimateIncrease) { } @@ -244,7 +245,8 @@ public TestDataView setItems(DataProvider dataProvider) { } @Override - public TestDataView setItems(InMemoryDataProvider dataProvider) { + public TestDataView setItems( + InMemoryDataProvider dataProvider) { return null; } diff --git a/flow-data/src/test/java/com/vaadin/flow/data/provider/hierarchy/HierarchicalCommunicatorTest.java b/flow-data/src/test/java/com/vaadin/flow/data/provider/hierarchy/HierarchicalCommunicatorTest.java index d39ebc9c2e7..d3d56b12e24 100644 --- a/flow-data/src/test/java/com/vaadin/flow/data/provider/hierarchy/HierarchicalCommunicatorTest.java +++ b/flow-data/src/test/java/com/vaadin/flow/data/provider/hierarchy/HierarchicalCommunicatorTest.java @@ -60,8 +60,7 @@ public class HierarchicalCommunicatorTest { private List enqueueFunctions = new ArrayList<>(); - private Map enqueueFunctionsWithParams = - new HashMap<>(); + private Map enqueueFunctionsWithParams = new HashMap<>(); private class UpdateQueue implements HierarchicalUpdate { @Override @@ -116,8 +115,7 @@ public void initialize() { } }; - private final HierarchicalArrayUpdater arrayUpdaterWithArguments = - new HierarchicalArrayUpdater() { + private final HierarchicalArrayUpdater arrayUpdaterWithArguments = new HierarchicalArrayUpdater() { @Override public HierarchicalUpdate startUpdate(int sizeChange) { return new UpdateQueueWithArguments(); @@ -144,16 +142,17 @@ public void setUp() { stateNode = Mockito.mock(StateNode.class); Mockito.when(stateNode.hasFeature(Mockito.any())).thenReturn(true); ComponentMapping mapping = Mockito.mock(ComponentMapping.class); - Mockito.when(stateNode.getFeatureIfInitialized(ComponentMapping.class)).thenReturn( - java.util.Optional.ofNullable(mapping)); - Mockito.when(mapping.getComponent()).thenReturn( - java.util.Optional.of(new TestComponent())); + Mockito.when(stateNode.getFeatureIfInitialized(ComponentMapping.class)) + .thenReturn(java.util.Optional.ofNullable(mapping)); + Mockito.when(mapping.getComponent()) + .thenReturn(java.util.Optional.of(new TestComponent())); communicator = new HierarchicalDataCommunicator<>( Mockito.mock(CompositeDataGenerator.class), arrayUpdater, json -> { }, stateNode, () -> null); communicator.setDataProvider(dataProvider, null); } + @Test public void folderRemoveRefreshAll() { testItemRemove(FOLDER, true); @@ -237,12 +236,10 @@ public void reset_expandSomeItems_hierarchicalUpdateContainsExpandItems() { // One expandItems for calling expand(...) // One expandItems and one ensureHierarchy for calling reset() Assert.assertEquals(3, enqueueFunctions.size()); - Assert.assertEquals("$connector.expandItems", - enqueueFunctions.get(0)); + Assert.assertEquals("$connector.expandItems", enqueueFunctions.get(0)); Assert.assertEquals("$connector.ensureHierarchy", enqueueFunctions.get(1)); - Assert.assertEquals("$connector.expandItems", - enqueueFunctions.get(2)); + Assert.assertEquals("$connector.expandItems", enqueueFunctions.get(2)); } @Test @@ -256,14 +253,13 @@ public void reset_expandSomeItems_updateContainsProperJsonObjectsToExpand() { hierarchyTreeData.addItem("first-1", "second-1-1"); hierarchyTreeData.addItem("first-2", "second-2-1"); - TreeDataProvider treeDataProvider = - new TreeDataProvider<>(hierarchyTreeData); + TreeDataProvider treeDataProvider = new TreeDataProvider<>( + hierarchyTreeData); - HierarchicalDataCommunicator dataCommunicator = - new HierarchicalDataCommunicator( - Mockito.mock(CompositeDataGenerator.class), - arrayUpdaterWithArguments, - json -> {}, stateNode, () -> null); + HierarchicalDataCommunicator dataCommunicator = new HierarchicalDataCommunicator( + Mockito.mock(CompositeDataGenerator.class), + arrayUpdaterWithArguments, json -> { + }, stateNode, () -> null); dataCommunicator.setDataProvider(treeDataProvider, null); diff --git a/flow-data/src/test/java/com/vaadin/flow/data/provider/hierarchy/HierarchyMapperWithDataTest.java b/flow-data/src/test/java/com/vaadin/flow/data/provider/hierarchy/HierarchyMapperWithDataTest.java index 2aeaf780c98..894a8038673 100644 --- a/flow-data/src/test/java/com/vaadin/flow/data/provider/hierarchy/HierarchyMapperWithDataTest.java +++ b/flow-data/src/test/java/com/vaadin/flow/data/provider/hierarchy/HierarchyMapperWithDataTest.java @@ -222,8 +222,8 @@ public void fetchWithFilter() { // Root nodes plus children of expanded nodes 0 and 4 that match the // filter List expectedResult = IntStream - .of(0, 1, 4, 6, 7, 10, 13, 26, 39, 52).mapToObj(testData::get) - .collect(Collectors.toList()); + .of(0, 1, 4, 6, 7, 10, 13, 26, 39, 52).mapToObj(testData::get) + .collect(Collectors.toList()); mapper.setFilter(filter); @@ -241,14 +241,12 @@ public void getExpandedItems_expandSomeItems_returnsCorrectExpandedItems() { TreeNode third11 = new TreeNode("third-1-1", second1); TreeNode third21 = new TreeNode("third-2-1", second2); - HierarchicalDataProvider dataProvider = - new ThreeLevelStaticHierarchicalDataProvider(root, - new TreeNode[]{second1, second2}, - new TreeNode[]{third11, third21}); + HierarchicalDataProvider dataProvider = new ThreeLevelStaticHierarchicalDataProvider( + root, new TreeNode[] { second1, second2 }, + new TreeNode[] { third11, third21 }); HierarchyMapper hierarchyMapper = new HierarchyMapper<>( - dataProvider - ); + dataProvider); Collection expandedItems = hierarchyMapper.getExpandedItems(); Assert.assertNotNull(expandedItems); @@ -260,10 +258,9 @@ public void getExpandedItems_expandSomeItems_returnsCorrectExpandedItems() { expandedItems = hierarchyMapper.getExpandedItems(); Assert.assertNotNull(expandedItems); Assert.assertEquals(2L, expandedItems.size()); - Assert.assertArrayEquals(new Object[]{"root", "second-2"}, - expandedItems.stream() - .map(TreeNode::getName) - .sorted().toArray()); + Assert.assertArrayEquals(new Object[] { "root", "second-2" }, + expandedItems.stream().map(TreeNode::getName).sorted() + .toArray()); } @Test @@ -277,14 +274,12 @@ public void getExpandedItems_tryToAddItemsToCollection_shouldThrowException() { TreeNode third11 = new TreeNode("third-1-1", second1); TreeNode third21 = new TreeNode("third-2-1", second2); - HierarchicalDataProvider dataProvider = - new ThreeLevelStaticHierarchicalDataProvider(root, - new TreeNode[]{second1, second2}, - new TreeNode[]{third11, third21}); + HierarchicalDataProvider dataProvider = new ThreeLevelStaticHierarchicalDataProvider( + root, new TreeNode[] { second1, second2 }, + new TreeNode[] { third11, third21 }); HierarchyMapper hierarchyMapper = new HierarchyMapper<>( - dataProvider - ); + dataProvider); hierarchyMapper.expand(root); hierarchyMapper.expand(second1); @@ -384,10 +379,8 @@ private static class ThreeLevelStaticHierarchicalDataProvider private TreeNode[] secondLevelNodes; private TreeNode[] thirdLevelNodes; - public ThreeLevelStaticHierarchicalDataProvider( - TreeNode root, - TreeNode[] secondLevelNodes, - TreeNode[] thirdLevelNodes) { + public ThreeLevelStaticHierarchicalDataProvider(TreeNode root, + TreeNode[] secondLevelNodes, TreeNode[] thirdLevelNodes) { this.root = root; this.secondLevelNodes = secondLevelNodes; this.thirdLevelNodes = thirdLevelNodes; @@ -413,18 +406,17 @@ public int getChildCount(HierarchicalQuery query) { @Override public boolean hasChildren(TreeNode item) { - return item.getParent() == null || - Arrays.stream(secondLevelNodes) - .anyMatch(node -> node == item); + return item.getParent() == null || Arrays.stream(secondLevelNodes) + .anyMatch(node -> node == item); } @Override protected Stream fetchChildrenFromBackEnd( HierarchicalQuery query) { if (query.getParent() == null) { - return Arrays.stream(new TreeNode[] {root}); + return Arrays.stream(new TreeNode[] { root }); } - if(query.getParent() == root) { + if (query.getParent() == root) { return Arrays.stream(secondLevelNodes); } return Arrays.stream(thirdLevelNodes) diff --git a/flow-data/src/test/java/com/vaadin/flow/data/provider/hierarchy/TreeDataProviderTest.java b/flow-data/src/test/java/com/vaadin/flow/data/provider/hierarchy/TreeDataProviderTest.java index db03e81b75b..1b8a2c6a08c 100644 --- a/flow-data/src/test/java/com/vaadin/flow/data/provider/hierarchy/TreeDataProviderTest.java +++ b/flow-data/src/test/java/com/vaadin/flow/data/provider/hierarchy/TreeDataProviderTest.java @@ -222,38 +222,40 @@ public void populate_treeData_with_stream_child_item_provider() { @Test public void filter_is_applied_to_children_provider_filter() { - final SerializablePredicate dataProviderFilter = item -> item.contains("Sub"); + final SerializablePredicate dataProviderFilter = item -> item + .contains("Sub"); final HierarchicalQuery> query = new HierarchicalQuery<>( - null, null); - filter_is_applied_to_children(dataProviderFilter,query); + null, null); + filter_is_applied_to_children(dataProviderFilter, query); } @Test public void filter_is_applied_to_children_query_filter() { final SerializablePredicate dataProviderFilter = null; final HierarchicalQuery> query = new HierarchicalQuery<>( - item -> item.contains("Sub"), null); - filter_is_applied_to_children(dataProviderFilter,query); + item -> item.contains("Sub"), null); + filter_is_applied_to_children(dataProviderFilter, query); } @Test public void filter_is_applied_to_children_both_filters() { - final SerializablePredicate dataProviderFilter = item -> item.contains("Sub"); + final SerializablePredicate dataProviderFilter = item -> item + .contains("Sub"); final HierarchicalQuery> query = new HierarchicalQuery<>( - dataProviderFilter, null); - filter_is_applied_to_children(dataProviderFilter,query); + dataProviderFilter, null); + filter_is_applied_to_children(dataProviderFilter, query); } private void filter_is_applied_to_children( - final SerializablePredicate dataProviderFilter, - final HierarchicalQuery> query) { + final SerializablePredicate dataProviderFilter, + final HierarchicalQuery> query) { final TreeData stringData = new TreeData<>(); final String root = "Main"; final List children = Arrays.asList("Sub1", "Sub2"); stringData.addRootItems(root); stringData.addItems(root, children); final TreeDataProvider provider = new TreeDataProvider<>( - stringData); + stringData); provider.setFilter(dataProviderFilter); assertEquals(1, provider.getChildCount(query)); assertTrue(provider.fetchChildren(query).allMatch(root::equals)); diff --git a/flow-data/src/test/java/com/vaadin/flow/data/renderer/ComponentRendererTest.java b/flow-data/src/test/java/com/vaadin/flow/data/renderer/ComponentRendererTest.java index 2878799ce33..47a98cf00da 100644 --- a/flow-data/src/test/java/com/vaadin/flow/data/renderer/ComponentRendererTest.java +++ b/flow-data/src/test/java/com/vaadin/flow/data/renderer/ComponentRendererTest.java @@ -82,8 +82,8 @@ public void templateRenderered_parentAttachedBeforeChild() { .render(container, keyMapper); // simulate a call from the grid to refresh data - template is not setup - containerParent.getNode().runWhenAttached( - ui2 -> ui2.getInternals().getStateTree() + containerParent.getNode() + .runWhenAttached(ui2 -> ui2.getInternals().getStateTree() .beforeClientResponse(containerParent.getNode(), context -> { Assert.assertNotNull( @@ -119,11 +119,12 @@ public void templateRenderered_childAttachedBeforeParent() { ComponentDataGenerator rendering = (ComponentDataGenerator) renderer .render(container, keyMapper); - containerParent.getNode().runWhenAttached( - ui2 -> ui2.getInternals().getStateTree() + containerParent.getNode() + .runWhenAttached(ui2 -> ui2.getInternals().getStateTree() .beforeClientResponse(containerParent.getNode(), context -> { - // if nodeid is null then the component won't be rendered correctly + // if nodeid is null then the component + // won't be rendered correctly Assert.assertNotNull( "NodeIdPropertyName should not be null", rendering.getNodeIdPropertyName()); @@ -193,14 +194,14 @@ public void updateFunction_invokedOnUpdate() { Assert.assertEquals("New item", item); return new TestLabel(); }, (component, item) -> { - updateInvocations.incrementAndGet(); - Assert.assertEquals("Updated item", item); - return component; - }); + updateInvocations.incrementAndGet(); + Assert.assertEquals("Updated item", item); + return component; + }); TestLabel div = renderer.createComponent("New item"); - Component updatedComponent = renderer - .updateComponent(div, "Updated item"); + Component updatedComponent = renderer.updateComponent(div, + "Updated item"); Assert.assertEquals( "The component creation function should have been invoked once", diff --git a/flow-data/src/test/java/com/vaadin/flow/data/renderer/TemplateRendererTest.java b/flow-data/src/test/java/com/vaadin/flow/data/renderer/TemplateRendererTest.java index 7a21a38aeae..a259f9e6e84 100644 --- a/flow-data/src/test/java/com/vaadin/flow/data/renderer/TemplateRendererTest.java +++ b/flow-data/src/test/java/com/vaadin/flow/data/renderer/TemplateRendererTest.java @@ -62,7 +62,7 @@ public void missingAttributeBindingDetector() { if (TemplateRenderer.hasClassOrStyleWithoutDollar(template)) { Assert.fail( "Missing dollar should not be detected for the string: " - + template); + + template); } } } diff --git a/flow-data/src/test/java/com/vaadin/flow/data/selection/MultiSelectTest.java b/flow-data/src/test/java/com/vaadin/flow/data/selection/MultiSelectTest.java index a7a25ef6574..def85b40861 100644 --- a/flow-data/src/test/java/com/vaadin/flow/data/selection/MultiSelectTest.java +++ b/flow-data/src/test/java/com/vaadin/flow/data/selection/MultiSelectTest.java @@ -31,7 +31,8 @@ public class MultiSelectTest { - private static class MultiSelectMock implements MultiSelect { + private static class MultiSelectMock + implements MultiSelect { private final TestLabel component = new TestLabel(); private final Set selectedItems = new LinkedHashSet<>(); diff --git a/flow-data/src/test/java/com/vaadin/flow/data/validator/BeanValidatorTest.java b/flow-data/src/test/java/com/vaadin/flow/data/validator/BeanValidatorTest.java index ba70e9b7afd..09368758408 100644 --- a/flow-data/src/test/java/com/vaadin/flow/data/validator/BeanValidatorTest.java +++ b/flow-data/src/test/java/com/vaadin/flow/data/validator/BeanValidatorTest.java @@ -69,8 +69,7 @@ public void testInvalidDecimalsFailsInFrench() { @Test public void testAddressNestedPropertyInvalidPostalCodeFails() { - assertFails(100_000, "must be less than or equal to 99999", - validator("address.postalCode")); + assertFails(100_000,"must be less than or equal to 99999",validator("address.postalCode")); } @Test diff --git a/flow-data/src/test/java/com/vaadin/flow/data/validator/NotEmptyValidator.java b/flow-data/src/test/java/com/vaadin/flow/data/validator/NotEmptyValidator.java index 0a61ed36cbd..04f0a3abf03 100644 --- a/flow-data/src/test/java/com/vaadin/flow/data/validator/NotEmptyValidator.java +++ b/flow-data/src/test/java/com/vaadin/flow/data/validator/NotEmptyValidator.java @@ -34,9 +34,9 @@ * with {@link HasValue#setRequiredIndicatorVisible(boolean)}. *

* Note that - * {@link BindingBuilder#asRequired(com.vaadin.flow.data.ErrorMessageProvider)} does - * almost the same thing, but verifies against the value NOT being equal to what - * {@link HasValue#getEmptyValue()} returns and sets the required indicator + * {@link BindingBuilder#asRequired(com.vaadin.flow.data.ErrorMessageProvider)} + * does almost the same thing, but verifies against the value NOT being equal to + * what {@link HasValue#getEmptyValue()} returns and sets the required indicator * visible with {@link HasValue#setRequiredIndicatorVisible(boolean)}. * * @see HasValue#setRequiredIndicatorVisible(boolean) diff --git a/flow-data/src/test/java/com/vaadin/flow/data/validator/RangeValidatorTest.java b/flow-data/src/test/java/com/vaadin/flow/data/validator/RangeValidatorTest.java index 2133b44923e..0c0bc40ed8c 100644 --- a/flow-data/src/test/java/com/vaadin/flow/data/validator/RangeValidatorTest.java +++ b/flow-data/src/test/java/com/vaadin/flow/data/validator/RangeValidatorTest.java @@ -111,12 +111,9 @@ public void testNullLessThanEverything() { @Test public void testDateRange() { - RangeValidator v = RangeValidator.of("Date must be in 2016", - LocalDate.of(2016, 1, 1), LocalDate.of(2016, 12, 31)); + RangeValidatorv=RangeValidator.of("Date must be in 2016",LocalDate.of(2016,1,1),LocalDate.of(2016,12,31)); - assertFails(LocalDate.ofEpochDay(0), v); - assertPasses(LocalDate.of(2016, 7, 31), v); - assertFails(LocalDate.ofEpochDay(1_000_000_000), v); + assertFails(LocalDate.ofEpochDay(0),v);assertPasses(LocalDate.of(2016,7,31),v);assertFails(LocalDate.ofEpochDay(1_000_000_000),v); } } \ No newline at end of file diff --git a/flow-data/src/test/java/com/vaadin/flow/data/value/ValueChangeModeTest.java b/flow-data/src/test/java/com/vaadin/flow/data/value/ValueChangeModeTest.java index 4a5b096ea18..a40214bf66b 100644 --- a/flow-data/src/test/java/com/vaadin/flow/data/value/ValueChangeModeTest.java +++ b/flow-data/src/test/java/com/vaadin/flow/data/value/ValueChangeModeTest.java @@ -42,8 +42,8 @@ public ValueChangeMode getValueChangeMode() { @Override public void setValueChangeTimeout(int valueChangeTimeout) { this.valueChangeTimeout = valueChangeTimeout; - ValueChangeMode.applyChangeTimeout(valueChangeMode, this.valueChangeTimeout, - getSynchronizationRegistration()); + ValueChangeMode.applyChangeTimeout(valueChangeMode, + this.valueChangeTimeout, getSynchronizationRegistration()); } @Override @@ -66,8 +66,7 @@ public void field_setMode() { assertValueSynchronizedWithEvent(field, "blur"); field.setValueChangeMode(null); - Assert.assertNull( - "value should not be a synchronized property", + Assert.assertNull("value should not be a synchronized property", getDisabledUpdateMode(field)); Assert.assertNull(field.getSynchronizationRegistration()); @@ -97,11 +96,13 @@ public void field_setValueChangeTimeout_applied() { field.setValueChangeMode(ValueChangeMode.TIMEOUT); assertDebounceEquals(field, - EnumSet.of(DebouncePhase.LEADING, DebouncePhase.INTERMEDIATE), 123); + EnumSet.of(DebouncePhase.LEADING, DebouncePhase.INTERMEDIATE), + 123); field.setValueChangeTimeout(456); assertDebounceEquals(field, - EnumSet.of(DebouncePhase.LEADING, DebouncePhase.INTERMEDIATE), 456); + EnumSet.of(DebouncePhase.LEADING, DebouncePhase.INTERMEDIATE), + 456); } @Test @@ -118,7 +119,7 @@ private void assertNoTimeoutApplied(ValueChangeMode valueChangeMode) { } private void assertDebounceEquals(ValueChangeModeField field, - EnumSet phases, int timeout) { + EnumSet phases, int timeout) { DomListenerRegistration reg = field.getSynchronizationRegistration(); Assert.assertEquals(timeout, reg.getDebounceTimeout()); Assert.assertEquals(phases, reg.getDebouncePhases()); @@ -132,8 +133,7 @@ private void assertDebounceDisabled(ValueChangeModeField field) { private void assertValueSynchronizedWithEvent(ValueChangeModeField field, String eventName) { - Assert.assertNotNull( - "value should be a synchronized property", + Assert.assertNotNull("value should be a synchronized property", getDisabledUpdateMode(field)); DomListenerRegistration reg = field.getSynchronizationRegistration(); @@ -143,9 +143,9 @@ private void assertValueSynchronizedWithEvent(ValueChangeModeField field, eventName, reg.getEventType()); } - private DisabledUpdateMode getDisabledUpdateMode(ValueChangeModeField field) { - return field.getElement().getNode() - .getFeature(ElementListenerMap.class) + private DisabledUpdateMode getDisabledUpdateMode( + ValueChangeModeField field) { + return field.getElement().getNode().getFeature(ElementListenerMap.class) .getPropertySynchronizationMode("value"); } diff --git a/flow-data/src/test/java/com/vaadin/flow/tests/data/DataSerializableTest.java b/flow-data/src/test/java/com/vaadin/flow/tests/data/DataSerializableTest.java index 47d28c02de4..362b2425609 100644 --- a/flow-data/src/test/java/com/vaadin/flow/tests/data/DataSerializableTest.java +++ b/flow-data/src/test/java/com/vaadin/flow/tests/data/DataSerializableTest.java @@ -15,12 +15,12 @@ public class DataSerializableTest extends ClassesSerializableTest { /* - * AbstractDataProvider.addDataProviderListener may return a Registration instance - * that is not deserializable due to self references. - * This happens for example if the dataprovider, member of a component, - * is used to add a com.vaadin.flow.data.provider.DataProviderListener - * into an inner component; the resulting Registration handles a reference - * to the dataprovider itself that is already referenced by the outer component + * AbstractDataProvider.addDataProviderListener may return a Registration + * instance that is not deserializable due to self references. This happens + * for example if the dataprovider, member of a component, is used to add a + * com.vaadin.flow.data.provider.DataProviderListener into an inner + * component; the resulting Registration handles a reference to the + * dataprovider itself that is already referenced by the outer component */ @Test public void selfReferenceSerialization() throws Throwable { @@ -38,7 +38,8 @@ public void setDataProvider(DataProvider dataProvider) { if (registration != null) { registration.remove(); } - registration = dataProvider.addDataProviderListener(event -> onDataProviderChange()); + registration = dataProvider + .addDataProviderListener(event -> onDataProviderChange()); } void onDataProviderChange() { @@ -48,7 +49,8 @@ void onDataProviderChange() { } static class Outer implements Serializable { - private final ListDataProvider dataProvider = new ListDataProvider<>(Collections.emptyList()); + private final ListDataProvider dataProvider = new ListDataProvider<>( + Collections.emptyList()); private final Inner inner = new Inner(); public Outer() { diff --git a/flow-data/src/test/java/com/vaadin/flow/tests/data/bean/Item.java b/flow-data/src/test/java/com/vaadin/flow/tests/data/bean/Item.java index fa099f076af..62d01d5dc17 100644 --- a/flow-data/src/test/java/com/vaadin/flow/tests/data/bean/Item.java +++ b/flow-data/src/test/java/com/vaadin/flow/tests/data/bean/Item.java @@ -59,11 +59,12 @@ public void setDescription(String description) { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; Item item = (Item) o; - return id == item.id && - Objects.equals(value, item.value); + return id == item.id && Objects.equals(value, item.value); } @Override diff --git a/flow-dnd/src/test/java/com/vaadin/flow/component/dnd/MockUI.java b/flow-dnd/src/test/java/com/vaadin/flow/component/dnd/MockUI.java index 1c450b56f10..b2fff82b634 100644 --- a/flow-dnd/src/test/java/com/vaadin/flow/component/dnd/MockUI.java +++ b/flow-dnd/src/test/java/com/vaadin/flow/component/dnd/MockUI.java @@ -43,7 +43,8 @@ protected void init(VaadinRequest request) { private static VaadinSession findOrCreateSession() { VaadinSession session = VaadinSession.getCurrent(); if (session == null) { - session = new AlwaysLockedVaadinSession(Mockito.mock(VaadinService.class)); + session = new AlwaysLockedVaadinSession( + Mockito.mock(VaadinService.class)); VaadinSession.setCurrent(session); } return session; diff --git a/flow-html-components/src/main/java/com/vaadin/flow/component/html/Hr.java b/flow-html-components/src/main/java/com/vaadin/flow/component/html/Hr.java index ff67d23c99d..81b0e14801b 100644 --- a/flow-html-components/src/main/java/com/vaadin/flow/component/html/Hr.java +++ b/flow-html-components/src/main/java/com/vaadin/flow/component/html/Hr.java @@ -26,7 +26,7 @@ */ @Tag(Tag.HR) public class Hr extends HtmlComponent { - + /** * Creates a new hr. */ diff --git a/flow-html-components/src/main/java/com/vaadin/flow/component/html/IFrame.java b/flow-html-components/src/main/java/com/vaadin/flow/component/html/IFrame.java index 8d3f7cf334e..78ff8716c4e 100644 --- a/flow-html-components/src/main/java/com/vaadin/flow/component/html/IFrame.java +++ b/flow-html-components/src/main/java/com/vaadin/flow/component/html/IFrame.java @@ -30,213 +30,252 @@ * @author Vaadin Ltd * @since 1.3 * - * @see The Inline Frame element + * @see The + * Inline Frame element */ @Tag(Tag.IFRAME) public class IFrame extends HtmlComponent { - private static final PropertyDescriptor srcDescriptor = PropertyDescriptors - .attributeWithDefault("src", ""); + private static final PropertyDescriptor srcDescriptor = PropertyDescriptors + .attributeWithDefault("src", ""); - private static final PropertyDescriptor> srcdocDescriptor = PropertyDescriptors - .optionalAttributeWithDefault("srcdoc", ""); + private static final PropertyDescriptor> srcdocDescriptor = PropertyDescriptors + .optionalAttributeWithDefault("srcdoc", ""); - private static final PropertyDescriptor> nameDescriptor = PropertyDescriptors - .optionalAttributeWithDefault("name", ""); + private static final PropertyDescriptor> nameDescriptor = PropertyDescriptors + .optionalAttributeWithDefault("name", ""); - private static final PropertyDescriptor> sandboxDescriptor = PropertyDescriptors - .optionalAttributeWithDefault("sandbox", "allow-all"); - - private static final PropertyDescriptor> allowDescriptor = PropertyDescriptors - .optionalAttributeWithDefault("allow", ""); - - private static final PropertyDescriptor> importanceDescriptor = PropertyDescriptors - .optionalAttributeWithDefault("importance", "auto"); - - /** - * Importance types. - */ - public enum ImportanceType { - AUTO("auto"), - HIGH("high"), - LOW("low"); - private final String value; - - ImportanceType(String value){ - this.value = value; - } - - public String getValue() { - return value; - } - - private static Optional fromAttributeValue(String value) { - return Stream.of(values()).filter(type-> type.value.equals(value)) - .findFirst(); - } - } - - /** - * Sandbox types. - */ - public enum SandboxType { - RESTRICT_ALL(""), - ALLOW_FORMS("allow-forms"), - ALLOW_MODALS("allow-modals"), - ALLOW_ORIENTATION_LOCK("allow-orientation-lock"), - ALLOW_POINTER_LOCK("allow-pointer-lock"), - ALLOW_POPUPS("allow-popups"), - ALLOW_POPUPS_TO_ESCAPE_SANDBOX("allow-popups-to-escape-sandbox"), - ALLOW_PRESENTATION("allow-presentation"), - ALLOW_SAME_ORIGIN("allow-same-origin"), - ALLOW_SCRIPTS("allow-scripts"), - ALLOW_STORAGE_ACCESS_BY_USER_ACTIVATION("allow-storage-access-by-user-activation"), - ALLOW_TOP_NAVIGATION("allow-top-navigation"), - ALLOW_TOP_NAVIGATION_BY_USER_ACTIVATION("allow-top-navigation-by-user-activation"); - - private final String value; - - SandboxType(String value){ - this.value = value; - } - - public String getValue() { - return value; - } - - private static Optional fromAttributeValue(String value) { - return Stream.of(values()).filter(type-> type.value.equals(value)) - .findFirst(); - } - - } - - /** - * Creates a new iframe. - */ - public IFrame() { } - - /** - * Creates a new iframe with a source URL. - * @param src Source URL - */ - public IFrame(String src) { - setSrc(src); - } - - /** - * Sets the source of the iframe. - * If the contents at the src of the IFrame has changed and - * you want to refresh it in the user's browser, the src - * does not to be reset. In this case use the #reload() method. - * @param src Source URL. - */ - public void setSrc(String src) { set(srcDescriptor, src); } - - /** - * Gets the source of the iframe. - * @return the source of the iframe. - */ - public String getSrc(){ - return get(srcDescriptor); - } - - /** - * Sets the srcdoc of the iframe. - * @param srcdoc srcdoc URL. - */ - public void setSrcdoc(String srcdoc){ - set(srcdocDescriptor, srcdoc); - } - - /** - * Gets the srcdoc of the iframe. - * @return the srcdoc of the iframe. - */ - public Optional getSrcdoc() { - return get(srcdocDescriptor); - } - - /** - * Sets the allow property to specify a feature policy. - * - * @param allow the allow attribute value. - * - * @see Feature Policy. - */ - public void setAllow(String allow){ - set(allowDescriptor, allow); - } - - /** - * Gets the value of allow attribute. - * @return the currently applied allow value. - */ - public Optional getAllow() { return get(allowDescriptor); } - - /** - * Sets the name attribute. - * @param name the value for the name attribute. - */ - public void setName(String name) { set(nameDescriptor, name); } - - /** - * Gets the name attribute. - * @return the name attribute. - */ - public Optional getName() { return get(nameDescriptor); } - - /** - * Sets the importance attribute to the specified {@link ImportanceType} value. - * @param importance {@link ImportanceType} value. - * - * @see ImportanceType - */ - public void setImportance(ImportanceType importance) { set(importanceDescriptor, importance != null ? importance.value : ""); } - - /** - * Gets the importance attribute value. - * @return the importance value. - * - * @see ImportanceType - */ - public Optional getImportance() { return get(importanceDescriptor).flatMap(ImportanceType::fromAttributeValue); } - - /** - * Sets the sandbox attribute to the given {@link SandboxType}s. - * @param types {@link SandboxType}s. - */ - public void setSandbox(SandboxType ...types) { - if (types == null || types.length == 0) { - - // NOTE: "allow-all" is used internally to remove the property in this case when types argument is null. - // It is the default value of the sandboxDescriptor, thus when it is set the descriptor will remove the property. - - set(sandboxDescriptor, "allow-all"); - - } else { - set(sandboxDescriptor, Stream.of(types).map(SandboxType::getValue).collect(Collectors.joining(" "))); - } - } - - /** - * Gets the list of sandbox attribute values. - * @return the current {@link SandboxType}s. - */ - public Optional getSandbox() { - return get(sandboxDescriptor) - .map(value -> Stream.of(value.split(" ")) - .map(SandboxType::fromAttributeValue) - .filter(Optional::isPresent) - .map(Optional::get) - .collect(Collectors.toList())) - .map(collection -> collection.toArray(new SandboxType[collection.size()])); - } - - /** - * Reloads the IFrame. - */ - public void reload() { - getElement().executeJs("this.src = this.src"); - } + private static final PropertyDescriptor> sandboxDescriptor = PropertyDescriptors + .optionalAttributeWithDefault("sandbox", "allow-all"); + + private static final PropertyDescriptor> allowDescriptor = PropertyDescriptors + .optionalAttributeWithDefault("allow", ""); + + private static final PropertyDescriptor> importanceDescriptor = PropertyDescriptors + .optionalAttributeWithDefault("importance", "auto"); + + /** + * Importance types. + */ + public enum ImportanceType { + AUTO("auto"), HIGH("high"), LOW("low"); + + private final String value; + + ImportanceType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + private static Optional fromAttributeValue( + String value) { + return Stream.of(values()).filter(type -> type.value.equals(value)) + .findFirst(); + } + } + + /** + * Sandbox types. + */ + public enum SandboxType { + RESTRICT_ALL(""), ALLOW_FORMS("allow-forms"), ALLOW_MODALS( + "allow-modals"), ALLOW_ORIENTATION_LOCK( + "allow-orientation-lock"), ALLOW_POINTER_LOCK( + "allow-pointer-lock"), ALLOW_POPUPS( + "allow-popups"), ALLOW_POPUPS_TO_ESCAPE_SANDBOX( + "allow-popups-to-escape-sandbox"), ALLOW_PRESENTATION( + "allow-presentation"), ALLOW_SAME_ORIGIN( + "allow-same-origin"), ALLOW_SCRIPTS( + "allow-scripts"), ALLOW_STORAGE_ACCESS_BY_USER_ACTIVATION( + "allow-storage-access-by-user-activation"), ALLOW_TOP_NAVIGATION( + "allow-top-navigation"), ALLOW_TOP_NAVIGATION_BY_USER_ACTIVATION( + "allow-top-navigation-by-user-activation"); + + private final String value; + + SandboxType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + private static Optional fromAttributeValue(String value) { + return Stream.of(values()).filter(type -> type.value.equals(value)) + .findFirst(); + } + + } + + /** + * Creates a new iframe. + */ + public IFrame() { + } + + /** + * Creates a new iframe with a source URL. + * + * @param src + * Source URL + */ + public IFrame(String src) { + setSrc(src); + } + + /** + * Sets the source of the iframe. If the contents at the src of the IFrame + * has changed and you want to refresh it in the user's browser, the src + * does not to be reset. In this case use the #reload() method. + * + * @param src + * Source URL. + */ + public void setSrc(String src) { + set(srcDescriptor, src); + } + + /** + * Gets the source of the iframe. + * + * @return the source of the iframe. + */ + public String getSrc() { + return get(srcDescriptor); + } + + /** + * Sets the srcdoc of the iframe. + * + * @param srcdoc + * srcdoc URL. + */ + public void setSrcdoc(String srcdoc) { + set(srcdocDescriptor, srcdoc); + } + + /** + * Gets the srcdoc of the iframe. + * + * @return the srcdoc of the iframe. + */ + public Optional getSrcdoc() { + return get(srcdocDescriptor); + } + + /** + * Sets the allow property to specify a feature policy. + * + * @param allow + * the allow attribute value. + * + * @see Feature + * Policy. + */ + public void setAllow(String allow) { + set(allowDescriptor, allow); + } + + /** + * Gets the value of allow attribute. + * + * @return the currently applied allow value. + */ + public Optional getAllow() { + return get(allowDescriptor); + } + + /** + * Sets the name attribute. + * + * @param name + * the value for the name attribute. + */ + public void setName(String name) { + set(nameDescriptor, name); + } + + /** + * Gets the name attribute. + * + * @return the name attribute. + */ + public Optional getName() { + return get(nameDescriptor); + } + + /** + * Sets the importance attribute to the specified {@link ImportanceType} + * value. + * + * @param importance + * {@link ImportanceType} value. + * + * @see ImportanceType + */ + public void setImportance(ImportanceType importance) { + set(importanceDescriptor, importance != null ? importance.value : ""); + } + + /** + * Gets the importance attribute value. + * + * @return the importance value. + * + * @see ImportanceType + */ + public Optional getImportance() { + return get(importanceDescriptor) + .flatMap(ImportanceType::fromAttributeValue); + } + + /** + * Sets the sandbox attribute to the given {@link SandboxType}s. + * + * @param types + * {@link SandboxType}s. + */ + public void setSandbox(SandboxType... types) { + if (types == null || types.length == 0) { + + // NOTE: "allow-all" is used internally to remove the property in + // this case when types argument is null. + // It is the default value of the sandboxDescriptor, thus when it is + // set the descriptor will remove the property. + + set(sandboxDescriptor, "allow-all"); + + } else { + set(sandboxDescriptor, Stream.of(types).map(SandboxType::getValue) + .collect(Collectors.joining(" "))); + } + } + + /** + * Gets the list of sandbox attribute values. + * + * @return the current {@link SandboxType}s. + */ + public Optional getSandbox() { + return get(sandboxDescriptor) + .map(value -> Stream.of(value.split(" ")) + .map(SandboxType::fromAttributeValue) + .filter(Optional::isPresent).map(Optional::get) + .collect(Collectors.toList())) + .map(collection -> collection + .toArray(new SandboxType[collection.size()])); + } + + /** + * Reloads the IFrame. + */ + public void reload() { + getElement().executeJs("this.src = this.src"); + } } diff --git a/flow-html-components/src/main/java/com/vaadin/flow/component/html/Input.java b/flow-html-components/src/main/java/com/vaadin/flow/component/html/Input.java index eb19fb33a0c..6e6476711dc 100644 --- a/flow-html-components/src/main/java/com/vaadin/flow/component/html/Input.java +++ b/flow-html-components/src/main/java/com/vaadin/flow/component/html/Input.java @@ -48,8 +48,8 @@ public class Input extends AbstractSinglePropertyField private ValueChangeMode currentMode; /** - * Creates a new input without any specific type, - * with {@link ValueChangeMode#ON_CHANGE ON_CHANGE} value change mode. + * Creates a new input without any specific type, with + * {@link ValueChangeMode#ON_CHANGE ON_CHANGE} value change mode. */ public Input() { this(ValueChangeMode.ON_CHANGE); @@ -59,8 +59,8 @@ public Input() { * Creates a new input without any specific type. * * @param valueChangeMode - * initial value change mode, or null - * to disable the value synchronization + * initial value change mode, or null to disable the + * value synchronization */ public Input(ValueChangeMode valueChangeMode) { super("value", "", false); diff --git a/flow-html-components/src/main/java/com/vaadin/flow/component/html/Pre.java b/flow-html-components/src/main/java/com/vaadin/flow/component/html/Pre.java index 3f19d7b4f0a..1681bd95eb3 100644 --- a/flow-html-components/src/main/java/com/vaadin/flow/component/html/Pre.java +++ b/flow-html-components/src/main/java/com/vaadin/flow/component/html/Pre.java @@ -26,8 +26,7 @@ * @author Vaadin Ltd */ @Tag(Tag.PRE) -public class Pre extends HtmlContainer - implements ClickNotifier
 {
+public class Pre extends HtmlContainer implements ClickNotifier
 {
 
     /**
      * Creates a new empty preformatted text block.
diff --git a/flow-html-components/src/test/java/com/vaadin/flow/component/html/AssertUtils.java b/flow-html-components/src/test/java/com/vaadin/flow/component/html/AssertUtils.java
index 5907030e940..e013e793446 100644
--- a/flow-html-components/src/test/java/com/vaadin/flow/component/html/AssertUtils.java
+++ b/flow-html-components/src/test/java/com/vaadin/flow/component/html/AssertUtils.java
@@ -15,19 +15,24 @@ class AssertUtils {
     /**
      * Asserts that two objects are equal. If they are not, an
      * {@link AssertionError} is thrown with the given message. If
-     * expected and actual are null,
-     * they are considered equal.
+     * expected and actual are null, they
+     * are considered equal.
      *
      * If both expected and actual are arrays or are
-     * Optionals wrapping arrays, Assert#assertArrayEquals is used
-     * to assert that the arrays content is equal.
+     * Optionals wrapping arrays,
+     * Assert#assertArrayEquals is used to assert that the arrays
+     * content is equal.
      *
-     * @param message the identifying message for the {@link AssertionError} (null
-     * okay)
-     * @param expected expected value
-     * @param actual actual value
+     * @param message
+     *            the identifying message for the {@link AssertionError}
+     *            (null okay)
+     * @param expected
+     *            expected value
+     * @param actual
+     *            actual value
      */
-    static public void assertEquals(String message, Object expected, Object actual) {
+    static public void assertEquals(String message, Object expected,
+            Object actual) {
 
         if (expected instanceof Optional && actual instanceof Optional) {
             expected = ((Optional) expected).orElseGet(() -> null);
@@ -43,7 +48,8 @@ static public void assertEquals(String message, Object expected, Object actual)
         }
 
         if (expected.getClass().isArray() && actual.getClass().isArray()) {
-            Assert.assertArrayEquals(message, (Object[]) expected, (Object[]) actual);
+            Assert.assertArrayEquals(message, (Object[]) expected,
+                    (Object[]) actual);
 
         } else {
             Assert.assertEquals(message, expected, actual);
diff --git a/flow-html-components/src/test/java/com/vaadin/flow/component/html/ComponentTest.java b/flow-html-components/src/test/java/com/vaadin/flow/component/html/ComponentTest.java
index a455641b4ed..93c2e1d97d6 100644
--- a/flow-html-components/src/test/java/com/vaadin/flow/component/html/ComponentTest.java
+++ b/flow-html-components/src/test/java/com/vaadin/flow/component/html/ComponentTest.java
@@ -243,9 +243,8 @@ private void testNullForStringPropertyWithEmptyStringDefault(
     private void testEmptyStringForOptionalStringProperty(ComponentProperty p) {
         try {
             p.setUsingSetter(component, "");
-            Assert.assertEquals(
-                    "The getter for '" + p.name
-                            + "' should return an empty optional after setting \"\"",
+            Assert.assertEquals("The getter for '" + p.name
+                    + "' should return an empty optional after setting \"\"",
                     Optional.empty(), p.getUsingGetter(component));
         } catch (Exception e) {
             throw new AssertionError(e);
@@ -255,9 +254,8 @@ private void testEmptyStringForOptionalStringProperty(ComponentProperty p) {
     private void testNullForOptionalNonStringProperty(ComponentProperty p) {
         try {
             p.setUsingSetter(component, null);
-            Assert.assertEquals(
-                    "Setting the property " + p.name
-                            + " to null should cause an empty optional to be returned by the getter",
+            Assert.assertEquals("Setting the property " + p.name
+                    + " to null should cause an empty optional to be returned by the getter",
                     Optional.empty(), p.getUsingGetter(component));
         } catch (Exception e) {
             throw new AssertionError(
diff --git a/flow-html-components/src/test/java/com/vaadin/flow/component/html/HtmlComponentSmokeTest.java b/flow-html-components/src/test/java/com/vaadin/flow/component/html/HtmlComponentSmokeTest.java
index 593f1db74bf..63c5d7ee57c 100644
--- a/flow-html-components/src/test/java/com/vaadin/flow/component/html/HtmlComponentSmokeTest.java
+++ b/flow-html-components/src/test/java/com/vaadin/flow/component/html/HtmlComponentSmokeTest.java
@@ -60,12 +60,16 @@ public class HtmlComponentSmokeTest {
         testValues.put(NumberingType.class, NumberingType.LOWERCASE_ROMAN);
         testValues.put(int.class, 42);
         testValues.put(IFrame.ImportanceType.class, IFrame.ImportanceType.HIGH);
-        testValues.put(IFrame.SandboxType[].class, new IFrame.SandboxType[] { IFrame.SandboxType.ALLOW_POPUPS, IFrame.SandboxType.ALLOW_MODALS });
+        testValues.put(IFrame.SandboxType[].class,
+                new IFrame.SandboxType[] { IFrame.SandboxType.ALLOW_POPUPS,
+                        IFrame.SandboxType.ALLOW_MODALS });
         testValues.put(AnchorTarget.class, AnchorTarget.TOP);
     }
 
-    // For classes registered here testStringConstructor will be ignored. This test checks whether the content of the
-    // element is the constructor argument. However, for some HTMLComponents this test is not valid.
+    // For classes registered here testStringConstructor will be ignored. This
+    // test checks whether the content of the
+    // element is the constructor argument. However, for some HTMLComponents
+    // this test is not valid.
     private static final Set> ignoredStringConstructors = new HashSet<>();
     static {
         ignoredStringConstructors.add(IFrame.class);
@@ -177,7 +181,8 @@ private static boolean isSpecialSetter(Method method) {
             return true;
         }
 
-        // Anchor.setTarget(AnchorTarget) - https://github.com/vaadin/flow/issues/8346
+        // Anchor.setTarget(AnchorTarget) -
+        // https://github.com/vaadin/flow/issues/8346
         if (method.getDeclaringClass() == Anchor.class
                 && method.getName().equals("setTarget")
                 && method.getParameterTypes()[0] == AnchorTarget.class) {
diff --git a/flow-html-components/src/test/java/com/vaadin/flow/component/html/IFrameTest.java b/flow-html-components/src/test/java/com/vaadin/flow/component/html/IFrameTest.java
index 0536a6e34d1..4556549bba7 100644
--- a/flow-html-components/src/test/java/com/vaadin/flow/component/html/IFrameTest.java
+++ b/flow-html-components/src/test/java/com/vaadin/flow/component/html/IFrameTest.java
@@ -34,10 +34,12 @@ protected void addProperties() {
         addOptionalStringProperty("allow");
 
         addProperty("importance", IFrame.ImportanceType.class,
-                IFrame.ImportanceType.AUTO, IFrame.ImportanceType.HIGH, true, true);
+                IFrame.ImportanceType.AUTO, IFrame.ImportanceType.HIGH, true,
+                true);
 
-        addProperty("sandbox", IFrame.SandboxType[].class,
-                null, new IFrame.SandboxType[] { IFrame.SandboxType.ALLOW_POPUPS, IFrame.SandboxType.ALLOW_MODALS },
+        addProperty("sandbox", IFrame.SandboxType[].class, null,
+                new IFrame.SandboxType[] { IFrame.SandboxType.ALLOW_POPUPS,
+                        IFrame.SandboxType.ALLOW_MODALS },
                 true, true);
     }
 
diff --git a/flow-html-components/src/test/java/com/vaadin/flow/component/html/InputTest.java b/flow-html-components/src/test/java/com/vaadin/flow/component/html/InputTest.java
index a51a905c40c..223f030f3db 100644
--- a/flow-html-components/src/test/java/com/vaadin/flow/component/html/InputTest.java
+++ b/flow-html-components/src/test/java/com/vaadin/flow/component/html/InputTest.java
@@ -25,7 +25,8 @@ public class InputTest extends ComponentTest {
     // Actual test methods in super class
 
     @Override
-    public void setup() throws IntrospectionException, InstantiationException, IllegalAccessException, ClassNotFoundException {
+    public void setup() throws IntrospectionException, InstantiationException,
+            IllegalAccessException, ClassNotFoundException {
         whitelistProperty("valueChangeMode");
         whitelistProperty("valueChangeTimeout");
         super.setup();
diff --git a/flow-lit-template/src/main/java/com/vaadin/flow/component/littemplate/IllegalAttributeException.java b/flow-lit-template/src/main/java/com/vaadin/flow/component/littemplate/IllegalAttributeException.java
index fa9dd0df883..fbf177b2efd 100644
--- a/flow-lit-template/src/main/java/com/vaadin/flow/component/littemplate/IllegalAttributeException.java
+++ b/flow-lit-template/src/main/java/com/vaadin/flow/component/littemplate/IllegalAttributeException.java
@@ -17,18 +17,18 @@
 package com.vaadin.flow.component.littemplate;
 
 /**
- * Thrown to indicate that an element had an illegal or
- * inappropriate attribute.
+ * Thrown to indicate that an element had an illegal or inappropriate attribute.
  *
  * @since
  */
 public class IllegalAttributeException extends RuntimeException {
 
     /**
-     * Constructs an IllegalAttributeException with the
-     * specified detail message.
+     * Constructs an IllegalAttributeException with the specified
+     * detail message.
      *
-     * @param   s   the detail message.
+     * @param s
+     *            the detail message.
      */
     public IllegalAttributeException(String s) {
         super(s);
diff --git a/flow-lit-template/src/main/java/com/vaadin/flow/component/littemplate/InjectableLitElementInitializer.java b/flow-lit-template/src/main/java/com/vaadin/flow/component/littemplate/InjectableLitElementInitializer.java
index 9dbba5ce6c4..9c3e8b38526 100644
--- a/flow-lit-template/src/main/java/com/vaadin/flow/component/littemplate/InjectableLitElementInitializer.java
+++ b/flow-lit-template/src/main/java/com/vaadin/flow/component/littemplate/InjectableLitElementInitializer.java
@@ -36,6 +36,7 @@ public class InjectableLitElementInitializer
 
     private static final String DYNAMIC_ATTRIBUTE_PREFIX = "Template {} contains an attribute {} in element {} which";
     private final Class templateClass;
+
     /**
      * Creates an initializer for the {@code element}.
      * 
@@ -52,13 +53,14 @@ public InjectableLitElementInitializer(Element element,
 
     @Override
     public void accept(Map templateAttributes) {
-        if(templateAttributes.containsKey("disabled")) {
+        if (templateAttributes.containsKey("disabled")) {
             String errorMessage = String.format(
-                "Lit template '%s' injected element '%s' with id '%s'"
-                    + " uses the disabled attribute.%n"
-                    + "Mapped components should instead be disabled "
-                    + "using the 'setEnabled(false)' method on the server side.",
-                templateClass.getName(), getElement().getTag(), templateAttributes.get("id"));
+                    "Lit template '%s' injected element '%s' with id '%s'"
+                            + " uses the disabled attribute.%n"
+                            + "Mapped components should instead be disabled "
+                            + "using the 'setEnabled(false)' method on the server side.",
+                    templateClass.getName(), getElement().getTag(),
+                    templateAttributes.get("id"));
             throw new IllegalAttributeException(errorMessage);
         }
         super.accept(templateAttributes);
diff --git a/flow-lit-template/src/main/java/com/vaadin/flow/component/littemplate/internal/LitTemplateParserImpl.java b/flow-lit-template/src/main/java/com/vaadin/flow/component/littemplate/internal/LitTemplateParserImpl.java
index 52afc9634c5..abafaa004bd 100644
--- a/flow-lit-template/src/main/java/com/vaadin/flow/component/littemplate/internal/LitTemplateParserImpl.java
+++ b/flow-lit-template/src/main/java/com/vaadin/flow/component/littemplate/internal/LitTemplateParserImpl.java
@@ -154,17 +154,17 @@ public TemplateData getTemplateContent(Class clazz,
     }
 
     /**
-     * Dependency should match the tag name  ignoring the extension of the file.
+     * Dependency should match the tag name ignoring the extension of the file.
      *
      * @param dependency
-     *     dependency to check
+     *            dependency to check
      * @param tag
-     *     tag name for element
+     *            tag name for element
      * @return true if dependency file matches the tag name.
      */
     private boolean dependencyHasTagName(Dependency dependency, String tag) {
         String url = FilenameUtils.removeExtension(dependency.getUrl())
-            .toLowerCase(Locale.ENGLISH);
+                .toLowerCase(Locale.ENGLISH);
         return url.endsWith("/" + tag);
     }
 
diff --git a/flow-lit-template/src/test/java/com/vaadin/flow/component/littemplate/InjectableLitElementInitializerTest.java b/flow-lit-template/src/test/java/com/vaadin/flow/component/littemplate/InjectableLitElementInitializerTest.java
index 8751b68974d..842afa495be 100644
--- a/flow-lit-template/src/test/java/com/vaadin/flow/component/littemplate/InjectableLitElementInitializerTest.java
+++ b/flow-lit-template/src/test/java/com/vaadin/flow/component/littemplate/InjectableLitElementInitializerTest.java
@@ -118,7 +118,8 @@ public void initializeElement_setStyle_styleIsSetAsAttribute() {
     public void initializeElement_disabled_exceptionIsThrown() {
 
         expectedEx.expect(IllegalAttributeException.class);
-        expectedEx.expectMessage(Matchers.containsString("element 'div' with id 'labelId'"));
+        expectedEx.expectMessage(
+                Matchers.containsString("element 'div' with id 'labelId'"));
 
         Map attributes = new HashMap<>();
         attributes.put("disabled", Boolean.TRUE.toString());
diff --git a/flow-lit-template/src/test/java/com/vaadin/flow/component/littemplate/LitTemplateTest.java b/flow-lit-template/src/test/java/com/vaadin/flow/component/littemplate/LitTemplateTest.java
index 5fd40e1020d..433be0d515e 100644
--- a/flow-lit-template/src/test/java/com/vaadin/flow/component/littemplate/LitTemplateTest.java
+++ b/flow-lit-template/src/test/java/com/vaadin/flow/component/littemplate/LitTemplateTest.java
@@ -77,7 +77,6 @@ public DisabledElementTemplate(VaadinService service) {
         }
     }
 
-
     @Tag("foo-bar")
     private static class ElementWithTextLitTemplate extends LitTemplate {
 
@@ -146,7 +145,7 @@ public void attachExistingElementWithAttributeValue_elementHasAttribute() {
     public void attachExistingElementWithDisabledAttributeValue_exceptionIsThrown() {
         expectedEx.expect(IllegalAttributeException.class);
         expectedEx.expectMessage(
-            Matchers.containsString("element 'label' with id 'labelId'"));
+                Matchers.containsString("element 'label' with id 'labelId'"));
 
         DisabledElementTemplate template = new DisabledElementTemplate(service);
     }
diff --git a/flow-maven-plugin/src/main/java/com/vaadin/flow/plugin/common/FlowPluginFrontendUtils.java b/flow-maven-plugin/src/main/java/com/vaadin/flow/plugin/common/FlowPluginFrontendUtils.java
index f4b19a5fbda..df4045d8f5a 100644
--- a/flow-maven-plugin/src/main/java/com/vaadin/flow/plugin/common/FlowPluginFrontendUtils.java
+++ b/flow-maven-plugin/src/main/java/com/vaadin/flow/plugin/common/FlowPluginFrontendUtils.java
@@ -37,8 +37,7 @@ public class FlowPluginFrontendUtils {
     /**
      * Additionally include compile-time-only dependencies matching the pattern.
      */
-    private static final String INCLUDE_FROM_COMPILE_DEPS_REGEX =
-            ".*(/|\\\\)(portlet-api|javax\\.servlet-api)-.+jar$";
+    private static final String INCLUDE_FROM_COMPILE_DEPS_REGEX = ".*(/|\\\\)(portlet-api|javax\\.servlet-api)-.+jar$";
 
     private FlowPluginFrontendUtils() {
     }
@@ -56,8 +55,8 @@ public static ClassFinder getClassFinder(MavenProject project) {
         try {
             classpathElements = Stream.concat(
                     project.getRuntimeClasspathElements().stream(),
-                    project.getCompileClasspathElements().stream()
-                        .filter(s -> s.matches(INCLUDE_FROM_COMPILE_DEPS_REGEX)));
+                    project.getCompileClasspathElements().stream().filter(
+                            s -> s.matches(INCLUDE_FROM_COMPILE_DEPS_REGEX)));
         } catch (DependencyResolutionRequiredException e) {
             throw new IllegalStateException(String.format(
                     "Failed to retrieve runtime classpath elements from project '%s'",
diff --git a/flow-maven-plugin/src/main/java/com/vaadin/flow/plugin/maven/BuildFrontendMojo.java b/flow-maven-plugin/src/main/java/com/vaadin/flow/plugin/maven/BuildFrontendMojo.java
index 0565f02316f..150f2cabfaa 100644
--- a/flow-maven-plugin/src/main/java/com/vaadin/flow/plugin/maven/BuildFrontendMojo.java
+++ b/flow-maven-plugin/src/main/java/com/vaadin/flow/plugin/maven/BuildFrontendMojo.java
@@ -148,7 +148,8 @@ public void execute() throws MojoExecutionException, MojoFailureException {
         getLog().info("update-frontend took " + ms + "ms.");
     }
 
-    private void runNodeUpdater() throws ExecutionFailedException, MojoExecutionException {
+    private void runNodeUpdater()
+            throws ExecutionFailedException, MojoExecutionException {
         Set jarFiles = project.getArtifacts().stream()
                 .filter(artifact -> "jar".equals(artifact.getType()))
                 .map(Artifact::getFile).collect(Collectors.toSet());
@@ -159,7 +160,8 @@ private void runNodeUpdater() throws ExecutionFailedException, MojoExecutionExce
         try {
             nodeDownloadRootURI = new URI(nodeDownloadRoot);
         } catch (URISyntaxException e) {
-            throw new MojoExecutionException("Failed to parse " + nodeDownloadRoot, e);
+            throw new MojoExecutionException(
+                    "Failed to parse " + nodeDownloadRoot, e);
         }
         // @formatter:off
         new NodeTasks.Builder(getClassFinder(project),
diff --git a/flow-maven-plugin/src/main/java/com/vaadin/flow/plugin/maven/FlowModeAbstractMojo.java b/flow-maven-plugin/src/main/java/com/vaadin/flow/plugin/maven/FlowModeAbstractMojo.java
index 7705b56e7be..ce62e18d553 100644
--- a/flow-maven-plugin/src/main/java/com/vaadin/flow/plugin/maven/FlowModeAbstractMojo.java
+++ b/flow-maven-plugin/src/main/java/com/vaadin/flow/plugin/maven/FlowModeAbstractMojo.java
@@ -126,7 +126,8 @@ public abstract class FlowModeAbstractMojo extends AbstractMojo {
      * environments where the node.js download can be provided from an intranet
      * mirror. Defaults to null which will cause the downloader to use
      * {@link NodeInstaller#DEFAULT_NODEJS_DOWNLOAD_ROOT}.
-     * 

+ *

+ *

* Example: "https://nodejs.org/dist/". */ @Parameter(property = "node.download.root", defaultValue = NodeInstaller.DEFAULT_NODEJS_DOWNLOAD_ROOT) diff --git a/flow-maven-plugin/src/main/java/com/vaadin/flow/plugin/maven/Fragment.java b/flow-maven-plugin/src/main/java/com/vaadin/flow/plugin/maven/Fragment.java index c94c498af92..98d06af3ceb 100644 --- a/flow-maven-plugin/src/main/java/com/vaadin/flow/plugin/maven/Fragment.java +++ b/flow-maven-plugin/src/main/java/com/vaadin/flow/plugin/maven/Fragment.java @@ -19,7 +19,7 @@ import java.util.Set; /** - * Intended to be used by Maven to specify fragments. + * Intended to be used by Maven to specify fragments. * * @author Vaadin Ltd * @since 1.0. @@ -48,9 +48,6 @@ public Set getFiles() { @Override public String toString() { - return "Fragment{" + - "name='" + name + '\'' + - ", files=" + files + - '}'; + return "Fragment{" + "name='" + name + '\'' + ", files=" + files + '}'; } } diff --git a/flow-maven-plugin/src/main/java/com/vaadin/flow/plugin/maven/PrepareFrontendMojo.java b/flow-maven-plugin/src/main/java/com/vaadin/flow/plugin/maven/PrepareFrontendMojo.java index 26fd7ebb9cd..7acaf78fd46 100644 --- a/flow-maven-plugin/src/main/java/com/vaadin/flow/plugin/maven/PrepareFrontendMojo.java +++ b/flow-maven-plugin/src/main/java/com/vaadin/flow/plugin/maven/PrepareFrontendMojo.java @@ -61,8 +61,8 @@ import static com.vaadin.flow.server.frontend.FrontendUtils.TOKEN_FILE; /** - * This goal checks that node and npm tools are installed and creates - * or updates `package.json` and `webpack.config.json` files. + * This goal checks that node and npm tools are installed and creates or updates + * `package.json` and `webpack.config.json` files. *

* Copies frontend resources available inside `.jar` dependencies to * `node_modules` when building a jar package. @@ -103,11 +103,13 @@ public void execute() throws MojoExecutionException, MojoFailureException { try { nodeDownloadRootURI = new URI(nodeDownloadRoot); } catch (URISyntaxException e) { - throw new MojoExecutionException("Failed to parse " + nodeDownloadRoot, e); + throw new MojoExecutionException( + "Failed to parse " + nodeDownloadRoot, e); } try { FrontendTools tools = new FrontendTools(npmFolder.getAbsolutePath(), - () -> FrontendUtils.getVaadinHomeDirectory().getAbsolutePath(), + () -> FrontendUtils.getVaadinHomeDirectory() + .getAbsolutePath(), nodeVersion, nodeDownloadRootURI); tools.validateNodeAndNpmVersion(); } catch (IllegalStateException exception) { @@ -132,8 +134,7 @@ public void execute() throws MojoExecutionException, MojoFailureException { .withFlowResourcesFolder(flowResourcesFolder) .createMissingPackageJson(true) .enableImportsUpdate(false) - .enablePackagesUpdate(false) - .runNpmInstall(false) + .enablePackagesUpdate(false).runNpmInstall(false) .withNodeVersion(nodeVersion) .withNodeDownloadRoot(nodeDownloadRootURI) .withHomeNodeExecRequired(requireHomeNodeExec); diff --git a/flow-maven-plugin/src/main/java/com/vaadin/flow/server/scanner/ReflectionsClassFinder.java b/flow-maven-plugin/src/main/java/com/vaadin/flow/server/scanner/ReflectionsClassFinder.java index f72f1cbcc77..4108d4357d3 100644 --- a/flow-maven-plugin/src/main/java/com/vaadin/flow/server/scanner/ReflectionsClassFinder.java +++ b/flow-maven-plugin/src/main/java/com/vaadin/flow/server/scanner/ReflectionsClassFinder.java @@ -67,8 +67,8 @@ private Set> getAnnotatedByRepeatedAnnotation( Repeatable repeatableAnnotation = annotationClass .getAnnotation(Repeatable.class); if (repeatableAnnotation != null) { - return reflections.getTypesAnnotatedWith( - repeatableAnnotation.value(), true); + return reflections + .getTypesAnnotatedWith(repeatableAnnotation.value(), true); } return Collections.emptySet(); } @@ -80,8 +80,7 @@ public URL getResource(String name) { @SuppressWarnings("unchecked") @Override - public Class loadClass(String name) - throws ClassNotFoundException { + public Class loadClass(String name) throws ClassNotFoundException { return (Class) classLoader.loadClass(name); } diff --git a/flow-maven-plugin/src/main/java/com/vaadin/flow/utils/FlowFileUtils.java b/flow-maven-plugin/src/main/java/com/vaadin/flow/utils/FlowFileUtils.java index 037d010d397..1bfcd8d43e1 100644 --- a/flow-maven-plugin/src/main/java/com/vaadin/flow/utils/FlowFileUtils.java +++ b/flow-maven-plugin/src/main/java/com/vaadin/flow/utils/FlowFileUtils.java @@ -36,31 +36,41 @@ private FlowFileUtils() { } /** - * A {@link FileUtils#forceMkdir(File)} wrapper that handles {@link IOException}. + * A {@link FileUtils#forceMkdir(File)} wrapper that handles + * {@link IOException}. * - * @param directory the directory to create, must not be {@code null} - * @throws UncheckedIOException if {@link FileUtils#forceMkdir(File)} throws {@link IOException} + * @param directory + * the directory to create, must not be {@code null} + * @throws UncheckedIOException + * if {@link FileUtils#forceMkdir(File)} throws + * {@link IOException} */ public static void forceMkdir(File directory) { try { FileUtils.forceMkdir(Objects.requireNonNull(directory)); } catch (IOException e) { - throw new UncheckedIOException(String.format("Failed to create directory '%s'", directory), e); + throw new UncheckedIOException( + String.format("Failed to create directory '%s'", directory), + e); } } /** * Converts {@link File} to {@link URL} wrapping checked exception. * - * @param file file to convert + * @param file + * file to convert * @return corresponding {@link URL} - * @throws IllegalArgumentException when fails to convert + * @throws IllegalArgumentException + * when fails to convert */ public static URL convertToUrl(File file) { try { return file.toURI().toURL(); } catch (MalformedURLException e) { - throw new IllegalArgumentException(String.format("Failed to convert file '%s' to URL", file), e); + throw new IllegalArgumentException( + String.format("Failed to convert file '%s' to URL", file), + e); } } } diff --git a/flow-maven-plugin/src/test/java/com/vaadin/flow/plugin/maven/BuildFrontendMojoTest.java b/flow-maven-plugin/src/test/java/com/vaadin/flow/plugin/maven/BuildFrontendMojoTest.java index abfb2cec2cc..6d174b3ffcf 100644 --- a/flow-maven-plugin/src/test/java/com/vaadin/flow/plugin/maven/BuildFrontendMojoTest.java +++ b/flow-maven-plugin/src/test/java/com/vaadin/flow/plugin/maven/BuildFrontendMojoTest.java @@ -107,7 +107,8 @@ public void setup() throws Exception { generatedFolder = new File(npmFolder, DEFAULT_GENERATED_DIR); importsFile = new File(generatedFolder, IMPORTS_NAME); nodeModulesPath = new File(npmFolder, NODE_MODULES); - flowResourcesFolder = new File(npmFolder, DEFAULT_FLOW_RESOURCES_FOLDER); + flowResourcesFolder = new File(npmFolder, + DEFAULT_FLOW_RESOURCES_FOLDER); File frontendDirectory = new File(npmFolder, DEFAULT_FRONTEND_DIR); packageJson = new File(npmFolder, PACKAGE_JSON).getAbsolutePath(); @@ -205,13 +206,13 @@ public void should_copyProjectFrontendResources() .map(File::getName).collect(Collectors.toSet()); Set filesInFlowResourcesFolder = Stream - .of(flowResourcesFolder.listFiles()) - .map(File::getName).collect(Collectors.toSet()); + .of(flowResourcesFolder.listFiles()).map(File::getName) + .collect(Collectors.toSet()); projectFrontendResources.forEach(fileName -> { Assert.assertTrue(String.format( - "Expected the copied file '%s' to be in the project resources", fileName), - filesInFlowResourcesFolder.contains(fileName)); + "Expected the copied file '%s' to be in the project resources", + fileName), filesInFlowResourcesFolder.contains(fileName)); }); } diff --git a/flow-maven-plugin/src/test/java/com/vaadin/flow/plugin/maven/PrepareFrontendMojoTest.java b/flow-maven-plugin/src/test/java/com/vaadin/flow/plugin/maven/PrepareFrontendMojoTest.java index ba062f9171c..ef0b5e5fe13 100644 --- a/flow-maven-plugin/src/test/java/com/vaadin/flow/plugin/maven/PrepareFrontendMojoTest.java +++ b/flow-maven-plugin/src/test/java/com/vaadin/flow/plugin/maven/PrepareFrontendMojoTest.java @@ -69,7 +69,8 @@ public void setup() throws Exception { project = Mockito.mock(MavenProject.class); Mockito.when(project.getBasedir()).thenReturn(projectBase); - flowResourcesFolder = new File(projectBase, DEFAULT_FLOW_RESOURCES_FOLDER); + flowResourcesFolder = new File(projectBase, + DEFAULT_FLOW_RESOURCES_FOLDER); webpackConfig = new File(projectBase, WEBPACK_CONFIG).getAbsolutePath(); packageJson = new File(projectBase, PACKAGE_JSON).getAbsolutePath(); webpackOutputDirectory = new File(projectBase, diff --git a/flow-polymer-template/src/test/java/com/vaadin/flow/component/polymertemplate/BundleParserTest.java b/flow-polymer-template/src/test/java/com/vaadin/flow/component/polymertemplate/BundleParserTest.java index b69ab22bb81..5a749d10bcf 100644 --- a/flow-polymer-template/src/test/java/com/vaadin/flow/component/polymertemplate/BundleParserTest.java +++ b/flow-polymer-template/src/test/java/com/vaadin/flow/component/polymertemplate/BundleParserTest.java @@ -16,8 +16,8 @@ public class BundleParserTest { - private static final String statsFile = - VAADIN_SERVLET_RESOURCES + "config/stats.json"; + private static final String statsFile = VAADIN_SERVLET_RESOURCES + + "config/stats.json"; private static JsonObject stats; @@ -32,15 +32,15 @@ public static void initClass() throws IOException { @Test public void nonLocalTemplate_sourcesShouldBeFound() { - final String source = BundleParser.getSourceFromStatistics( - "./src/hello-world.js", stats); + final String source = BundleParser + .getSourceFromStatistics("./src/hello-world.js", stats); Assert.assertNotNull("Source expected in stats.json", source); } @Test public void nonLocalTemplate_sourcesShouldBeFoundInTargetFolder() { - final String source = BundleParser.getSourceFromStatistics( - "./src/hello-world2.js", stats); + final String source = BundleParser + .getSourceFromStatistics("./src/hello-world2.js", stats); Assert.assertNotNull("Source expected in stats.json", source); } @@ -53,9 +53,10 @@ public void frontendPrefix_sourcesShouldBeFound() { @Test public void typeScriptExtension_sourcesShouldBeFound() { - final String source = BundleParser.getSourceFromStatistics( - "./frontend/my-form.ts", stats); - Assert.assertNotNull("TypeScript sources expected in stats.json", source); + final String source = BundleParser + .getSourceFromStatistics("./frontend/my-form.ts", stats); + Assert.assertNotNull("TypeScript sources expected in stats.json", + source); } @Test @@ -70,8 +71,8 @@ public void startsWithSingleLetterDirector_sourcesShouldNotBeFound() { // This test exposes a common error in String#replaceFirst (unescaped // period in regex) in BundleParser#getSourceFromObject final JsonObject module = Json.createObject(); - module.put("name","a/src/hello-world.js"); - module.put("source","some-source.js"); + module.put("name", "a/src/hello-world.js"); + module.put("source", "some-source.js"); final String source = BundleParser.getSourceFromStatistics( "a/frontend/src/hello-world.js", module); Assert.assertNull("Source not expected in module", source); diff --git a/flow-polymer-template/src/test/java/com/vaadin/flow/component/polymertemplate/InjectablePolymerElementInitializerTest.java b/flow-polymer-template/src/test/java/com/vaadin/flow/component/polymertemplate/InjectablePolymerElementInitializerTest.java index d0b27ca0a5d..49099ca9812 100644 --- a/flow-polymer-template/src/test/java/com/vaadin/flow/component/polymertemplate/InjectablePolymerElementInitializerTest.java +++ b/flow-polymer-template/src/test/java/com/vaadin/flow/component/polymertemplate/InjectablePolymerElementInitializerTest.java @@ -120,7 +120,8 @@ public void initializeElement_disabled_elementIsEnabledContainsProperty() { Collections.singletonMap("disabled", Boolean.TRUE.toString())); Assert.assertTrue("Element should stay enabled", element.isEnabled()); - Assert.assertTrue("Disabled should show as a property", element.hasProperty("disabled")); + Assert.assertTrue("Disabled should show as a property", + element.hasProperty("disabled")); } public void initializeElement_setText_textIsSet() { diff --git a/flow-polymer-template/src/test/java/com/vaadin/flow/component/polymertemplate/PolymerTemplateTest.java b/flow-polymer-template/src/test/java/com/vaadin/flow/component/polymertemplate/PolymerTemplateTest.java index 317d68f5fcc..63805cde3cb 100644 --- a/flow-polymer-template/src/test/java/com/vaadin/flow/component/polymertemplate/PolymerTemplateTest.java +++ b/flow-polymer-template/src/test/java/com/vaadin/flow/component/polymertemplate/PolymerTemplateTest.java @@ -848,11 +848,11 @@ public void attachExistingElementWithAttributeValue_elementIsDisabled() { DisabledElementTemplate template = new DisabledElementTemplate(); Assert.assertTrue("Element is missing id", - template.label.hasAttribute("id")); + template.label.hasAttribute("id")); Assert.assertTrue("Server side element should be enabled", - template.label.isEnabled()); + template.label.isEnabled()); Assert.assertTrue("Element should contain 'disabled' property", - template.label.hasProperty("disabled")); + template.label.hasProperty("disabled")); } @Test diff --git a/flow-server/src/main/java/com/vaadin/flow/component/AbstractCompositeField.java b/flow-server/src/main/java/com/vaadin/flow/component/AbstractCompositeField.java index 75bf2a92bdd..239bd095dab 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/AbstractCompositeField.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/AbstractCompositeField.java @@ -24,8 +24,8 @@ /** * An abstract field class that is backed by a composite component. *

- * Note that composite fields do not automatically show client side - * validation error messages or required indicators. + * Note that composite fields do not automatically show client side validation + * error messages or required indicators. *

* See the detailed documentation for {@link AbstractField} and * {@link Composite} for detailed information. diff --git a/flow-server/src/main/java/com/vaadin/flow/component/AbstractField.java b/flow-server/src/main/java/com/vaadin/flow/component/AbstractField.java index c575caa5c7c..26f9318c315 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/AbstractField.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/AbstractField.java @@ -69,7 +69,7 @@ public abstract class AbstractField, T> * Value change event fired by components. * * @author Vaadin Ltd - * @since 1.0 + * @since 1.0 * @param * the source component type * @param diff --git a/flow-server/src/main/java/com/vaadin/flow/component/ClickNotifier.java b/flow-server/src/main/java/com/vaadin/flow/component/ClickNotifier.java index c930b11a71c..f6b9c775314 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/ClickNotifier.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/ClickNotifier.java @@ -61,24 +61,23 @@ default Registration addClickListener( * Use the returned {@link ShortcutRegistration} to fluently configure the * shortcut. *

- * By default, the returned {@code ShortcutRegistration} allows - * browser's default behavior, unlike other {@code ShortcutRegistrations}. - * This is used to make sure that value synchronization of input fields is - * not blocked for the shortcut key (e.g. Enter key). - * To change this behavior, call - * {@link ShortcutRegistration#setBrowserDefaultAllowed(boolean)}. + * By default, the returned {@code ShortcutRegistration} allows browser's + * default behavior, unlike other {@code ShortcutRegistrations}. This is + * used to make sure that value synchronization of input fields is not + * blocked for the shortcut key (e.g. Enter key). To change this behavior, + * call {@link ShortcutRegistration#setBrowserDefaultAllowed(boolean)}. * * @param key - * primary {@link Key} used to trigger the shortcut. Cannot - * be null. + * primary {@link Key} used to trigger the shortcut. Cannot be + * null. * @param keyModifiers - * {@link KeyModifier KeyModifiers} that need to be pressed - * along with the {@code key} for the shortcut to trigger - * @return {@link ShortcutRegistration} for configuring the shortcut and - * removing + * {@link KeyModifier KeyModifiers} that need to be pressed along + * with the {@code key} for the shortcut to trigger + * @return {@link ShortcutRegistration} for configuring the shortcut and + * removing */ default ShortcutRegistration addClickShortcut(Key key, - KeyModifier... keyModifiers) { + KeyModifier... keyModifiers) { if (!(this instanceof Component)) { throw new IllegalStateException(String.format( "The class '%s' doesn't extend '%s'. " @@ -94,10 +93,10 @@ default ShortcutRegistration addClickShortcut(Key key, final Component thisComponent = (Component) this; - return new ShortcutRegistration(thisComponent, () -> new Component[] { thisComponent.getUI().get() }, + return new ShortcutRegistration(thisComponent, + () -> new Component[] { thisComponent.getUI().get() }, event -> ComponentUtil.fireEvent(thisComponent, new ClickEvent<>(thisComponent)), - key).withModifiers(keyModifiers) - .allowBrowserDefault(); + key).withModifiers(keyModifiers).allowBrowserDefault(); } } diff --git a/flow-server/src/main/java/com/vaadin/flow/component/ComponentEventBusUtil.java b/flow-server/src/main/java/com/vaadin/flow/component/ComponentEventBusUtil.java index 1bcc51ad154..91f4240c657 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/ComponentEventBusUtil.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/ComponentEventBusUtil.java @@ -101,7 +101,7 @@ private static LinkedHashMap> findEventDataExpressions( p.getName(), eventConstructor.toString(), EventData.class.getSimpleName())); } - eventDataExpressions.put(eventData.value(),p.getType()); + eventDataExpressions.put(eventData.value(), p.getType()); } return eventDataExpressions; } diff --git a/flow-server/src/main/java/com/vaadin/flow/component/Focusable.java b/flow-server/src/main/java/com/vaadin/flow/component/Focusable.java index c46572d6e4c..d1e8b3319b0 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/Focusable.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/Focusable.java @@ -162,7 +162,8 @@ default ShortcutRegistration addFocusShortcut(Key key, final Component thisComponent = (Component) this; - return new ShortcutRegistration((Component) this, () -> new Component[] {thisComponent.getUI().get()}, + return new ShortcutRegistration((Component) this, + () -> new Component[] { thisComponent.getUI().get() }, event -> this.focus(), key).withModifiers(keyModifiers); } } diff --git a/flow-server/src/main/java/com/vaadin/flow/component/HasHelper.java b/flow-server/src/main/java/com/vaadin/flow/component/HasHelper.java index afa828b3cce..06dd0f77607 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/HasHelper.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/HasHelper.java @@ -27,72 +27,74 @@ * @since 2.4 */ public interface HasHelper extends HasElement { - /** - * String used for the helper text. - * - * @return the {@code helperText} property from the web component - */ - default String getHelperText() { - return getElement().getProperty("helperText"); - } + /** + * String used for the helper text. + * + * @return the {@code helperText} property from the web component + */ + default String getHelperText() { + return getElement().getProperty("helperText"); + } + + /** + *

+ * String used for the helper text. It shows a text adjacent to the field + * that can be used, e.g., to inform to the users which values it expects. + * Example: a text "The password must contain numbers" for the + * PasswordField. + *

+ * + *

+ * In case both {@link #setHelperText(String)} and + * {@link #setHelperComponent(Component)} are used, only the element defined + * by {@link #setHelperComponent(Component)} will be visible, regardless of + * the order on which they are defined. + *

+ * + * @param helperText + * the String value to set + */ + default void setHelperText(String helperText) { + getElement().setProperty("helperText", helperText); + } - /** - *

- * String used for the helper text. It shows a text adjacent to the field that - * can be used, e.g., to inform to the users which values it expects. Example: - * a text "The password must contain numbers" for the PasswordField. - *

- * - *

- * In case both {@link #setHelperText(String)} and - * {@link #setHelperComponent(Component)} are used, only the element defined - * by {@link #setHelperComponent(Component)} will be visible, regardless of - * the order on which they are defined. - *

- * - * @param helperText - * the String value to set - */ - default void setHelperText(String helperText) { - getElement().setProperty("helperText", helperText); - } - /** - * Adds the given component into helper slot of component, replacing any - * existing helper component. It adds the component adjacent to the field that - * can be used, e.g., to inform to the users which values it expects. Example: - * a component that shows the password strength for the PasswordField. - * - * @param component - * the component to set, can be {@code null} to remove existing - * helper component - * - * @see #setHelperText(String) - */ - default void setHelperComponent(Component component) { - getElement().getChildren() - .filter(child -> "helper".equals(child.getAttribute("slot"))) - .findAny() - .ifPresent(getElement()::removeChild); + /** + * Adds the given component into helper slot of component, replacing any + * existing helper component. It adds the component adjacent to the field + * that can be used, e.g., to inform to the users which values it expects. + * Example: a component that shows the password strength for the + * PasswordField. + * + * @param component + * the component to set, can be {@code null} to remove existing + * helper component + * + * @see #setHelperText(String) + */ + default void setHelperComponent(Component component) { + getElement().getChildren() + .filter(child -> "helper".equals(child.getAttribute("slot"))) + .findAny().ifPresent(getElement()::removeChild); - if (component != null) { - component.getElement().setAttribute("slot", "helper"); - getElement().appendChild(component.getElement()); + if (component != null) { + component.getElement().setAttribute("slot", "helper"); + getElement().appendChild(component.getElement()); + } } - } - /** - * Gets the component in the helper slot of this field. - * - * @return the helper component of this field, or {@code null} if no helper - * component has been set - * @see #setHelperComponent(Component) - */ - default Component getHelperComponent() { - Optional component = getElement().getChildren() - .filter(child -> "helper".equals(child.getAttribute("slot"))) - .map(Element::getComponent) - .findFirst().orElse(Optional.empty()); + /** + * Gets the component in the helper slot of this field. + * + * @return the helper component of this field, or {@code null} if no helper + * component has been set + * @see #setHelperComponent(Component) + */ + default Component getHelperComponent() { + Optional component = getElement().getChildren() + .filter(child -> "helper".equals(child.getAttribute("slot"))) + .map(Element::getComponent).findFirst() + .orElse(Optional.empty()); - return component.orElse(null); - } + return component.orElse(null); + } } diff --git a/flow-server/src/main/java/com/vaadin/flow/component/HasLabel.java b/flow-server/src/main/java/com/vaadin/flow/component/HasLabel.java index d65c25a969e..a20030dc201 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/HasLabel.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/HasLabel.java @@ -20,15 +20,15 @@ /** * A component that supports label definition. *

- * The default implementations set the label of the component to the given text for - * {@link #getElement()}. Override all methods in this interface if the text + * The default implementations set the label of the component to the given text + * for {@link #getElement()}. Override all methods in this interface if the text * should be added to some other element. * * * @author Vaadin Ltd * @since */ -public interface HasLabel extends HasElement{ +public interface HasLabel extends HasElement { /** * Set the label of the component to the given text. * @@ -42,10 +42,11 @@ default void setLabel(String label) { /** * Gets the label of the component. * - * @return the label of the component or {@code null} if no label has - * been set + * @return the label of the component or {@code null} if no label has been + * set */ default String getLabel() { - return getElement().getProperty(ElementConstants.LABEL_PROPERTY_NAME, null); + return getElement().getProperty(ElementConstants.LABEL_PROPERTY_NAME, + null); } } diff --git a/flow-server/src/main/java/com/vaadin/flow/component/HasSize.java b/flow-server/src/main/java/com/vaadin/flow/component/HasSize.java index 1e2ddb24ac1..8a45f6a4afe 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/HasSize.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/HasSize.java @@ -58,28 +58,29 @@ default void setWidth(float width, Unit unit) { if (unit == null) { throw new IllegalArgumentException("Unit can not be null"); } - setWidth(getCssSize(width,unit)); + setWidth(getCssSize(width, unit)); } - + /** * Sets the min-width of the component. *

* The width should be in a format understood by the browser, e.g. "100px" * or "2.5em". *

- * If the provided {@code minWidth} value is {@literal null} then min-width is - * removed. + * If the provided {@code minWidth} value is {@literal null} then min-width + * is removed. * * @param minWidth - * the min-width value (if null, the property will be removed) + * the min-width value (if null, the property will + * be removed) */ default void setMinWidth(String minWidth) { getElement().getStyle().set(ElementConstants.STYLE_MIN_WIDTH, minWidth); } /** - * Sets the min-width of the component. Negative number implies unspecified size - * (terminal is free to set the size). + * Sets the min-width of the component. Negative number implies unspecified + * size (terminal is free to set the size). * * @param minWidth * the min-width of the object. @@ -90,7 +91,7 @@ default void setMinWidth(float minWidth, Unit unit) { if (unit == null) { throw new IllegalArgumentException("Unit can not be null"); } - setMinWidth(getCssSize(minWidth,unit)); + setMinWidth(getCssSize(minWidth, unit)); } /** @@ -99,19 +100,20 @@ default void setMinWidth(float minWidth, Unit unit) { * The width should be in a format understood by the browser, e.g. "100px" * or "2.5em". *

- * If the provided {@code maxWidth} value is {@literal null} then max-width is - * removed. + * If the provided {@code maxWidth} value is {@literal null} then max-width + * is removed. * * @param maxWidth - * the max-width value (if null, the property will be removed) + * the max-width value (if null, the property will + * be removed) */ default void setMaxWidth(String maxWidth) { getElement().getStyle().set(ElementConstants.STYLE_MAX_WIDTH, maxWidth); } /** - * Sets the max-width of the component. Negative number implies unspecified size - * (terminal is free to set the size). + * Sets the max-width of the component. Negative number implies unspecified + * size (terminal is free to set the size). * * @param maxWidth * the max-width of the object. @@ -122,7 +124,7 @@ default void setMaxWidth(float maxWidth, Unit unit) { if (unit == null) { throw new IllegalArgumentException("Unit can not be null"); } - setMaxWidth(getCssSize(maxWidth,unit)); + setMaxWidth(getCssSize(maxWidth, unit)); } /** @@ -181,8 +183,8 @@ default void setHeight(String height) { } /** - * Sets the height of the component. Negative number implies unspecified size - * (terminal is free to set the size). + * Sets the height of the component. Negative number implies unspecified + * size (terminal is free to set the size). * * @param height * the height of the object. @@ -193,7 +195,7 @@ default void setHeight(float height, Unit unit) { if (unit == null) { throw new IllegalArgumentException("Unit can not be null"); } - setHeight(getCssSize(height,unit)); + setHeight(getCssSize(height, unit)); } /** @@ -202,19 +204,21 @@ default void setHeight(float height, Unit unit) { * The height should be in a format understood by the browser, e.g. "100px" * or "2.5em". *

- * If the provided {@code minHeight} value is {@literal null} then min-height is - * removed. + * If the provided {@code minHeight} value is {@literal null} then + * min-height is removed. * * @param minHeight - * the min-height value (if null, the property will be removed) + * the min-height value (if null, the property will + * be removed) */ default void setMinHeight(String minHeight) { - getElement().getStyle().set(ElementConstants.STYLE_MIN_HEIGHT, minHeight); + getElement().getStyle().set(ElementConstants.STYLE_MIN_HEIGHT, + minHeight); } /** - * Sets the min-height of the component. Negative number implies unspecified size - * (terminal is free to set the size). + * Sets the min-height of the component. Negative number implies unspecified + * size (terminal is free to set the size). * * @param minHeight * the min-height of the object. @@ -225,7 +229,7 @@ default void setMinHeight(float minHeight, Unit unit) { if (unit == null) { throw new IllegalArgumentException("Unit can not be null"); } - setMinHeight(getCssSize(minHeight,unit)); + setMinHeight(getCssSize(minHeight, unit)); } /** @@ -234,19 +238,21 @@ default void setMinHeight(float minHeight, Unit unit) { * The height should be in a format understood by the browser, e.g. "100px" * or "2.5em". *

- * If the provided {@code maxHeight} value is {@literal null} then max-height is - * removed. + * If the provided {@code maxHeight} value is {@literal null} then + * max-height is removed. * * @param maxHeight - * the max-height value (if null, the property will be removed) + * the max-height value (if null, the property will + * be removed) */ default void setMaxHeight(String maxHeight) { - getElement().getStyle().set(ElementConstants.STYLE_MAX_HEIGHT, maxHeight); + getElement().getStyle().set(ElementConstants.STYLE_MAX_HEIGHT, + maxHeight); } /** - * Sets the max-height of the component. Negative number implies unspecified size - * (terminal is free to set the size). + * Sets the max-height of the component. Negative number implies unspecified + * size (terminal is free to set the size). * * @param maxHeight * the max-height of the object. @@ -257,7 +263,7 @@ default void setMaxHeight(float maxHeight, Unit unit) { if (unit == null) { throw new IllegalArgumentException("Unit can not be null"); } - setMaxHeight(getCssSize(maxHeight,unit)); + setMaxHeight(getCssSize(maxHeight, unit)); } /** @@ -312,8 +318,7 @@ default void setSizeFull() { * Sets the width of the component to "100%". *

* This is just a convenience method which delegates its call to the - * {@link #setWidth(String)} with - * {@literal "100%"} as the argument value + * {@link #setWidth(String)} with {@literal "100%"} as the argument value */ default void setWidthFull() { setWidth("100%"); @@ -323,8 +328,7 @@ default void setWidthFull() { * Sets the height of the component to "100%". *

* This is just a convenience method which delegates its call to the - * {@link #setHeight(String)} with - * {@literal "100%"} as the argument value + * {@link #setHeight(String)} with {@literal "100%"} as the argument value */ default void setHeightFull() { setHeight("100%"); @@ -345,8 +349,10 @@ default void setSizeUndefined() { /** * Utility method for internal use. * - * @param size Size - * @param unit Unit + * @param size + * Size + * @param unit + * Unit * @return Css format size string */ static String getCssSize(float size, Unit unit) { diff --git a/flow-server/src/main/java/com/vaadin/flow/component/HasStyle.java b/flow-server/src/main/java/com/vaadin/flow/component/HasStyle.java index 33b3859b7f8..438571c22cf 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/HasStyle.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/HasStyle.java @@ -63,7 +63,7 @@ default boolean removeClassName(String className) { * null to remove all class names */ default void setClassName(String className) { - if(className == null) { + if (className == null) { getElement().removeAttribute("class"); } else { getElement().setAttribute("class", className); @@ -133,20 +133,23 @@ default Style getStyle() { } /** - * Adds one or more CSS class names to this component. Multiple class names can be - * specified by using multiple parameters. + * Adds one or more CSS class names to this component. Multiple class names + * can be specified by using multiple parameters. * - * @param classNames the CSS class name or class names to be added to the component + * @param classNames + * the CSS class name or class names to be added to the component */ default void addClassNames(String... classNames) { getClassNames().addAll(Arrays.asList(classNames)); } /** - * Removes one or more CSS class names from component. Multiple class names can be - * specified by using multiple parameters. + * Removes one or more CSS class names from component. Multiple class names + * can be specified by using multiple parameters. * - * @param classNames the CSS class name or class names to be removed from the component + * @param classNames + * the CSS class name or class names to be removed from the + * component */ default void removeClassNames(String... classNames) { getClassNames().removeAll(Arrays.asList(classNames)); diff --git a/flow-server/src/main/java/com/vaadin/flow/component/HasValue.java b/flow-server/src/main/java/com/vaadin/flow/component/HasValue.java index 56bef71d81b..58baf8bbecd 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/HasValue.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/HasValue.java @@ -35,7 +35,8 @@ * @author Vaadin Ltd * @since 1.0. */ -public interface HasValue, V> extends Serializable { +public interface HasValue, V> + extends Serializable { /** * An event fired when the value of a {@code HasValue} changes. diff --git a/flow-server/src/main/java/com/vaadin/flow/component/PushConfiguration.java b/flow-server/src/main/java/com/vaadin/flow/component/PushConfiguration.java index 2ef8c63e52b..d5006c82c90 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/PushConfiguration.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/PushConfiguration.java @@ -158,12 +158,14 @@ public interface PushConfiguration extends Serializable { * @return the URL to use for push requests, or null to use to default */ String getPushUrl(); - + /** - * Sets the factory that will be used to create new instances of {@link PushConnection}. + * Sets the factory that will be used to create new instances of + * {@link PushConnection}. * * @param factory - * the factory that will be used to create new instances of {@link PushConnection} + * the factory that will be used to create new instances of + * {@link PushConnection} */ void setPushConnectionFactory(PushConnectionFactory factory); @@ -226,7 +228,7 @@ public void setPushMode(PushMode pushMode) { // The push connection is initially in a disconnected state; // the client will establish the connection ui.getInternals() - .setPushConnection(pushConnectionFactory.apply(ui)); + .setPushConnection(pushConnectionFactory.apply(ui)); } // Nothing to do here if disabling push; // the client will close the connection @@ -280,9 +282,10 @@ public Collection getParameterNames() { } @Override - public void setPushConnectionFactory(PushConnectionFactory pushConnectionFactory) { + public void setPushConnectionFactory( + PushConnectionFactory pushConnectionFactory) { this.pushConnectionFactory = Objects.requireNonNull( - pushConnectionFactory, "Push connection factory must not be null" - ); + pushConnectionFactory, + "Push connection factory must not be null"); } } diff --git a/flow-server/src/main/java/com/vaadin/flow/component/ShortcutEvent.java b/flow-server/src/main/java/com/vaadin/flow/component/ShortcutEvent.java index 5cefcb29788..baecb370635 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/ShortcutEvent.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/ShortcutEvent.java @@ -27,7 +27,7 @@ /** * Event when shortcut is detected. * - * @author Vaadin Ltd. + * @author Vaadin Ltd. * @since 1.3 */ public class ShortcutEvent extends EventObject implements Serializable { @@ -39,27 +39,27 @@ public class ShortcutEvent extends EventObject implements Serializable { * Creates a new {@code ShortcutEvent}. * * @param source - * shortcut's {@code listenOn} {@link Component} + * shortcut's {@code listenOn} {@link Component} * @param lifecycleOwner - * shortcut's {@code lifecycleOwner} {@link Component} + * shortcut's {@code lifecycleOwner} {@link Component} * @param key - * primary {@link Key} of the shortcut + * primary {@link Key} of the shortcut * @param keyModifiers - * set of {@link KeyModifier KeyModifiers} of the shortcut + * set of {@link KeyModifier KeyModifiers} of the shortcut */ public ShortcutEvent(Component source, Component lifecycleOwner, Key key, - Set keyModifiers) { + Set keyModifiers) { super(source); this.lifecycleOwner = lifecycleOwner; this.key = key; - this.keyModifiers = keyModifiers == null ? Collections.emptySet() : - Collections.unmodifiableSet(keyModifiers); + this.keyModifiers = keyModifiers == null ? Collections.emptySet() + : Collections.unmodifiableSet(keyModifiers); } /** * Component which listened for the shortcut. - * @return - * listening {@link Component} + * + * @return listening {@link Component} */ @Override public Component getSource() { @@ -68,8 +68,8 @@ public Component getSource() { /** * Component which owns the shortcut. - * @return - * owning {@link Component} + * + * @return owning {@link Component} */ public Component getLifecycleOwner() { return lifecycleOwner; @@ -78,8 +78,8 @@ public Component getLifecycleOwner() { /** * Primary {@link Key} that triggered the shortcut. Primary key can be * anything that is not a {@link KeyModifier}. - * @return - * primary key + * + * @return primary key */ public Key getKey() { return key; @@ -88,8 +88,8 @@ public Key getKey() { /** * Set of {@link KeyModifier KeyModifiers} that, in combination with the * primary key, triggered the shortcut. - * @return - * set of key modifiers + * + * @return set of key modifiers */ public Set getKeyModifiers() { return keyModifiers; @@ -100,8 +100,10 @@ public Set getKeyModifiers() { * {@link KeyModifier KeyModifiers}. If {@code key} is null or a wrong * number of {@code keyModifiers} is given, returns {@code false}. * - * @param key {@code key} to compare - * @param keyModifiers {@code keyModifiers} to compare + * @param key + * {@code key} to compare + * @param keyModifiers + * {@code keyModifiers} to compare * @return Did the given parameters match those in the event? */ public boolean matches(Key key, KeyModifier... keyModifiers) { @@ -113,8 +115,8 @@ public boolean matches(Key key, KeyModifier... keyModifiers) { } List keyStrings = Stream.of(keyModifiers) .map(k -> k.getKeys().get(0)).collect(Collectors.toList()); - return key.matches(this.key.getKeys().get(0)) && this.keyModifiers - .stream().allMatch(k -> keyStrings.stream() - .anyMatch(k::matches)); + return key.matches(this.key.getKeys().get(0)) + && this.keyModifiers.stream().allMatch( + k -> keyStrings.stream().anyMatch(k::matches)); } } diff --git a/flow-server/src/main/java/com/vaadin/flow/component/ShortcutEventListener.java b/flow-server/src/main/java/com/vaadin/flow/component/ShortcutEventListener.java index fcc94f659ac..2be1d3a81e7 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/ShortcutEventListener.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/ShortcutEventListener.java @@ -22,7 +22,7 @@ /** * Listener for shortcut events. * - * @author Vaadin Ltd. + * @author Vaadin Ltd. * @since 1.3 */ @FunctionalInterface @@ -31,7 +31,7 @@ public interface ShortcutEventListener extends EventListener, Serializable { * Invoked when shortcut has been used. * * @param event - * {@link ShortcutEvent} based on the registered shortcut + * {@link ShortcutEvent} based on the registered shortcut */ void onShortcut(ShortcutEvent event); } diff --git a/flow-server/src/main/java/com/vaadin/flow/component/Shortcuts.java b/flow-server/src/main/java/com/vaadin/flow/component/Shortcuts.java index 719406fafed..e7fbaf7cf91 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/Shortcuts.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/Shortcuts.java @@ -18,12 +18,11 @@ import com.vaadin.flow.server.Command; - /** * Collections of methods for configuring more complex Shortcut interactions. *

- * Unlike the shortcut methods offered by {@link Focusable} and {@link - * ClickNotifier}, these methods allow for configuring the {@code + * Unlike the shortcut methods offered by {@link Focusable} and + * {@link ClickNotifier}, these methods allow for configuring the {@code * lifecycleOwner} directly, making it possible to added the shortcut onto any * component. The {@code lifecycleOwner} denotes the component to which the * shortcut is bound to. If the lifecycle owner is not attached, visible, or @@ -33,9 +32,9 @@ * @since 1.3 * * @see Focusable#addFocusShortcut(Key, KeyModifier...) for adding a shortcut - * for focusing the component + * for focusing the component * @see ClickNotifier#addClickShortcut(Key, KeyModifier...) for adding a - * shortcut which performs the click-action + * shortcut which performs the click-action */ public final class Shortcuts { static final String NULL = "Parameter '%s' must not be null!"; @@ -50,21 +49,22 @@ private Shortcuts() { * lifecycleOwner} and the shortcut is available in the global scope. *

* By default, the shortcut's listener is bound to {@link UI}. The listening - * component can be changed by calling {@link ShortcutRegistration#listenOn(Component...)}. + * component can be changed by calling + * {@link ShortcutRegistration#listenOn(Component...)}. * * @param lifecycleOwner - * the component that controls, when the shortcut is active. If the - * component is either invisible or detached, the shortcut won't - * work. Cannot be {@code null} + * the component that controls, when the shortcut is active. If + * the component is either invisible or detached, the shortcut + * won't work. Cannot be {@code null} * @param command - * code to execute when the shortcut is invoked. Cannot be {@code + * code to execute when the shortcut is invoked. Cannot be {@code * null} * @param key - * primary {@link Key} used to trigger the shortcut. Cannot be - * {@code null} + * primary {@link Key} used to trigger the shortcut. Cannot be + * {@code null} * @param keyModifiers - * {@link KeyModifier KeyModifiers} which also need to be pressed - * for the shortcut to trigger + * {@link KeyModifier KeyModifiers} which also need to be pressed + * for the shortcut to trigger * @return {@link ShortcutRegistration} for configuring and removing the * shortcut */ @@ -72,8 +72,8 @@ public static ShortcutRegistration addShortcutListener( Component lifecycleOwner, Command command, Key key, KeyModifier... keyModifiers) { if (lifecycleOwner == null) { - throw new IllegalArgumentException(String.format(NULL, - "lifecycleOwner")); + throw new IllegalArgumentException( + String.format(NULL, "lifecycleOwner")); } if (command == null) { throw new IllegalArgumentException(String.format(NULL, "command")); @@ -81,7 +81,8 @@ public static ShortcutRegistration addShortcutListener( if (key == null) { throw new IllegalArgumentException(String.format(NULL, "key")); } - return new ShortcutRegistration(lifecycleOwner, () -> new Component[] { lifecycleOwner.getUI().get() }, + return new ShortcutRegistration(lifecycleOwner, + () -> new Component[] { lifecycleOwner.getUI().get() }, event -> command.execute(), key).withModifiers(keyModifiers); } @@ -92,21 +93,22 @@ public static ShortcutRegistration addShortcutListener( * lifecycleOwner} and the shortcut is available in the global scope. *

* By default, the shortcut's listener is bound to {@link UI}. The listening - * component can be changed by calling {@link ShortcutRegistration#listenOn(Component...)}. + * component can be changed by calling + * {@link ShortcutRegistration#listenOn(Component...)}. * * @param lifecycleOwner - * the component that controls, when the shortcut is active. If the - * component is either invisible or detached, the shortcut won't - * work. Cannot be {@code null} + * the component that controls, when the shortcut is active. If + * the component is either invisible or detached, the shortcut + * won't work. Cannot be {@code null} * @param listener - * listener to execute when the shortcut is invoked. Receives a - * {@link ShortcutEvent}. Cannot be {@code null} + * listener to execute when the shortcut is invoked. Receives a + * {@link ShortcutEvent}. Cannot be {@code null} * @param key - * primary {@link Key} used to trigger the shortcut. Cannot be - * {@code null} + * primary {@link Key} used to trigger the shortcut. Cannot be + * {@code null} * @param keyModifiers - * {@link KeyModifier KeyModifiers} which also need to be pressed - * for the shortcut to trigger + * {@link KeyModifier KeyModifiers} which also need to be pressed + * for the shortcut to trigger * @return {@link ShortcutRegistration} for configuring and removing the * shortcut */ @@ -115,17 +117,17 @@ public static ShortcutRegistration addShortcutListener( KeyModifier... keyModifiers) { if (lifecycleOwner == null) { - throw new IllegalArgumentException(String.format(NULL, - "lifecycleOwner")); + throw new IllegalArgumentException( + String.format(NULL, "lifecycleOwner")); } if (listener == null) { - throw new IllegalArgumentException(String.format(NULL, - "listener")); + throw new IllegalArgumentException(String.format(NULL, "listener")); } if (key == null) { throw new IllegalArgumentException(String.format(NULL, "key")); } - return new ShortcutRegistration(lifecycleOwner, () -> new Component[] { lifecycleOwner.getUI().get() }, + return new ShortcutRegistration(lifecycleOwner, + () -> new Component[] { lifecycleOwner.getUI().get() }, listener, key).withModifiers(keyModifiers); } } diff --git a/flow-server/src/main/java/com/vaadin/flow/component/UI.java b/flow-server/src/main/java/com/vaadin/flow/component/UI.java index 7b039d09c56..6f4f52550ea 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/UI.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/UI.java @@ -766,8 +766,7 @@ public void setLocale(Locale locale) { */ public void setDirection(Direction direction) { Objects.requireNonNull(direction, "Direction cannot be null"); - getPage().executeJs("document.dir = $0", - direction.getClientName()); + getPage().executeJs("document.dir = $0", direction.getClientName()); } /** @@ -884,9 +883,8 @@ public > void navigate( * parameters to pass to view. * @throws IllegalArgumentException * if navigationTarget is a {@link HasUrlParameter} with a - * mandatory parameter, but parameters argument doesn't - * provide {@link HasUrlParameterFormat#PARAMETER_NAME} - * parameter. + * mandatory parameter, but parameters argument doesn't provide + * {@link HasUrlParameterFormat#PARAMETER_NAME} parameter. * @throws NotFoundException * in case there is no route defined for the given * navigationTarget matching the parameters. @@ -897,7 +895,7 @@ public void navigate(Class navigationTarget, .forRegistry(getInternals().getRouter().getRegistry()); navigate(configuration.getUrl(navigationTarget, parameters)); } - + /** * Updates this UI to show the view corresponding to the given location. The * location must be a relative path without any ".." segments. @@ -938,7 +936,8 @@ public void navigate(String location) { */ public void navigate(String location, QueryParameters queryParameters) { Objects.requireNonNull(location, "Location must not be null"); - Objects.requireNonNull(queryParameters, "Query parameters must not be null"); + Objects.requireNonNull(queryParameters, + "Query parameters must not be null"); getInternals().getRouter().navigate(this, new Location(location, queryParameters), diff --git a/flow-server/src/main/java/com/vaadin/flow/component/Unit.java b/flow-server/src/main/java/com/vaadin/flow/component/Unit.java index 27936a1edc9..2abc1e4e4d6 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/Unit.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/Unit.java @@ -59,8 +59,8 @@ public enum Unit { */ INCH("in"), /** - * Unit code representing in percentage of the containing element - * defined by terminal. + * Unit code representing in percentage of the containing element defined by + * terminal. */ PERCENTAGE("%"); @@ -86,21 +86,24 @@ static Stream getUnits() { /** * Gives size unit of the css string representing a size. * - * @param cssSize Css compliant size string such as "50px". + * @param cssSize + * Css compliant size string such as "50px". * * @return A Optional unit. */ public static Optional getUnit(String cssSize) { if (cssSize == null) { - throw new IllegalArgumentException("The parameter can't be null"); + throw new IllegalArgumentException("The parameter can't be null"); } - return getUnits().filter(unit -> cssSize.endsWith(unit.toString())).findFirst(); + return getUnits().filter(unit -> cssSize.endsWith(unit.toString())) + .findFirst(); } /** * Gives size component as float of the css string representing a size. * - * @param cssSize Css compliant size string such as "50px". + * @param cssSize + * Css compliant size string such as "50px". * * @return Size as float, 0 if string contained only the unit. */ @@ -113,8 +116,8 @@ public static float getSize(String cssSize) { .orElseThrow(() -> new IllegalArgumentException(String.format( "The parameter string '%s' does not contain valid unit", cssSize))); - String size = cssSize - .substring(0, cssSize.length() - unit.toString().length()); + String size = cssSize.substring(0, + cssSize.length() - unit.toString().length()); if (size.isEmpty()) { size = "0"; } @@ -124,7 +127,8 @@ public static float getSize(String cssSize) { /** * Convert unit string symbol to Unit. * - * @param symbol A String. + * @param symbol + * A String. * @return A Unit, Unit.PIXELS if symbol was null or not matching. */ public static Unit getUnitFromSymbol(String symbol) { diff --git a/flow-server/src/main/java/com/vaadin/flow/component/internal/CompositionEvent.java b/flow-server/src/main/java/com/vaadin/flow/component/internal/CompositionEvent.java index b2ef8f696d1..856ac947b85 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/internal/CompositionEvent.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/internal/CompositionEvent.java @@ -47,8 +47,8 @@ public abstract class CompositionEvent extends ComponentEvent { * language code for the composition event, if available; * otherwise, the empty string */ - public CompositionEvent(Component source, boolean fromClient, - String data, String locale) { + public CompositionEvent(Component source, boolean fromClient, String data, + String locale) { super(source, fromClient); this.data = data; this.locale = locale == null ? null : Locale.forLanguageTag(locale); diff --git a/flow-server/src/main/java/com/vaadin/flow/component/internal/HeartbeatEvent.java b/flow-server/src/main/java/com/vaadin/flow/component/internal/HeartbeatEvent.java index f722ea6b19f..09e4416ea24 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/internal/HeartbeatEvent.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/internal/HeartbeatEvent.java @@ -32,9 +32,9 @@ public class HeartbeatEvent extends EventObject { * Constructs a heartbeat Event. * * @param ui - * UI for which the Event occurred + * UI for which the Event occurred * @param heartbeatTime - * value for the heartbeat + * value for the heartbeat */ public HeartbeatEvent(UI ui, long heartbeatTime) { super(ui); diff --git a/flow-server/src/main/java/com/vaadin/flow/component/internal/JavaScriptBootstrapUI.java b/flow-server/src/main/java/com/vaadin/flow/component/internal/JavaScriptBootstrapUI.java index b61cbd8d12c..8ae7a107fa5 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/internal/JavaScriptBootstrapUI.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/internal/JavaScriptBootstrapUI.java @@ -133,7 +133,7 @@ public void connectClient(String clientElementTag, String clientElementId, if (getForwardToClientUrl() != null) { navigateToClient(getForwardToClientUrl()); acknowledgeClient(); - + } else if (isPostponed()) { cancelClient(); } else { @@ -185,7 +185,7 @@ public void navigate(String pathname, QueryParameters queryParameters) { // prevent looping if (navigationInProgress || getInternals().hasLastHandledLocation() && sameLocation(getInternals().getLastHandledLocation(), - location)) { + location)) { return; } @@ -243,7 +243,8 @@ private void navigateToPlaceholder(Location location) { NavigationTrigger.CLIENT_SIDE); } - private void renderViewForRoute(Location location, NavigationTrigger trigger) { + private void renderViewForRoute(Location location, + NavigationTrigger trigger) { if (!shouldHandleNavigation(location)) { return; } @@ -280,7 +281,8 @@ private boolean sameLocation(Location oldLocation, Location newLocation) { .trimPath(oldLocation.getPathWithQueryParameters())); } - private void handleNavigation(Location location, NavigationState navigationState, NavigationTrigger trigger) { + private void handleNavigation(Location location, + NavigationState navigationState, NavigationTrigger trigger) { try { NavigationEvent navigationEvent = new NavigationEvent( getInternals().getRouter(), location, this, trigger); @@ -290,7 +292,8 @@ private void handleNavigation(Location location, NavigationState navigationState clientNavigationStateRenderer.handle(navigationEvent); - forwardToClientUrl = clientNavigationStateRenderer.getClientForwardRoute(); + forwardToClientUrl = clientNavigationStateRenderer + .getClientForwardRoute(); adjustPageTitle(); @@ -337,7 +340,8 @@ private void adjustPageTitle() { // app shell title is computed from the title tag in index.html String appShellTitle = getInternals().getAppShellTitle(); // restore the app shell title when there is no one for the route - if ((newTitle == null || newTitle.isEmpty()) && appShellTitle != null && !appShellTitle.isEmpty()) { + if ((newTitle == null || newTitle.isEmpty()) && appShellTitle != null + && !appShellTitle.isEmpty()) { getInternals().cancelPendingTitleUpdate(); getInternals().setTitle(appShellTitle); } @@ -354,8 +358,8 @@ private void handleErrorNavigation(Location location) { ErrorParameter errorParameter = new ErrorParameter<>( NotFoundException.class, notFoundException); ErrorNavigationEvent errorNavigationEvent = new ErrorNavigationEvent( - getInternals().getRouter(), location, this, NavigationTrigger.CLIENT_SIDE, - errorParameter); + getInternals().getRouter(), location, this, + NavigationTrigger.CLIENT_SIDE, errorParameter); errorStateRenderer.handle(errorNavigationEvent); } diff --git a/flow-server/src/main/java/com/vaadin/flow/component/internal/JavaScriptNavigationStateRenderer.java b/flow-server/src/main/java/com/vaadin/flow/component/internal/JavaScriptNavigationStateRenderer.java index ee8f1b3e3de..bcf7fbf0e12 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/internal/JavaScriptNavigationStateRenderer.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/internal/JavaScriptNavigationStateRenderer.java @@ -69,8 +69,8 @@ public String getClientForwardRoute() { @Override public int handle(NavigationEvent event) { - continueNavigationAction = event.getUI() - .getInternals().getContinueNavigationAction(); + continueNavigationAction = event.getUI().getInternals() + .getContinueNavigationAction(); return super.handle(event); } diff --git a/flow-server/src/main/java/com/vaadin/flow/component/internal/KeyboardEvent.java b/flow-server/src/main/java/com/vaadin/flow/component/internal/KeyboardEvent.java index 23796ab3a03..12cf7d6f85f 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/internal/KeyboardEvent.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/internal/KeyboardEvent.java @@ -77,15 +77,14 @@ public abstract class KeyboardEvent extends ComponentEvent { * composition session */ public KeyboardEvent(Component source, boolean fromClient, String key, - String code, int location, boolean ctrlKey, - boolean shiftKey, boolean altKey, boolean metaKey, - boolean repeat, boolean composing) { + String code, int location, boolean ctrlKey, boolean shiftKey, + boolean altKey, boolean metaKey, boolean repeat, + boolean composing) { super(source, fromClient); this.key = Key.of(key); // code might not be present for all keys for all browsers // it is quite implementation dependent - this.code = (code == null || code.isEmpty()) ? - null : Key.of(code); + this.code = (code == null || code.isEmpty()) ? null : Key.of(code); this.location = KeyLocation.of(location); this.repeat = repeat; this.composing = composing; @@ -144,9 +143,12 @@ public Key getKey() { /** * Gets the code of the event. If the event did not contain a valid code, an * empty Optional will be given. + * * @return the optional code of the event as a {@link Key} */ - public Optional getCode() { return Optional.ofNullable(code); } + public Optional getCode() { + return Optional.ofNullable(code); + } /** * Gets the {@link KeyLocation} of the event. diff --git a/flow-server/src/main/java/com/vaadin/flow/component/internal/UIInternals.java b/flow-server/src/main/java/com/vaadin/flow/component/internal/UIInternals.java index aad9ed1075b..6b8c5e9c55e 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/internal/UIInternals.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/internal/UIInternals.java @@ -616,7 +616,7 @@ public void setTitle(String title) { * @param appShellTitle * the appShellTitle to set */ - public void setAppShellTitle(String appShellTitle){ + public void setAppShellTitle(String appShellTitle) { this.appShellTitle = appShellTitle; } @@ -674,8 +674,8 @@ public boolean cancelPendingTitleUpdate() { * @param layouts * the parent layouts */ - public void showRouteTarget(Location viewLocation, - Component target, List layouts) { + public void showRouteTarget(Location viewLocation, Component target, + List layouts) { assert target != null; assert viewLocation != null; diff --git a/flow-server/src/main/java/com/vaadin/flow/component/page/AppShellConfigurator.java b/flow-server/src/main/java/com/vaadin/flow/component/page/AppShellConfigurator.java index 29953196e72..8aff8104ec9 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/page/AppShellConfigurator.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/page/AppShellConfigurator.java @@ -40,7 +40,8 @@ * *

* There is a single application shell for the entire Vaadin application, and - * therefore there can be at max one class implementing {@link AppShellConfigurator}. + * therefore there can be at max one class implementing + * {@link AppShellConfigurator}. *

* *

diff --git a/flow-server/src/main/java/com/vaadin/flow/component/page/LoadingIndicatorConfiguration.java b/flow-server/src/main/java/com/vaadin/flow/component/page/LoadingIndicatorConfiguration.java index b615dc976da..e191dcbdfdc 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/page/LoadingIndicatorConfiguration.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/page/LoadingIndicatorConfiguration.java @@ -28,7 +28,8 @@ public interface LoadingIndicatorConfiguration extends Serializable { * Sets the delay before the loading indicator is shown. The default is * 300ms. * - * @param firstDelay The first delay (in ms) + * @param firstDelay + * The first delay (in ms) */ void setFirstDelay(int firstDelay); @@ -44,7 +45,8 @@ public interface LoadingIndicatorConfiguration extends Serializable { * The delay is calculated from the time when the loading indicator was * triggered. The default is 1500ms. * - * @param secondDelay The delay before going into the "second" state (in ms) + * @param secondDelay + * The delay before going into the "second" state (in ms) */ void setSecondDelay(int secondDelay); @@ -62,7 +64,8 @@ public interface LoadingIndicatorConfiguration extends Serializable { * The delay is calculated from the time when the loading indicator was * triggered. The default is 5000ms. * - * @param thirdDelay The delay before going into the "third" state (in ms) + * @param thirdDelay + * The delay before going into the "third" state (in ms) */ void setThirdDelay(int thirdDelay); @@ -94,7 +97,8 @@ public interface LoadingIndicatorConfiguration extends Serializable { * of the viewport shown after a delay to the users while there is an active * server request in process. * - * @param applyDefaultTheme {@code true} to apply default theming, {@code false} for not + * @param applyDefaultTheme + * {@code true} to apply default theming, {@code false} for not */ void setApplyDefaultTheme(boolean applyDefaultTheme); } diff --git a/flow-server/src/main/java/com/vaadin/flow/component/page/PendingJavaScriptResult.java b/flow-server/src/main/java/com/vaadin/flow/component/page/PendingJavaScriptResult.java index 4880b8391c0..46c7d42d317 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/page/PendingJavaScriptResult.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/page/PendingJavaScriptResult.java @@ -64,8 +64,8 @@ public JavaScriptException(String message) { } /** - * Cancel the javascript execution, if it was not yet sent to the - * browser for execution. + * Cancel the javascript execution, if it was not yet sent to the browser + * for execution. * * @return true if the execution was canceled, * false if not diff --git a/flow-server/src/main/java/com/vaadin/flow/component/page/Push.java b/flow-server/src/main/java/com/vaadin/flow/component/page/Push.java index 1aa37a2cb04..71d37cf4af6 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/page/Push.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/page/Push.java @@ -26,9 +26,10 @@ import com.vaadin.flow.shared.ui.Transport; /** - * Configures automatic server push for a root {@link com.vaadin.flow.router.Route navigation target} - * (or custom {@link UI}). If some other push mode is desired, it can be passed as a parameter, e.g. - * @Push(PushMode.MANUAL). + * Configures automatic server push for a root + * {@link com.vaadin.flow.router.Route navigation target} (or custom + * {@link UI}). If some other push mode is desired, it can be passed as a + * parameter, e.g. @Push(PushMode.MANUAL). * * @see PushMode * @see com.vaadin.flow.router.Route @@ -42,17 +43,18 @@ @Target(ElementType.TYPE) public @interface Push { /** - * The {@link PushMode} to use for the annotated root navigation target (or custom UI). The default - * push mode when this annotation is present is {@link PushMode#AUTOMATIC}. + * The {@link PushMode} to use for the annotated root navigation target (or + * custom UI). The default push mode when this annotation is present is + * {@link PushMode#AUTOMATIC}. * * @return the push mode to use */ PushMode value() default PushMode.AUTOMATIC; /** - * Transport type used for the push for the annotated root navigation target (or custom UI). The - * default transport type when this annotation is present is - * {@link Transport#WEBSOCKET_XHR}. + * Transport type used for the push for the annotated root navigation target + * (or custom UI). The default transport type when this annotation is + * present is {@link Transport#WEBSOCKET_XHR}. * * @return the transport type to use */ diff --git a/flow-server/src/main/java/com/vaadin/flow/component/webcomponent/EventOptions.java b/flow-server/src/main/java/com/vaadin/flow/component/webcomponent/EventOptions.java index ad4a9796285..73d9304a026 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/webcomponent/EventOptions.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/webcomponent/EventOptions.java @@ -36,7 +36,7 @@ public class EventOptions implements Serializable { * * @see #EventOptions(boolean, boolean, boolean) for all properties * @see com.vaadin.flow.component.WebComponentExporter for exporting web - * components + * components */ public EventOptions() { } @@ -46,11 +46,11 @@ public EventOptions() { * by an exported web component. * * @param bubbles - * A Boolean indicating whether the event bubbles up through the DOM - * or not. + * A Boolean indicating whether the event bubbles up through the + * DOM or not. * @see #EventOptions(boolean, boolean, boolean) for all properties * @see com.vaadin.flow.component.WebComponentExporter for exporting web - * components + * components */ public EventOptions(boolean bubbles) { this.bubbles = bubbles; @@ -61,17 +61,16 @@ public EventOptions(boolean bubbles) { * by an exported web component. * * @param bubbles - * indicates whether the event bubbles up through the DOM or not. + * indicates whether the event bubbles up through the DOM or not. * @param cancelable - * indicates whether the event is cancelable. + * indicates whether the event is cancelable. * @param composed - * indicates whether or not the event can bubble across the boundary - * between the shadow DOM and the regular DOM. + * indicates whether or not the event can bubble across the + * boundary between the shadow DOM and the regular DOM. * @see com.vaadin.flow.component.WebComponentExporter for exporting web - * components + * components */ - public EventOptions(boolean bubbles, boolean cancelable, - boolean composed) { + public EventOptions(boolean bubbles, boolean cancelable, boolean composed) { this.bubbles = bubbles; this.cancelable = cancelable; this.composed = composed; diff --git a/flow-server/src/main/java/com/vaadin/flow/component/webcomponent/PropertyConfiguration.java b/flow-server/src/main/java/com/vaadin/flow/component/webcomponent/PropertyConfiguration.java index 1333b14aded..d077d1882e3 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/webcomponent/PropertyConfiguration.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/webcomponent/PropertyConfiguration.java @@ -26,14 +26,14 @@ * produced by {@link com.vaadin.flow.component.WebComponentExporter}. * * @param - * type of the {@code component} exported as a web component + * type of the {@code component} exported as a web component * @param

- * type of the property exposed on the web component + * type of the property exposed on the web component * @author Vaadin Ltd. * @since 2.0 */ -public interface PropertyConfiguration extends Serializable { +public interface PropertyConfiguration + extends Serializable { /** * Sets a Property change handler. {@code onChange} can only be called once @@ -63,11 +63,12 @@ public interface PropertyConfiguration * * @param onChangeHandler - * {@code component}'s method which is called with the property - * value + * {@code component}'s method which is called with the property + * value * @return this {@code PropertyConfiguration} */ - PropertyConfiguration onChange(SerializableBiConsumer onChangeHandler); + PropertyConfiguration onChange( + SerializableBiConsumer onChangeHandler); /** * Mark the property as read-only. It cannot be written to by the client. diff --git a/flow-server/src/main/java/com/vaadin/flow/component/webcomponent/WebComponent.java b/flow-server/src/main/java/com/vaadin/flow/component/webcomponent/WebComponent.java index 50f5be28df6..28c9ad8fa07 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/webcomponent/WebComponent.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/webcomponent/WebComponent.java @@ -29,24 +29,24 @@ import elemental.json.JsonValue; /** - * Acts as a proxy to the web component root onto which the exporter {@link - * Component} is added. Allows updating web component properties and firing - * custom events on the client-side. + * Acts as a proxy to the web component root onto which the exporter + * {@link Component} is added. Allows updating web component properties and + * firing custom events on the client-side. * * @param - * type of the {@code component} exported as web component + * type of the {@code component} exported as web component * @author Vaadin Ltd. * @since 2.0 */ public final class WebComponent implements Serializable { - private static final String UPDATE_PROPERTY = "this" + - "._updatePropertyFromServer($0, $1);"; - private static final String UPDATE_PROPERTY_NULL = "this" + - "._updatePropertyFromServer($0, null);"; - private static final String UPDATE_PROPERTY_FORMAT = "this" + - "._updatePropertyFromServer($0, %s);"; - private static final String CUSTOM_EVENT = "this.dispatchEvent(new " + - "CustomEvent($0, %s));"; + private static final String UPDATE_PROPERTY = "this" + + "._updatePropertyFromServer($0, $1);"; + private static final String UPDATE_PROPERTY_NULL = "this" + + "._updatePropertyFromServer($0, null);"; + private static final String UPDATE_PROPERTY_FORMAT = "this" + + "._updatePropertyFromServer($0, %s);"; + private static final String CUSTOM_EVENT = "this.dispatchEvent(new " + + "CustomEvent($0, %s));"; private static final EventOptions BASIC_OPTIONS = new EventOptions(); @@ -59,23 +59,22 @@ private WebComponent() { /** * Constructs a {@link WebComponent}. {@link WebComponentBinding} provides * the instance of the {@link Component} exported as a web component. {@code - * Binding} also defines the properties the web component has. {@link - * Element} is the host element which contains the exported {@code + * Binding} also defines the properties the web component has. + * {@link Element} is the host element which contains the exported {@code * component} instance (provided by the {@code binding}). * * @param binding - * binds web component configuration to {@code component X} + * binds web component configuration to {@code component X} * @param componentHost - * host {@code component X} on the embedding page - * @see com.vaadin.flow.component.webcomponent.WebComponentWrapper for - * the web component host + * host {@code component X} on the embedding page + * @see com.vaadin.flow.component.webcomponent.WebComponentWrapper for the + * web component host */ - public WebComponent(WebComponentBinding binding, - Element componentHost) { - Objects.requireNonNull(binding, "Parameter 'binding' must not be " + - "null!"); - Objects.requireNonNull(componentHost, "Parameter " + - "'webComponentWrapper' must not be null!"); + public WebComponent(WebComponentBinding binding, Element componentHost) { + Objects.requireNonNull(binding, + "Parameter 'binding' must not be " + "null!"); + Objects.requireNonNull(componentHost, + "Parameter " + "'webComponentWrapper' must not be null!"); this.binding = binding; this.componentHost = componentHost; } @@ -85,9 +84,8 @@ public WebComponent(WebComponentBinding binding, * component. This event does not bubble in the DOM hierarchy. * * @param eventName - * name of the event, not null - * @see #fireEvent(String, JsonValue, EventOptions) for full set of - * options + * name of the event, not null + * @see #fireEvent(String, JsonValue, EventOptions) for full set of options */ public void fireEvent(String eventName) { fireEvent(eventName, Json.createNull(), BASIC_OPTIONS); @@ -99,12 +97,11 @@ public void fireEvent(String eventName) { * hierarchy. * * @param eventName - * name of the event, not null + * name of the event, not null * @param objectData - * data the event should carry. This data is placed as the {@code + * data the event should carry. This data is placed as the {@code * detail} property of the event, nullable - * @see #fireEvent(String, JsonValue, EventOptions) for full set of - * options + * @see #fireEvent(String, JsonValue, EventOptions) for full set of options */ public void fireEvent(String eventName, JsonValue objectData) { fireEvent(eventName, objectData, BASIC_OPTIONS); @@ -116,83 +113,89 @@ public void fireEvent(String eventName, JsonValue objectData) { * behavior with {@link EventOptions}. * * @param eventName - * name of the event, not null + * name of the event, not null * @param objectData - * data the event should carry. This data is placed as the {@code + * data the event should carry. This data is placed as the {@code * detail} property of the event, nullable * @param options - * event options for {@code bubbles}, {@code cancelable}, and {@code + * event options for {@code bubbles}, {@code cancelable}, and + * {@code * composed} flags, not null * @throws NullPointerException - * if either {@code eventName} or {@code options} is {@code null} + * if either {@code eventName} or {@code options} is + * {@code null} */ - public void fireEvent(String eventName, JsonValue objectData, EventOptions options) { - Objects.requireNonNull(eventName, "Parameter 'eventName' must not be " + - "null!"); + public void fireEvent(String eventName, JsonValue objectData, + EventOptions options) { + Objects.requireNonNull(eventName, + "Parameter 'eventName' must not be " + "null!"); Objects.requireNonNull(options, "Parameter 'options' must not be null"); JsonObject object = Json.createObject(); object.put("bubbles", options.isBubbles()); object.put("cancelable", options.isCancelable()); object.put("composed", options.isComposed()); - object.put("detail", objectData == null ? - Json.createNull() : objectData); + object.put("detail", + objectData == null ? Json.createNull() : objectData); - componentHost.executeJs(String.format(CUSTOM_EVENT, - object.toJson()), eventName); + componentHost.executeJs(String.format(CUSTOM_EVENT, object.toJson()), + eventName); } /** * Sets property value on the client-side to the given {@code value}. The - * required {@link PropertyConfigurationImpl} is received from {@link - * com.vaadin.flow.component.WebComponentExporter} when a new property is - * added for the web component. + * required {@link PropertyConfigurationImpl} is received from + * {@link com.vaadin.flow.component.WebComponentExporter} when a new + * property is added for the web component. * * @param propertyConfiguration - * identifies the property for which the value is being set, not - * {@code null} + * identifies the property for which the value is being set, not + * {@code null} * @param value - * new value for the property, can be {@code null} + * new value for the property, can be {@code null} * @param

- * type of the property value being set. If the type does not match - * the original property type, throws an exception + * type of the property value being set. If the type does not + * match the original property type, throws an exception * @throws NullPointerException - * if {@code propertyConfiguration} is {@code null} + * if {@code propertyConfiguration} is {@code null} * @throws IllegalArgumentException - * if {@code PropertyConfiguration} is not a correct implementation + * if {@code PropertyConfiguration} is not a correct + * implementation * @throws IllegalArgumentException - * if the web component does not have a property identified by - * {@code propertyConfiguration} + * if the web component does not have a property identified by + * {@code propertyConfiguration} * @throws IllegalArgumentException - * the provided {@code value} is not of the type expected by the - * property + * the provided {@code value} is not of the type expected by the + * property */ @SuppressWarnings("unchecked") - public

void setProperty(PropertyConfiguration propertyConfiguration, P value) { - Objects.requireNonNull(propertyConfiguration, "Parameter " + - "'propertyConfiguration' must not be null!"); + public

void setProperty( + PropertyConfiguration propertyConfiguration, P value) { + Objects.requireNonNull(propertyConfiguration, + "Parameter " + "'propertyConfiguration' must not be null!"); if (!(propertyConfiguration instanceof PropertyConfigurationImpl)) { - throw new IllegalArgumentException(String.format("Parameter " + - "'propertyConfiguration' is not an implementation of %s", + throw new IllegalArgumentException(String.format("Parameter " + + "'propertyConfiguration' is not an implementation of %s", PropertyConfigurationImpl.class)); } - PropertyConfigurationImpl propertyConfigurationImpl = - (PropertyConfigurationImpl) propertyConfiguration; + PropertyConfigurationImpl propertyConfigurationImpl = (PropertyConfigurationImpl) propertyConfiguration; - String propertyName = propertyConfigurationImpl.getPropertyData().getName(); + String propertyName = propertyConfigurationImpl.getPropertyData() + .getName(); // does the binding actually have the property if (!binding.hasProperty(propertyName)) { - throw new IllegalArgumentException(String.format("%s does not " + - "have a property identified by '%s'!", + throw new IllegalArgumentException(String.format( + "%s does not " + "have a property identified by '%s'!", WebComponent.class.getSimpleName(), propertyName)); } // is the property's value type correct - if (value != null && !binding.getPropertyType(propertyName).isAssignableFrom(value.getClass())) { - throw new IllegalArgumentException(String.format("Property '%s' " + - "of type '%s' cannot be assigned value of type '%s'!", + if (value != null && !binding.getPropertyType(propertyName) + .isAssignableFrom(value.getClass())) { + throw new IllegalArgumentException(String.format("Property '%s' " + + "of type '%s' cannot be assigned value of type '%s'!", propertyName, binding.getPropertyType(propertyName).getName(), value.getClass().getCanonicalName())); @@ -224,8 +227,7 @@ private void setProperty(String propertyName, Object value) { // Since properties can take JsonValues, this was needed to allow // that expected behavior. componentHost.executeJs(String.format(UPDATE_PROPERTY_FORMAT, - ((JsonValue) value).toJson()), - propertyName); + ((JsonValue) value).toJson()), propertyName); } } } diff --git a/flow-server/src/main/java/com/vaadin/flow/component/webcomponent/WebComponentWrapper.java b/flow-server/src/main/java/com/vaadin/flow/component/webcomponent/WebComponentWrapper.java index 7133ade0f14..be7623c15e5 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/webcomponent/WebComponentWrapper.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/webcomponent/WebComponentWrapper.java @@ -90,7 +90,6 @@ protected WebComponentWrapper(Element rootElement, getElement().getShadowRoot().ifPresent(shadow -> shadow .appendChild(bootstrapElements.toArray(new Element[0]))); } - /** * Synchronize method for client side to send property value updates to the @@ -106,7 +105,8 @@ public void sync(String property, JsonValue newValue) { try { webComponentBinding.updateProperty(property, newValue); } catch (IllegalArgumentException e) { - LoggerFactory.getLogger(webComponentBinding.getComponent().getClass()) + LoggerFactory + .getLogger(webComponentBinding.getComponent().getClass()) .error("Failed to synchronise property '{}'", property, e); } } diff --git a/flow-server/src/main/java/com/vaadin/flow/dom/DomListenerRegistration.java b/flow-server/src/main/java/com/vaadin/flow/dom/DomListenerRegistration.java index 4bd679d3183..44ec6e561c7 100644 --- a/flow-server/src/main/java/com/vaadin/flow/dom/DomListenerRegistration.java +++ b/flow-server/src/main/java/com/vaadin/flow/dom/DomListenerRegistration.java @@ -181,8 +181,8 @@ default DomListenerRegistration throttle(int period) { * @see #debounce(int) * @see #throttle(int) * - * @return timeout in milliseconds, - * or 0 if debouncing is disabled + * @return timeout in milliseconds, or 0 if debouncing is + * disabled */ default int getDebounceTimeout() { /* diff --git a/flow-server/src/main/java/com/vaadin/flow/dom/Element.java b/flow-server/src/main/java/com/vaadin/flow/dom/Element.java index f4db9becf6b..2f5003d45d0 100644 --- a/flow-server/src/main/java/com/vaadin/flow/dom/Element.java +++ b/flow-server/src/main/java/com/vaadin/flow/dom/Element.java @@ -678,9 +678,9 @@ public Element setPropertyJson(String name, JsonValue value) { * or {@link DomListenerRegistration#synchronizeProperty(String)}. * * @param name - * the property name, not null + * the property name, not null * @param value - * the property value, not null + * the property value, not null * @return this element */ // Distinct name so setProperty("foo", null) is not ambiguous @@ -702,11 +702,11 @@ public Element setPropertyBean(String name, Object value) { * or {@link DomListenerRegistration#synchronizeProperty(String)}. * * @param - * the type of items in the list + * the type of items in the list * @param name - * the property name, not null + * the property name, not null * @param value - * the property value, not null + * the property value, not null * @return this element */ public Element setPropertyList(String name, List value) { @@ -728,9 +728,9 @@ public Element setPropertyList(String name, List value) { * or {@link DomListenerRegistration#synchronizeProperty(String)}. * * @param name - * the property name, not null + * the property name, not null * @param value - * the property value, not null + * the property value, not null * @return this element */ public Element setPropertyMap(String name, Map value) { diff --git a/flow-server/src/main/java/com/vaadin/flow/dom/ElementUtil.java b/flow-server/src/main/java/com/vaadin/flow/dom/ElementUtil.java index 66ab9edcba9..57ce38f4958 100644 --- a/flow-server/src/main/java/com/vaadin/flow/dom/ElementUtil.java +++ b/flow-server/src/main/java/com/vaadin/flow/dom/ElementUtil.java @@ -253,7 +253,7 @@ public static Optional fromJsoup(Node node) { if (node instanceof TextNode) { return Optional.of(Element.createText(((TextNode) node).text())); } else if (node instanceof org.jsoup.nodes.Element) { - ret = new Element(((org.jsoup.nodes.Element)node).tagName()); + ret = new Element(((org.jsoup.nodes.Element) node).tagName()); } else { LoggerFactory.getLogger(ElementUtil.class).error( "Could not convert a {}, '{}' into {}!", diff --git a/flow-server/src/main/java/com/vaadin/flow/dom/NodeVisitor.java b/flow-server/src/main/java/com/vaadin/flow/dom/NodeVisitor.java index 6fd175b3d08..85273e14dae 100644 --- a/flow-server/src/main/java/com/vaadin/flow/dom/NodeVisitor.java +++ b/flow-server/src/main/java/com/vaadin/flow/dom/NodeVisitor.java @@ -30,7 +30,7 @@ public interface NodeVisitor { * The type of the element. * * @author Vaadin Ltd - * @since 1.0 + * @since 1.0 * */ enum ElementType { diff --git a/flow-server/src/main/java/com/vaadin/flow/dom/impl/AbstractNodeStateProvider.java b/flow-server/src/main/java/com/vaadin/flow/dom/impl/AbstractNodeStateProvider.java index ef5dcc9be20..376b74f55f6 100644 --- a/flow-server/src/main/java/com/vaadin/flow/dom/impl/AbstractNodeStateProvider.java +++ b/flow-server/src/main/java/com/vaadin/flow/dom/impl/AbstractNodeStateProvider.java @@ -120,7 +120,8 @@ public void removeChild(StateNode node, Element child) { ElementChildrenList childrenFeature = getChildrenFeature(node); int pos = childrenFeature.indexOf(child.getNode()); if (pos == -1) { - throw new IllegalArgumentException("Trying to detach an element from parent that does not have it."); + throw new IllegalArgumentException( + "Trying to detach an element from parent that does not have it."); } childrenFeature.remove(pos); } diff --git a/flow-server/src/main/java/com/vaadin/flow/dom/impl/BasicTextElementStateProvider.java b/flow-server/src/main/java/com/vaadin/flow/dom/impl/BasicTextElementStateProvider.java index 436c7491fd6..587d172749d 100644 --- a/flow-server/src/main/java/com/vaadin/flow/dom/impl/BasicTextElementStateProvider.java +++ b/flow-server/src/main/java/com/vaadin/flow/dom/impl/BasicTextElementStateProvider.java @@ -93,5 +93,5 @@ public Node getParent(StateNode node) { protected Object readResolve() throws ObjectStreamException { return INSTANCE; - } + } } diff --git a/flow-server/src/main/java/com/vaadin/flow/dom/impl/ShadowRootStateProvider.java b/flow-server/src/main/java/com/vaadin/flow/dom/impl/ShadowRootStateProvider.java index 67a7061be26..3e41a61ac25 100644 --- a/flow-server/src/main/java/com/vaadin/flow/dom/impl/ShadowRootStateProvider.java +++ b/flow-server/src/main/java/com/vaadin/flow/dom/impl/ShadowRootStateProvider.java @@ -222,8 +222,8 @@ public void setVisible(StateNode node, boolean visible) { public boolean isVisible(StateNode node) { throw new UnsupportedOperationException(); } - + protected Object readResolve() throws ObjectStreamException { return INSTANCE; - } + } } diff --git a/flow-server/src/main/java/com/vaadin/flow/function/DeploymentConfiguration.java b/flow-server/src/main/java/com/vaadin/flow/function/DeploymentConfiguration.java index 42e4b7f7d0a..adc2ade477e 100644 --- a/flow-server/src/main/java/com/vaadin/flow/function/DeploymentConfiguration.java +++ b/flow-server/src/main/java/com/vaadin/flow/function/DeploymentConfiguration.java @@ -283,7 +283,8 @@ default boolean disableAutomaticServletRegistration() { * false to not serve Brotli files. */ default boolean isBrotli() { - return getBooleanProperty(InitParameters.SERVLET_PARAMETER_BROTLI, false); + return getBooleanProperty(InitParameters.SERVLET_PARAMETER_BROTLI, + false); } default String getCompiledWebComponentsPath() { @@ -295,8 +296,8 @@ default String getCompiledWebComponentsPath() { * Returns an array with polyfills to be loaded when the app is loaded. * * The default value is empty, but it can be changed by setting the - * {@link InitParameters#SERVLET_PARAMETER_POLYFILLS} as a comma separated list - * of JS files to load. + * {@link InitParameters#SERVLET_PARAMETER_POLYFILLS} as a comma separated + * list of JS files to load. * * @return polyfills to load */ @@ -314,8 +315,8 @@ default List getPolyfills() { * @return true if dev server should be used */ default boolean enableDevServer() { - return getBooleanProperty(InitParameters.SERVLET_PARAMETER_ENABLE_DEV_SERVER, - true); + return getBooleanProperty( + InitParameters.SERVLET_PARAMETER_ENABLE_DEV_SERVER, true); } /** @@ -326,8 +327,8 @@ default boolean enableDevServer() { * @return true if dev server should be reused */ default boolean reuseDevServer() { - return getBooleanProperty(InitParameters.SERVLET_PARAMETER_REUSE_DEV_SERVER, - true); + return getBooleanProperty( + InitParameters.SERVLET_PARAMETER_REUSE_DEV_SERVER, true); } /** @@ -377,7 +378,8 @@ default boolean isEagerServerLoad() { /** * Checks if dev mode live reload is enabled or not. * - * @return {@code true} if dev mode live reload is enabled, {@code false} otherwise + * @return {@code true} if dev mode live reload is enabled, {@code false} + * otherwise */ boolean isDevModeLiveReloadEnabled(); diff --git a/flow-server/src/main/java/com/vaadin/flow/function/ValueProvider.java b/flow-server/src/main/java/com/vaadin/flow/function/ValueProvider.java index 1fdff0ab1f5..f946355f451 100644 --- a/flow-server/src/main/java/com/vaadin/flow/function/ValueProvider.java +++ b/flow-server/src/main/java/com/vaadin/flow/function/ValueProvider.java @@ -32,7 +32,7 @@ */ @FunctionalInterface public interface ValueProvider -extends SerializableFunction { + extends SerializableFunction { /** * Returns a value provider that always returns its input argument. diff --git a/flow-server/src/main/java/com/vaadin/flow/internal/BeanUtil.java b/flow-server/src/main/java/com/vaadin/flow/internal/BeanUtil.java index b457a679cc6..111add0daa8 100644 --- a/flow-server/src/main/java/com/vaadin/flow/internal/BeanUtil.java +++ b/flow-server/src/main/java/com/vaadin/flow/internal/BeanUtil.java @@ -174,8 +174,7 @@ private static List getPropertyDescriptors( exception); // handle next descriptor } catch (IntrospectionException e) { - LoggerFactory.getLogger(BeanUtil.class.getName()).info(null, - e); + LoggerFactory.getLogger(BeanUtil.class.getName()).info(null, e); result.add(descriptor); } } @@ -243,9 +242,9 @@ private static boolean isAvailable() { return true; } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException e) { - LoggerFactory.getLogger("com.vaadin.validator.BeanValidator").info( - "A JSR-303 bean validation implementation not found on the classpath or could not be initialized. BeanValidator cannot be used.", - e); + LoggerFactory.getLogger("com.vaadin.validator.BeanValidator") + .info("A JSR-303 bean validation implementation not found on the classpath or could not be initialized. BeanValidator cannot be used.", + e); return false; } catch (IllegalAccessException | IllegalArgumentException e) { throw new RuntimeException( diff --git a/flow-server/src/main/java/com/vaadin/flow/internal/BootstrapHandlerHelper.java b/flow-server/src/main/java/com/vaadin/flow/internal/BootstrapHandlerHelper.java index 9c7e72c6597..7f6e8f03941 100644 --- a/flow-server/src/main/java/com/vaadin/flow/internal/BootstrapHandlerHelper.java +++ b/flow-server/src/main/java/com/vaadin/flow/internal/BootstrapHandlerHelper.java @@ -63,7 +63,7 @@ public static String getServiceUrl(VaadinRequest vaadinRequest) { * @return the relative push URL */ public static String getPushURL(VaadinSession vaadinSession, - VaadinRequest vaadinRequest) { + VaadinRequest vaadinRequest) { String serviceUrl = getServiceUrl(vaadinRequest); String pushURL = vaadinSession.getConfiguration().getPushURL(); diff --git a/flow-server/src/main/java/com/vaadin/flow/internal/BrowserLiveReload.java b/flow-server/src/main/java/com/vaadin/flow/internal/BrowserLiveReload.java index 0afb4c83745..05a41f4feb2 100644 --- a/flow-server/src/main/java/com/vaadin/flow/internal/BrowserLiveReload.java +++ b/flow-server/src/main/java/com/vaadin/flow/internal/BrowserLiveReload.java @@ -44,7 +44,7 @@ enum Backend { * Sets the live reload backend technology explicitly. * * @param backend - * enabling technology, not null. + * enabling technology, not null. */ void setBackend(Backend backend); @@ -69,7 +69,7 @@ enum Backend { * connection. * * @param resource - * a web socket connection resource, not null. + * a web socket connection resource, not null. * @return whether the web socket connection is for live reload */ boolean isLiveReload(AtmosphereResource resource); diff --git a/flow-server/src/main/java/com/vaadin/flow/internal/BrowserLiveReloadAccess.java b/flow-server/src/main/java/com/vaadin/flow/internal/BrowserLiveReloadAccess.java index 259d2989d1c..fbc6f14d7dd 100644 --- a/flow-server/src/main/java/com/vaadin/flow/internal/BrowserLiveReloadAccess.java +++ b/flow-server/src/main/java/com/vaadin/flow/internal/BrowserLiveReloadAccess.java @@ -42,13 +42,14 @@ public class BrowserLiveReloadAccess { */ public BrowserLiveReload getLiveReload(VaadinService service) { if (service.getDeploymentConfiguration().isProductionMode()) { - LoggerFactory.getLogger(BrowserLiveReloadAccess.class) - .debug("BrowserLiveReloadAccess::getLiveReload is called in production mode."); + LoggerFactory.getLogger(BrowserLiveReloadAccess.class).debug( + "BrowserLiveReloadAccess::getLiveReload is called in production mode."); return null; } - if (!service.getDeploymentConfiguration().isDevModeLiveReloadEnabled()) { - LoggerFactory.getLogger(BrowserLiveReloadAccess.class) - .debug("BrowserLiveReloadAccess::getLiveReload is called when live reload is disabled."); + if (!service.getDeploymentConfiguration() + .isDevModeLiveReloadEnabled()) { + LoggerFactory.getLogger(BrowserLiveReloadAccess.class).debug( + "BrowserLiveReloadAccess::getLiveReload is called when live reload is disabled."); return null; } VaadinContext context = service.getContext(); diff --git a/flow-server/src/main/java/com/vaadin/flow/internal/BrowserLiveReloadImpl.java b/flow-server/src/main/java/com/vaadin/flow/internal/BrowserLiveReloadImpl.java index bb8ec7256d8..c6d17e1641d 100644 --- a/flow-server/src/main/java/com/vaadin/flow/internal/BrowserLiveReloadImpl.java +++ b/flow-server/src/main/java/com/vaadin/flow/internal/BrowserLiveReloadImpl.java @@ -43,7 +43,8 @@ class BrowserLiveReloadImpl implements BrowserLiveReload { private Backend backend = null; - private static final EnumMap> IDENTIFIER_CLASSES = new EnumMap<>(Backend.class); + private static final EnumMap> IDENTIFIER_CLASSES = new EnumMap<>( + Backend.class); static { IDENTIFIER_CLASSES.put(Backend.JREBEL, Collections.singletonList( @@ -101,7 +102,6 @@ public void setBackend(Backend backend) { this.backend = backend; } - @Override public void onConnect(AtmosphereResource resource) { resource.suspend(-1); diff --git a/flow-server/src/main/java/com/vaadin/flow/internal/CustomElementNameValidator.java b/flow-server/src/main/java/com/vaadin/flow/internal/CustomElementNameValidator.java index 93423077eb0..d33ee41f89a 100644 --- a/flow-server/src/main/java/com/vaadin/flow/internal/CustomElementNameValidator.java +++ b/flow-server/src/main/java/com/vaadin/flow/internal/CustomElementNameValidator.java @@ -29,7 +29,8 @@ * @since 1.0 */ public final class CustomElementNameValidator { - private static final Pattern STARTS_WITH_A_DIGIT = Pattern.compile("^\\d.*"); + private static final Pattern STARTS_WITH_A_DIGIT = Pattern + .compile("^\\d.*"); private static final Set RESERVED_NAMES = Stream .of("annotation-xml", "color-profile", "font-face", "font-face-src", diff --git a/flow-server/src/main/java/com/vaadin/flow/internal/JsonUtils.java b/flow-server/src/main/java/com/vaadin/flow/internal/JsonUtils.java index 29d4c354672..cff867fae14 100644 --- a/flow-server/src/main/java/com/vaadin/flow/internal/JsonUtils.java +++ b/flow-server/src/main/java/com/vaadin/flow/internal/JsonUtils.java @@ -289,7 +289,7 @@ public static JsonObject createObject(Map map, * Converts the given bean to JSON. * * @param bean - * the bean to convert, not {@code null} + * the bean to convert, not {@code null} * @return a JSON representation of the bean */ public static JsonObject beanToJson(Object bean) { @@ -306,7 +306,7 @@ public static JsonObject beanToJson(Object bean) { * Converts the given list to JSON. * * @param list - * the list to convert, not {@code null} + * the list to convert, not {@code null} * @return a JSON representation of the bean */ public static JsonArray listToJson(List list) { @@ -322,7 +322,7 @@ public static JsonArray listToJson(List list) { * Converts the given map to JSON. * * @param map - * the map to convert, not {@code null} + * the map to convert, not {@code null} * @return a JSON representation of the bean */ public static JsonObject mapToJson(Map map) { diff --git a/flow-server/src/main/java/com/vaadin/flow/internal/LocaleUtil.java b/flow-server/src/main/java/com/vaadin/flow/internal/LocaleUtil.java index 3783d115650..7cbd323ab11 100644 --- a/flow-server/src/main/java/com/vaadin/flow/internal/LocaleUtil.java +++ b/flow-server/src/main/java/com/vaadin/flow/internal/LocaleUtil.java @@ -65,8 +65,8 @@ public static Optional getExactLocaleMatch(VaadinRequest request, * application provided locales * @return found locale or null if no matches by language */ - public static Optional getLocaleMatchByLanguage(VaadinRequest request, - List providedLocales) { + public static Optional getLocaleMatchByLanguage( + VaadinRequest request, List providedLocales) { Locale foundLocale = null; Enumeration locales = request.getLocales(); while (locales.hasMoreElements()) { diff --git a/flow-server/src/main/java/com/vaadin/flow/internal/Pair.java b/flow-server/src/main/java/com/vaadin/flow/internal/Pair.java index 01f6b4d5e35..e4625d1caca 100644 --- a/flow-server/src/main/java/com/vaadin/flow/internal/Pair.java +++ b/flow-server/src/main/java/com/vaadin/flow/internal/Pair.java @@ -31,10 +31,11 @@ public class Pair /** * Creates a new pair. + * * @param u - * the value of the first component + * the value of the first component * @param v - * the value of the second component + * the value of the second component */ public Pair(U u, V v) { first = u; @@ -43,8 +44,8 @@ public Pair(U u, V v) { /** * Gets the first component of the pair. - * @return - * the first component of the pair + * + * @return the first component of the pair */ public U getFirst() { return first; @@ -52,8 +53,8 @@ public U getFirst() { /** * Gets the second component of the pair. - * @return - * the second component of the pair + * + * @return the second component of the pair */ public V getSecond() { return second; diff --git a/flow-server/src/main/java/com/vaadin/flow/internal/ResponseWriter.java b/flow-server/src/main/java/com/vaadin/flow/internal/ResponseWriter.java index 1a4e253bcb1..0828eb573e1 100644 --- a/flow-server/src/main/java/com/vaadin/flow/internal/ResponseWriter.java +++ b/flow-server/src/main/java/com/vaadin/flow/internal/ResponseWriter.java @@ -51,18 +51,20 @@ public class ResponseWriter implements Serializable { private static final int DEFAULT_BUFFER_SIZE = 32 * 1024; - private static final Pattern RANGE_HEADER_PATTERN = Pattern.compile( - "^bytes=((\\d*-\\d*\\s*,\\s*)*\\d*-\\d*\\s*)$"); - private static final Pattern BYTE_RANGE_PATTERN = Pattern.compile( - "(\\d*)-(\\d*)"); + private static final Pattern RANGE_HEADER_PATTERN = Pattern + .compile("^bytes=((\\d*-\\d*\\s*,\\s*)*\\d*-\\d*\\s*)$"); + private static final Pattern BYTE_RANGE_PATTERN = Pattern + .compile("(\\d*)-(\\d*)"); /** - * Maximum number of ranges accepted in a single Range header. Remaining ranges will be ignored. + * Maximum number of ranges accepted in a single Range header. Remaining + * ranges will be ignored. */ private static final int MAX_RANGE_COUNT = 16; /** - * Maximum number of overlapping ranges allowed. The request will be denied if above this threshold. + * Maximum number of overlapping ranges allowed. The request will be denied + * if above this threshold. */ private static final int MAX_OVERLAPPING_RANGE_COUNT = 2; @@ -168,7 +170,7 @@ public void writeResponseContents(String filenameWithPath, URL resourceUrl, } catch (IOException e) { getLogger().debug("Error writing static file to user", e); } finally { - if (dataStream !=null ) { + if (dataStream != null) { closeStream(dataStream); } } @@ -215,7 +217,8 @@ private void writeRangeContents(String range, HttpServletResponse response, if (startGroup.isEmpty() && endGroup.isEmpty()) { response.setContentLengthLong(0L); response.setStatus(416); // Range Not Satisfiable - getLogger().info("received a malformed range: '{}'", rangeMatcher.group()); + getLogger().info("received a malformed range: '{}'", + rangeMatcher.group()); return; } long start = startGroup.isEmpty() ? 0L : Long.parseLong(startGroup); @@ -224,7 +227,8 @@ private void writeRangeContents(String range, HttpServletResponse response, if (end < start || (resourceLength >= 0 && start >= resourceLength)) { // illegal range -> 416 - getLogger().info("received an illegal range '{}' for resource '{}'", + getLogger().info( + "received an illegal range '{}' for resource '{}'", rangeMatcher.group(), resourceURL); response.setContentLengthLong(0L); response.setStatus(416); @@ -234,7 +238,8 @@ private void writeRangeContents(String range, HttpServletResponse response, if (!verifyRangeLimits(ranges)) { ranges.pop(); - getLogger().info("serving only {} ranges for resource '{}' even though more were requested", + getLogger().info( + "serving only {} ranges for resource '{}' even though more were requested", ranges.size(), resourceURL); break; } @@ -258,7 +263,7 @@ private void writeRangeContents(String range, HttpServletResponse response, final InputStream dataStream = connection.getInputStream(); try { long skipped = dataStream.skip(start); - assert(skipped == start); + assert (skipped == start); writeStream(outputStream, dataStream, end - start + 1); } finally { closeStream(dataStream); @@ -312,7 +317,7 @@ private void writeMultipartRangeContents(List> ranges, position = 0L; } long skipped = dataStream.skip(start - position); - assert(skipped == start - position); + assert (skipped == start - position); writeStream(outputStream, dataStream, end - start + 1); position = end + 1; } @@ -321,12 +326,12 @@ private void writeMultipartRangeContents(List> ranges, } outputStream.write(String.format("\r\n--%s", partBoundary).getBytes()); } - + private String createContentRangeHeader(long start, long end, long size) { String lengthString = size >= 0 ? Long.toString(size) : "*"; return String.format("bytes %d-%d/%s", start, end, lengthString); } - + private void setContentLength(HttpServletResponse response, long contentLength) { try { @@ -337,9 +342,10 @@ private void setContentLength(HttpServletResponse response, } /** - * Returns true if the number of ranges in ranges is less than the - * upper limit and the number that overlap (= have at least one byte in common) - * with the range [start, end] are less than the upper limit. + * Returns true if the number of ranges in ranges is less than + * the upper limit and the number that overlap (= have at least one byte in + * common) with the range [start, end] are less than the upper + * limit. */ private boolean verifyRangeLimits(List> ranges) { if (ranges.size() > MAX_RANGE_COUNT) { @@ -350,13 +356,15 @@ private boolean verifyRangeLimits(List> ranges) { for (int i = 0; i < ranges.size(); i++) { for (int j = i + 1; j < ranges.size(); j++) { if (ranges.get(i).getFirst() <= ranges.get(j).getSecond() - && ranges.get(j).getFirst() <= ranges.get(i).getSecond()) { + && ranges.get(j).getFirst() <= ranges.get(i) + .getSecond()) { count++; } } } if (count > MAX_OVERLAPPING_RANGE_COUNT) { - getLogger().info("more than {} overlapping ranges requested", MAX_OVERLAPPING_RANGE_COUNT); + getLogger().info("more than {} overlapping ranges requested", + MAX_OVERLAPPING_RANGE_COUNT); return false; } return true; @@ -404,7 +412,7 @@ private void writeStream(ServletOutputStream outputStream, long bytesTotal = 0L; int bytes; while (bytesTotal < count && (bytes = dataStream.read(buffer, 0, - (int)Long.min(bufferSize, count - bytesTotal))) >= 0) { + (int) Long.min(bufferSize, count - bytesTotal))) >= 0) { outputStream.write(buffer, 0, bytes); bytesTotal += bytes; } diff --git a/flow-server/src/main/java/com/vaadin/flow/internal/UsageStatistics.java b/flow-server/src/main/java/com/vaadin/flow/internal/UsageStatistics.java index 67660645e66..a268e887939 100644 --- a/flow-server/src/main/java/com/vaadin/flow/internal/UsageStatistics.java +++ b/flow-server/src/main/java/com/vaadin/flow/internal/UsageStatistics.java @@ -111,8 +111,7 @@ public static Stream getEntries() { * Remove a entry of the current usage entries. * * @param name - * the feature name - * want to be removed, not null + * the feature name want to be removed, not null */ public static void removeEntry(String name) { entires.remove(name); diff --git a/flow-server/src/main/java/com/vaadin/flow/internal/UsageStatisticsExporter.java b/flow-server/src/main/java/com/vaadin/flow/internal/UsageStatisticsExporter.java index cfc94743560..79dd51a9e90 100644 --- a/flow-server/src/main/java/com/vaadin/flow/internal/UsageStatisticsExporter.java +++ b/flow-server/src/main/java/com/vaadin/flow/internal/UsageStatisticsExporter.java @@ -35,7 +35,8 @@ public class UsageStatisticsExporter implements Serializable { * Export {@link UsageStatistics} entries to a document. It appends a * {@code