com.vaadin.flow.component.dependency.JsModule Java Examples

The following examples show how to use com.vaadin.flow.component.dependency.JsModule. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FullDependenciesScannerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void getModules_noTheme_returnAllNoThemeModules_orderPerClassIsPreserved_getClassesReturnAllModuleAnnotatedComponents()
        throws ClassNotFoundException {
    FrontendDependenciesScanner scanner = setUpAnnotationScanner(
            JsModule.class);
    List<String> modules = scanner.getModules();

    Assert.assertEquals(17, modules.size());

    assertJsModules(modules);

    Set<String> classes = scanner.getClasses();
    Assert.assertEquals(12, classes.size());

    assertJsModulesClasses(classes);
    Assert.assertFalse(classes.contains(LumoTest.class.getName()));
}
 
Example #2
Source File: FullDependenciesScanner.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new scanner instance which discovers all dependencies in the
 * classpath using a given annotation finder.
 *
 * @param finder
 *            a class finder
 * @param annotationFinder
 *            a strategy to discover class annotations
 */
FullDependenciesScanner(ClassFinder finder,
        SerializableBiFunction<Class<?>, Class<? extends Annotation>, List<? extends Annotation>> annotationFinder) {
    super(finder);
    long start = System.currentTimeMillis();
    this.annotationFinder = annotationFinder;
    try {
        abstractTheme = finder.loadClass(AbstractTheme.class.getName());
    } catch (ClassNotFoundException exception) {
        throw new IllegalStateException("Could not load "
                + AbstractTheme.class.getName() + " class", exception);
    }

    packages = discoverPackages();

    Map<String, Set<String>> themeModules = new HashMap<>();
    LinkedHashSet<String> regularModules = new LinkedHashSet<>();

    collectAnnotationValues(
            (clazz, module) -> handleModule(clazz, module, regularModules,
                    themeModules),
            JsModule.class,
            module -> invokeAnnotationMethodAsString(module, VALUE));

    collectAnnotationValues((clazz, script) -> {
        classes.add(clazz.getName());
        scripts.add(script);
    }, JavaScript.class,
            module -> invokeAnnotationMethodAsString(module, VALUE));
    cssData = discoverCss();

    discoverTheme();

    modules = calculateModules(regularModules, themeModules);
    getLogger().info("Visited {} classes. Took {} ms.", getClasses().size(),
            System.currentTimeMillis() - start);
}
 
Example #3
Source File: FrontendClassVisitor.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public AnnotationVisitor visitAnnotation(String descriptor,
        boolean visible) {
    addSignatureToClasses(children, descriptor);

    // We return different visitor implementations depending on the
    // annotation
    String cname = descriptor.replace("/", ".");
    if (className.equals(endPoint.name)
            && cname.contains(Route.class.getName())) {
        return routeVisitor;
    }
    if (cname.contains(JsModule.class.getName())) {
        return jsModuleVisitor;
    }
    if (cname.contains(JavaScript.class.getName())) {
        return jScriptVisitor;
    }
    if (cname.contains(NoTheme.class.getName())) {
        if (className.equals(endPoint.name)) {
            endPoint.theme.notheme = true;
        }
        return null;
    }
    if (cname.contains(Theme.class.getName())) {
        if (className.equals(endPoint.name)) {
            return themeRouteVisitor;
        }
        if (className.equals(endPoint.layout)) {
            return themeLayoutVisitor;
        }
    }
    if (cname.contains(CssImport.class.getName())) {
        return new CssAnnotationVisitor(endPoint.css);
    }
    // default visitor
    return annotationVisitor;
}
 
Example #4
Source File: DevModeClassFinderTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void applicableClasses_knownClasses() {
    Collection<Class<?>> classes = getApplicableClasses();

    List<Class<?>> knownClasses = Arrays.asList(
        Route.class,
        UIInitListener.class,
        VaadinServiceInitListener.class,
        WebComponentExporter.class,
        WebComponentExporterFactory.class,
        NpmPackage.class,
        NpmPackage.Container.class,
        JsModule.class,
        JsModule.Container.class,
        JavaScript.class,
        JavaScript.Container.class,
        CssImport.class,
        CssImport.Container.class,
        Theme.class,
        NoTheme.class,
        HasErrorParameter.class);

    for (Class<?> clz : classes) {
        assertTrue("should be a known class " + clz.getName(), knownClasses.contains(clz));
    }
    Assert.assertEquals(knownClasses.size(), classes.size());
}
 
Example #5
Source File: ComponentMetaData.java    From flow with Apache License 2.0 4 votes vote down vote up
List<JsModule> getJsModules() {
    return Collections.unmodifiableList(jsModules);
}
 
Example #6
Source File: UIInternals.java    From flow with Apache License 2.0 4 votes vote down vote up
private void addFallbackDependencies(DependencyInfo dependency) {
    if (isFallbackChunkLoaded) {
        return;
    }
    VaadinContext context = ui.getSession().getService().getContext();
    FallbackChunk chunk = context.getAttribute(FallbackChunk.class);
    if (chunk == null) {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug(
                    "Fallback chunk is not available, skipping fallback dependencies load");
        }
        return;
    }

    Set<String> modules = chunk.getModules();
    Set<CssImportData> cssImportsData = chunk.getCssImports();
    if (modules.isEmpty() && cssImportsData.isEmpty()) {
        getLogger().debug(
                "Fallback chunk is empty, skipping fallback dependencies load");
        return;
    }

    List<CssImport> cssImports = dependency.getCssImports();
    List<JavaScript> javaScripts = dependency.getJavaScripts();
    List<JsModule> jsModules = dependency.getJsModules();

    if (jsModules.stream().map(JsModule::value)
            .anyMatch(modules::contains)) {
        loadFallbackChunk();
        return;
    }

    if (javaScripts.stream().map(JavaScript::value)
            .anyMatch(modules::contains)) {
        loadFallbackChunk();
        return;
    }

    if (cssImports.stream().map(this::buildData)
            .anyMatch(cssImportsData::contains)) {
        loadFallbackChunk();
        return;
    }
}
 
Example #7
Source File: NpmTemplateParser.java    From flow with Apache License 2.0 4 votes vote down vote up
@Override
public TemplateData getTemplateContent(
        Class<? extends PolymerTemplate<?>> clazz, String tag,
        VaadinService service) {

    List<Dependency> dependencies = AnnotationReader
            .getAnnotationsFor(clazz, JsModule.class).stream()
            .map(jsModule -> new Dependency(Dependency.Type.JS_MODULE,
                    jsModule.value(),
                    LoadMode.EAGER)) // load mode doesn't matter here
            .collect(Collectors.toList());

    for (DependencyFilter filter : service.getDependencyFilters()) {
        dependencies = filter.filter(new ArrayList<>(dependencies),
                service);
    }

    Pair<Dependency, String> chosenDep = null;

    for (Dependency dependency : dependencies) {
        if (dependency.getType() != Dependency.Type.JS_MODULE) {
            continue;
        }

        String url = dependency.getUrl();
        String source = getSourcesFromTemplate(tag, url);
        if (source == null) {
            try {
                source = getSourcesFromStats(service, url);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }
        if (source == null) {
            continue;
        }
        if (chosenDep == null) {
            chosenDep = new Pair<>(dependency, source);
        }
        if (dependencyHasTagName(dependency, tag)) {
            chosenDep = new Pair<>(dependency, source);
            break;
        }
    }

    if (chosenDep != null) {

        Element templateElement = BundleParser.parseTemplateElement(
                chosenDep.getFirst().getUrl(), chosenDep.getSecond());
        if (!JsoupUtils.getDomModule(templateElement, null).isPresent()) {
            // Template needs to be wrapped in an element with id, to look
            // like a P2 template
            Element parent = new Element(tag);
            parent.attr("id", tag);
            templateElement.appendTo(parent);
        }

        return new TemplateData(chosenDep.getFirst().getUrl(),
                templateElement);
    }

    throw new IllegalStateException(String.format("Couldn't find the "
            + "definition of the element with tag '%s' "
            + "in any template file declared using '@%s' annotations. "
            + "Check the availability of the template files in your WAR "
            + "file or provide alternative implementation of the "
            + "method getTemplateContent() which should return an element "
            + "representing the content of the template file", tag,
            JsModule.class.getSimpleName()));
}
 
Example #8
Source File: AbstractUpdateImportsTest.java    From flow with Apache License 2.0 4 votes vote down vote up
@Test
public void assertFullSortOrder() throws MalformedURLException {
    Class[] testClasses = { MainView.class,
            NodeTestComponents.TranslatedImports.class,
            NodeTestComponents.LocalP3Template.class,
            NodeTestComponents.JavaScriptOrder.class };
    ClassFinder classFinder = getClassFinder(testClasses);

    updater = new UpdateImports(classFinder, getScanner(classFinder),
            tmpRoot, new File(tmpRoot, TOKEN_FILE));
    updater.run();

    // Imports are collected as
    // - theme and css
    // - JsModules (external e.g. in node_modules/)
    // - JavaScript
    // - Generated webcompoents
    // - JsModules (internal e.g. in frontend/)
    List<String> expectedImports = new ArrayList<>();
    expectedImports.addAll(updater.getExportLines());
    expectedImports.addAll(updater.getThemeLines());

    getAnntotationsAsStream(JsModule.class, testClasses)
            .map(JsModule::value).map(this::updateToImport).sorted()
            .forEach(expectedImports::add);
    getAnntotationsAsStream(JavaScript.class, testClasses)
            .map(JavaScript::value).map(this::updateToImport).sorted()
            .forEach(expectedImports::add);

    List<String> internals = expectedImports.stream()
            .filter(importValue -> importValue
                    .contains(FrontendUtils.WEBPACK_PREFIX_ALIAS))
            .sorted().collect(Collectors.toList());
    updater.getGeneratedModules().stream().map(this::updateToImport)
            .forEach(expectedImports::add);
    // Remove internals from the full list
    expectedImports.removeAll(internals);
    // Add internals to end of list
    expectedImports.addAll(internals);

    Assert.assertEquals(expectedImports, updater.resultingLines);
}
 
Example #9
Source File: FullDependenciesScannerTest.java    From flow with Apache License 2.0 4 votes vote down vote up
@Test
public void getModules_explcitTheme_returnAllModulesExcludingNotUsedTheme_getClassesReturnAllModuleAnnotatedComponents()
        throws ClassNotFoundException {
    // use this fake/mock class for the loaded class to check that annotated
    // classes are requested for the loaded class and not for the
    // annotationType
    Class clazz = Object.class;

    Mockito.when(finder.loadClass(JsModule.class.getName()))
            .thenReturn(clazz);

    Mockito.when(finder.getAnnotatedClasses(clazz))
            .thenReturn(getAnnotatedClasses(JsModule.class));

    Class themeClass = Throwable.class;

    Mockito.when(finder.loadClass(Theme.class.getName()))
            .thenReturn(themeClass);

    Set<Class<?>> themeClasses = getAnnotatedClasses(Theme.class);
    themeClasses.add(FakeLumoTheme.class);
    Mockito.when(finder.getAnnotatedClasses(themeClass))
            .thenReturn(themeClasses);
    Assert.assertTrue(themeClasses.size() >= 2);

    Mockito.when(finder.loadClass(LumoTest.class.getName()))
            .thenReturn((Class) LumoTest.class);
    Mockito.when(finder.loadClass(FakeLumoTheme.class.getName()))
            .thenReturn((Class) FakeLumoTheme.class);

    FrontendDependenciesScanner scanner = new FullDependenciesScanner(
            finder, (type, annotation) -> {
                if (annotation.equals(clazz)) {
                    return findAnnotations(type, JsModule.class);
                } else if (annotation.equals(themeClass)) {
                    return findAnnotations(type, Theme.class);
                }
                Assert.fail();
                return null;
            });

    List<String> modules = scanner.getModules();
    Assert.assertEquals(23, modules.size());
    assertJsModules(modules);

    // Theme modules should be included now
    Assert.assertTrue(
            modules.contains("@vaadin/vaadin-lumo-styles/color.js"));
    Assert.assertTrue(
            modules.contains("@vaadin/vaadin-lumo-styles/typography.js"));
    Assert.assertTrue(
            modules.contains("@vaadin/vaadin-lumo-styles/sizing.js"));
    Assert.assertTrue(
            modules.contains("@vaadin/vaadin-lumo-styles/spacing.js"));
    Assert.assertTrue(
            modules.contains("@vaadin/vaadin-lumo-styles/style.js"));
    Assert.assertTrue(
            modules.contains("@vaadin/vaadin-lumo-styles/icons.js"));

    // not used theme module is not included
    Assert.assertFalse(modules.contains("./foo-bar-baz.js"));

    Set<String> classes = scanner.getClasses();
    Assert.assertEquals(13, classes.size());

    assertJsModulesClasses(classes);
    Assert.assertTrue(classes.contains(LumoTest.class.getName()));
    Assert.assertFalse(classes.contains(FakeLumoTheme.class.getName()));
}
 
Example #10
Source File: AnnotationReader.java    From flow with Apache License 2.0 2 votes vote down vote up
/**
 * Finds all {@link JsModule} annotation on the given {@link Component}
 * class, its super classes and implenented interfaces.
 *
 * @param componentClass
 *            the component class to search for the annotation
 * @return a list the JavaScript annotations found
 */
public static List<JsModule> getJsModuleAnnotations(
        Class<? extends Component> componentClass) {
    return getAnnotationsFor(componentClass, JsModule.class);
}