diff --git a/.prettierignore b/.prettierignore deleted file mode 100644 index 43753eae..00000000 --- a/.prettierignore +++ /dev/null @@ -1,6 +0,0 @@ -# This file inherits .gitignore, there is no need to copy its content here -.yarn -.github/ISSUE_TEMPLATE - -# Do not format expected dist files -**/fixtures/expected diff --git a/dprint.json b/dprint.json new file mode 100644 index 00000000..be41c206 --- /dev/null +++ b/dprint.json @@ -0,0 +1,9 @@ +{ + "plugins": [ + "https://github.com/speakeasy-api/dprint-plugin-java/releases/download/v0.5.0/dprint_plugin_java.wasm", + "https://plugins.dprint.dev/typescript-0.95.15.wasm", + "https://plugins.dprint.dev/json-0.21.1.wasm" + ], + "excludes": ["**/.yarn/releases/**", ".github/**", "**/fixtures/expected"], + "java": { "formatJavadoc": true } +} diff --git a/eslint.config.js b/eslint.config.js index 64610a4b..b70f534b 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -1,12 +1,12 @@ // @ts-check -import { defineConfig } from "eslint/config"; +import eslintReact from "@eslint-react/eslint-plugin"; import { includeIgnoreFile } from "@eslint/compat"; import eslint from "@eslint/js"; -import tseslint from "typescript-eslint"; -import path from "node:path"; -import globals from "globals"; -import eslintReact from "@eslint-react/eslint-plugin"; import pluginCypress from "eslint-plugin-cypress"; +import { defineConfig } from "eslint/config"; +import globals from "globals"; +import path from "node:path"; +import tseslint from "typescript-eslint"; export default defineConfig( { @@ -14,11 +14,9 @@ export default defineConfig( globals: { ...globals.browser, ...globals.jest, ...globals.node }, }, }, - // JS/TS recommended eslint.configs.recommended, { files: ["**/*.ts", "**/*.tsx"], extends: tseslint.configs.recommended }, - // React eslintReact.configs["recommended-typescript"], { @@ -27,7 +25,6 @@ export default defineConfig( "@eslint-react/dom/no-dangerously-set-innerhtml": "off", }, }, - // Cypress pluginCypress.configs.recommended, { @@ -37,7 +34,6 @@ export default defineConfig( "@typescript-eslint/no-unused-expressions": "off", }, }, - // Ignore the same files as .gitignore includeIgnoreFile(path.resolve(import.meta.dirname, ".gitignore")), { ignores: ["**/fixtures/expected/**"] }, diff --git a/jahia-test-module/javascript/head-script.js b/jahia-test-module/javascript/head-script.js index 9464f6db..e1f1a8ed 100644 --- a/jahia-test-module/javascript/head-script.js +++ b/jahia-test-module/javascript/head-script.js @@ -1,5 +1,5 @@ console.log("Executing head script..."); -document.addEventListener("DOMContentLoaded", function () { +document.addEventListener("DOMContentLoaded", function() { var newDiv = document.createElement("div"); newDiv.id = "testHeadElement"; document.body.appendChild(newDiv); diff --git a/jahia-test-module/package.json b/jahia-test-module/package.json index 863dcc95..3156f075 100644 --- a/jahia-test-module/package.json +++ b/jahia-test-module/package.json @@ -17,7 +17,7 @@ "build": "tsc --noEmit && vite build && run pack", "clean": "rm -rf dist/", "deploy": "jahia-deploy", - "format": "prettier --write --list-different .", + "format": "dprint fmt", "pack": "yarn pack --out dist/package.tgz" }, "devDependencies": { diff --git a/jahia-test-module/src/client/components/SampleRenderInBrowserReact.tsx b/jahia-test-module/src/client/components/SampleRenderInBrowserReact.tsx index 235280fd..bf27fc60 100644 --- a/jahia-test-module/src/client/components/SampleRenderInBrowserReact.tsx +++ b/jahia-test-module/src/client/components/SampleRenderInBrowserReact.tsx @@ -27,8 +27,7 @@ export default function SampleRenderInBrowserReact({ path }: { path: string }) { Able to display current node path: {path}

- And refreshing date every 2 sec:{" "} - {currentDate.toLocaleString()} + And refreshing date every 2 sec: {currentDate.toLocaleString()}

Countdown: {counter} diff --git a/jahia-test-module/src/react/server/templates/EventDefault.tsx b/jahia-test-module/src/react/server/templates/EventDefault.tsx index 0e2ed4e7..fb15aec9 100644 --- a/jahia-test-module/src/react/server/templates/EventDefault.tsx +++ b/jahia-test-module/src/react/server/templates/EventDefault.tsx @@ -8,7 +8,6 @@ jahiaComponent( displayName: "Default event template", componentType: "template", }, - (_, { currentResource }) => { return ( diff --git a/jahia-test-module/src/react/server/templates/PageHome.tsx b/jahia-test-module/src/react/server/templates/PageHome.tsx index 14f3b795..632f9770 100644 --- a/jahia-test-module/src/react/server/templates/PageHome.tsx +++ b/jahia-test-module/src/react/server/templates/PageHome.tsx @@ -1,4 +1,4 @@ -import { AddResources, Render, Area, jahiaComponent } from "@jahia/javascript-modules-library"; +import { AddResources, Area, jahiaComponent, Render } from "@jahia/javascript-modules-library"; import { footer, header, login } from "./pageComponents"; jahiaComponent( diff --git a/jahia-test-module/src/react/server/views/testAbsoluteAreas/TestAbsoluteAreas.tsx b/jahia-test-module/src/react/server/views/testAbsoluteAreas/TestAbsoluteAreas.tsx index f5312f73..9546d77c 100644 --- a/jahia-test-module/src/react/server/views/testAbsoluteAreas/TestAbsoluteAreas.tsx +++ b/jahia-test-module/src/react/server/views/testAbsoluteAreas/TestAbsoluteAreas.tsx @@ -58,7 +58,7 @@ jahiaComponent( /> -

Non editable area

+

Non editable area

diff --git a/jahia-test-module/src/react/server/views/testAreas/TestAreas.tsx b/jahia-test-module/src/react/server/views/testAreas/TestAreas.tsx index 926b4e8d..227be010 100644 --- a/jahia-test-module/src/react/server/views/testAreas/TestAreas.tsx +++ b/jahia-test-module/src/react/server/views/testAreas/TestAreas.tsx @@ -36,7 +36,7 @@ jahiaComponent( -

Non editable area

+

Non editable area

diff --git a/jahia-test-module/src/react/server/views/testConfig/TestConfig.tsx b/jahia-test-module/src/react/server/views/testConfig/TestConfig.tsx index e07fa7f8..47b10ac2 100644 --- a/jahia-test-module/src/react/server/views/testConfig/TestConfig.tsx +++ b/jahia-test-module/src/react/server/views/testConfig/TestConfig.tsx @@ -52,7 +52,7 @@ jahiaComponent(

allConfigPIDs={server.config.getConfigPids()}

OSGi Config Complex Values

- {Object.keys(complexObject).map(function (key) { + {Object.keys(complexObject).map(function(key) { return (
{key}: {complexObject[key]} diff --git a/jahia-test-module/src/react/server/views/testGQL/TestGQL.tsx b/jahia-test-module/src/react/server/views/testGQL/TestGQL.tsx index 385d5877..5af0fc5b 100644 --- a/jahia-test-module/src/react/server/views/testGQL/TestGQL.tsx +++ b/jahia-test-module/src/react/server/views/testGQL/TestGQL.tsx @@ -10,8 +10,7 @@ jahiaComponent( }, (_, { currentNode }) => { const result = useGQLQuery({ - query: - "query ($path:String!) { jcr { nodeByPath(path:$path) { name, properties { name, value } } } }", + query: "query ($path:String!) { jcr { nodeByPath(path:$path) { name, properties { name, value } } } }", variables: { path: currentNode.getPath() }, }); const resultFromDocument = useGQLQuery({ diff --git a/jahia-test-module/src/react/server/views/testGetChildNodes/TestGetChildNodes.tsx b/jahia-test-module/src/react/server/views/testGetChildNodes/TestGetChildNodes.tsx index 2c621591..01c74a0f 100644 --- a/jahia-test-module/src/react/server/views/testGetChildNodes/TestGetChildNodes.tsx +++ b/jahia-test-module/src/react/server/views/testGetChildNodes/TestGetChildNodes.tsx @@ -19,8 +19,8 @@ const PrintChildren = ({ <>

${title}

- {children && - children.map(function (child, i) { + {children + && children.map(function(child, i) { return (
{child.getPath()} diff --git a/jahia-test-module/src/react/server/views/testGetNodeProps/TestGetNodeProps.tsx b/jahia-test-module/src/react/server/views/testGetNodeProps/TestGetNodeProps.tsx index 2d9944d2..8a886463 100644 --- a/jahia-test-module/src/react/server/views/testGetNodeProps/TestGetNodeProps.tsx +++ b/jahia-test-module/src/react/server/views/testGetNodeProps/TestGetNodeProps.tsx @@ -76,8 +76,8 @@ jahiaComponent( richText = false, ) => { return ( - values && - values.map(function (value, i) { + values + && values.map(function(value, i) { if (richText) { return (
{ return ( - values && - values.map(function (value, i) { + values + && values.map(function(value, i) { return (
{value.getPath()} diff --git a/jahia-test-module/src/react/server/views/testJCRQuery/TestJCRQuery.tsx b/jahia-test-module/src/react/server/views/testJCRQuery/TestJCRQuery.tsx index ebf68014..7d2773df 100644 --- a/jahia-test-module/src/react/server/views/testJCRQuery/TestJCRQuery.tsx +++ b/jahia-test-module/src/react/server/views/testJCRQuery/TestJCRQuery.tsx @@ -13,8 +13,8 @@ const PrintQueryResults = ({ <>

${title}

- {nodes && - nodes.map(function (node, i) { + {nodes + && nodes.map(function(node, i) { return (
{node.getPath()} diff --git a/jahia-test-module/src/react/server/views/testReactClientSide/TestReactClientSide.tsx b/jahia-test-module/src/react/server/views/testReactClientSide/TestReactClientSide.tsx index 3831f5dc..0604df62 100644 --- a/jahia-test-module/src/react/server/views/testReactClientSide/TestReactClientSide.tsx +++ b/jahia-test-module/src/react/server/views/testReactClientSide/TestReactClientSide.tsx @@ -1,6 +1,6 @@ -import { Island, jahiaComponent } from "@jahia/javascript-modules-library"; import SampleHydrateInBrowserReact from "$client/components/SampleHydrateInBrowserReact"; import SampleRenderInBrowserReact from "$client/components/SampleRenderInBrowserReact"; +import { Island, jahiaComponent } from "@jahia/javascript-modules-library"; jahiaComponent( { @@ -11,7 +11,7 @@ jahiaComponent( (_, { currentResource }) => { return ( <> -

Just a normal view, that is using a client side react component:

+

Just a normal view, that is using a client side react component:

Render generates editable items by default

- {allChildren && - allChildren.map(function (child) { + {allChildren + && allChildren.map(function(child) { return ; })}
@@ -22,8 +22,8 @@ jahiaComponent(

Render generates editable items when precised true

- {allChildren && - allChildren.map(function (child) { + {allChildren + && allChildren.map(function(child) { return ; })}
@@ -31,8 +31,8 @@ jahiaComponent(

Render generates non editable items when precised false

- {allChildren && - allChildren.map(function (child) { + {allChildren + && allChildren.map(function(child) { return ; })}
diff --git a/jahia-test-module/src/react/server/views/testUrl/TestUrl.tsx b/jahia-test-module/src/react/server/views/testUrl/TestUrl.tsx index 53b8f80e..bd5eff03 100644 --- a/jahia-test-module/src/react/server/views/testUrl/TestUrl.tsx +++ b/jahia-test-module/src/react/server/views/testUrl/TestUrl.tsx @@ -1,10 +1,10 @@ /// import { - jahiaComponent, - server, buildEndpointUrl, buildModuleFileUrl, buildNodeUrl, + jahiaComponent, + server, } from "@jahia/javascript-modules-library"; import goat from "./goat.png"; diff --git a/jahia-test-module/vite.config.mjs b/jahia-test-module/vite.config.mjs index 0072c1fd..82c92bc9 100644 --- a/jahia-test-module/vite.config.mjs +++ b/jahia-test-module/vite.config.mjs @@ -1,7 +1,7 @@ // @ts-check -import { defineConfig } from "vite"; import jahia from "@jahia/vite-plugin"; import path from "node:path"; +import { defineConfig } from "vite"; export default defineConfig({ resolve: { diff --git a/javascript-create-module/index.js b/javascript-create-module/index.js index b9d4ced6..26723286 100755 --- a/javascript-create-module/index.js +++ b/javascript-create-module/index.js @@ -8,8 +8,7 @@ import { styleText } from "node:util"; import pkg from "./package.json" with { type: "json" }; /** Renames the `dot` directory to dotfiles and dotdirs. */ -const renameDot = (/** @type {string} */ name) => - name.startsWith(`dot${path.sep}`) ? `.${name.slice(4)}` : name; +const renameDot = (/** @type {string} */ name) => name.startsWith(`dot${path.sep}`) ? `.${name.slice(4)}` : name; try { prompts.intro("Jahia JavaScript Module Creator"); @@ -31,8 +30,9 @@ Upgrade guide: ${styleText("underline", "https://nodejs.org/en/download")} initialValue: process.argv[2], validate(value) { if (!/^[a-z]/.test(value)) return "Module name must start with a lowercase letter."; - if (!/^[a-z0-9-]+$/.test(value)) + if (!/^[a-z0-9-]+$/.test(value)) { return "Module name can only contain lowercase letters, numbers, and hyphens."; + } }, }); @@ -116,9 +116,15 @@ Upgrade guide: ${styleText("underline", "https://nodejs.org/en/download")} Run the following commands to get started: ${styleText("dim", "1.")} ${styleText("greenBright", `cd ${output}`)} - ${styleText("dim", "2.")} ${styleText("cyanBright", "yarn install")} ${styleText("dim", "# Install dependencies")} - ${styleText("dim", "3.")} ${styleText("blueBright", "docker compose up --wait")} ${styleText("dim", "# Start Jahia in Docker")} - ${styleText("dim", "4.")} ${styleText("magentaBright", "yarn dev")} ${styleText("dim", "# Start the dev mode")} + ${styleText("dim", "2.")} ${styleText("cyanBright", "yarn install")} ${ + styleText("dim", "# Install dependencies") + } + ${styleText("dim", "3.")} ${styleText("blueBright", "docker compose up --wait")} ${ + styleText("dim", "# Start Jahia in Docker") + } + ${styleText("dim", "4.")} ${styleText("magentaBright", "yarn dev")} ${ + styleText("dim", "# Start the dev mode") + } The ${styleText("underline", "README.md")} file contains a reminder of all commands. `); diff --git a/javascript-create-module/templates/hello-world/src/components/Hello/World/Celebrate.client.tsx b/javascript-create-module/templates/hello-world/src/components/Hello/World/Celebrate.client.tsx index 137fe343..131eb298 100644 --- a/javascript-create-module/templates/hello-world/src/components/Hello/World/Celebrate.client.tsx +++ b/javascript-create-module/templates/hello-world/src/components/Hello/World/Celebrate.client.tsx @@ -1,9 +1,9 @@ import clsx from "clsx"; import { useEffect, useState } from "react"; -import classes from "./styles.module.css"; import { useTranslation } from "react-i18next"; +import classes from "./styles.module.css"; -export default function () { +export default function() { const [confetti, setConfetti] = useState(); useEffect(() => { diff --git a/javascript-create-module/templates/hello-world/src/components/Hello/World/default.server.tsx b/javascript-create-module/templates/hello-world/src/components/Hello/World/default.server.tsx index 59b2f389..d0545171 100644 --- a/javascript-create-module/templates/hello-world/src/components/Hello/World/default.server.tsx +++ b/javascript-create-module/templates/hello-world/src/components/Hello/World/default.server.tsx @@ -1,9 +1,4 @@ -import { - Island, - RenderChildren, - buildModuleFileUrl, - jahiaComponent, -} from "@jahia/javascript-modules-library"; +import { buildModuleFileUrl, Island, jahiaComponent, RenderChildren } from "@jahia/javascript-modules-library"; import { Trans, useTranslation } from "react-i18next"; import down from "./arrows/down.svg"; import left from "./arrows/left.svg"; diff --git a/javascript-create-module/templates/module/eslint.config.js b/javascript-create-module/templates/module/eslint.config.js index 9caa93a8..4b368e7f 100644 --- a/javascript-create-module/templates/module/eslint.config.js +++ b/javascript-create-module/templates/module/eslint.config.js @@ -1,11 +1,11 @@ // @ts-check -import { defineConfig } from "eslint/config"; +import eslintReact from "@eslint-react/eslint-plugin"; import { includeIgnoreFile } from "@eslint/compat"; import eslint from "@eslint/js"; -import tseslint from "typescript-eslint"; -import path from "node:path"; +import { defineConfig } from "eslint/config"; import globals from "globals"; -import eslintReact from "@eslint-react/eslint-plugin"; +import path from "node:path"; +import tseslint from "typescript-eslint"; export default defineConfig( { @@ -13,14 +13,11 @@ export default defineConfig( globals: { ...globals.browser, ...globals.node }, }, }, - // JS/TS recommended eslint.configs.recommended, { files: ["**/*.ts", "**/*.tsx"], extends: tseslint.configs.recommended }, - // React eslintReact.configs["recommended-typescript"], - // Ignore the same files as .gitignore includeIgnoreFile(path.resolve(import.meta.dirname, ".gitignore")), ); diff --git a/javascript-create-module/templates/module/vite.config.mjs b/javascript-create-module/templates/module/vite.config.mjs index 91dbaa52..1c0f80c2 100644 --- a/javascript-create-module/templates/module/vite.config.mjs +++ b/javascript-create-module/templates/module/vite.config.mjs @@ -1,6 +1,6 @@ -import { defineConfig } from "vite"; import jahia from "@jahia/vite-plugin"; import { spawnSync } from "node:child_process"; +import { defineConfig } from "vite"; export default defineConfig({ plugins: [ diff --git a/javascript-create-module/templates/template-set/src/templates/Layout.tsx b/javascript-create-module/templates/template-set/src/templates/Layout.tsx index 47beee8b..ebd4f072 100644 --- a/javascript-create-module/templates/template-set/src/templates/Layout.tsx +++ b/javascript-create-module/templates/template-set/src/templates/Layout.tsx @@ -1,8 +1,4 @@ -import { - AddResources, - buildModuleFileUrl, - useServerContext, -} from "@jahia/javascript-modules-library"; +import { AddResources, buildModuleFileUrl, useServerContext } from "@jahia/javascript-modules-library"; import type { ReactNode } from "react"; import "modern-normalize/modern-normalize.css"; diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/JavascriptModuleListener.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/JavascriptModuleListener.java index 9c79172e..b94fd4d8 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/JavascriptModuleListener.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/JavascriptModuleListener.java @@ -15,6 +15,13 @@ */ package org.jahia.modules.javascript.modules.engine; +import static org.jahia.modules.javascript.modules.engine.jshandler.JavascriptProtocolConnection.BUNDLE_HEADER_JAVASCRIPT_INIT_SCRIPT; + +import java.util.Arrays; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.stream.Collectors; import org.jahia.modules.javascript.modules.engine.jsengine.GraalVMEngine; import org.jahia.modules.javascript.modules.engine.registrars.Registrar; import org.osgi.framework.Bundle; @@ -25,14 +32,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Arrays; -import java.util.List; -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.stream.Collectors; - -import static org.jahia.modules.javascript.modules.engine.jshandler.JavascriptProtocolConnection.BUNDLE_HEADER_JAVASCRIPT_INIT_SCRIPT; - /** * Listener to execute scripts at activate/deactivate time */ @@ -47,7 +46,11 @@ public void setEngine(GraalVMEngine engine) { this.engine = engine; } - @Reference(service = Registrar.class, policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.MULTIPLE, policyOption = ReferencePolicyOption.GREEDY) + @Reference( + service = Registrar.class, + policy = ReferencePolicy.DYNAMIC, + cardinality = ReferenceCardinality.MULTIPLE, + policyOption = ReferencePolicyOption.GREEDY) public void addRegistrar(Registrar registrar) { for (Bundle bundle : getJavascriptModules()) { registrar.register(bundle); @@ -111,7 +114,7 @@ public List getJavascriptModules() { } public boolean isJavascriptModule(Bundle bundle) { - return bundle.getBundleId() != engine.getBundleContext().getBundle().getBundleId() && - bundle.getHeaders().get(BUNDLE_HEADER_JAVASCRIPT_INIT_SCRIPT) != null; + return bundle.getBundleId() != engine.getBundleContext().getBundle().getBundleId() + && bundle.getHeaders().get(BUNDLE_HEADER_JAVASCRIPT_INIT_SCRIPT) != null; } } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/injector/OSGiService.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/injector/OSGiService.java index 941a6412..a07eca66 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/injector/OSGiService.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/injector/OSGiService.java @@ -23,38 +23,28 @@ /** * Identify the annotated member as a reference of an OSGI Service. * - *

- * When the annotation is applied to a method, the method is the bind method of - * the reference. When the annotation is applied to a field, the field will - * contain the bound service(s) of the reference. + *

When the annotation is applied to a method, the method is the bind method of the reference. When the annotation + * is applied to a field, the field will contain the bound service(s) of the reference. * - *

- * This annotation is processed at runtime by {@link OSGiServiceInjector}. + *

This annotation is processed at runtime by {@link OSGiServiceInjector} . */ -@Target({ ElementType.METHOD, ElementType.FIELD }) +@Target({ElementType.METHOD, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface OSGiService { /** * The type of the service for this reference. * - *

- * If not specified, the type of the service for this reference is based - * upon how this annotation is used: - *

    - *
  • Annotated method - The type of the service is the type of the first - * argument of the method.
  • - *
  • Annotated field - The type of the service is the - * type of the field.
  • - *
+ *

If not specified, the type of the service for this reference is based upon how this annotation is used:

    + *
  • Annotated method - The type of the service is the type of the first argument of the method.
  • + *
  • Annotated field - The type of the service is the type of the field.
*/ Class service() default Object.class; /** * The OSGI filter for this reference. * - *

- * If not specified, no filter is used for service lookup. + *

If not specified, no filter is used for service lookup. */ String filter() default ""; } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/injector/OSGiServiceInjector.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/injector/OSGiServiceInjector.java index 76d44b9b..1381a3cf 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/injector/OSGiServiceInjector.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/injector/OSGiServiceInjector.java @@ -1,15 +1,14 @@ package org.jahia.modules.javascript.modules.engine.js.injector; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import javax.inject.Inject; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.reflect.FieldUtils; import org.apache.commons.lang3.reflect.MethodUtils; import org.jahia.osgi.BundleUtils; -import javax.inject.Inject; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - public class OSGiServiceInjector { public static void handleMethodInjection(Object data) throws IllegalAccessException, InvocationTargetException { for (Method method : MethodUtils.getMethodsListWithAnnotation(data.getClass(), Inject.class, true, true)) { @@ -21,11 +20,13 @@ public static void handleMethodInjection(Object data) throws IllegalAccessExcept } } - private static void handleMethodInjection(Object data, Method method) throws IllegalAccessException, InvocationTargetException { + private static void handleMethodInjection(Object data, Method method) + throws IllegalAccessException, InvocationTargetException { if (method.isAnnotationPresent(OSGiService.class) && method.getParameterTypes().length > 0) { OSGiService annotation = method.getAnnotation(OSGiService.class); - Class klass = annotation.service().equals(Object.class) ? method.getParameterTypes()[0] : annotation.service(); + Class klass = + annotation.service().equals(Object.class) ? method.getParameterTypes()[0] : annotation.service(); String filter = StringUtils.isNotEmpty(annotation.filter()) ? annotation.filter() : null; if (!method.isAccessible()) { @@ -50,5 +51,4 @@ private static void handleFieldInjection(Object data, Field field) throws Illega field.set(data, BundleUtils.getOsgiService(klass, filter)); } } - } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/mock/MockBodyContent.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/mock/MockBodyContent.java index aa520d50..07003b94 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/mock/MockBodyContent.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/mock/MockBodyContent.java @@ -1,22 +1,20 @@ package org.jahia.modules.javascript.modules.engine.js.mock; -import javax.servlet.jsp.tagext.BodyContent; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.io.Writer; +import javax.servlet.jsp.tagext.BodyContent; public class MockBodyContent extends BodyContent { private MockJspWriter writer; - public MockBodyContent(MockJspWriter writer) { super(writer); this.writer = writer; } - public Reader getReader() { return new StringReader(writer.getString()); } @@ -25,13 +23,11 @@ public String getString() { return writer.getString(); } - public void writeOut(Writer writer) throws IOException { - } - + public void writeOut(Writer writer) throws IOException {} - //--------------------------------------------------------------------- + // --------------------------------------------------------------------- // Delegating implementations of JspWriter's abstract methods - //--------------------------------------------------------------------- + // --------------------------------------------------------------------- public void clear() throws IOException { getEnclosingWriter().clear(); @@ -132,5 +128,4 @@ public void println(Object value) throws IOException { public void println(String value) throws IOException { getEnclosingWriter().println(value); } - } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/mock/MockJspWriter.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/mock/MockJspWriter.java index a7cda4c9..fdff6616 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/mock/MockJspWriter.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/mock/MockJspWriter.java @@ -15,17 +15,16 @@ */ package org.jahia.modules.javascript.modules.engine.js.mock; -import javax.servlet.jsp.JspWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; +import javax.servlet.jsp.JspWriter; /** * Mock implementation of the {@link javax.servlet.jsp.JspWriter} class. * - *

Used for testing the web framework; only necessary for testing - * applications when testing custom JSP tags. + *

Used for testing the web framework; only necessary for testing applications when testing custom JSP tags. * * @author Juergen Hoeller * @since 2.5 @@ -61,8 +60,7 @@ public void clear() throws IOException { init(); } - public void clearBuffer() throws IOException { - } + public void clearBuffer() throws IOException {} public void flush() throws IOException { targetWriter.flush(); diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/mock/MockPageContext.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/mock/MockPageContext.java index 9a5d018e..878e81b4 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/mock/MockPageContext.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/mock/MockPageContext.java @@ -15,8 +15,11 @@ */ package org.jahia.modules.javascript.modules.engine.js.mock; -import org.jahia.services.render.RenderContext; - +import java.io.IOException; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; import javax.el.ELContext; import javax.servlet.*; import javax.servlet.http.HttpSession; @@ -24,11 +27,7 @@ import javax.servlet.jsp.PageContext; import javax.servlet.jsp.el.ExpressionEvaluator; import javax.servlet.jsp.el.VariableResolver; -import java.io.IOException; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; +import org.jahia.services.render.RenderContext; public class MockPageContext extends PageContext { private final Map pageAttrs = Collections.synchronizedMap(new HashMap<>()); @@ -49,11 +48,16 @@ public void flushWriters() throws IOException { writer.flush(); } - public void initialize(Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL, boolean needSession, int bufferSize, boolean autoFlush) { - } + public void initialize( + Servlet servlet, + ServletRequest request, + ServletResponse response, + String errorPageURL, + boolean needSession, + int bufferSize, + boolean autoFlush) {} - public void release() { - } + public void release() {} public void setAttribute(String name, Object attribute) { this.pageAttrs.put(name, attribute); @@ -76,7 +80,6 @@ public void setAttribute(String name, Object attribute, int scope) { default: throw new IllegalArgumentException("Bad scope " + scope); } - } public Object getAttribute(String name) { @@ -118,7 +121,6 @@ public void removeAttribute(String name) { } else if (this.renderContext.getRequest().getSession().getAttribute(name) != null) { this.renderContext.getRequest().getSession().removeAttribute(name); } else this.appAttr.remove(name); - } public void removeAttribute(String name, int scope) { @@ -138,7 +140,6 @@ public void removeAttribute(String name, int scope) { default: throw new IllegalArgumentException("Bad scope " + scope); } - } public int getAttributesScope(String name) { @@ -189,20 +190,15 @@ public ServletContext getServletContext() { return null; } - public void forward(String path) { - } + public void forward(String path) {} - public void include(String path) { - } + public void include(String path) {} - public void handlePageException(Exception exc) { - } + public void handlePageException(Exception exc) {} - public void handlePageException(Throwable exc) { - } + public void handlePageException(Throwable exc) {} - public void include(String relativeUrlPath, boolean flush) { - } + public void include(String relativeUrlPath, boolean flush) {} public ExpressionEvaluator getExpressionEvaluator() { return null; diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/ConfigHelper.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/ConfigHelper.java index ea7ea247..e79367f7 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/ConfigHelper.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/ConfigHelper.java @@ -1,11 +1,10 @@ package org.jahia.modules.javascript.modules.engine.js.server; +import java.util.HashMap; import org.graalvm.polyglot.proxy.ProxyArray; import org.graalvm.polyglot.proxy.ProxyObject; import org.jahia.taglibs.functions.Functions; -import java.util.HashMap; - /** * Java helper to expose OSGi configuration values to Javascript code */ @@ -25,7 +24,8 @@ public ProxyArray getConfigPids() { * @return an array of String containing the OSGi configuration factory PIDs */ public ProxyArray getConfigFactoryIdentifiers(String factoryPid) { - return ProxyArray.fromArray(Functions.getConfigFactoryIdentifiers(factoryPid).toArray()); + return ProxyArray.fromArray( + Functions.getConfigFactoryIdentifiers(factoryPid).toArray()); } /** @@ -39,10 +39,9 @@ public ProxyObject getConfigValues(String configPid) { } /** - * Get the configuration values for a given OSGi configuration factory PID and - * factory identifier + * Get the configuration values for a given OSGi configuration factory PID and factory identifier * - * @param factoryPid the factory PID + * @param factoryPid the factory PID * @param factoryIdentifier the factory identifier within the given factory PID * @return a Map<String, Object> containing the configuration values */ @@ -51,11 +50,10 @@ public ProxyObject getConfigFactoryValues(String factoryPid, String factoryIdent } /** - * Get a single configuration value for a given OSGi configuration PID and a - * property key + * Get a single configuration value for a given OSGi configuration PID and a property key * * @param configPid the unique identifier of the OSGi configuration - * @param key the property key + * @param key the property key * @return a String containing the configuration value */ public String getConfigValue(String configPid, String key) { @@ -63,13 +61,12 @@ public String getConfigValue(String configPid, String key) { } /** - * Get a single configuration value for a given OSGi configuration factory PID, - * factory identifier and a - * property key + * Get a single configuration value for a given OSGi configuration factory PID, factory identifier and a property + * key * - * @param factoryPid the factory PID + * @param factoryPid the factory PID * @param factoryIdentifier the factory identifier within the given factory PID - * @param key the property key + * @param key the property key * @return a String containing the configuration value */ public String getConfigFactoryValue(String factoryPid, String factoryIdentifier, String key) { diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/JcrHelper.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/JcrHelper.java index 7a8cb719..1ed84352 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/JcrHelper.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/JcrHelper.java @@ -1,7 +1,6 @@ package org.jahia.modules.javascript.modules.engine.js.server; import java.util.Locale; - import org.jahia.services.content.JCRCallback; import org.jahia.services.content.JCRTemplate; import org.jahia.services.usermanager.JahiaUserManagerService; @@ -16,9 +15,8 @@ public class JcrHelper { private static final Logger logger = LoggerFactory.getLogger(JcrHelper.class); /** - * Execute JCR operations on a JCR session authenticated using the guest user - * and the "live" workspace. - * This is intended for server-side use. Example: + * Execute JCR operations on a JCR session authenticated using the guest user and the "live" workspace. This is + * intended for server-side use. Example: * *

      *     import {server, useServerContext} from '@jahia/javascript-modules-library';
diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/OSGiHelper.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/OSGiHelper.java
index c37d51bc..6a34346d 100644
--- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/OSGiHelper.java
+++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/OSGiHelper.java
@@ -15,6 +15,12 @@
  */
 package org.jahia.modules.javascript.modules.engine.js.server;
 
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.*;
+import java.util.stream.Collectors;
+import javax.inject.Inject;
 import org.graalvm.polyglot.proxy.ProxyObject;
 import org.jahia.data.templates.JahiaTemplatesPackage;
 import org.jahia.modules.javascript.modules.engine.js.injector.OSGiService;
@@ -26,16 +32,8 @@
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import javax.inject.Inject;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.*;
-import java.util.stream.Collectors;
-
 /**
- * Helper class to make it possible to access OSGi bundle resources from the
- * JavaScript engine
+ * Helper class to make it possible to access OSGi bundle resources from the JavaScript engine
  */
 public class OSGiHelper {
     private static final Logger logger = LoggerFactory.getLogger(OSGiHelper.class);
@@ -49,9 +47,8 @@ public void setTemplateManagerService(JahiaTemplateManagerService templateManage
     }
 
     /**
-     * Retrieves an OSGi service instance by its fully qualified class name.
-     * An interface name can be used as long as a service properly declares
-     * implementing it.
+     * Retrieves an OSGi service instance by its fully qualified class name. An interface name can be used as long as a
+     * service properly declares implementing it.
      *
      * @param clazz the fully qualified class name of the OSGi service
      * @return the OSGi instance associated to the fully qualified class name
@@ -61,11 +58,10 @@ public Object getService(String clazz) {
     }
 
     /**
-     * Retrieves an OSGi service instance by its fully qualified class name.
-     * An interface name can be used as long as a service properly declares
-     * implementing it.
+     * Retrieves an OSGi service instance by its fully qualified class name. An interface name can be used as long as a
+     * service properly declares implementing it.
      *
-     * @param clazz  the fully qualified class name of the OSGi service
+     * @param clazz the fully qualified class name of the OSGi service
      * @param filter the filter to apply to the service
      * @return the OSGi instance associated to the fully qualified class name
      */
@@ -90,12 +86,11 @@ public Bundle getBundle(String symbolicName) {
     /**
      * Load a resource from an OSGi bundle
      *
-     * @param bundle   the bundle to load the resource from
-     * @param path     the path to the resource in the bundle
-     * @param optional if false an error message will be logged if the resource is
-     *                 not found, otherwise null will be returned
-     * @return a String containing the content of the resource if it was found, null
-     *         otherwise
+     * @param bundle the bundle to load the resource from
+     * @param path the path to the resource in the bundle
+     * @param optional if false an error message will be logged if the resource is not found, otherwise null will be
+     * returned
+     * @return a String containing the content of the resource if it was found, null otherwise
      * @throws RenderException
      */
     public String loadResource(Bundle bundle, String path, boolean optional) throws RenderException {
@@ -111,7 +106,7 @@ public String loadResource(Bundle bundle, String path, boolean optional) throws
      * Load a properties resource from an OSGi bundle
      *
      * @param bundle the bundle to load the resource from
-     * @param path   the path to the resource in the bundle
+     * @param path the path to the resource in the bundle
      * @return A Map<String,String> containing the properties
      * @throws RenderException
      */
@@ -121,8 +116,8 @@ public ProxyObject loadPropertiesResource(Bundle bundle, String path) throws Ren
             Properties properties = new Properties();
             try (InputStream inStream = url.openStream()) {
                 properties.load(inStream);
-                return ProxyObject.fromMap(properties.entrySet().stream().collect(
-                        Collectors.toMap(
+                return ProxyObject.fromMap(properties.entrySet().stream()
+                        .collect(Collectors.toMap(
                                 e -> String.valueOf(e.getKey()),
                                 e -> String.valueOf(e.getValue()),
                                 (prev, next) -> next)));
diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/RegistryHelper.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/RegistryHelper.java
index ac22cee4..45c9416c 100644
--- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/RegistryHelper.java
+++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/RegistryHelper.java
@@ -15,16 +15,14 @@
  */
 package org.jahia.modules.javascript.modules.engine.js.server;
 
-import org.graalvm.polyglot.proxy.ProxyObject;
-import org.jahia.modules.javascript.modules.engine.jsengine.Registry;
-
 import java.util.List;
 import java.util.Map;
 import java.util.stream.Collectors;
+import org.graalvm.polyglot.proxy.ProxyObject;
+import org.jahia.modules.javascript.modules.engine.jsengine.Registry;
 
 /**
- * Helper class to make it possible to access the registry from the JavaScript
- * engine
+ * Helper class to make it possible to access the registry from the JavaScript engine
  */
 public class RegistryHelper {
     private final Registry registry;
@@ -37,7 +35,7 @@ public RegistryHelper(Registry registry) {
      * Get an object from the registry by type and key
      *
      * @param type the type of the object to retrieve
-     * @param key  the key in the type of the object to retrieve
+     * @param key the key in the type of the object to retrieve
      * @return the object if found as a Map<String,Object>, otherwise null
      */
     public Object get(String type, String key) {
@@ -50,45 +48,36 @@ public Object get(String type, String key) {
     }
 
     /**
-     * Search objects from the registry by using a map filter. The filter is a map
-     * of key-value pairs that will be used
-     * to match objects that have the same values for the keys specified in the
-     * filter.
+     * Search objects from the registry by using a map filter. The filter is a map of key-value pairs that will be used
+     * to match objects that have the same values for the keys specified in the filter.
      *
      * @param filter a map of key-value pairs to filter the objects to retrieve
      * @return a List of matching objects
      */
     public List find(Map filter) {
-        return registry.find(filter).stream().map(ProxyObject::fromMap)
-                .collect(Collectors.toList());
+        return registry.find(filter).stream().map(ProxyObject::fromMap).collect(Collectors.toList());
     }
 
     /**
-     * Search objects from the registry by using a map filter and an order by
-     * clause. The filter is a map of key-value
-     * pairs that will be used to match objects that have the same values for the
-     * keys specified in the filter.
+     * Search objects from the registry by using a map filter and an order by clause. The filter is a map of key-value
+     * pairs that will be used to match objects that have the same values for the keys specified in the filter.
      *
-     * @param filter  a map of key-value pairs to filter the objects to retrieve
-     * @param orderBy a string representing the key to use to order the resulting
-     *                objects. Not that this only works if
-     *                the key refers to an integer value
+     * @param filter a map of key-value pairs to filter the objects to retrieve
+     * @param orderBy a string representing the key to use to order the resulting objects. Not that this only works if
+     * the key refers to an integer value
      * @return a sorted List of matching objects
      */
     public List find(Map filter, String orderBy) {
-        return registry.find(filter, orderBy).stream().map(ProxyObject::fromMap)
-                .collect(Collectors.toList());
+        return registry.find(filter, orderBy).stream().map(ProxyObject::fromMap).collect(Collectors.toList());
     }
 
     /**
-     * Add a new object in the registry. The object is a map of key-value pairs that
-     * will be stored using the specified
-     * type and key. Note that if the object already exists, an exception will be
-     * thrown. If you want to force the
+     * Add a new object in the registry. The object is a map of key-value pairs that will be stored using the specified
+     * type and key. Note that if the object already exists, an exception will be thrown. If you want to force the
      * object to be store you should instead use the addOrReplace method.
      *
-     * @param type      the type of the object to store
-     * @param key       the key of the object to store within the type
+     * @param type the type of the object to store
+     * @param key the key of the object to store within the type
      * @param arguments a Map of key-value pairs representing the object to store
      */
     public void add(String type, String key, Map... arguments) {
@@ -96,13 +85,11 @@ public void add(String type, String key, Map... arguments) {
     }
 
     /**
-     * Add a new object in the registry or replace an existing one. The object is a
-     * map of key-value pairs that will be
-     * stored using the specified type and key. If the object already exists, it
-     * will be replaced by the new one.
+     * Add a new object in the registry or replace an existing one. The object is a map of key-value pairs that will be
+     * stored using the specified type and key. If the object already exists, it will be replaced by the new one.
      *
-     * @param type      the type of the object to store
-     * @param key       the key of the object to store within the type
+     * @param type the type of the object to store
+     * @param key the key of the object to store within the type
      * @param arguments a Map of key-value pairs representing the object to store
      */
     public void addOrReplace(String type, String key, Map... arguments) {
@@ -113,7 +100,7 @@ public void addOrReplace(String type, String key, Map... argumen
      * Remove an object from the registry by type and key
      *
      * @param type the type of the object to remove
-     * @param key  the key of the object to remove within the type
+     * @param key the key of the object to remove within the type
      */
     public void remove(String type, String key) {
         registry.remove(type, key);
diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/RenderHelper.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/RenderHelper.java
index 08da5727..2c6a27cf 100644
--- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/RenderHelper.java
+++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/RenderHelper.java
@@ -15,12 +15,25 @@
  */
 package org.jahia.modules.javascript.modules.engine.js.server;
 
+import java.io.IOException;
+import java.io.Serializable;
+import java.lang.reflect.InvocationTargetException;
+import java.net.URLDecoder;
+import java.util.*;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+import javax.inject.Inject;
+import javax.jcr.RepositoryException;
+import javax.servlet.jsp.JspException;
+import javax.servlet.jsp.tagext.BodyTagSupport;
+import javax.servlet.jsp.tagext.TagSupport;
 import org.apache.commons.beanutils.BeanUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.jackrabbit.util.Text;
 import org.apache.taglibs.standard.tag.common.core.ParamParent;
 import org.graalvm.polyglot.proxy.ProxyArray;
 import org.graalvm.polyglot.proxy.ProxyObject;
+import org.jahia.api.Constants;
 import org.jahia.modules.javascript.modules.engine.js.injector.OSGiService;
 import org.jahia.modules.javascript.modules.engine.js.mock.MockBodyContent;
 import org.jahia.modules.javascript.modules.engine.js.mock.MockPageContext;
@@ -39,38 +52,32 @@
 import org.jahia.taglibs.uicomponents.Functions;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.jahia.api.Constants;
-
-import javax.annotation.Nullable;
-import javax.inject.Inject;
-import javax.jcr.RepositoryException;
-import javax.servlet.jsp.JspException;
-import javax.servlet.jsp.tagext.BodyTagSupport;
-import javax.servlet.jsp.tagext.TagSupport;
-import java.io.IOException;
-import java.io.Serializable;
-import java.lang.reflect.InvocationTargetException;
-import java.net.URLDecoder;
-import java.util.*;
-import java.util.stream.Collectors;
 
 /**
  * Helper class to provide rendering functions to the Javascript engine
  */
 public class RenderHelper {
     private static final Logger logger = LoggerFactory.getLogger(RenderHelper.class);
-    private static final Set ABSOLUTEAREA_ALLOWED_ATTRIBUTES = Set.of("name", "parent", "view",
-            "allowedNodeTypes", "numberOfItems", "nodeType", "editable", "areaType", "limitedAbsoluteAreaEdit",
+    private static final Set ABSOLUTEAREA_ALLOWED_ATTRIBUTES = Set.of(
+            "name",
+            "parent",
+            "view",
+            "allowedNodeTypes",
+            "numberOfItems",
+            "nodeType",
+            "editable",
+            "areaType",
+            "limitedAbsoluteAreaEdit",
             "parameters");
-    private static final Set AREA_ALLOWED_ATTRIBUTES = Set.of("name", "view", "allowedNodeTypes",
-            "numberOfItems", "nodeType", "editable", "parameters");
+    private static final Set AREA_ALLOWED_ATTRIBUTES =
+            Set.of("name", "view", "allowedNodeTypes", "numberOfItems", "nodeType", "editable", "parameters");
 
     private JCRSessionFactory jcrSessionFactory;
     private JCRTemplate jcrTemplate;
     private RenderService renderService;
 
-    public ProxyObject transformToJsNode(JCRNodeWrapper node, boolean includeChildren, boolean includeDescendants,
-            boolean includeAllTranslations) throws RepositoryException {
+    public ProxyObject transformToJsNode(
+            JCRNodeWrapper node, boolean includeChildren, boolean includeDescendants, boolean includeAllTranslations) throws RepositoryException {
         return recursiveProxyMap(
                 JSNodeMapper.toJSNode(node, includeChildren, includeDescendants, includeAllTranslations));
     }
@@ -87,10 +94,9 @@ public ProxyObject getRenderParameters(Resource resource) {
     }
 
     /**
-     * Does a URL encoding of the path. The characters that
-     * don't need encoding are those defined 'unreserved' in section 2.3 of
-     * the 'URI generic syntax' RFC 2396. Not the entire path string is escaped,
-     * but every individual part (i.e. the slashes are not escaped).
+     * Does a URL encoding of the path. The characters that don't need encoding are those defined
+     * 'unreserved' in section 2.3 of the 'URI generic syntax' RFC 2396. Not the entire path string is escaped, but
+     * every individual part (i.e. the slashes are not escaped).
      *
      * @param path the path to encode
      * @return a String containing the escaped path
@@ -101,25 +107,24 @@ public String escapePath(String path) {
     }
 
     /**
-     * Find the first displayable node in the given node's hierarchy. A displayable
-     * node is a node that has a content
-     * or page template associated with it.
+     * Find the first displayable node in the given node's hierarchy. A displayable node is a node that has a content or
+     * page template associated with it.
      *
-     * @param node          the node at which to start the resolution
+     * @param node the node at which to start the resolution
      * @param renderContext the current render context
-     * @param contextSite   the site in which to resolve the template
+     * @param contextSite the site in which to resolve the template
      * @return the first displayable {@link JCRNodeWrapper} found in the hierarchy
      */
-    public JCRNodeWrapper findDisplayableNode(JCRNodeWrapper node, RenderContext renderContext,
-            @Nullable JCRSiteNode contextSite) {
+    public JCRNodeWrapper findDisplayableNode(
+            JCRNodeWrapper node, RenderContext renderContext, @Nullable JCRSiteNode contextSite) {
         return JCRContentUtils.findDisplayableNode(node, renderContext, contextSite);
     }
 
     /**
-     * Returns the node which corresponds to the bound component of the
-     * j:bindedComponent property in the specified node.
+     * Returns the node which corresponds to the bound component of the j:bindedComponent property in the specified
+     * node.
      *
-     * @param node    the node to get the bound component for
+     * @param node the node to get the bound component for
      * @param context current render context
      * @return the bound {@link JCRNodeWrapper}
      */
@@ -134,14 +139,16 @@ public String renderComponent(Map attr, RenderContext renderContext)
         if (user == null) {
             user = jcrSessionFactory.getCurrentUser();
         }
-        return jcrTemplate.doExecuteWithSystemSessionAsUser(user, renderContext.getWorkspace(),
-                renderContext.getMainResource().getLocale(), session -> {
-
-                    JCRNodeWrapper node = JSNodeMapper.toVirtualNode((Map) attr.get("content"), session,
-                            renderContext);
-                    String renderConfig = attr.get("advanceRenderingConfig") != null
-                            ? (String) attr.get("advanceRenderingConfig")
-                            : "";
+        return jcrTemplate.doExecuteWithSystemSessionAsUser(
+                user,
+                renderContext.getWorkspace(),
+                renderContext.getMainResource().getLocale(),
+                session -> {
+
+                    JCRNodeWrapper node =
+                            JSNodeMapper.toVirtualNode((Map) attr.get("content"), session, renderContext);
+                    String renderConfig =
+                            attr.get("advanceRenderingConfig") != null ? (String) attr.get("advanceRenderingConfig") : "";
                     String templateType = attr.get("templateType") != null ? (String) attr.get("templateType") : "html";
 
                     if ("OPTION".equals(renderConfig)) {
@@ -157,7 +164,10 @@ public String renderComponent(Map attr, RenderContext renderContext)
                             throw new RepositoryException(e);
                         }
                     } else {
-                        Resource r = new Resource(node, templateType, (String) attr.get("view"),
+                        Resource r = new Resource(
+                                node,
+                                templateType,
+                                (String) attr.get("view"),
                                 "INCLUDE".equals(renderConfig) ? "include" : "module");
                         r.getModuleParams().put(Constants.TO_CACHE_WITH_PARENT_FRAGMENT, true);
 
@@ -170,8 +180,10 @@ public String renderComponent(Map attr, RenderContext renderContext)
                                     // only allow String params for compatibility reasons due to JSP ParamParent
                                     // parameters being a  map
                                     if (renderParam.getValue() instanceof String) {
-                                        r.getModuleParams().put(URLDecoder.decode(renderParam.getKey(), charset),
-                                                URLDecoder.decode((String) renderParam.getValue(), charset));
+                                        r.getModuleParams()
+                                                .put(
+                                                        URLDecoder.decode(renderParam.getKey(), charset),
+                                                        URLDecoder.decode((String) renderParam.getValue(), charset));
                                     }
                                 }
                             }
@@ -184,8 +196,12 @@ public String renderComponent(Map attr, RenderContext renderContext)
                 });
     }
 
-    public String createContentButtons(String childName, String nodeTypes, boolean editCheck,
-            RenderContext renderContext, Resource currentResource)
+    public String createContentButtons(
+            String childName,
+            String nodeTypes,
+            boolean editCheck,
+            RenderContext renderContext,
+            Resource currentResource)
             throws JspException, InvocationTargetException, IllegalAccessException, RepositoryException, IOException {
         boolean childExists = !"*".equals(childName) && currentResource.getNode().hasNode(childName);
         if (!childExists && (!editCheck || renderContext.isEditMode())) {
@@ -223,8 +239,8 @@ public String render(Map attr, RenderContext renderContext, Reso
             }
         }
 
-        String renderConfig = attr.get("advanceRenderingConfig") != null ? (String) attr.get("advanceRenderingConfig")
-                : "";
+        String renderConfig =
+                attr.get("advanceRenderingConfig") != null ? (String) attr.get("advanceRenderingConfig") : "";
         switch (renderConfig) {
             case "INCLUDE": {
                 return renderTag(new IncludeTag(), attr, renderContext);
@@ -239,68 +255,35 @@ public String render(Map attr, RenderContext renderContext, Reso
     }
 
     /**
-     * Render a tag that adds resources to the page. Resources might for example be
-     * CSS files, Javascript files or inline
+     * Render a tag that adds resources to the page. Resources might for example be CSS files, Javascript files or
+     * inline
      *
-     * @param attr          may contain the following:
-     *                      
    - *
  • insert (boolean) : If true, the resource will be - * inserted into the document. Typically used - * for on-demand loading of resources.
  • - *
  • async (boolean) : If true, the resource will be - * loaded asynchronously. For scripts, this means - * the script - * will be executed as soon as it's available, without - * blocking the rest of the page.
  • - *
  • defer (boolean) : If true, the resource will be - * deferred, i.e., loaded after the document - * has been parsed. - * For scripts, this means the script will not be executed - * until after the page has loaded.
  • - *
  • type (string) : The type of the resource. This could - * be 'javascript' for .js files, 'css' for - * .css files, etc. - * The type will be used to resolve the directory in the - * module where the resources are located. For example - * for the 'css' type it will look for the resources in the - * css directory of the module.
  • - *
  • resources (string) : The path to the resource file, - * relative to the module. It is also allowed to - * specify multiple resources by separating them with - * commas. It is also allowed to use absolute URLs to - * include remote resources.
  • - *
  • inlineResource (string) : Inline HTML that markup - * will be considered as a resource.
  • - *
  • title (string) : The title of the resource. This is - * typically not used for scripts or stylesheets, - * but may be used for other types of resources.
  • - *
  • key (string) : A unique key for the resource. This - * could be used to prevent duplicate resources - * from being added to the document.
  • - *
  • targetTag (string): The HTML tag where the resource - * should be added. This could be 'head' for - * resources that should be added to the <head> tag, - * 'body' for resources that should be added to - * the <body> tag, etc.
  • - *
  • rel (string) : The relationship of the resource to - * the document. This is typically 'stylesheet' - * for CSS files.
  • - *
  • media (string) : The media for which the resource is - * intended. This is typically used for CSS - * files, with values like 'screen', 'print', etc.
  • - *
  • condition (string) : A condition that must be met - * for the resource to be loaded. This could be - * used for conditional comments in IE, for example.
  • - *
+ * @param attr may contain the following:
  • insert (boolean) : If true, the resource will be inserted into + * the document. Typically used for on-demand loading of resources.
  • async (boolean) : If true, the resource + * will be loaded asynchronously. For scripts, this means the script will be executed as soon as it's available, + * without blocking the rest of the page.
  • defer (boolean) : If true, the resource will be deferred, i.e., + * loaded after the document has been parsed. For scripts, this means the script will not be executed until after + * the page has loaded.
  • type (string) : The type of the resource. This could be 'javascript' for .js files, + * 'css' for .css files, etc. The type will be used to resolve the directory in the module where the resources are + * located. For example for the 'css' type it will look for the resources in the css directory of the module.
  • + *
  • resources (string) : The path to the resource file, relative to the module. It is also allowed to specify + * multiple resources by separating them with commas. It is also allowed to use absolute URLs to include remote + * resources.
  • inlineResource (string) : Inline HTML that markup will be considered as a resource.
  • + *
  • title (string) : The title of the resource. This is typically not used for scripts or stylesheets, but may be + * used for other types of resources.
  • key (string) : A unique key for the resource. This could be used to + * prevent duplicate resources from being added to the document.
  • targetTag (string): The HTML tag where the + * resource should be added. This could be 'head' for resources that should be added to the <head> tag, 'body' + * for resources that should be added to the <body> tag, etc.
  • rel (string) : The relationship of the + * resource to the document. This is typically 'stylesheet' for CSS files.
  • media (string) : The media for + * which the resource is intended. This is typically used for CSS files, with values like 'screen', 'print', + * etc.
  • condition (string) : A condition that must be met for the resource to be loaded. This could be used + * for conditional comments in IE, for example.
* @param renderContext the current rendering context - * @return a String containing the rendered HTML tags for the provided - * resources. - * @throws IllegalAccessException if the underlying tag cannot be accessed + * @return a String containing the rendered HTML tags for the provided resources. + * @throws IllegalAccessException if the underlying tag cannot be accessed * @throws InvocationTargetException if the underlying tag cannot be invoked - * @throws JspException if the underlying tag throws a JSP - * exception - * @throws IOException if the underlying tag throws an IO - * exception + * @throws JspException if the underlying tag throws a JSP exception + * @throws IOException if the underlying tag throws an IO exception */ public String addResources(Map attr, RenderContext renderContext) throws IllegalAccessException, InvocationTargetException, JspException, IOException { @@ -313,30 +296,18 @@ public String addResources(Map attr, RenderContext renderContext } /** - * Add a cache dependency to the current resource. This will be used to flush - * the current resource when the + * Add a cache dependency to the current resource. This will be used to flush the current resource when the * dependencies are modified. * - * @param attr may be the following: - *
    - *
  • node (JCRNodeWrapper) : The node to add as a - * dependency.
  • - *
  • uuid (String) : The UUID of the node to add as a - * dependency.
  • - *
  • path (String) : The path of the node to add as a - * dependency.
  • - *
  • flushOnPathMatchingRegexp (String) : A regular - * expression that will be used to flush the cache - * when the path of the modified nodes matches the regular - * expression.
  • - *
+ * @param attr may be the following:
  • node (JCRNodeWrapper) : The node to add as a dependency.
  • uuid + * (String) : The UUID of the node to add as a dependency.
  • path (String) : The path of the node to add as a + * dependency.
  • flushOnPathMatchingRegexp (String) : A regular expression that will be used to flush the + * cache when the path of the modified nodes matches the regular expression.
* @param renderContext the current rendering context - * @throws IllegalAccessException if the underlying tag cannot be accessed + * @throws IllegalAccessException if the underlying tag cannot be accessed * @throws InvocationTargetException if the underlying tag cannot be invoked - * @throws JspException if the underlying tag throws a JSP - * exception - * @throws IOException if the underlying tag throws an IO - * exception + * @throws JspException if the underlying tag throws a JSP exception + * @throws IOException if the underlying tag throws an IO exception */ public void addCacheDependency(Map attr, RenderContext renderContext) throws IllegalAccessException, InvocationTargetException, JspException, IOException { @@ -346,12 +317,9 @@ public void addCacheDependency(Map attr, RenderContext renderCon /** * Calculate the relative path from one node to another node. * - * @param currentPath the path of the current node from which to calculate the - * relative path - * @param basePath the path of the base node to which to calculate the - * relative path - * @return the relative path from currentPath to - * basePath + * @param currentPath the path of the current node from which to calculate the relative path + * @param basePath the path of the base node to which to calculate the relative path + * @return the relative path from currentPath to basePath */ static String calculateRelativePath(String currentPath, String basePath) { // special case when the parent is the current node @@ -363,7 +331,8 @@ static String calculateRelativePath(String currentPath, String basePath) { // Find the common prefix length int commonLength = 0; - while (commonLength < currentPathParts.length && commonLength < parentPathParts.length + while (commonLength < currentPathParts.length + && commonLength < parentPathParts.length && currentPathParts[commonLength].equals(parentPathParts[commonLength])) { commonLength++; } @@ -447,7 +416,7 @@ private String internalRenderArea(Map attr, String moduleType, R } areaAttr.put("areaType", areaAttr.remove("nodeType")); areaAttr.put("level", -1); // force the "path" parameter to be computed against the root node of the site - // (ex: /sites/) + // (ex: /sites/) // Now we remove any null attribute to make sure they don't override default tag // attributes @@ -466,7 +435,8 @@ private String renderTag(TagSupport tag, Map attr, RenderContext throws IllegalAccessException, InvocationTargetException, JspException, IOException { Map renderParameters = (Map) attr.get("parameters"); if (renderParameters != null && !renderParameters.isEmpty() && tag instanceof ParamParent) { - for (Map.Entry tagParam : renderParameters.entrySet()) { + for (Map.Entry< + String, Serializable> tagParam : renderParameters.entrySet()) { // only allow String params due to ParamParent parameters being a // map if (tagParam.getValue() instanceof String) { @@ -507,13 +477,17 @@ private ProxyObject recursiveProxyMap(Map mapToProxy) { mapToProxy.put(entry.getKey(), recursiveProxyMap((Map) entry.getValue())); } if (entry.getValue() instanceof Collection) { - mapToProxy.put(entry.getKey(), - ProxyArray.fromList((List) ((Collection) entry.getValue()).stream().map(o -> { - if (o instanceof Map) { - return recursiveProxyMap((Map) o); - } - return o; - }).collect(Collectors.toList()))); + mapToProxy.put( + entry.getKey(), + ProxyArray.fromList( + (List) ((Collection) entry.getValue()).stream() + .map(o -> { + if (o instanceof Map) { + return recursiveProxyMap((Map) o); + } + return o; + }) + .collect(Collectors.toList()))); } } return ProxyObject.fromMap(mapToProxy); @@ -556,5 +530,4 @@ private void checkAttributes(Map attributes, Set allowed } } } - } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/gql/GQLHelper.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/gql/GQLHelper.java index 58e2182a..4f76577b 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/gql/GQLHelper.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/gql/GQLHelper.java @@ -16,6 +16,11 @@ package org.jahia.modules.javascript.modules.engine.js.server.gql; import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.util.*; +import javax.inject.Inject; +import javax.servlet.*; +import javax.servlet.http.*; import org.jahia.modules.javascript.modules.engine.js.injector.OSGiService; import org.jahia.services.render.RenderContext; import org.jahia.services.securityfilter.PermissionService; @@ -23,13 +28,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import javax.servlet.*; -import javax.servlet.http.*; -import java.io.IOException; -import java.util.*; - -/** Helper class to execute GraphQL queries. */ +/** + * Helper class to execute GraphQL queries. + */ public class GQLHelper { private static final Logger logger = LoggerFactory.getLogger(GQLHelper.class); @@ -38,22 +39,13 @@ public class GQLHelper { private PermissionService permissionService; /** - * Execute a synchronous GraphQL query using the specified parameters and return - * the result + * Execute a synchronous GraphQL query using the specified parameters and return the result * - * @param parameters the parameters can contain the following keys: - *
    - *
  • query (string) : the GraphQL query to be executed
  • - *
  • operationName (string) : the GraphQL operation name - *
  • - *
  • variables: the variables as a JSON string or a - * Map<String, Object>
  • - *
  • renderContext (RenderContext) : the render context - * if the renderContext is null, a request will be created - * with the parameters that were passed, - * otherwise the request from the renderContext will be used. - *
  • - *
+ * @param parameters the parameters can contain the following keys:
  • query (string) : the GraphQL query to + * be executed
  • operationName (string) : the GraphQL operation name
  • variables: the variables as a + * JSON string or a Map<String, Object>
  • renderContext (RenderContext) : the render context if the + * renderContext is null, a request will be created with the parameters that were passed, otherwise the request from + * the renderContext will be used.
* @return the result of the query as a JSON string * @throws ServletException * @throws IOException @@ -76,7 +68,8 @@ public String executeQuerySync(Map parameters) throws ServletExceptio || currentScopes.stream().noneMatch(scope -> "graphql".equals(scope.getScopeName()))) { // Inject graphql scope if missing Optional graphqlScope = permissionService.getAvailableScopes().stream() - .filter(scope -> scope.getScopeName().equals("graphql")).findFirst(); + .filter(scope -> scope.getScopeName().equals("graphql")) + .findFirst(); if (graphqlScope.isPresent()) { Set newScopes = new HashSet<>(); if (currentScopes != null) { @@ -91,7 +84,8 @@ public String executeQuerySync(Map parameters) throws ServletExceptio } RenderContext renderContext = (RenderContext) parameters.get("renderContext"); - HttpServletRequest request = renderContext == null ? new HttpServletRequestMock(params) + HttpServletRequest request = renderContext == null + ? new HttpServletRequestMock(params) : new HttpServletRequestWrapper(renderContext.getRequest()) { public String getParameter(String name) { if (params.containsKey(name)) { @@ -112,9 +106,10 @@ public void setPermissionService(PermissionService permissionService) { } @Inject - @OSGiService(service = HttpServlet.class, filter = "(component.name=graphql.kickstart.servlet.OsgiGraphQLHttpServlet)") + @OSGiService( + service = HttpServlet.class, + filter = "(component.name=graphql.kickstart.servlet.OsgiGraphQLHttpServlet)") public void setServlet(HttpServlet servlet) { this.servlet = servlet; } - } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/gql/HttpServletRequestMock.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/gql/HttpServletRequestMock.java index 528df190..c8550065 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/gql/HttpServletRequestMock.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/gql/HttpServletRequestMock.java @@ -1,33 +1,29 @@ package org.jahia.modules.javascript.modules.engine.js.server.gql; -import javax.servlet.*; -import javax.servlet.http.*; import java.io.BufferedReader; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.Principal; import java.util.*; +import javax.servlet.*; +import javax.servlet.http.*; /** - * A mock implementation of {@link HttpServletRequest} used for testing and server-side rendering - * within the Jahia JavaScript modules engine. + * A mock implementation of {@link HttpServletRequest} used for testing and server-side rendering within the Jahia + * JavaScript modules engine. * - *

This class provides a minimal, non-functional implementation of the HttpServletRequest interface - * that can be used in environments where a real HTTP request context is not available, such as during - * server-side rendering of JavaScript components or in unit tests.

+ *

This class provides a minimal, non-functional implementation of the HttpServletRequest interface that can be used + * in environments where a real HTTP request context is not available, such as during server-side rendering of + * JavaScript components or in unit tests.

* - *

Key characteristics of this mock implementation:

- *
    - *
  • Returns sensible default values for most methods (null, empty collections, or false)
  • - *
  • Always returns "GET" as the HTTP method
  • - *
  • Returns "/" as the path info
  • - *
  • Supports basic parameter retrieval through the constructor-provided parameter map
  • - *
  • Does not maintain session state or authentication information
  • - *
+ *

Key characteristics of this mock implementation:

  • Returns sensible default values for most methods + * (null, empty collections, or false)
  • Always returns "GET" as the HTTP method
  • Returns "/" as the path + * info
  • Supports basic parameter retrieval through the constructor-provided parameter map
  • Does not + * maintain session state or authentication information
* - *

The primary use case is to provide a minimal request context when executing JavaScript - * code that expects an HttpServletRequest object to be available, particularly during - * server-side rendering scenarios in the Jahia JavaScript modules framework.

+ *

The primary use case is to provide a minimal request context when executing JavaScript code that expects an + * HttpServletRequest object to be available, particularly during server-side rendering scenarios in the Jahia + * JavaScript modules framework.

* * @see HttpServletRequest */ @@ -174,14 +170,10 @@ public boolean authenticate(HttpServletResponse httpServletResponse) throws IOEx } @Override - public void login(String s, String s1) throws ServletException { - - } + public void login(String s, String s1) throws ServletException {} @Override - public void logout() throws ServletException { - - } + public void logout() throws ServletException {} @Override public Collection getParts() throws IOException, ServletException { @@ -214,9 +206,7 @@ public String getCharacterEncoding() { } @Override - public void setCharacterEncoding(String env) throws UnsupportedEncodingException { - - } + public void setCharacterEncoding(String env) throws UnsupportedEncodingException {} @Override public int getContentLength() { @@ -294,14 +284,10 @@ public String getRemoteHost() { } @Override - public void setAttribute(String name, Object o) { - - } + public void setAttribute(String name, Object o) {} @Override - public void removeAttribute(String name) { - - } + public void removeAttribute(String name) {} @Override public Locale getLocale() { @@ -359,7 +345,8 @@ public AsyncContext startAsync() throws IllegalStateException { } @Override - public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException { + public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) + throws IllegalStateException { return null; } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/gql/HttpServletResponseMock.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/gql/HttpServletResponseMock.java index fb266a4d..336dad41 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/gql/HttpServletResponseMock.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/gql/HttpServletResponseMock.java @@ -1,36 +1,32 @@ package org.jahia.modules.javascript.modules.engine.js.server.gql; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.Collection; import java.util.Collections; import java.util.Locale; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletResponse; /** - * A mock implementation of {@link HttpServletResponse} used for testing and server-side rendering - * within the Jahia JavaScript modules engine. + * A mock implementation of {@link HttpServletResponse} used for testing and server-side rendering within the Jahia + * JavaScript modules engine. * - *

This class provides a minimal, non-functional implementation of the HttpServletResponse interface - * that can be used in environments where a real HTTP response context is not available, such as during - * server-side rendering of JavaScript components or in unit tests.

+ *

This class provides a minimal, non-functional implementation of the HttpServletResponse interface that can be used + * in environments where a real HTTP response context is not available, such as during server-side rendering of + * JavaScript components or in unit tests.

* - *

Key characteristics of this mock implementation:

- *
    - *
  • Provides a functional {@link ServletOutputStream} through {@link ServletOutputStreamMock}
  • - *
  • Supports character encoding configuration via constructor
  • - *
  • Returns sensible default values for most methods (null, empty collections, or false)
  • - *
  • URL encoding methods return the original URL unchanged
  • - *
  • Header and cookie operations are no-ops (do nothing)
  • - *
  • Error handling and redirection methods are no-ops
  • - *
  • Buffer and locale operations return default values
  • - *
+ *

Key characteristics of this mock implementation:

  • Provides a functional {@link ServletOutputStream} + * through {@link ServletOutputStreamMock}
  • Supports character encoding configuration via constructor
  • + *
  • Returns sensible default values for most methods (null, empty collections, or false)
  • URL encoding + * methods return the original URL unchanged
  • Header and cookie operations are no-ops (do nothing)
  • + *
  • Error handling and redirection methods are no-ops
  • Buffer and locale operations return default + * values
* - *

The primary use case is to provide a minimal response context when executing JavaScript - * code that expects an HttpServletResponse object to be available, particularly during - * server-side rendering scenarios where output needs to be captured through the ServletOutputStream.

+ *

The primary use case is to provide a minimal response context when executing JavaScript code that expects an + * HttpServletResponse object to be available, particularly during server-side rendering scenarios where output needs to + * be captured through the ServletOutputStream.

* * @see HttpServletResponse * @see ServletOutputStreamMock @@ -45,9 +41,7 @@ public HttpServletResponseMock(String characterEncoding) { } @Override - public void addCookie(Cookie cookie) { - - } + public void addCookie(Cookie cookie) {} @Override public boolean containsHeader(String name) { @@ -75,54 +69,34 @@ public String encodeRedirectUrl(String url) { } @Override - public void sendError(int sc, String msg) throws IOException { - - } + public void sendError(int sc, String msg) throws IOException {} @Override - public void sendError(int sc) throws IOException { - - } + public void sendError(int sc) throws IOException {} @Override - public void sendRedirect(String location) throws IOException { - - } + public void sendRedirect(String location) throws IOException {} @Override - public void setDateHeader(String name, long date) { - - } + public void setDateHeader(String name, long date) {} @Override - public void addDateHeader(String name, long date) { - - } + public void addDateHeader(String name, long date) {} @Override - public void setHeader(String name, String value) { - - } + public void setHeader(String name, String value) {} @Override - public void addHeader(String name, String value) { - - } + public void addHeader(String name, String value) {} @Override - public void setIntHeader(String name, int value) { - - } + public void setIntHeader(String name, int value) {} @Override - public void addIntHeader(String name, int value) { - - } + public void addIntHeader(String name, int value) {} @Override - public void setStatus(int sc, String sm) { - - } + public void setStatus(int sc, String sm) {} @Override public int getStatus() { @@ -130,9 +104,7 @@ public int getStatus() { } @Override - public void setStatus(int sc) { - - } + public void setStatus(int sc) {} @Override public String getHeader(String s) { @@ -155,9 +127,7 @@ public String getCharacterEncoding() { } @Override - public void setCharacterEncoding(String charset) { - - } + public void setCharacterEncoding(String charset) {} @Override public String getContentType() { @@ -165,9 +135,7 @@ public String getContentType() { } @Override - public void setContentType(String type) { - - } + public void setContentType(String type) {} @Override public ServletOutputStream getOutputStream() throws IOException { @@ -180,14 +148,10 @@ public PrintWriter getWriter() throws IOException { } @Override - public void setContentLength(int len) { - - } + public void setContentLength(int len) {} @Override - public void setContentLengthLong(long l) { - - } + public void setContentLengthLong(long l) {} @Override public int getBufferSize() { @@ -195,19 +159,13 @@ public int getBufferSize() { } @Override - public void setBufferSize(int size) { - - } + public void setBufferSize(int size) {} @Override - public void flushBuffer() throws IOException { - - } + public void flushBuffer() throws IOException {} @Override - public void resetBuffer() { - - } + public void resetBuffer() {} @Override public boolean isCommitted() { @@ -215,9 +173,7 @@ public boolean isCommitted() { } @Override - public void reset() { - - } + public void reset() {} @Override public Locale getLocale() { @@ -225,7 +181,5 @@ public Locale getLocale() { } @Override - public void setLocale(Locale loc) { - - } + public void setLocale(Locale loc) {} } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/gql/ServletOutputStreamMock.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/gql/ServletOutputStreamMock.java index a8efa374..55502811 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/gql/ServletOutputStreamMock.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/js/server/gql/ServletOutputStreamMock.java @@ -1,34 +1,30 @@ package org.jahia.modules.javascript.modules.engine.js.server.gql; -import javax.servlet.ServletOutputStream; -import javax.servlet.WriteListener; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; +import javax.servlet.ServletOutputStream; +import javax.servlet.WriteListener; /** - * A mock implementation of {@link ServletOutputStream} that captures output to an internal buffer - * for testing and server-side rendering within the Jahia JavaScript modules engine. + * A mock implementation of {@link ServletOutputStream} that captures output to an internal buffer for testing and + * server-side rendering within the Jahia JavaScript modules engine. * - *

This class extends ServletOutputStream and provides a functional implementation that writes - * data to an internal {@link ByteArrayOutputStream} buffer. This allows capturing and retrieving - * the output content as a string, which is particularly useful during server-side rendering - * scenarios where the rendered content needs to be captured and processed.

+ *

This class extends ServletOutputStream and provides a functional implementation that writes data to an internal + * {@link ByteArrayOutputStream} buffer. This allows capturing and retrieving the output content as a string, which is + * particularly useful during server-side rendering scenarios where the rendered content needs to be captured and + * processed.

* - *

Key features of this mock implementation:

- *
    - *
  • Captures all written data in an internal {@link ByteArrayOutputStream} buffer
  • - *
  • Supports configurable character encoding for string conversion
  • - *
  • Defaults to UTF-8 encoding if no encoding is specified
  • - *
  • Always reports as ready for writing ({@link #isReady()} returns true)
  • - *
  • Provides a {@link #getContent()} method to retrieve buffered content as a string
  • - *
  • Write listener operations are no-ops (not supported)
  • - *
+ *

Key features of this mock implementation:

  • Captures all written data in an internal + * {@link ByteArrayOutputStream} buffer
  • Supports configurable character encoding for string conversion
  • + *
  • Defaults to UTF-8 encoding if no encoding is specified
  • Always reports as ready for writing ( + * {@link #isReady()} returns true)
  • Provides a {@link #getContent()} method to retrieve buffered content as a + * string
  • Write listener operations are no-ops (not supported)
* - *

The primary use case is to capture output from JavaScript components during server-side - * rendering, allowing the rendered HTML content to be retrieved and used within the Jahia - * framework. The captured content can be accessed via the {@link #getContent()} method.

+ *

The primary use case is to capture output from JavaScript components during server-side rendering, allowing the + * rendered HTML content to be retrieved and used within the Jahia framework. The captured content can be accessed via + * the {@link #getContent()} method.

* * @see ServletOutputStream * @see HttpServletResponseMock @@ -55,8 +51,7 @@ public boolean isReady() { } @Override - public void setWriteListener(WriteListener writeListener) { - } + public void setWriteListener(WriteListener writeListener) {} public String getContent() { try { diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jsengine/GraalVMEngine.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jsengine/GraalVMEngine.java index 2baabd4f..ddb7b195 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jsengine/GraalVMEngine.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jsengine/GraalVMEngine.java @@ -15,6 +15,16 @@ */ package org.jahia.modules.javascript.modules.engine.jsengine; +import static org.jahia.modules.javascript.modules.engine.jshandler.JavascriptProtocolConnection.BUNDLE_HEADER_JAVASCRIPT_INIT_SCRIPT; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; +import java.util.function.Function; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; @@ -39,17 +49,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.*; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Consumer; -import java.util.function.Function; - -import static org.jahia.modules.javascript.modules.engine.jshandler.JavascriptProtocolConnection.BUNDLE_HEADER_JAVASCRIPT_INIT_SCRIPT; - /** * Base JS engine based on GraalVM */ @@ -63,7 +62,8 @@ public class GraalVMEngine { /** * Mimetype used by Graal to identify ESM source code. * - * @see ECMAScript Modules + * @see ECMAScript + * Modules */ private static final String JS_MODULE_MIMETYPE = "application/javascript+module"; @@ -83,8 +83,8 @@ public BundleContext getBundleContext() { public void enableJavascriptModule(Bundle bundle) { try { - initScripts.put(bundle, - getGraalSource(bundle, bundle.getHeaders().get(BUNDLE_HEADER_JAVASCRIPT_INIT_SCRIPT))); + initScripts.put( + bundle, getGraalSource(bundle, bundle.getHeaders().get(BUNDLE_HEADER_JAVASCRIPT_INIT_SCRIPT))); version.incrementAndGet(); logger.info("Registered bundle {} in GraalVM engine", bundle.getSymbolicName()); } catch (IOException ioe) { @@ -105,8 +105,8 @@ public void activate(BundleContext bundleContext, Map props) { this.bundleContext = bundleContext; try { - initScripts.put(bundleContext.getBundle(), - getGraalSource(bundleContext.getBundle(), "META-INF/js/main.js")); + initScripts.put( + bundleContext.getBundle(), getGraalSource(bundleContext.getBundle(), "META-INF/js/main.js")); } catch (IOException e) { logger.error("Cannot execute main init script", e); } @@ -202,8 +202,11 @@ public ContextProvider create() throws Exception { .allowHostClassLookup(s -> true) .allowHostAccess(HostAccess.ALL) .allowPolyglotAccess(PolyglotAccess.ALL) - .allowIO(IOAccess.newBuilder().fileSystem(new JSFileSystem(bundleContext)).build()) - .engine(sharedEngine).build(); + .allowIO(IOAccess.newBuilder() + .fileSystem(new JSFileSystem(bundleContext)) + .build()) + .engine(sharedEngine) + .build(); ContextProvider contextProvider = new ContextProvider(context, version.get()); // Add the global "server" variable to the context @@ -263,9 +266,7 @@ public void destroyObject(PooledObject p) throws Exception { } /** - * Creates the global js variable named `server` in js context. It holds a - * reference to several - * server-side helpers. + * Creates the global js variable named `server` in js context. It holds a reference to several server-side helpers. */ public ProxyObject getServer(ContextProvider contextProvider) { // Because JS is single-threaded but Java is not, Graal enforces strict safety diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jsengine/GraalVMException.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jsengine/GraalVMException.java index 74b82fc8..03afa9f0 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jsengine/GraalVMException.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jsengine/GraalVMException.java @@ -16,8 +16,7 @@ package org.jahia.modules.javascript.modules.engine.jsengine; public class GraalVMException extends RuntimeException { - public GraalVMException() { - } + public GraalVMException() {} public GraalVMException(String message) { super(message); diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jsengine/JSFileSystem.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jsengine/JSFileSystem.java index 386d5386..6ee332bc 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jsengine/JSFileSystem.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jsengine/JSFileSystem.java @@ -15,152 +15,138 @@ import java.nio.file.attribute.FileAttribute; import java.util.Map; import java.util.Set; - -import org.graalvm.polyglot.io.FileSystem; -import org.osgi.framework.BundleContext; import org.apache.commons.compress.utils.SeekableInMemoryByteChannel; import org.apache.commons.io.IOUtils; +import org.graalvm.polyglot.io.FileSystem; +import org.osgi.framework.BundleContext; /** - * This class defines a virtual filesystem used to resolve - * import statements. + * This class defines a virtual filesystem used to resolve import statements. * - * For now it's really basic but it opens the door for more advanced features in - * the future. + * For now it's really basic but it opens the door for more advanced features in the future. * * See each method for explanations on the import resolution process. */ public class JSFileSystem implements FileSystem { - private static final String ROOT_JS_LIBS_DIR = "/META-INF/js/libs/"; - - final private BundleContext bundleContext; - - JSFileSystem(BundleContext bundleContext) { - this.bundleContext = bundleContext; - } - - // Methods are in the same order as the execution order - - /** - * parsePath is called on non-path imports (e.g. import "react" but - * not import "./react.js"). It's the first step in the resolution - * process. - * - * However, parsePath, for reasons foreign to me, might be called - * with the stringified version of an already parsed path. And for internal - * implementation-specific imports. - * - * For instance, it might receive - * /META-INF/js/libs/react-i18next.js (stringified output of the - * method) or /usr/local/graalvm/languages/js (internal import) or - * even worse d:\jdk17\languages\js on Windows. - * - * This is safe-guarded by this path.startsWith check until - * someone comes with a better solution. - */ - @Override - public Path parsePath(String path) { - if (path.startsWith("/") || path.contains("\\")) { - return Path.of(path); + private static final String ROOT_JS_LIBS_DIR = "/META-INF/js/libs/"; + + private final BundleContext bundleContext; + + JSFileSystem(BundleContext bundleContext) { + this.bundleContext = bundleContext; + } + + // Methods are in the same order as the execution order + + /** + * parsePath is called on non-path imports (e.g. import "react" but not import + * "./react.js"). It's the first step in the resolution process. + * + * However, parsePath, for reasons foreign to me, might be called with the stringified version of an already parsed + * path. And for internal implementation-specific imports. + * + * For instance, it might receive /META-INF/js/libs/react-i18next.js (stringified output of the method) + * or /usr/local/graalvm/languages/js (internal import) or even worse + * d:\jdk17\languages\js on Windows. + * + * This is safe-guarded by this path.startsWith check until someone comes with a better solution. + */ + @Override + public Path parsePath(String path) { + if (path.startsWith("/") || path.contains("\\")) { + return Path.of(path); + } + + return Path.of(ROOT_JS_LIBS_DIR, path + ".js"); + } + + /** + * This method throws when access is refused, does nothing otherwise. + */ + @Override + public void checkAccess(Path path, Set modes, LinkOption... linkOptions) throws IOException { + String resourceName = pathToResourceName(path); + if (!resourceName.startsWith(ROOT_JS_LIBS_DIR)) { + throw new IOException("Access refused to import " + resourceName); + } + } + + /** + * This method is called for every path, like outputs of {@link #parsePath(String)} } and valid relative imports + * after they were resolved, like /META-INF/js/libs/I18nextProvider-BnrOfLKR.js. All paths are valid at + * this point, so we just return them. + */ + @Override + public Path toRealPath(Path path, LinkOption... linkOptions) throws IOException { + return path; } - return Path.of(ROOT_JS_LIBS_DIR, path + ".js"); - } - - /** - * This method throws when access is refused, does nothing otherwise. - */ - @Override - public void checkAccess(Path path, Set modes, LinkOption... linkOptions) throws IOException { - String resourceName = pathToResourceName(path); - if (!resourceName.startsWith(ROOT_JS_LIBS_DIR)) { - throw new IOException("Access refused to import " + resourceName); + /** + * This method is called during the resolution process but the result is discarded. Not sure why, maybe just a + * sanity check in Graal. + */ + @Override + public Path toAbsolutePath(Path path) { + return path; } - } - - /** - * This method is called for every path, like outputs of - * {@link #parsePath(String)}} and valid relative imports after they were - * resolved, like /META-INF/js/libs/I18nextProvider-BnrOfLKR.js. - * All paths are valid at this point, so we just return them. - */ - @Override - public Path toRealPath(Path path, LinkOption... linkOptions) throws IOException { - return path; - } - - /** - * This method is called during the resolution process but the result is - * discarded. Not sure why, maybe just a sanity check in Graal. - */ - @Override - public Path toAbsolutePath(Path path) { - return path; - } - - /** - * This method transforms a path into a source code file. These are fancy words - * to say "read the file". - */ - @Override - public SeekableByteChannel newByteChannel(Path path, Set options, FileAttribute... attrs) - throws IOException { - String resourceName = pathToResourceName(path); - URL url = bundleContext.getBundle().getResource(resourceName); - if (url == null) { - throw new FileNotFoundException("Cannot import " + resourceName + ", the file does not exist"); + + /** + * This method transforms a path into a source code file. These are fancy words to say "read the file". + */ + @Override + public SeekableByteChannel newByteChannel(Path path, Set options, FileAttribute... attrs) + throws IOException { + String resourceName = pathToResourceName(path); + URL url = bundleContext.getBundle().getResource(resourceName); + if (url == null) { + throw new FileNotFoundException("Cannot import " + resourceName + ", the file does not exist"); + } + + try (InputStream inputStream = url.openStream()) { + return new SeekableInMemoryByteChannel(IOUtils.toByteArray(inputStream)); + } + } + + /** + * This method is called for imports with a protocol (e.g. import "http://example.com" or import + * "node:http"). We might be able to build cool things in the future with this! + */ + @Override + public Path parsePath(URI uri) { + throw new UnsupportedOperationException("Import not supported: " + uri.toString()); } - try (InputStream inputStream = url.openStream()) { - return new SeekableInMemoryByteChannel(IOUtils.toByteArray(inputStream)); + // Other methods are not involved in the resolution process + + @Override + public void createDirectory(Path dir, FileAttribute... attrs) throws IOException { + throw new UnsupportedOperationException("Unimplemented method 'createDirectory'"); + } + + @Override + public void delete(Path path) throws IOException { + throw new UnsupportedOperationException("Unimplemented method 'delete'"); + } + + @Override + public DirectoryStream newDirectoryStream(Path dir, Filter filter) throws IOException { + throw new UnsupportedOperationException("Unimplemented method 'newDirectoryStream'"); + } + + @Override + public Map readAttributes(Path path, String attributes, LinkOption... options) throws IOException { + throw new UnsupportedOperationException("Unimplemented method 'readAttributes'"); + } + + // Helper methods + + /** + * The {@link FileSystem} interface enforces the use of {@link Path} which is platform-dependent (uses \ on Windows, + * / on Unix). But OSGi bundle resources always use forward slashes. + * + * 1. Normalize (resolve . and ..) 2. Convert system-specific separators into OSGi-compatible forward slashes + */ + private String pathToResourceName(Path path) { + return path.normalize().toString().replace('\\', '/'); } - } - - /** - * This method is called for imports with a protocol (e.g. - * import "http://example.com" or import "node:http"). - * We might be able to build cool things in the future with this! - */ - @Override - public Path parsePath(URI uri) { - throw new UnsupportedOperationException("Import not supported: " + uri.toString()); - } - - // Other methods are not involved in the resolution process - - @Override - public void createDirectory(Path dir, FileAttribute... attrs) throws IOException { - throw new UnsupportedOperationException("Unimplemented method 'createDirectory'"); - } - - @Override - public void delete(Path path) throws IOException { - throw new UnsupportedOperationException("Unimplemented method 'delete'"); - } - - @Override - public DirectoryStream newDirectoryStream(Path dir, Filter filter) - throws IOException { - throw new UnsupportedOperationException("Unimplemented method 'newDirectoryStream'"); - } - - @Override - public Map readAttributes(Path path, String attributes, LinkOption... options) - throws IOException { - throw new UnsupportedOperationException("Unimplemented method 'readAttributes'"); - } - - // Helper methods - - /** - * The {@link FileSystem} interface enforces the use of {@link Path} which is - * platform-dependent (uses \ on Windows, / on Unix). But OSGi bundle resources - * always use forward slashes. - * - * 1. Normalize (resolve . and ..) - * 2. Convert system-specific separators into OSGi-compatible forward slashes - */ - private String pathToResourceName(Path path) { - return path.normalize().toString().replace('\\', '/'); - } } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jsengine/JSNodeMapper.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jsengine/JSNodeMapper.java index 28a6098e..e0d9af1c 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jsengine/JSNodeMapper.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jsengine/JSNodeMapper.java @@ -1,5 +1,8 @@ package org.jahia.modules.javascript.modules.engine.jsengine; +import java.util.*; +import java.util.stream.Collectors; +import javax.jcr.*; import org.jahia.services.content.JCRNodeIteratorWrapper; import org.jahia.services.content.JCRNodeWrapper; import org.jahia.services.content.JCRPropertyWrapperImpl; @@ -11,23 +14,27 @@ import org.slf4j.LoggerFactory; import pl.touk.throwing.ThrowingFunction; -import javax.jcr.*; -import java.util.*; -import java.util.stream.Collectors; - /** - * Mapper able to transform a JCR Node into future JS object to be used in HBS templates for example - * HBS template does not allow to call functions on JS objects, helpers are required for that. - * In order to simplify the reading of nodes infos (mixins, properties, etc) we transform the JCR Node into a Map, this way - * it will be easier to read in HBS templates. + * Mapper able to transform a JCR Node into future JS object to be used in HBS templates for example HBS template does + * not allow to call functions on JS objects, helpers are required for that. In order to simplify the reading of nodes + * infos (mixins, properties, etc) we transform the JCR Node into a Map, this way it will be easier to read in HBS + * templates. */ public class JSNodeMapper { private static final Logger logger = LoggerFactory.getLogger(JSNodeMapper.class); - private static final List IGNORED_I18N_PROPERTIES = Arrays.asList("jcr:lastModifiedBy", "jcr:language", - "jcr:predecessors", "jcr:baseVersion", "jcr:uuid", "jcr:lastModified", "jcr:isCheckedOut", - "jcr:primaryType", "jcr:versionHistory"); - private static final List IGNORED_PROPERTIES = Arrays.asList("jcr:predecessors", "jcr:baseVersion", "jcr:versionHistory"); + private static final List IGNORED_I18N_PROPERTIES = Arrays.asList( + "jcr:lastModifiedBy", + "jcr:language", + "jcr:predecessors", + "jcr:baseVersion", + "jcr:uuid", + "jcr:lastModified", + "jcr:isCheckedOut", + "jcr:primaryType", + "jcr:versionHistory"); + private static final List IGNORED_PROPERTIES = + Arrays.asList("jcr:predecessors", "jcr:baseVersion", "jcr:versionHistory"); /** * Transform a JCR Node into a JS readable data (Map is used on Java side) @@ -35,13 +42,14 @@ public class JSNodeMapper { * @param node the node to transform * @param includeChildren should we recurse on children ? * @param includeDescendants should we recurse on all descendants tree ? - * @param includeAllTranslations should we generate all i18n properties ? - * true: will generate all i18n properties (stored under i18nProperties) - * false: will generate only i18n properties related to current session locale (stored under properties like non-i18n props) + * @param includeAllTranslations should we generate all i18n properties ? true: will generate all i18n properties + * (stored under i18nProperties) false: will generate only i18n properties related to current session locale (stored + * under properties like non-i18n props) * @return the JS Node * @throws RepositoryException in case something bad happens related to JCR */ - public static Map toJSNode(JCRNodeWrapper node, boolean includeChildren, boolean includeDescendants, boolean includeAllTranslations) throws RepositoryException { + public static Map toJSNode( + JCRNodeWrapper node, boolean includeChildren, boolean includeDescendants, boolean includeAllTranslations) throws RepositoryException { Map jsNode = new HashMap<>(); jsNode.put("name", node.getName()); try { @@ -70,7 +78,8 @@ public static Map toJSNode(JCRNodeWrapper node, boolean includeC NodeIterator i18nNodeIterator = node.getI18Ns(); while (i18nNodeIterator.hasNext()) { Node i18nNode = i18nNodeIterator.nextNode(); - jsI18nProperties.put(i18nNode.getProperty("jcr:language").getString(), + jsI18nProperties.put( + i18nNode.getProperty("jcr:language").getString(), toJSNodeProperties(i18nNode, false, IGNORED_I18N_PROPERTIES)); } jsNode.put("i18nProperties", jsI18nProperties); @@ -83,7 +92,11 @@ public static Map toJSNode(JCRNodeWrapper node, boolean includeC List> children = new ArrayList<>(); JCRNodeIteratorWrapper iterator = node.getNodes(); while (iterator.hasNext()) { - children.add(toJSNode((JCRNodeWrapper) iterator.next(), includeDescendants, includeDescendants, includeAllTranslations)); + children.add(toJSNode( + (JCRNodeWrapper) iterator.next(), + includeDescendants, + includeDescendants, + includeAllTranslations)); } jsNode.put("children", children); } @@ -91,8 +104,8 @@ public static Map toJSNode(JCRNodeWrapper node, boolean includeC return jsNode; } - private static Map toJSNodeProperties(Node node, boolean includeI18NProperties, List ignoredProperties) - throws RepositoryException { + private static Map toJSNodeProperties( + Node node, boolean includeI18NProperties, List ignoredProperties) throws RepositoryException { Map jsProperties = new HashMap<>(); PropertyIterator propertyIterator = node.getProperties(); while (propertyIterator.hasNext()) { @@ -102,13 +115,15 @@ private static Map toJSNodeProperties(Node node, boolean include continue; } - if (!includeI18NProperties && property instanceof JCRPropertyWrapperImpl && - ((JCRPropertyWrapperImpl) property).getDefinition().isInternationalized()) { + if (!includeI18NProperties + && property instanceof JCRPropertyWrapperImpl + && ((JCRPropertyWrapperImpl) property).getDefinition().isInternationalized()) { continue; } if (property.isMultiple()) { - jsProperties.put(property.getName(), + jsProperties.put( + property.getName(), Arrays.stream(property.getValues()) .map(ThrowingFunction.unchecked(value -> toJSNodePropertyValue(property, value))) .collect(Collectors.toList())); @@ -136,8 +151,8 @@ private static Object toJSNodePropertyValue(Property property, Value value) thro } /** - * Transform a JS node into a virtual JCR Node - * "Virtual" because this node is not means to be saved, it will be used by Jahia rendering system to be rendered only. + * Transform a JS node into a virtual JCR Node "Virtual" because this node is not means to be saved, it will be used + * by Jahia rendering system to be rendered only. * * @param jsonNode the JS Node * @param session the current session @@ -145,12 +160,15 @@ private static Object toJSNodePropertyValue(Property property, Value value) thro * @return the unsaved "Virtual" JCR Node instance * @throws RepositoryException in case something bad happens related to JCR */ - public static JCRNodeWrapper toVirtualNode(Map jsonNode, JCRSessionWrapper session, RenderContext renderContext) throws RepositoryException { - JCRNodeWrapper parent = jsonNode.containsKey("parent") ? session.getNode((String) jsonNode.get("parent")) : session.getNode("/"); + public static JCRNodeWrapper toVirtualNode( + Map jsonNode, JCRSessionWrapper session, RenderContext renderContext) throws RepositoryException { + JCRNodeWrapper parent = + jsonNode.containsKey("parent") ? session.getNode((String) jsonNode.get("parent")) : session.getNode("/"); return toVirtualNode(jsonNode, parent, renderContext); } - private static JCRNodeWrapper toVirtualNode(Map jsonNode, JCRNodeWrapper parent, RenderContext renderContext) throws RepositoryException { + private static JCRNodeWrapper toVirtualNode( + Map jsonNode, JCRNodeWrapper parent, RenderContext renderContext) throws RepositoryException { JCRSessionWrapper session = parent.getSession(); Locale locale = renderContext.getMainResource().getLocale(); // TODO: stop support temp-node name @@ -162,8 +180,10 @@ private static JCRNodeWrapper toVirtualNode(Map jsonNode, JCRNodeWrap Object mixins = jsonNode.get("mixins"); if (mixins instanceof String) { node.addMixin((String) mixins); - } else if (mixins instanceof List) { - for (Object mixinName : (List) mixins) { + } else if (mixins instanceof List< + ?>) { + for (Object mixinName : (List< + ?>) mixins) { node.addMixin(mixinName.toString()); } } @@ -172,7 +192,8 @@ private static JCRNodeWrapper toVirtualNode(Map jsonNode, JCRNodeWrap // handle properties Map properties = (Map) jsonNode.get("properties"); if (properties != null) { - for (Map.Entry entry : properties.entrySet()) { + for (Map.Entry< + String, ?> entry : properties.entrySet()) { toVirtualNodeProperty(node, entry.getKey(), entry.getValue()); } } @@ -180,11 +201,13 @@ private static JCRNodeWrapper toVirtualNode(Map jsonNode, JCRNodeWrap // handle i18n properties Map i18nProperties = (Map) jsonNode.get("i18nProperties"); if (i18nProperties != null) { - for (Map.Entry entry : i18nProperties.entrySet()) { + for (Map.Entry< + String, ?> entry : i18nProperties.entrySet()) { Locale entryLocale = new Locale(entry.getKey()); if (locale.equals(entryLocale)) { Map localeProperties = (Map) entry.getValue(); - for (Map.Entry localeProperty : localeProperties.entrySet()) { + for (Map.Entry< + String, ?> localeProperty : localeProperties.entrySet()) { toVirtualNodeProperty(node, localeProperty.getKey(), localeProperty.getValue()); } } @@ -194,7 +217,10 @@ private static JCRNodeWrapper toVirtualNode(Map jsonNode, JCRNodeWrap // handle bound component try { if (node.isNodeType("jmix:bindedComponent") && jsonNode.containsKey("boundComponentRelativePath")) { - String boundComponentPath = renderContext.getMainResource().getNodePath().concat((String) jsonNode.get("boundComponentRelativePath")); + String boundComponentPath = renderContext + .getMainResource() + .getNodePath() + .concat((String) jsonNode.get("boundComponentRelativePath")); JCRNodeWrapper boundComponent = session.getNode(boundComponentPath); renderContext.getMainResource().getDependencies().add(boundComponent.getPath()); node.setProperty("j:bindedComponent", boundComponent); @@ -212,7 +238,8 @@ private static JCRNodeWrapper toVirtualNode(Map jsonNode, JCRNodeWrap // handle children List> children = (List>) jsonNode.get("children"); if (children != null) { - for (Map child : children) { + for (Map< + String, Object> child : children) { toVirtualNode(child, node, renderContext); } } @@ -220,12 +247,14 @@ private static JCRNodeWrapper toVirtualNode(Map jsonNode, JCRNodeWrap return node; } - private static void toVirtualNodeProperty(JCRNodeWrapper node, String propertyName, Object value) throws RepositoryException { + private static void toVirtualNodeProperty(JCRNodeWrapper node, String propertyName, Object value) + throws RepositoryException { ExtendedPropertyDefinition epd = node.getApplicablePropertyDefinition(propertyName); if (epd != null && epd.isMultiple()) { if (value instanceof List && ((List) value).size() > 0) { List values = (List) value; - List stringList = values.stream().map(Object::toString).collect(Collectors.toUnmodifiableList()); + List stringList = + values.stream().map(Object::toString).collect(Collectors.toUnmodifiableList()); node.setProperty(propertyName, stringList.toArray(new String[stringList.size()])); } else { node.setProperty(propertyName, ((String) value).split(" ")); diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jsengine/Registry.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jsengine/Registry.java index abfeeef3..51ad4f4a 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jsengine/Registry.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jsengine/Registry.java @@ -15,11 +15,10 @@ */ package org.jahia.modules.javascript.modules.engine.jsengine; -import org.osgi.framework.Bundle; - import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.osgi.framework.Bundle; public class Registry { private final ContextProvider contextProvider; @@ -44,8 +43,8 @@ public List> find(Map filter, String orderBy .filter(item -> filter.entrySet().stream().allMatch(f -> f.getValue().equals(item.get(f.getKey())))); if (orderBy != null) { - filtered = filtered.sorted(Comparator.comparing(m -> (Integer) m.get(orderBy), - Comparator.nullsFirst(Comparator.reverseOrder()))); + filtered = filtered.sorted(Comparator.comparing( + m -> (Integer) m.get(orderBy), Comparator.nullsFirst(Comparator.reverseOrder()))); } return filtered.collect(Collectors.toList()); diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/FileinstallTgzTransformer.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/FileinstallTgzTransformer.java index 220fdee3..cc851bce 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/FileinstallTgzTransformer.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/FileinstallTgzTransformer.java @@ -15,17 +15,22 @@ */ package org.jahia.modules.javascript.modules.engine.jshandler; +import java.io.File; +import java.net.URL; import org.apache.felix.fileinstall.ArtifactListener; import org.apache.felix.fileinstall.ArtifactUrlTransformer; import org.osgi.service.component.annotations.Component; -import java.io.File; -import java.net.URL; - /** * Artifact transformer for tgz files dropped in file install */ -@Component(service = {ArtifactUrlTransformer.class, ArtifactListener.class}, property = {"url.handler.protocol=js"}, immediate = true) +@Component( + service = { + ArtifactUrlTransformer.class, + ArtifactListener.class + }, + property = {"url.handler.protocol=js"}, + immediate = true) public class FileinstallTgzTransformer implements ArtifactUrlTransformer { @Override public boolean canHandle(File file) { diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/JavascriptProtocolConnection.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/JavascriptProtocolConnection.java index d7109444..becafaa8 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/JavascriptProtocolConnection.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/JavascriptProtocolConnection.java @@ -16,6 +16,15 @@ package org.jahia.modules.javascript.modules.engine.jshandler; import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.*; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.nio.file.Files; +import java.util.*; +import java.util.jar.JarOutputStream; +import java.util.zip.GZIPInputStream; +import java.util.zip.ZipEntry; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; @@ -27,19 +36,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.*; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; -import java.nio.file.Files; -import java.util.*; -import java.util.jar.JarOutputStream; -import java.util.zip.GZIPInputStream; -import java.util.zip.ZipEntry; - /** - * javascript protocol handler - * Transform javascript module into bundle + * javascript protocol handler Transform javascript module into bundle */ public class JavascriptProtocolConnection extends URLConnection { public static final String BUNDLE_HEADER_JAVASCRIPT_INIT_SCRIPT = "Jahia-javascript-InitScript"; @@ -96,7 +94,8 @@ public InputStream getInputStream() throws IOException { } // Calculate relative path of the file in the package - String packageRelativePath = packageDir.toURI().relativize(file.toURI()).getPath(); + String packageRelativePath = + packageDir.toURI().relativize(file.toURI()).getPath(); // Copy file path (try to detect good path for file in the final package jar.) if (packageRelativePath.equals("package.json")) { @@ -110,27 +109,32 @@ public InputStream getInputStream() throws IOException { } else if (packageRelativePath.startsWith("settings/")) { // Special mapping settings/content-editor-forms to META-INF/jahia-content-editor-forms if (packageRelativePath.startsWith("settings/content-editor-forms/")) { - jos.putNextEntry(new ZipEntry("META-INF/jahia-content-editor-forms/" + StringUtils.substringAfter(packageRelativePath, "settings/content-editor-forms/"))); - } - // Special mapping settings/content-types-icons to icons/ + jos.putNextEntry(new ZipEntry("META-INF/jahia-content-editor-forms/" + + StringUtils.substringAfter(packageRelativePath, "settings/content-editor-forms/"))); + }// Special mapping settings/content-types-icons to icons/ + else if (packageRelativePath.startsWith("settings/content-types-icons/")) { - jos.putNextEntry(new ZipEntry("icons/" + StringUtils.substringAfter(packageRelativePath, "content-types-icons/"))); - } - // Special mapping settings/resources/*.properties to resources/*.properties - else if (packageRelativePath.startsWith("settings/resources/") && packageRelativePath.endsWith(".properties")) { + jos.putNextEntry(new ZipEntry("icons/" + + StringUtils.substringAfter(packageRelativePath, "content-types-icons/"))); + }// Special mapping settings/resources/*.properties to resources/*.properties + + else if (packageRelativePath.startsWith("settings/resources/") + && packageRelativePath.endsWith(".properties")) { jos.putNextEntry(new ZipEntry(StringUtils.substringAfter(packageRelativePath, "settings/"))); - } - // Special mapping settings/template-thumbnail.png to images/template-preview/template-thumbnail.png + }// Special mapping settings/template-thumbnail.png to images/template-preview/template-thumbnail.png + else if (packageRelativePath.equals("settings/template-thumbnail.png")) { - jos.putNextEntry(new ZipEntry("images/template-preview/" + StringUtils.substringAfter(packageRelativePath, "settings/"))); - } - // Map everything else in settings/ to META-INF/ + jos.putNextEntry(new ZipEntry("images/template-preview/" + + StringUtils.substringAfter(packageRelativePath, "settings/"))); + }// Map everything else in settings/ to META-INF/ + else { // Extract required nodetypes from imported xml files. if (packageRelativePath.endsWith(".xml")) { - extractNodetypes(file, parsingContext, importXmlFileParser); + extractNodetypes(file, parsingContext, importXmlFileParser); } - jos.putNextEntry(new ZipEntry("META-INF/" + StringUtils.substringAfter(packageRelativePath, "settings/"))); + jos.putNextEntry(new ZipEntry("META-INF/" + + StringUtils.substringAfter(packageRelativePath, "settings/"))); } } else if (packageRelativePath.startsWith("components") && packageRelativePath.endsWith(".png")) { String[] parts = StringUtils.split(packageRelativePath, "/"); @@ -143,7 +147,9 @@ else if (packageRelativePath.equals("settings/template-thumbnail.png")) { jos.putNextEntry(entry); processedImages.add(entry); } else { - logger.warn("File with the name {} already copied into the /images folder, the current file won't be copied", file.getName()); + logger.warn( + "File with the name {} already copied into the /images folder, the current file won't be copied", + file.getName()); continue; } } @@ -172,7 +178,8 @@ else if (packageRelativePath.equals("settings/template-thumbnail.png")) { } else { // Multiple cnd files, merge them if (logger.isDebugEnabled()) { - logger.debug("Multiple CND files detected in the package, they will be merged into a single file"); + logger.debug( + "Multiple CND files detected in the package, they will be merged into a single file"); } finalCndFile = mergeDefinitionFiles(cndFiles, packageDir); } @@ -194,7 +201,6 @@ else if (packageRelativePath.equals("settings/template-thumbnail.png")) { FileUtils.deleteDirectory(outputDir); } - Properties instructions = new Properties(); // Extract instructions from package.json and nodetype capabilities instructions.putAll(generateInstructions(packageJson, parsingContext)); @@ -202,15 +208,26 @@ else if (packageRelativePath.equals("settings/template-thumbnail.png")) { logger.debug("JS module transformed to bundle using instructions: {}", instructions); } - return BndUtils.createBundle(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()), instructions, wrappedUrl.toExternalForm()); + return BndUtils.createBundle( + new ByteArrayInputStream(byteArrayOutputStream.toByteArray()), + instructions, + wrappedUrl.toExternalForm()); } - private void extractNodetypes(File fileToBeParsed, ParsingContext parsingContext, AbstractFileParser parser) throws IOException { + private void extractNodetypes(File fileToBeParsed, ParsingContext parsingContext, AbstractFileParser parser) + throws IOException { try (InputStream inputStream = new FileInputStream(fileToBeParsed)) { logger.info("Extracting node types from {}", fileToBeParsed.getAbsolutePath()); - if (parser.parse(fileToBeParsed.getName(), inputStream, fileToBeParsed.getParent(), false, false, null, parsingContext)) { + if (parser.parse( + fileToBeParsed.getName(), + inputStream, + fileToBeParsed.getParent(), + false, + false, + null, + parsingContext)) { logger.info("Successfully extracted node types from {}", fileToBeParsed.getAbsolutePath()); - }; + } } } @@ -223,15 +240,22 @@ private Properties generateInstructions(Map properties, ParsingC setIfPresent(properties, "description", instructions, "Bundle-Description"); String name = StringUtils.defaultString((String) jahiaProps.get("name"), (String) properties.get("name")); instructions.put("Bundle-Name", name + " (javascript module)"); - instructions.put("Bundle-SymbolicName", - ((String) properties.get("name")).replace("@", "").replace('/', '-').replaceAll("[^a-zA-Z0-9\\-\\.\\s]", "_")); + instructions.put( + "Bundle-SymbolicName", + ((String) properties.get("name")) + .replace("@", "") + .replace('/', '-') + .replaceAll("[^a-zA-Z0-9\\-\\.\\s]", "_")); setIfPresent(properties, "author", instructions, "Bundle-Vendor"); instructions.put("Bundle-Version", getBundleVersion(properties, jahiaProps)); instructions.put("Implementation-Version", getImplementationVersion(properties, jahiaProps)); setIfPresent(properties, "license", instructions, "Bundle-License"); // Next lets setup Jahia headers - instructions.put("Jahia-Depends", StringUtils.defaultIfEmpty((String) jahiaProps.get("module-dependencies"), "default") + ",javascript-modules-engine"); + instructions.put( + "Jahia-Depends", + StringUtils.defaultIfEmpty((String) jahiaProps.get("module-dependencies"), "default") + + ",javascript-modules-engine"); setIfPresent(jahiaProps, "deploy-on-site", instructions, "Jahia-Deploy-On-Site"); Map mavenProps = getMavenProps(jahiaProps); instructions.put("Jahia-GroupId", mavenProps.getOrDefault("groupId", "org.example.javascript")); @@ -242,17 +266,26 @@ private Properties generateInstructions(Map properties, ParsingC instructions.put("Jahia-Required-Version", jahiaProps.getOrDefault("required-version", "8.2.1.0")); setIfPresent(jahiaProps, "server", instructions, BUNDLE_HEADER_JAVASCRIPT_INIT_SCRIPT); // always include "/static" as folder for the static resources - instructions.put("Jahia-Static-Resources", StringUtils.defaultIfEmpty((String) jahiaProps.get("static-resources"), "/css,/icons,/images,/img,/javascript") + ",/static"); + instructions.put( + "Jahia-Static-Resources", + StringUtils.defaultIfEmpty( + (String) jahiaProps.get("static-resources"), "/css,/icons,/images,/img,/javascript") + + ",/static"); instructions.put("-removeheaders", "Private-Package, Export-Package"); // Add Provide-Capability for provided node types if (!parsingContext.getContentTypeDefinitions().isEmpty()) { String provideCapability = String.join(",", parsingContext.getContentTypeDefinitions()); - instructions.put("Provide-Capability", "com.jahia.services.content; nodetypes:List=\"" + provideCapability + "\""); + instructions.put( + "Provide-Capability", + "com.jahia.services.content; nodetypes:List=\"" + provideCapability + "\""); } // Add Require-Capability for required node types if (!parsingContext.getContentTypeReferences().isEmpty()) { - String nodeTypeRequirements = String.join("\"),com.jahia.services.content; filter:=\"(nodetypes=", parsingContext.getContentTypeReferences()); - instructions.put("Require-Capability", "com.jahia.services.content; filter:=\"(nodetypes=" + nodeTypeRequirements + "\")"); + String nodeTypeRequirements = String.join( + "\"),com.jahia.services.content; filter:=\"(nodetypes=", parsingContext.getContentTypeReferences()); + instructions.put( + "Require-Capability", + "com.jahia.services.content; filter:=\"(nodetypes=" + nodeTypeRequirements + "\")"); } return instructions; } @@ -274,7 +307,8 @@ static String getImplementationVersion(Map properties, Map properties, Map jahiaProps, String snapshotSuffix) { + private static String getVersionWithSnapshotSuffix( + Map properties, Map jahiaProps, String snapshotSuffix) { Object snapshotModeObj = jahiaProps.getOrDefault("snapshot", false); String version = (String) properties.get("version"); if (version.endsWith("-SNAPSHOT")) { @@ -284,7 +318,8 @@ private static String getVersionWithSnapshotSuffix(Map propertie return version + (Boolean.parseBoolean(String.valueOf(snapshotModeObj)) ? snapshotSuffix : ""); } - private void setIfPresent(Map inputProperties, String propertyName, Properties instructions, String instructionName) { + private void setIfPresent( + Map inputProperties, String propertyName, Properties instructions, String instructionName) { if (inputProperties.containsKey(propertyName)) { instructions.put(instructionName, inputProperties.get(propertyName)); } @@ -334,10 +369,10 @@ private File buildDefinitionFile(Set namespaces, String allDefinitionLin logger.error("Error creating temporary definitions.cnd file", e); return null; } - try (FileWriter writer = new FileWriter(mergedDefinitions); - BufferedWriter bw = new BufferedWriter(writer)) { + try (FileWriter writer = new FileWriter(mergedDefinitions); BufferedWriter bw = new BufferedWriter(writer)) { - String mergedNamespaces = namespaces.stream().reduce("", (partialString, element) -> partialString + element + System.lineSeparator()); + String mergedNamespaces = namespaces.stream() + .reduce("", (partialString, element) -> partialString + element + System.lineSeparator()); bw.write(mergedNamespaces); bw.write(allDefinitionLines); if (logger.isDebugEnabled()) { diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/JavascriptProtocolStreamHandler.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/JavascriptProtocolStreamHandler.java index 7fd3428d..43369c47 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/JavascriptProtocolStreamHandler.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/JavascriptProtocolStreamHandler.java @@ -15,13 +15,12 @@ */ package org.jahia.modules.javascript.modules.engine.jshandler; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.url.AbstractURLStreamHandlerService; -import org.osgi.service.url.URLStreamHandlerService; - import java.io.IOException; import java.net.URL; import java.net.URLConnection; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.url.AbstractURLStreamHandlerService; +import org.osgi.service.url.URLStreamHandlerService; /** * Javascript protocol handler diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/TarUtils.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/TarUtils.java index 8a184ce2..dab59e7e 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/TarUtils.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/TarUtils.java @@ -15,16 +15,15 @@ */ package org.jahia.modules.javascript.modules.engine.jshandler; +import java.io.*; +import java.util.LinkedList; +import java.util.List; import org.apache.commons.compress.archivers.ArchiveException; import org.apache.commons.compress.archivers.ArchiveStreamFactory; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.io.IOUtils; -import java.io.*; -import java.util.LinkedList; -import java.util.List; - /** * Util to untar */ @@ -39,7 +38,8 @@ static List unTar(final InputStream is, final File outputDir) throws IOExc if (entry.isDirectory()) { if (!outputFile.exists()) { if (!outputFile.mkdirs()) { - throw new IllegalStateException(String.format("Couldn't create directory %s.", outputFile.getAbsolutePath())); + throw new IllegalStateException( + String.format("Couldn't create directory %s.", outputFile.getAbsolutePath())); } } } else { diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/AbstractFileParser.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/AbstractFileParser.java index 3798ebdb..19c864ca 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/AbstractFileParser.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/AbstractFileParser.java @@ -20,14 +20,13 @@ /** * Abstract file parser * - * TEMPORARY WORKAROUND - DO NOT USE - * This class duplicates poor legacy code to provide backward compatibility. - * Marked for immediate replacement and removal. + * TEMPORARY WORKAROUND - DO NOT USE This class duplicates poor legacy code to provide backward compatibility. Marked + * for immediate replacement and removal. * * @deprecated since 1.0.0 Technical debt. Will be removed in next major version. */ @Deprecated(since = "1.0.0") - public abstract class AbstractFileParser implements FileParser, Comparable { +public abstract class AbstractFileParser implements FileParser, Comparable { private Logger logger; protected int priority = 0; diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/AbstractXmlFileParser.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/AbstractXmlFileParser.java index b187a63f..6405c8ed 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/AbstractXmlFileParser.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/AbstractXmlFileParser.java @@ -15,6 +15,10 @@ */ package org.jahia.modules.javascript.modules.engine.jshandler.parsers; +import java.io.*; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.jdom2.Attribute; @@ -24,36 +28,43 @@ import org.jdom2.input.SAXBuilder; import org.jdom2.xpath.XPath; -import java.io.*; -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - /** * Generic file parser for different XML file types * - * TEMPORARY WORKAROUND - DO NOT USE - * This class duplicates poor legacy code to provide backward compatibility. - * Marked for immediate replacement and removal. + * TEMPORARY WORKAROUND - DO NOT USE This class duplicates poor legacy code to provide backward compatibility. Marked + * for immediate replacement and removal. * * @deprecated since 1.0.0 Technical debt. Will be removed in next major version. */ @Deprecated(since = "1.0.0") - abstract class AbstractXmlFileParser extends AbstractFileParser { +abstract class AbstractXmlFileParser extends AbstractFileParser { public static final Pattern XPATH_PREFIX_PATTERN = Pattern.compile("(\\w+):[\\w-]+"); public abstract boolean canParse(String fileName, Element rootElement); - public abstract void parse(String fileName, Element rootElement, String fileParent, boolean externalDependency, boolean optionalDependency, String version, ParsingContext parsingContext) - throws JDOMException; + public abstract void parse( + String fileName, + Element rootElement, + String fileParent, + boolean externalDependency, + boolean optionalDependency, + String version, + ParsingContext parsingContext) throws JDOMException; public boolean canParse(String fileName) { String ext = FilenameUtils.getExtension(fileName).toLowerCase(); return "xml".equals(ext); } - public boolean parse(String fileName, InputStream inputStream, String fileParent, boolean externalDependency, boolean optionalDependency, String version, ParsingContext parsingContext) { + public boolean parse( + String fileName, + InputStream inputStream, + String fileParent, + boolean externalDependency, + boolean optionalDependency, + String version, + ParsingContext parsingContext) { boolean processed = true; SAXBuilder saxBuilder = new SAXBuilder(); saxBuilder.setValidation(false); @@ -71,15 +82,32 @@ public boolean parse(String fileName, InputStream inputStream, String fileParent // getLog().debug("Parsed XML file" + fileName + " successfully."); if (canParse(fileName, rootElement)) { - parse(fileName, rootElement, fileParent, externalDependency, optionalDependency, version, parsingContext); + parse( + fileName, + rootElement, + fileParent, + externalDependency, + optionalDependency, + version, + parsingContext); } else { processed = false; } } catch (JDOMException e) { - getLogger().warn("Error parsing XML file " + fileName + ": " + e.getMessage() + " enable debug mode (-X) for more detailed exception"); + getLogger() + .warn("Error parsing XML file " + + fileName + + ": " + + e.getMessage() + + " enable debug mode (-X) for more detailed exception"); getLogger().debug("Detailed exception", e); } catch (IOException e) { - getLogger().warn("Error parsing XML file " + fileName + ": " + e.getMessage() + " enable debug mode (-X) for more detailed exception"); + getLogger() + .warn("Error parsing XML file " + + fileName + + ": " + + e.getMessage() + + " enable debug mode (-X) for more detailed exception"); getLogger().debug("Detailed exception", e); } finally { IOUtils.closeQuietly(inputStreamCopy); @@ -88,13 +116,13 @@ public boolean parse(String fileName, InputStream inputStream, String fileParent } public boolean hasNamespaceURI(Element element, String namespaceURI) { - //getLog().debug("Main namespace URI=" + element.getNamespace().getURI()); + // getLog().debug("Main namespace URI=" + element.getNamespace().getURI()); if (element.getNamespace().getURI().equals(namespaceURI)) { return true; } List additionalNamespaces = (List) element.getAdditionalNamespaces(); for (Namespace additionalNamespace : additionalNamespaces) { - //getLog().debug("Additional namespace URI=" + additionalNamespace.getURI()); + // getLog().debug("Additional namespace URI=" + additionalNamespace.getURI()); if (additionalNamespace.getURI().equals(namespaceURI)) { return true; } @@ -103,15 +131,14 @@ public boolean hasNamespaceURI(Element element, String namespaceURI) { } /** - * Utility method to retrieve an XML element using an XPath expression. Note that this method is - * namespace aware and will require you to use the "xp" prefix in your XPath queries. For example, an XPath query - * for a Spring XML configuration will look like this : - * /xp:beans/xp:bean[@id="FileListSync"]/xp:property[@name="syncUrl"] - * Currently there is no way to rename the prefix. + * Utility method to retrieve an XML element using an XPath expression. Note that this method is namespace aware and + * will require you to use the "xp" prefix in your XPath queries. For example, an XPath query for a Spring XML + * configuration will look like this : /xp:beans/xp:bean[@id="FileListSync"]/xp:property[@name="syncUrl"] Currently + * there is no way to rename the prefix. * - * @param scopeElement the scope in which to execute the XPath query + * @param scopeElement the scope in which to execute the XPath query * @param xPathExpression the XPath query to select the element we wish to retrieve. In the case where multiple - * elements match, only the first one will be returned. + * elements match, only the first one will be returned. * @return the first element that matches the XPath expression, or null if no element matches. * @throws JDOMException raised if there was a problem navigating the JDOM structure. */ @@ -121,7 +148,8 @@ public static Element getElement(Element scopeElement, String xPathExpression) t if ((namespaceURI != null) && (!"".equals(namespaceURI))) { xPath.addNamespace("xp", namespaceURI); } - for (Namespace additionalNamespace : (List) scopeElement.getDocument().getRootElement().getAdditionalNamespaces()) { + for (Namespace additionalNamespace : (List< + Namespace>) scopeElement.getDocument().getRootElement().getAdditionalNamespaces()) { xPath.addNamespace(additionalNamespace); } return (Element) xPath.selectSingleNode(scopeElement); @@ -159,7 +187,8 @@ public List getAttributes(Element scopeElement, String xPathExpressio if ((namespaceURI != null) && (!"".equals(namespaceURI))) { xPath.addNamespace("xp", namespaceURI); } - for (Namespace additionalNamespace : (List) scopeElement.getDocument().getRootElement().getAdditionalNamespaces()) { + for (Namespace additionalNamespace : (List< + Namespace>) scopeElement.getDocument().getRootElement().getAdditionalNamespaces()) { xPath.addNamespace(additionalNamespace); } for (Object obj : xPath.selectNodes(scopeElement)) { @@ -196,7 +225,8 @@ public Set getMissingQueryPrefixes(Element root, String xPathQuery) { return missingPrefixes; } - public List getNodes(Element scopeElement, String xPathExpression, String defaultPrefix) throws JDOMException { + public List getNodes(Element scopeElement, String xPathExpression, String defaultPrefix) + throws JDOMException { List nodes = new LinkedList(); XPath xPath = XPath.newInstance(xPathExpression); String namespaceURI = scopeElement.getDocument().getRootElement().getNamespaceURI(); @@ -213,34 +243,42 @@ public List getNodes(Element scopeElement, String xPathExpression, Strin } /** - * Use an array of XPath queries to extract class name, package or content type references from - * a JDOM document. + * Use an array of XPath queries to extract class name, package or content type references from a JDOM document. * - * @param fileName the name of the file (mostly used for logging) - * @param root the root element to search the DOM - * @param classNameReferences if true, indicates that the queries reference class names, if false - * we check the value of packageReferences parameter. If both are false - * we assume we are dealing with content node types - * @param packageReferences if true, indicates that the queries reference package names, if false - * and classNameReferences is also false, we assume we are searching for - * content node types - * @param xPathQueries the XPath queries to execute to extract the references + * @param fileName the name of the file (mostly used for logging) + * @param root the root element to search the DOM + * @param classNameReferences if true, indicates that the queries reference class names, if false we check the value + * of packageReferences parameter. If both are false we assume we are dealing with content node types + * @param packageReferences if true, indicates that the queries reference package names, if false and + * classNameReferences is also false, we assume we are searching for content node types + * @param xPathQueries the XPath queries to execute to extract the references * @param defaultNamespacePrefix the default namespace prefix to use for the XPath queries * @param optionalDependency - *@param parsingContext the context in which we will store the references, depending on the type - * of references we are parsing. @throws JDOMException + * @param parsingContext the context in which we will store the references, depending on the type of references we + * are parsing. @throws JDOMException */ - public void getRefsUsingXPathQueries(String fileName, Element root, - boolean classNameReferences, - boolean packageReferences, - String[] xPathQueries, String defaultNamespacePrefix, - String fileParent, - String version, - boolean optionalDependency, ParsingContext parsingContext) throws JDOMException { + public void getRefsUsingXPathQueries( + String fileName, + Element root, + boolean classNameReferences, + boolean packageReferences, + String[] xPathQueries, + String defaultNamespacePrefix, + String fileParent, + String version, + boolean optionalDependency, + ParsingContext parsingContext) throws JDOMException { for (String xPathQuery : xPathQueries) { Set missingPrefixes = getMissingQueryPrefixes(root, xPathQuery); if (missingPrefixes.size() > 0) { - getLogger().debug(fileParent + " / " + fileName + ": xPath query " + xPathQuery + " cannot be executed on this file since it has prefixes not declared in the file: " + missingPrefixes); + getLogger() + .debug(fileParent + + " / " + + fileName + + ": xPath query " + + xPathQuery + + " cannot be executed on this file since it has prefixes not declared in the file: " + + missingPrefixes); continue; } List referenceObjects = getNodes(root, xPathQuery, defaultNamespacePrefix); @@ -251,7 +289,15 @@ public void getRefsUsingXPathQueries(String fileName, Element root, } else if (referenceObject instanceof Element) { referenceValue = ((Element) referenceObject).getTextTrim(); } else { - getLogger().warn(fileParent + " / " + fileName + ": xPath query" + xPathQuery + " return unknown XML node type " + referenceObject + "..."); + getLogger() + .warn(fileParent + + " / " + + fileName + + ": xPath query" + + xPathQuery + + " return unknown XML node type " + + referenceObject + + "..."); } if (referenceValue != null) { if (classNameReferences) { @@ -285,11 +331,20 @@ public void getRefsUsingXPathQueries(String fileName, Element root, public void dumpElementNamespaces(Element element) { Namespace mainNamespace = element.getNamespace(); - getLogger().debug("Main namespace prefix=[" + mainNamespace.getPrefix() + "] uri=[" + mainNamespace.getURI() + "] getNamespaceURI=[" + element.getNamespaceURI() + "]"); + getLogger() + .debug("Main namespace prefix=[" + + mainNamespace.getPrefix() + + "] uri=[" + + mainNamespace.getURI() + + "] getNamespaceURI=[" + + element.getNamespaceURI() + + "]"); for (Namespace additionalNamespace : (List) element.getAdditionalNamespaces()) { - getLogger().debug("Additional namespace prefix=" + additionalNamespace.getPrefix() + " uri=" + additionalNamespace.getURI()); + getLogger() + .debug("Additional namespace prefix=" + + additionalNamespace.getPrefix() + + " uri=" + + additionalNamespace.getURI()); } } - - } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/CndFileParser.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/CndFileParser.java index 4968dedf..a3288ace 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/CndFileParser.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/CndFileParser.java @@ -15,25 +15,23 @@ */ package org.jahia.modules.javascript.modules.engine.jshandler.parsers; -import org.apache.commons.io.FilenameUtils; -import org.jahia.modules.javascript.modules.engine.jshandler.parsers.cnd.JahiaCndReader; -import org.jahia.modules.javascript.modules.engine.jshandler.parsers.cnd.NodeTypeRegistry; -import org.jahia.modules.javascript.modules.engine.jshandler.parsers.cnd.ParseException; - -import javax.jcr.RepositoryException; -import javax.jcr.ValueFormatException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Set; import java.util.TreeSet; +import javax.jcr.RepositoryException; +import javax.jcr.ValueFormatException; +import org.apache.commons.io.FilenameUtils; +import org.jahia.modules.javascript.modules.engine.jshandler.parsers.cnd.JahiaCndReader; +import org.jahia.modules.javascript.modules.engine.jshandler.parsers.cnd.NodeTypeRegistry; +import org.jahia.modules.javascript.modules.engine.jshandler.parsers.cnd.ParseException; /** * A CND (JCR content definition) file parser * - * TEMPORARY WORKAROUND - DO NOT USE - * This class duplicates poor legacy code to provide backward compatibility. - * Marked for immediate replacement and removal. + * TEMPORARY WORKAROUND - DO NOT USE This class duplicates poor legacy code to provide backward compatibility. Marked + * for immediate replacement and removal. * * @deprecated since 1.0.0 Technical debt. Will be removed in next major version. */ @@ -45,11 +43,19 @@ public boolean canParse(String fileName) { return "cnd".equals(ext); } - public boolean parse(String fileName, InputStream inputStream, String fileParent, boolean externalDependency, boolean optionalDependency, String version, ParsingContext parsingContext) throws IOException { + public boolean parse( + String fileName, + InputStream inputStream, + String fileParent, + boolean externalDependency, + boolean optionalDependency, + String version, + ParsingContext parsingContext) throws IOException { getLogger().debug("Processing CND " + fileName + "..."); try { - JahiaCndReader jahiaCndReader = new JahiaCndReader(new InputStreamReader(inputStream), fileName, fileName, NodeTypeRegistry.getInstance()); + JahiaCndReader jahiaCndReader = new JahiaCndReader( + new InputStreamReader(inputStream), fileName, fileName, NodeTypeRegistry.getInstance()); jahiaCndReader.setDoRegister(false); jahiaCndReader.parse(); diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/FileParser.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/FileParser.java index be7843b5..8764ab31 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/FileParser.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/FileParser.java @@ -15,17 +15,15 @@ */ package org.jahia.modules.javascript.modules.engine.jshandler.parsers; -import org.slf4j.Logger; - import java.io.IOException; import java.io.InputStream; +import org.slf4j.Logger; /** * Defines a parser interface that will parse the contents of a file to find package references inside of it. * - * TEMPORARY WORKAROUND - DO NOT USE - * This class duplicates poor legacy code to provide backward compatibility. - * Marked for immediate replacement and removal. + * TEMPORARY WORKAROUND - DO NOT USE This class duplicates poor legacy code to provide backward compatibility. Marked + * for immediate replacement and removal. * * @deprecated since 1.0.0 Technical debt. Will be removed in next major version. */ @@ -40,6 +38,12 @@ public interface FileParser { boolean canParse(String fileName); - boolean parse(String fileName, InputStream inputStream, String fileParent, boolean externalDependency, boolean optionalDependency, String version, ParsingContext parsingContext) throws IOException; - + boolean parse( + String fileName, + InputStream inputStream, + String fileParent, + boolean externalDependency, + boolean optionalDependency, + String version, + ParsingContext parsingContext) throws IOException; } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/JCRImportXmlFileParser.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/JCRImportXmlFileParser.java index 96ea9aaf..8d6b56d8 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/JCRImportXmlFileParser.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/JCRImportXmlFileParser.java @@ -21,19 +21,15 @@ /** * JCR Import file parser * - * TEMPORARY WORKAROUND - DO NOT USE - * This class duplicates poor legacy code to provide backward compatibility. - * Marked for immediate replacement and removal. + * TEMPORARY WORKAROUND - DO NOT USE This class duplicates poor legacy code to provide backward compatibility. Marked + * for immediate replacement and removal. * * @deprecated since 1.0.0 Technical debt. Will be removed in next major version. */ @Deprecated(since = "1.0.0") public class JCRImportXmlFileParser extends AbstractXmlFileParser { - private final static String[] JCR_IMPORT_XPATH_QUERIES = { - "//@jcr:primaryType", - "//@jcr:mixinTypes" - }; + private static final String[] JCR_IMPORT_XPATH_QUERIES = {"//@jcr:primaryType", "//@jcr:mixinTypes"}; @Override public boolean canParse(String fileName, Element rootElement) { @@ -41,9 +37,26 @@ public boolean canParse(String fileName, Element rootElement) { } @Override - public void parse(String fileName, Element rootElement, String fileParent, boolean externalDependency, boolean optionalDependency, String version, ParsingContext parsingContext) throws JDOMException { + public void parse( + String fileName, + Element rootElement, + String fileParent, + boolean externalDependency, + boolean optionalDependency, + String version, + ParsingContext parsingContext) throws JDOMException { getLogger().debug("Processing JCR import file " + fileParent + " / " + fileName + "..."); - getRefsUsingXPathQueries(fileName, rootElement, false, false, JCR_IMPORT_XPATH_QUERIES, "xp", fileParent, version, optionalDependency, parsingContext); + getRefsUsingXPathQueries( + fileName, + rootElement, + false, + false, + JCR_IMPORT_XPATH_QUERIES, + "xp", + fileParent, + version, + optionalDependency, + parsingContext); } } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/ParsingContext.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/ParsingContext.java index 3bed777c..8c507e29 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/ParsingContext.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/ParsingContext.java @@ -16,16 +16,14 @@ package org.jahia.modules.javascript.modules.engine.jshandler.parsers; import com.fasterxml.jackson.annotation.JsonIgnore; - import java.io.Serializable; import java.util.*; /** * Context for parsing files * - * TEMPORARY WORKAROUND - DO NOT USE - * This class duplicates poor legacy code to provide backward compatibility. - * Marked for immediate replacement and removal. + * TEMPORARY WORKAROUND - DO NOT USE This class duplicates poor legacy code to provide backward compatibility. Marked + * for immediate replacement and removal. * * @deprecated since 1.0.0 Technical debt. Will be removed in next major version. */ @@ -44,13 +42,14 @@ public class ParsingContext implements Serializable { private boolean osgiBundle = false; private List bundleClassPath = new ArrayList<>(); - @JsonIgnore protected List children = new ArrayList<>(); - @JsonIgnore Boolean optional = null; - @JsonIgnore Boolean external = null; - - public ParsingContext() { - } + @JsonIgnore + protected List children = new ArrayList<>(); + @JsonIgnore + Boolean optional = null; + @JsonIgnore + Boolean external = null; + public ParsingContext() {} public Set getContentTypeDefinitions() { return contentTypeDefinitions; @@ -116,9 +115,7 @@ public boolean isExternal() { } public void setExternal(boolean external) { - if (this.external != null) { - - } + if (this.external != null) {} this.external = external; } @@ -147,5 +144,4 @@ public String toString() { sb.append('}'); return sb.toString(); } - } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/Constants.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/Constants.java index 58c94af2..6f18b4c2 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/Constants.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/Constants.java @@ -16,11 +16,8 @@ package org.jahia.modules.javascript.modules.engine.jshandler.parsers.cnd; /** - * Created with IntelliJ IDEA. - * User: loom - * Date: 27.02.13 - * Time: 10:39 - * To change this template use File | Settings | File Templates. + * Created with IntelliJ IDEA. User: loom Date: 27.02.13 Time: 10:39 To change this template use File | Settings | File + * Templates. */ class Constants { public static final String MIX_REFERENCEABLE = "mix:referenceable"; diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/DynamicValueImpl.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/DynamicValueImpl.java index 1e80739e..b5b6b257 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/DynamicValueImpl.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/DynamicValueImpl.java @@ -15,26 +15,22 @@ */ package org.jahia.modules.javascript.modules.engine.jshandler.parsers.cnd; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; - -import javax.jcr.Binary; -import javax.jcr.RepositoryException; -import javax.jcr.Value; -import javax.jcr.ValueFormatException; import java.io.InputStream; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.List; +import javax.jcr.Binary; +import javax.jcr.RepositoryException; +import javax.jcr.Value; +import javax.jcr.ValueFormatException; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; /** * - * User: toto - * Date: Apr 3, 2008 - * Time: 12:26:22 PM - * + * User: toto Date: Apr 3, 2008 Time: 12:26:22 PM */ class DynamicValueImpl implements Value { @@ -46,7 +42,12 @@ class DynamicValueImpl implements Value { protected int type; private boolean isConstraint; - public DynamicValueImpl(String fn, List params, int type, boolean isConstraint, ExtendedPropertyDefinition declaringPropertyDefinition) { + public DynamicValueImpl( + String fn, + List params, + int type, + boolean isConstraint, + ExtendedPropertyDefinition declaringPropertyDefinition) { this.type = type; this.fn = fn; this.params = params; @@ -98,27 +99,27 @@ public List getParams() { return params; } -// public String getString() { -// if (fn.equals("now")) { -// return ISO8601.format(new GregorianCalendar()); -// } else if (fn.equals("resourceKey")) { -// String bundleId = ((ExtendedNodeType) declaringPropertyDefinition.getDeclaringNodeType()).getResourceBundleId(); -// return ResourceBundleMarker.drawMarker(bundleId,declaringPropertyDefinition.getResourceBundleKey()+"."+getParams().get(0),getParams().get(0)); -// } else if (fn.equals("useClass")) { -// String classname = getParams().get(0); -// try { -// ValueInitializer init = (ValueInitializer) Class.forName(classname).newInstance(); -// return init.getValue(Jahia.getThreadParamBean()); -// } catch (InstantiationException e) { -// logger.error(e.getMessage(), e); -// } catch (IllegalAccessException e) { -// logger.error(e.getMessage(), e); -// } catch (ClassNotFoundException e) { -// logger.error(e.getMessage(), e); -// } -// } -// return null; -// } + // public String getString() { + // if (fn.equals("now")) { + // return ISO8601.format(new GregorianCalendar()); + // } else if (fn.equals("resourceKey")) { + // String bundleId = ((ExtendedNodeType) declaringPropertyDefinition.getDeclaringNodeType()).getResourceBundleId(); + // return ResourceBundleMarker.drawMarker(bundleId,declaringPropertyDefinition.getResourceBundleKey()+"."+getParams().get(0),getParams().get(0)); + // } else if (fn.equals("useClass")) { + // String classname = getParams().get(0); + // try { + // ValueInitializer init = (ValueInitializer) Class.forName(classname).newInstance(); + // return init.getValue(Jahia.getThreadParamBean()); + // } catch (InstantiationException e) { + // logger.error(e.getMessage(), e); + // } catch (IllegalAccessException e) { + // logger.error(e.getMessage(), e); + // } catch (ClassNotFoundException e) { + // logger.error(e.getMessage(), e); + // } + // } + // return null; + // } public Value[] expand() { Value[] v = null; @@ -126,7 +127,7 @@ public Value[] expand() { if (fn.equals("useClass")) { classname = getParams().get(0); } else { - classname = "org.jahia.services.content.nodetypes.initializers."+ StringUtils.capitalize(fn); + classname = "org.jahia.services.content.nodetypes.initializers." + StringUtils.capitalize(fn); } try { ValueInitializer init = (ValueInitializer) Class.forName(classname).newInstance(); @@ -143,7 +144,7 @@ public Value[] expand() { for (int i = 0; i < v.length; i++) { Value value = v[i]; if (value instanceof DynamicValueImpl) { - res.addAll(Arrays.asList(((DynamicValueImpl)value).expand())); + res.addAll(Arrays.asList(((DynamicValueImpl) value).expand())); } else { res.add(value); } @@ -157,7 +158,7 @@ private Value getExpandedValue() throws ValueFormatException { if (v.length == 1) { return v[0]; } else { - throw new ValueFormatException("Dynamic value expanded to none/multiple values : "+v.length ); + throw new ValueFormatException("Dynamic value expanded to none/multiple values : " + v.length); } } } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ExtendedItemDefinition.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ExtendedItemDefinition.java index 6259655b..b0d180fd 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ExtendedItemDefinition.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ExtendedItemDefinition.java @@ -15,18 +15,15 @@ */ package org.jahia.modules.javascript.modules.engine.jshandler.parsers.cnd; -import javax.jcr.nodetype.ItemDefinition; -import javax.jcr.version.OnParentVersionAction; import java.util.Collections; import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import javax.jcr.nodetype.ItemDefinition; +import javax.jcr.version.OnParentVersionAction; /** - * Jahia specific {@link ItemDefinition} implementation. - * User: toto - * Date: 15 janv. 2008 - * Time: 17:43:58 + * Jahia specific {@link ItemDefinition} implementation. User: toto Date: 15 janv. 2008 Time: 17:43:58 */ class ExtendedItemDefinition implements ItemDefinition { @@ -40,10 +37,10 @@ class ExtendedItemDefinition implements ItemDefinition { private int onParentVersion = OnParentVersionAction.VERSION; private int onConflict = OnConflictAction.USE_LATEST; protected int selector = 0; - private Map selectorOptions = new ConcurrentHashMap(); + private Map selectorOptions = new ConcurrentHashMap(); private Map labels = new ConcurrentHashMap(1); - private Map> labelsByNodeType = new ConcurrentHashMap>(1); - private Map> tooltipsByNodeType = new ConcurrentHashMap>(1); + private Map> labelsByNodeType = new ConcurrentHashMap>(1); + private Map> tooltipsByNodeType = new ConcurrentHashMap>(1); private boolean override = false; public ExtendedNodeType getDeclaringNodeType() { @@ -126,11 +123,11 @@ public void setSelector(int selector) { this.selector = selector; } - public Map getSelectorOptions() { + public Map getSelectorOptions() { return Collections.unmodifiableMap(selectorOptions); } - public void setSelectorOptions(Map selectorOptions) { + public void setSelectorOptions(Map selectorOptions) { this.selectorOptions = selectorOptions; } @@ -151,10 +148,8 @@ public String getResourceBundleKey() { } public String getResourceBundleKey(ExtendedNodeType nodeType) { - if(nodeType==null) - return replaceColon((getDeclaringNodeType().getName() + "." + getName())); - else - return replaceColon((nodeType.getName() + "." + getName())); + if (nodeType == null) return replaceColon((getDeclaringNodeType().getName() + "." + getName())); + else return replaceColon((nodeType.getName() + "." + getName())); } public String getItemType() { @@ -181,28 +176,27 @@ public void setItemType(String itemType) { } public boolean isContentItem() { - return !isHidden()&&"content".equals(getItemType()); -// declaringNodeType.isNodeType("jmix:droppableContent") || declaringNodeType.isNodeType("jnt:container") -// || declaringNodeType.isNodeType("jnt:content") || declaringNodeType.isNodeType("jmix:contentItem") || name.toString().equals("jcr:title") || name.toString().equals("jcr:language") || name.toString().equals("jcr:statement"); + return !isHidden() && "content".equals(getItemType()); + // declaringNodeType.isNodeType("jmix:droppableContent") || declaringNodeType.isNodeType("jnt:container") + // || declaringNodeType.isNodeType("jnt:content") || declaringNodeType.isNodeType("jmix:contentItem") || name.toString().equals("jcr:title") || name.toString().equals("jcr:language") || name.toString().equals("jcr:statement"); } public ExtendedItemDefinition getOverridenDefinition() { ExtendedItemDefinition overridenItemDefintion = this; if (isOverride()) { - for (ExtendedItemDefinition itemDef : declaringNodeType.getItems()) { - if (itemDef.getName().equals(this.getName()) && !itemDef.isOverride()) { - overridenItemDefintion = itemDef; - break; - } - } + for (ExtendedItemDefinition itemDef : declaringNodeType.getItems()) { + if (itemDef.getName().equals(this.getName()) && !itemDef.isOverride()) { + overridenItemDefintion = itemDef; + break; + } + } } return overridenItemDefintion; } @Override public boolean equals(Object obj) { - if (this == obj) - return true; + if (this == obj) return true; if (obj == null || this.getClass() != obj.getClass()) { return false; @@ -211,8 +205,9 @@ public boolean equals(Object obj) { final ExtendedItemDefinition other = (ExtendedItemDefinition) obj; return (getName() != null ? getName().equals(other.getName()) : other.getName() == null) - && (getDeclaringNodeType().getName() != null ? getDeclaringNodeType().getName().equals( - other.getDeclaringNodeType().getName()) : other.getDeclaringNodeType().getName() == null); + && (getDeclaringNodeType().getName() != null + ? getDeclaringNodeType().getName().equals(other.getDeclaringNodeType().getName()) + : other.getDeclaringNodeType().getName() == null); } @Override @@ -231,5 +226,4 @@ public void clearLabels() { public static String replaceColon(String name) { return name != null ? Patterns.COLON.matcher(name).replaceAll("_") : name; } - } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ExtendedNodeDefinition.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ExtendedNodeDefinition.java index 911fd777..613db0ca 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ExtendedNodeDefinition.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ExtendedNodeDefinition.java @@ -15,19 +15,15 @@ */ package org.jahia.modules.javascript.modules.engine.jshandler.parsers.cnd; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import java.util.Arrays; import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.nodetype.NodeDefinition; -import java.util.Arrays; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * - * User: toto - * Date: 4 janv. 2008 - * Time: 14:08:56 - * + * User: toto Date: 4 janv. 2008 Time: 14:08:56 */ class ExtendedNodeDefinition extends ExtendedItemDefinition implements NodeDefinition { private static final transient Logger logger = LoggerFactory.getLogger(ExtendedItemDefinition.class); @@ -37,7 +33,7 @@ class ExtendedNodeDefinition extends ExtendedItemDefinition implements NodeDefin private String[] requiredPrimaryTypes; private String defaultPrimaryType; private boolean allowsSameNameSiblings; -// private boolean liveContent = false; + // private boolean liveContent = false; private String workflow; public ExtendedNodeDefinition(NodeTypeRegistry registry) { @@ -58,7 +54,7 @@ public ExtendedNodeType[] getRequiredPrimaryTypes() { try { res[i] = registry.getNodeType(requiredPrimaryTypes[i]); } catch (NoSuchNodeTypeException e) { - logger.error("Nodetype not found",e); + logger.error("Nodetype not found", e); } } return res; @@ -68,7 +64,6 @@ public String[] getRequiredPrimaryTypeNames() { return requiredPrimaryTypes; } - public void setRequiredPrimaryTypes(String[] requiredPrimaryTypes) { this.requiredPrimaryTypes = requiredPrimaryTypes; } @@ -78,7 +73,7 @@ public ExtendedNodeType getDefaultPrimaryType() { try { return registry.getNodeType(defaultPrimaryType); } catch (NoSuchNodeTypeException e) { - logger.error("Nodetype not found",e); + logger.error("Nodetype not found", e); } } return null; @@ -108,13 +103,13 @@ public void setWorkflow(String workflow) { this.workflow = workflow; } -// public boolean isLiveContent() { -// return liveContent; -// } -// -// public void setLiveContent(boolean liveContent) { -// this.liveContent = liveContent; -// } + // public boolean isLiveContent() { + // return liveContent; + // } + // + // public void setLiveContent(boolean liveContent) { + // this.liveContent = liveContent; + // } public boolean isNode() { return true; diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ExtendedNodeType.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ExtendedNodeType.java index e6ad52da..04e9f3f3 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ExtendedNodeType.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ExtendedNodeType.java @@ -15,25 +15,22 @@ */ package org.jahia.modules.javascript.modules.engine.jshandler.parsers.cnd; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; - +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; import javax.jcr.PropertyType; import javax.jcr.RepositoryException; import javax.jcr.Value; import javax.jcr.nodetype.*; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; /** * Jahia extended JCR node type information. - * @author Thomas Draier - * Date: 4 janv. 2008 - * Time: 14:02:22 + * @author Thomas Draier Date: 4 janv. 2008 Time: 14:02:22 */ class ExtendedNodeType implements NodeType { - private static final Logger logger = org.slf4j.LoggerFactory.getLogger(ExtendedNodeType.class); + private static final Logger logger = org.slf4j.LoggerFactory.getLogger(ExtendedNodeType.class); private NodeTypeRegistry registry; private String systemId; @@ -41,9 +38,12 @@ class ExtendedNodeType implements NodeType { private List groupedItems; private Map nodes = new ConcurrentHashMap(); - private Map properties = new ConcurrentHashMap(); - private Map unstructuredNodes = new ConcurrentHashMap(); - private Map unstructuredProperties = new ConcurrentHashMap(); + private Map properties = + new ConcurrentHashMap(); + private Map unstructuredNodes = + new ConcurrentHashMap(); + private Map unstructuredProperties = + new ConcurrentHashMap(); private Map allNodes; private Map allProperties; @@ -63,11 +63,12 @@ class ExtendedNodeType implements NodeType { private String itemsType; private List mixinExtendNames = new ArrayList(); private List mixinExtend = new ArrayList(); -// private boolean liveContent = false; + // private boolean liveContent = false; private Map labels = new ConcurrentHashMap(1); private Map descriptions = new ConcurrentHashMap(1); private boolean systemType; + public ExtendedNodeType(NodeTypeRegistry registry, String systemId) { this.registry = registry; this.systemId = systemId; @@ -115,16 +116,16 @@ public void setMixin(boolean mixin) { isMixin = mixin; } -// public boolean isLiveContent() { -// return liveContent; -// } -// -// public void setLiveContent(boolean liveContent) { -// this.liveContent = liveContent; -// } + // public boolean isLiveContent() { + // return liveContent; + // } + // + // public void setLiveContent(boolean liveContent) { + // this.liveContent = liveContent; + // } public boolean hasOrderableChildNodes() { - if(!hasOrderableChildNodes) { + if (!hasOrderableChildNodes) { return hasOrderableChildNodes(true); } return hasOrderableChildNodes; @@ -163,7 +164,6 @@ public void setPrimaryItemName(String primaryItemName) { this.primaryItemName = primaryItemName; } - public ExtendedNodeType[] getSupertypes() { Set l = getSupertypeSet(); return l.toArray(new ExtendedNodeType[l.size()]); @@ -182,15 +182,15 @@ public Set getSupertypeSet() { primaryFound = true; } } - if(s != null && s.getNameObject().equals(getNameObject())) { - logger.error("Loop detected in definition "+getName()); + if (s != null && s.getNameObject().equals(getNameObject())) { + logger.error("Loop detected in definition " + getName()); } } if (!primaryFound && !Constants.NT_BASE.equals(getName()) && !isMixin) { try { l.add(registry.getNodeType(Constants.NT_BASE)); } catch (NoSuchNodeTypeException e) { - logger.error("No such supertype for "+getName(),e); + logger.error("No such supertype for " + getName(), e); } } return l; @@ -212,7 +212,7 @@ public ExtendedNodeType[] getPrimarySupertypes() { try { l.add(registry.getNodeType(Constants.NT_BASE)); } catch (NoSuchNodeTypeException e) { - logger.error("No such supertype for "+getName(),e); + logger.error("No such supertype for " + getName(), e); } } return l.toArray(new ExtendedNodeType[l.size()]); @@ -226,16 +226,16 @@ public void setDeclaredSupertypes(String[] declaredSupertypes) { this.declaredSupertypeNames = declaredSupertypes; } - public void validate() throws NoSuchNodeTypeException { this.declaredSupertypes = new ExtendedNodeType[declaredSupertypeNames.length]; int mixIndex = 0; for (int i = 0; i < declaredSupertypeNames.length; i++) { final ExtendedNodeType nodeType = registry.getNodeType(declaredSupertypeNames[i]); - if (!nodeType.isMixin && i>0) { - System.arraycopy(this.declaredSupertypes, mixIndex, this.declaredSupertypes, mixIndex+1, i-mixIndex); + if (!nodeType.isMixin && i > 0) { + System.arraycopy( + this.declaredSupertypes, mixIndex, this.declaredSupertypes, mixIndex + 1, i - mixIndex); this.declaredSupertypes[mixIndex] = nodeType; - mixIndex ++; + mixIndex++; } else { this.declaredSupertypes[i] = nodeType; } @@ -268,11 +268,10 @@ public String[] getDeclaredSupertypeNames() { return declaredSupertypeNames; } - public NodeTypeIterator getSubtypes() { List l = new ArrayList(); - for (Iterator iterator = declaredSubtypes.iterator(); iterator.hasNext();) { - ExtendedNodeType s = iterator.next(); + for (Iterator iterator = declaredSubtypes.iterator(); iterator.hasNext(); ) { + ExtendedNodeType s = iterator.next(); l.add(s); NodeTypeIterator subtypes = s.getSubtypes(); while (subtypes.hasNext()) { @@ -284,8 +283,8 @@ public NodeTypeIterator getSubtypes() { public List getSubtypesAsList() { List l = new ArrayList(); - for (Iterator iterator = declaredSubtypes.iterator(); iterator.hasNext();) { - ExtendedNodeType s = iterator.next(); + for (Iterator iterator = declaredSubtypes.iterator(); iterator.hasNext(); ) { + ExtendedNodeType s = iterator.next(); l.add(s); NodeTypeIterator subtypes = s.getSubtypes(); while (subtypes.hasNext()) { @@ -297,8 +296,8 @@ public List getSubtypesAsList() { public ExtendedNodeType[] getMixinSubtypes() { List l = new ArrayList(); - for (Iterator iterator = declaredSubtypes.iterator(); iterator.hasNext();) { - ExtendedNodeType s = iterator.next(); + for (Iterator iterator = declaredSubtypes.iterator(); iterator.hasNext(); ) { + ExtendedNodeType s = iterator.next(); if (s.isMixin()) { l.add(s); l.addAll(Arrays.asList(s.getMixinSubtypes())); @@ -321,25 +320,25 @@ public boolean isNodeType(String typeName) { return false; } - public List getItems() { + public List getItems() { List l = new ArrayList(); l.addAll(getDeclaredItems()); /* - ExtendedNodeType[] supertypes = getSupertypes(); - for (int i = 0; i < supertypes.length ; i++) { - l.addAll(supertypes[i].getDeclaredItems()); - } - */ + * ExtendedNodeType[] supertypes = getSupertypes(); + * for (int i = 0; i < supertypes.length ; i++) { + * l.addAll(supertypes[i].getDeclaredItems()); + * } + */ return l; } - public List getDeclaredItems() { + public List getDeclaredItems() { return getDeclaredItems(false); } - public List getDeclaredItems(boolean includeOverride) { + public List getDeclaredItems(boolean includeOverride) { getPropertyDefinitionsAsMap(); getChildNodeDefinitionsAsMap(); List res; @@ -358,46 +357,49 @@ public List getDeclaredItems(boolean includeOverride) { public Map getPropertyDefinitionsAsMap() { if (allProperties == null) { - synchronized (this) { - if (allProperties == null) { - LinkedHashMap props = new LinkedHashMap(); + synchronized (this) { + if (allProperties == null) { + LinkedHashMap props = + new LinkedHashMap(); - props.putAll(properties); + props.putAll(properties); /* - ExtendedNodeType[] supertypes = getSupertypes(); - for (int i = supertypes.length-1; i >=0 ; i--) { - ExtendedNodeType nodeType = supertypes[i]; - Map c = new HashMap(nodeType.getDeclaredPropertyDefinitionsAsMap()); - Map over = new HashMap(properties); - over.keySet().retainAll(c.keySet()); - for (ExtendedPropertyDefinition s : over.values()) { - s.setOverride(true); - } - c.keySet().removeAll(over.keySet()); - props.putAll(c); - } - */ - - allProperties = Collections.unmodifiableMap(props); - } - } + * ExtendedNodeType[] supertypes = getSupertypes(); + * for (int i = supertypes.length-1; i >=0 ; i--) { + * ExtendedNodeType nodeType = supertypes[i]; + * Map c = new HashMap(nodeType.getDeclaredPropertyDefinitionsAsMap()); + * Map over = new HashMap(properties); + * over.keySet().retainAll(c.keySet()); + * for (ExtendedPropertyDefinition s : over.values()) { + * s.setOverride(true); + * } + * c.keySet().removeAll(over.keySet()); + * props.putAll(c); + * } + */ + + allProperties = Collections.unmodifiableMap(props); + } + } } return allProperties; } - public Map getUnstructuredPropertyDefinitions() { + public Map getUnstructuredPropertyDefinitions() { if (allUnstructuredProperties == null) { - allUnstructuredProperties = new LinkedHashMap(); + allUnstructuredProperties = new LinkedHashMap(); allUnstructuredProperties.putAll(unstructuredProperties); ExtendedNodeType[] supertypes = getSupertypes(); - for (int i = supertypes.length-1; i >=0 ; i--) { + for (int i = supertypes.length - 1; i >= 0; i--) { ExtendedNodeType nodeType = supertypes[i]; - Map c = new HashMap(nodeType.getDeclaredUnstructuredPropertyDefinitions()); - Map over = new HashMap(unstructuredProperties); + Map c = new HashMap( + nodeType.getDeclaredUnstructuredPropertyDefinitions()); + Map over = + new HashMap(unstructuredProperties); over.keySet().retainAll(c.keySet()); for (ExtendedPropertyDefinition s : over.values()) { s.setOverride(true); @@ -430,7 +432,7 @@ public Map getDeclaredPropertyDefinitionsAsM return properties; } - public Map getDeclaredUnstructuredPropertyDefinitions() { + public Map getDeclaredUnstructuredPropertyDefinitions() { getUnstructuredPropertyDefinitions(); return unstructuredProperties; } @@ -441,7 +443,7 @@ public ExtendedPropertyDefinition[] getDeclaredPropertyDefinitions() { final List i = getDeclaredItems(); for (ExtendedItemDefinition item : i) { if (!item.isNode()) { // && ("*".equals(item.getName()) || !keys.contains(item.getName()))) { - list.add((ExtendedPropertyDefinition) item); + list.add((ExtendedPropertyDefinition) item); } } return list.toArray(new ExtendedPropertyDefinition[list.size()]); @@ -452,16 +454,18 @@ public Map getChildNodeDefinitionsAsMap() { return Collections.unmodifiableMap(over); } - public Map getUnstructuredChildNodeDefinitions() { + public Map getUnstructuredChildNodeDefinitions() { if (allUnstructuredNodes == null) { - allUnstructuredNodes = new ConcurrentHashMap(); + allUnstructuredNodes = new ConcurrentHashMap(); allUnstructuredNodes.putAll(unstructuredNodes); ExtendedNodeType[] supertypes = getSupertypes(); - for (int i = supertypes.length-1; i >=0 ; i--) { + for (int i = supertypes.length - 1; i >= 0; i--) { ExtendedNodeType nodeType = supertypes[i]; - Map c = new HashMap(nodeType.getDeclaredUnstructuredChildNodeDefinitions()); - Map over = new HashMap(unstructuredNodes); + Map c = new HashMap( + nodeType.getDeclaredUnstructuredChildNodeDefinitions()); + Map over = + new HashMap(unstructuredNodes); over.keySet().retainAll(c.keySet()); for (ExtendedNodeDefinition s : over.values()) { s.setOverride(true); @@ -493,7 +497,7 @@ public Map getDeclaredChildNodeDefinitionsAsMap( return nodes; } - public Map getDeclaredUnstructuredChildNodeDefinitions() { + public Map getDeclaredUnstructuredChildNodeDefinitions() { getUnstructuredChildNodeDefinitions(); return unstructuredNodes; } @@ -503,7 +507,7 @@ public ExtendedNodeDefinition[] getDeclaredChildNodeDefinitions() { final List i = getDeclaredItems(); for (ExtendedItemDefinition item : i) { if (item.isNode()) { // && ("*".equals(item.getName()) || !keys.contains(item.getName()))) { - list.add((ExtendedNodeDefinition) item); + list.add((ExtendedNodeDefinition) item); } } return list.toArray(new ExtendedNodeDefinition[list.size()]); @@ -522,29 +526,26 @@ public boolean canSetProperty(String propertyName, Value value) { // setting a property to null is equivalent of removing it return canRemoveItem(propertyName); } - ExtendedPropertyDefinition def = getPropertyDefinitionsAsMap() - .containsKey(propertyName) ? getPropertyDefinitionsAsMap().get(propertyName) - : getMatchingPropDef(getUnstructuredPropertyDefinitions().values(), - value.getType(), false); - if (def == null) { - def = getMatchingPropDef(getUnstructuredPropertyDefinitions().values(), - PropertyType.UNDEFINED, false); + ExtendedPropertyDefinition def = getPropertyDefinitionsAsMap().containsKey(propertyName) + ? getPropertyDefinitionsAsMap().get(propertyName) + : getMatchingPropDef(getUnstructuredPropertyDefinitions().values(), value.getType(), false); + if (def == null) { + def = getMatchingPropDef(getUnstructuredPropertyDefinitions().values(), PropertyType.UNDEFINED, false); + } + if (def != null) { + if (def.isMultiple() || def.isProtected()) { + return false; } - if (def != null) { - if (def.isMultiple() || def.isProtected()) { - return false; - } - int targetType; - if (def.getRequiredType() != PropertyType.UNDEFINED - && def.getRequiredType() != value.getType()) { - // type conversion required - targetType = def.getRequiredType(); - } else { - // no type conversion required - targetType = value.getType(); - } - return true; + int targetType; + if (def.getRequiredType() != PropertyType.UNDEFINED && def.getRequiredType() != value.getType()) { + // type conversion required + targetType = def.getRequiredType(); + } else { + // no type conversion required + targetType = value.getType(); } + return true; + } return false; } @@ -553,42 +554,40 @@ public boolean canSetProperty(String propertyName, Value[] values) { // setting a property to null is equivalent of removing it return canRemoveItem(propertyName); } - // determine type of values - int type = PropertyType.UNDEFINED; - for (Value value : values) { - if (value == null) { - // skip null values as those would be purged - continue; - } - if (type == PropertyType.UNDEFINED) { - type = value.getType(); - } else if (type != value.getType()) { - // inhomogeneous types - return false; - } + // determine type of values + int type = PropertyType.UNDEFINED; + for (Value value : values) { + if (value == null) { + // skip null values as those would be purged + continue; } - ExtendedPropertyDefinition def = getPropertyDefinitionsAsMap() - .containsKey(propertyName) ? getPropertyDefinitionsAsMap().get(propertyName) - : getMatchingPropDef(getUnstructuredPropertyDefinitions().values(), type, true); - if (def == null) { - def = getMatchingPropDef(getUnstructuredPropertyDefinitions().values(), - PropertyType.UNDEFINED, true); + if (type == PropertyType.UNDEFINED) { + type = value.getType(); + } else if (type != value.getType()) { + // inhomogeneous types + return false; } - if (def != null) { - if (!def.isMultiple() || def.isProtected()) { - return false; - } - int targetType; - if (def.getRequiredType() != PropertyType.UNDEFINED - && def.getRequiredType() != type) { - // type conversion required, but Jahia cannot do it, because we have no valueFactory, resolver, store or session object here - targetType = def.getRequiredType(); - } else { - // no type conversion required - targetType = type; - } - return true; + } + ExtendedPropertyDefinition def = getPropertyDefinitionsAsMap().containsKey(propertyName) + ? getPropertyDefinitionsAsMap().get(propertyName) + : getMatchingPropDef(getUnstructuredPropertyDefinitions().values(), type, true); + if (def == null) { + def = getMatchingPropDef(getUnstructuredPropertyDefinitions().values(), PropertyType.UNDEFINED, true); + } + if (def != null) { + if (!def.isMultiple() || def.isProtected()) { + return false; + } + int targetType; + if (def.getRequiredType() != PropertyType.UNDEFINED && def.getRequiredType() != type) { + // type conversion required, but Jahia cannot do it, because we have no valueFactory, resolver, store or session object here + targetType = def.getRequiredType(); + } else { + // no type conversion required + targetType = type; } + return true; + } return false; } @@ -606,13 +605,14 @@ public boolean canAddChildNode(String childNodeName, String nodeTypeName) { ExtendedNodeType nt = NodeTypeRegistry.getInstance().getNodeType(nodeTypeName); if (!nt.isAbstract() && !nt.isMixin()) { if (getChildNodeDefinitionsAsMap().containsKey(childNodeName)) { - if (canAddChildNode(nt,getChildNodeDefinitionsAsMap().get(childNodeName))) { + if (canAddChildNode(nt, getChildNodeDefinitionsAsMap().get(childNodeName))) { return true; } } - Collection unstruct = getUnstructuredChildNodeDefinitions().values(); + Collection unstruct = + getUnstructuredChildNodeDefinitions().values(); for (ExtendedNodeDefinition definition : unstruct) { - if (canAddChildNode(nt,definition)) { + if (canAddChildNode(nt, definition)) { return true; } } @@ -765,7 +765,7 @@ public NodeTypeDefinition getNodeTypeDefinition() { } public String getLocalName() { - return this.name.getLocalName(); + return this.name.getLocalName(); } public String getPrefix() { @@ -783,7 +783,7 @@ public String[] getDeclaredSupertypeNames() { ExtendedPropertyDefinition[] defs = ExtendedNodeType.this.getDeclaredPropertyDefinitions(); for (ExtendedPropertyDefinition def : defs) { if (def.isInternationalized()) { - String[] newRes = new String[d.length+1]; + String[] newRes = new String[d.length + 1]; System.arraycopy(d, 0, newRes, 0, d.length); newRes[d.length] = "jmix:i18n"; return newRes; @@ -820,7 +820,9 @@ public PropertyDefinition[] getDeclaredPropertyDefinitions() { if (!def.isInternationalized() && !def.isOverride()) { r.add(new PropertyDefinition() { public int getRequiredType() { - return def.getRequiredType() != PropertyType.REFERENCE ? def.getRequiredType() : PropertyType.WEAKREFERENCE; + return def.getRequiredType() != PropertyType.REFERENCE + ? def.getRequiredType() + : PropertyType.WEAKREFERENCE; } public String[] getValueConstraints() { @@ -879,7 +881,6 @@ public boolean isProtected() { public NodeDefinition[] getDeclaredChildNodeDefinitions() { ExtendedNodeDefinition[] defs = ExtendedNodeType.this.getDeclaredChildNodeDefinitions(); - List r = new ArrayList(); for (final ExtendedNodeDefinition def : defs) { if (!def.isOverride()) { @@ -960,12 +961,12 @@ private void checkRemoveItemConstraints(String s) throws ConstraintViolationExce private void checkRemoveNodeConstraints(String name) throws ConstraintViolationException { ExtendedNodeDefinition def = getChildNodeDefinitionsAsMap().get(name); if (def != null) { - if (def.isMandatory()) { - throw new ConstraintViolationException("can't remove mandatory node"); - } - if (def.isProtected()) { - throw new ConstraintViolationException("can't remove protected node"); - } + if (def.isMandatory()) { + throw new ConstraintViolationException("can't remove mandatory node"); + } + if (def.isProtected()) { + throw new ConstraintViolationException("can't remove protected node"); + } } } @@ -973,8 +974,7 @@ private void checkRemoveNodeConstraints(String name) throws ConstraintViolationE * @param propertyName * @throws ConstraintViolationException */ - private void checkRemovePropertyConstraints(String propertyName) - throws ConstraintViolationException { + private void checkRemovePropertyConstraints(String propertyName) throws ConstraintViolationException { ExtendedPropertyDefinition def = getPropertyDefinitionsAsMap().get(propertyName); if (def != null) { if (def.isMandatory()) { @@ -986,14 +986,13 @@ private void checkRemovePropertyConstraints(String propertyName) } } - private ExtendedPropertyDefinition getMatchingPropDef(Collection defs, int type, - boolean multiValued) { + private ExtendedPropertyDefinition getMatchingPropDef( + Collection defs, int type, boolean multiValued) { ExtendedPropertyDefinition match = null; for (ExtendedPropertyDefinition pd : defs) { int reqType = pd.getRequiredType(); // match type - if (reqType == PropertyType.UNDEFINED || type == PropertyType.UNDEFINED - || reqType == type) { + if (reqType == PropertyType.UNDEFINED || type == PropertyType.UNDEFINED || reqType == type) { // match multiValued flag if (multiValued == pd.isMultiple()) { // found match @@ -1041,7 +1040,7 @@ public void clearLabels() { propertyDefinition.clearLabels(); } } - if(items!=null) { + if (items != null) { for (ExtendedItemDefinition item : items) { item.clearLabels(); } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ExtendedPropertyDefinition.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ExtendedPropertyDefinition.java index 9749f64a..94d929c7 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ExtendedPropertyDefinition.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ExtendedPropertyDefinition.java @@ -15,23 +15,20 @@ */ package org.jahia.modules.javascript.modules.engine.jshandler.parsers.cnd; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.jcr.PropertyType; -import javax.jcr.RepositoryException; -import javax.jcr.Value; -import javax.jcr.nodetype.PropertyDefinition; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import javax.jcr.PropertyType; +import javax.jcr.RepositoryException; +import javax.jcr.Value; +import javax.jcr.nodetype.PropertyDefinition; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * User: toto - * Date: 4 janv. 2008 - * Time: 14:02:49 + * User: toto Date: 4 janv. 2008 Time: 14:02:49 */ class ExtendedPropertyDefinition extends ExtendedItemDefinition implements PropertyDefinition { private static Logger logger = LoggerFactory.getLogger(ExtendedPropertyDefinition.class); @@ -94,7 +91,7 @@ public Value[] getValueConstraintsAsValue() { List res = new ArrayList(); for (int i = 0; i < valueConstraints.length; i++) { if (valueConstraints[i] instanceof DynamicValueImpl) { - Value[] v = ((DynamicValueImpl)valueConstraints[i]).expand(); + Value[] v = ((DynamicValueImpl) valueConstraints[i]).expand(); for (Value value : v) { res.add(value); } @@ -111,8 +108,7 @@ public String[] getValueConstraints() { for (int i = 0; i < value.length; i++) { try { res[i] = value[i].getString(); - } catch (RepositoryException e) { - } + } catch (RepositoryException e) {} } return res; } @@ -127,7 +123,7 @@ public Value[] getDefaultValues() { List res = new ArrayList(); for (int i = 0; i < defaultValues.length; i++) { if (defaultValues[i] instanceof DynamicValueImpl) { - Value[] v = ((DynamicValueImpl)defaultValues[i]).expand(); + Value[] v = ((DynamicValueImpl) defaultValues[i]).expand(); for (Value value : v) { res.add(value); } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ExtendedPropertyType.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ExtendedPropertyType.java index cb424952..cc1afe26 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ExtendedPropertyType.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ExtendedPropertyType.java @@ -60,45 +60,43 @@ class ExtendedPropertyType { public static final String TYPENAME_UNDEFINED = "undefined"; /** - * Returns the name of the specified type, - * as used in serialization. + * Returns the name of the specified type, as used in serialization. * * @param type the property type * @return the name of the specified type - * @throws IllegalArgumentException if type - * is not a valid property type. + * @throws IllegalArgumentException if type is not a valid property type. */ public static String nameFromValue(int type) { - switch (type) { - case STRING: - return TYPENAME_STRING; - case BINARY: - return TYPENAME_BINARY; - case BOOLEAN: - return TYPENAME_BOOLEAN; - case LONG: - return TYPENAME_LONG; - case DOUBLE: - return TYPENAME_DOUBLE; - case DATE: - return TYPENAME_DATE; - case NAME: - return TYPENAME_NAME; - case PATH: - return TYPENAME_PATH; - case REFERENCE: - return TYPENAME_REFERENCE; - case WEAKREFERENCE: - return TYPENAME_WEAKREFERENCE; - case URI: - return TYPENAME_URI; - case DECIMAL: - return TYPENAME_DECIMAL; - case UNDEFINED: - return TYPENAME_UNDEFINED; - default: - throw new IllegalArgumentException("unknown type: " + type); - } + switch (type) { + case STRING: + return TYPENAME_STRING; + case BINARY: + return TYPENAME_BINARY; + case BOOLEAN: + return TYPENAME_BOOLEAN; + case LONG: + return TYPENAME_LONG; + case DOUBLE: + return TYPENAME_DOUBLE; + case DATE: + return TYPENAME_DATE; + case NAME: + return TYPENAME_NAME; + case PATH: + return TYPENAME_PATH; + case REFERENCE: + return TYPENAME_REFERENCE; + case WEAKREFERENCE: + return TYPENAME_WEAKREFERENCE; + case URI: + return TYPENAME_URI; + case DECIMAL: + return TYPENAME_DECIMAL; + case UNDEFINED: + return TYPENAME_UNDEFINED; + default: + throw new IllegalArgumentException("unknown type: " + type); + } } /** @@ -106,45 +104,42 @@ public static String nameFromValue(int type) { * * @param name the name of the property type * @return the numeric constant value - * @throws IllegalArgumentException if name - * is not a valid property type name. + * @throws IllegalArgumentException if name is not a valid property type name. */ public static int valueFromName(String name) { - if (name.equals(TYPENAME_STRING)) { - return STRING; - } else if (name.equals(TYPENAME_BINARY)) { - return BINARY; - } else if (name.equals(TYPENAME_BOOLEAN)) { - return BOOLEAN; - } else if (name.equals(TYPENAME_LONG)) { - return LONG; - } else if (name.equals(TYPENAME_DOUBLE)) { - return DOUBLE; - } else if (name.equals(TYPENAME_DATE)) { - return DATE; - } else if (name.equals(TYPENAME_NAME)) { - return NAME; - } else if (name.equals(TYPENAME_PATH)) { - return PATH; - } else if (name.equals(TYPENAME_REFERENCE)) { - return REFERENCE; - } else if (name.equals(TYPENAME_WEAKREFERENCE)) { - return WEAKREFERENCE; - } else if (name.equals(TYPENAME_URI)) { - return URI; - } else if (name.equals(TYPENAME_DECIMAL)) { - return DECIMAL; - } else if (name.equals(TYPENAME_UNDEFINED)) { - return UNDEFINED; - } else { - throw new IllegalArgumentException("unknown type: " + name); - } + if (name.equals(TYPENAME_STRING)) { + return STRING; + } else if (name.equals(TYPENAME_BINARY)) { + return BINARY; + } else if (name.equals(TYPENAME_BOOLEAN)) { + return BOOLEAN; + } else if (name.equals(TYPENAME_LONG)) { + return LONG; + } else if (name.equals(TYPENAME_DOUBLE)) { + return DOUBLE; + } else if (name.equals(TYPENAME_DATE)) { + return DATE; + } else if (name.equals(TYPENAME_NAME)) { + return NAME; + } else if (name.equals(TYPENAME_PATH)) { + return PATH; + } else if (name.equals(TYPENAME_REFERENCE)) { + return REFERENCE; + } else if (name.equals(TYPENAME_WEAKREFERENCE)) { + return WEAKREFERENCE; + } else if (name.equals(TYPENAME_URI)) { + return URI; + } else if (name.equals(TYPENAME_DECIMAL)) { + return DECIMAL; + } else if (name.equals(TYPENAME_UNDEFINED)) { + return UNDEFINED; + } else { + throw new IllegalArgumentException("unknown type: " + name); + } } /** * private constructor to prevent instantiation */ - private ExtendedPropertyType() { - } - + private ExtendedPropertyType() {} } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ISO8601.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ISO8601.java index b94c1337..74481d09 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ISO8601.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ISO8601.java @@ -20,11 +20,9 @@ import java.util.*; /** - * The ISO8601 utility class provides helper methods - * to deal with date/time formatting using a specific ISO8601-compliant - * format (see ISO 8601). - *

- * The currently supported format is: + * The ISO8601 utility class provides helper methods to deal with date/time formatting using a specific + * ISO8601-compliant format (see ISO 8601).

The currently supported + * format is: *

  *   ±YYYY-MM-DDThh:mm:ss.SSSTZD
  * 
@@ -49,8 +47,7 @@ public final class ISO8601 { /** * Flyweight instances of known time zones. */ - private static final Map TZS = - new HashMap(); + private static final Map TZS = new HashMap(); static { TimeZone gmt = TimeZone.getTimeZone("GMT"); @@ -59,14 +56,8 @@ public final class ISO8601 { TZS.put("-00:00", gmt); // http://en.wikipedia.org/wiki/List_of_UTC_time_offsets - String[] tzs = { - "-12:00", "-11:00", "-10:00", "-09:30", "-09:00", "-08:00", - "-07:00", "-06:00", "-05:00", "-04:30", "-04:00", "-03:30", - "-03:00", "-02:00", "-01:00", "+01:00", "+02:00", "+03:00", - "+03:30", "+04:00", "+04:30", "+05:00", "+05:30", "+05:45", - "+06:00", "+06:30", "+07:00", "+08:00", "+08:45", "+09:00", - "+09:30", "+10:00", "+10:30", "+11:00", "+11:30", "+12:00", - "+12:45", "+13:00", "+14:00" }; + String[] tzs = + {"-12:00", "-11:00", "-10:00", "-09:30", "-09:00", "-08:00", "-07:00", "-06:00", "-05:00", "-04:30", "-04:00", "-03:30", "-03:00", "-02:00", "-01:00", "+01:00", "+02:00", "+03:00", "+03:30", "+04:00", "+04:30", "+05:00", "+05:30", "+05:45", "+06:00", "+06:30", "+07:00", "+08:00", "+08:45", "+09:00", "+09:30", "+10:00", "+10:30", "+11:00", "+11:30", "+12:00", "+12:45", "+13:00", "+14:00"}; for (String tz : tzs) { TZS.put(tz, TimeZone.getTimeZone("GMT" + tz)); } @@ -78,8 +69,7 @@ public final class ISO8601 { * Parses an ISO8601-compliant date/time string. * * @param text the date/time string to be parsed - * @return a Calendar, or null if the input could - * not be parsed + * @return a Calendar, or null if the input could not be parsed * @throws IllegalArgumentException if a null argument is passed */ public static Calendar parse(String text) { @@ -102,11 +92,9 @@ public static Calendar parse(String text) { } /** - * the expected format of the remainder of the string is: - * YYYY-MM-DDThh:mm:ss.SSSTZD + * the expected format of the remainder of the string is: YYYY-MM-DDThh:mm:ss.SSSTZD * - * note that we cannot use java.text.SimpleDateFormat for - * parsing because it can't handle years <= 0 and TZD's + * note that we cannot use java.text.SimpleDateFormat for parsing because it can't handle years <= 0 and TZD's */ int year, month, day, hour, min, sec, ms; @@ -209,8 +197,8 @@ public static Calendar parse(String text) { try { /** - * the following call will trigger an IllegalArgumentException - * if any of the set values are illegal or out of range + * the following call will trigger an IllegalArgumentException if any of the set values are illegal or out + * of range */ cal.getTime(); /** @@ -225,15 +213,12 @@ public static Calendar parse(String text) { } /** - * Formats a time instant into an ISO8601-compliant date/time string using - * the UTC timezone. + * Formats a time instant into an ISO8601-compliant date/time string using the UTC timezone. * - * @param date - * date to be formatted + * @param date date to be formatted * @return the formatted date/time string. - * @throws IllegalArgumentException - * if the calendar cannot be represented as defined by ISO 8601 - * (i.e. year with more than four digits). + * @throws IllegalArgumentException if the calendar cannot be represented as defined by ISO 8601 (i.e. year with + * more than four digits). */ public static String format(Date date) throws IllegalArgumentException { return format(date, 0); @@ -242,44 +227,37 @@ public static String format(Date date) throws IllegalArgumentException { /** * Formats a clock time instant into an ISO8601-compliant date/time string. * - * @param clock - * clock to obtain time and time zone from + * @param clock clock to obtain time and time zone from * @return the formatted date/time string. - * @throws IllegalArgumentException - * if the calendar cannot be represented as defined by ISO 8601 - * (i.e. year with more than four digits). + * @throws IllegalArgumentException if the calendar cannot be represented as defined by ISO 8601 (i.e. year with + * more than four digits). */ public static String format(Clock clock) throws IllegalArgumentException { - return format(clock.millis(), clock.getZone().getRules().getOffset(clock.instant()).getTotalSeconds()); + return format( + clock.millis(), + clock.getZone().getRules().getOffset(clock.instant()).getTotalSeconds()); } /** - * Formats a time instant into an ISO8601-compliant date/time string using - * the UTC timezone. + * Formats a time instant into an ISO8601-compliant date/time string using the UTC timezone. * - * @param millisSinceEpoch - * milliseconds since the epoch + * @param millisSinceEpoch milliseconds since the epoch * @return the formatted date/time string. - * @throws IllegalArgumentException - * if the calendar cannot be represented as defined by ISO 8601 - * (i.e. year with more than four digits). + * @throws IllegalArgumentException if the calendar cannot be represented as defined by ISO 8601 (i.e. year with + * more than four digits). */ public static String format(long millisSinceEpoch) throws IllegalArgumentException { return format(millisSinceEpoch, 0); } /** - * Formats a time instant and a timezone offset into an ISO8601-compliant - * date/time string. + * Formats a time instant and a timezone offset into an ISO8601-compliant date/time string. * - * @param date - * date to be formatted - * @param tzOffsetInSeconds - * timezone offset from UTC in seconds + * @param date date to be formatted + * @param tzOffsetInSeconds timezone offset from UTC in seconds * @return the formatted date/time string. - * @throws IllegalArgumentException - * if the calendar cannot be represented as defined by ISO 8601 - * (i.e. year with more than four digits). + * @throws IllegalArgumentException if the calendar cannot be represented as defined by ISO 8601 (i.e. year with + * more than four digits). */ public static String format(Date date, int tzOffsetInSeconds) throws IllegalArgumentException { if (date == null) { @@ -289,18 +267,13 @@ public static String format(Date date, int tzOffsetInSeconds) throws IllegalArgu } /** - * Formats a time instant and a timezone offset into an ISO8601-compliant - * date/time string. + * Formats a time instant and a timezone offset into an ISO8601-compliant date/time string. * - * @param millisSinceEpoch - * milliseconds since the epoch - * @param tzOffsetInSeconds - * timezone offset from UTC in seconds + * @param millisSinceEpoch milliseconds since the epoch + * @param tzOffsetInSeconds timezone offset from UTC in seconds * @return the formatted date/time string. - * @throws IllegalArgumentException - * if a null argument is passed the calendar cannot - * be represented as defined by ISO 8601 (i.e. year with more - * than four digits). + * @throws IllegalArgumentException if a null argument is passed the calendar cannot be represented as + * defined by ISO 8601 (i.e. year with more than four digits). */ public static String format(long millisSinceEpoch, int tzOffsetInSeconds) throws IllegalArgumentException { Calendar cal = Calendar.getInstance(); @@ -310,14 +283,12 @@ public static String format(long millisSinceEpoch, int tzOffsetInSeconds) throws } /** - * Formats a Calendar value into an ISO8601-compliant - * date/time string. + * Formats a Calendar value into an ISO8601-compliant date/time string. * * @param cal the time value to be formatted into a date/time string. * @return the formatted date/time string. - * @throws IllegalArgumentException if a null argument is passed - * or the calendar cannot be represented as defined by ISO 8601 (i.e. year - * with more than four digits). + * @throws IllegalArgumentException if a null argument is passed or the calendar cannot be represented + * as defined by ISO 8601 (i.e. year with more than four digits). */ public static String format(Calendar cal) throws IllegalArgumentException { return format(cal, true); @@ -329,11 +300,10 @@ private static String format(Calendar cal, boolean includeMs) throws IllegalArgu } /** - * the format of the date/time string is: - * YYYY-MM-DDThh:mm:ss.SSSTZD + * the format of the date/time string is: YYYY-MM-DDThh:mm:ss.SSSTZD * - * note that we cannot use java.text.SimpleDateFormat for - * formatting because it can't handle years <= 0 and TZD's + * note that we cannot use java.text.SimpleDateFormat for formatting because it can't handle years <= 0 and + * TZD's */ StringBuilder buf = new StringBuilder(); // year ([-]YYYY) @@ -380,33 +350,29 @@ private static String format(Calendar cal, boolean includeMs) throws IllegalArgu * * @param cal a calendar instance. * @return the astronomical year. - * @throws IllegalArgumentException if calendar cannot be represented as - * defined by ISO 8601 (i.e. year with more - * than four digits). + * @throws IllegalArgumentException if calendar cannot be represented as defined by ISO 8601 (i.e. year with more + * than four digits). */ public static int getYear(Calendar cal) throws IllegalArgumentException { // determine era and adjust year if necessary int year = cal.get(Calendar.YEAR); - if (cal.isSet(Calendar.ERA) - && cal.get(Calendar.ERA) == GregorianCalendar.BC) { + if (cal.isSet(Calendar.ERA) && cal.get(Calendar.ERA) == GregorianCalendar.BC) { /** - * calculate year using astronomical system: - * year n BCE => astronomical year -n + 1 + * calculate year using astronomical system: year n BCE => astronomical year -n + 1 */ year = 0 - year + 1; } if (year > 9999 || year < -9999) { - throw new IllegalArgumentException("Calendar has more than four " + - "year digits, cannot be formatted as ISO8601: " + year); + throw new IllegalArgumentException("Calendar has more than four " + + "year digits, cannot be formatted as ISO8601: " + + year); } return year; } - /** * Variants that exclude the milliseconds from the formatted string. - * */ public static class SHORT { @@ -421,7 +387,9 @@ public static String format(Date date) throws IllegalArgumentException { * @see ISO8601#format(Clock) */ public static String format(Clock clock) throws IllegalArgumentException { - return format(clock.millis(), clock.getZone().getRules().getOffset(clock.instant()).getTotalSeconds()); + return format( + clock.millis(), + clock.getZone().getRules().getOffset(clock.instant()).getTotalSeconds()); } /** @@ -460,10 +428,8 @@ public static String format(Calendar cal) throws IllegalArgumentException { } /** - * Appends a zero-padded number to the given string buffer. - *

- * This is an internal helper method which doesn't perform any - * validation on the given arguments. + * Appends a zero-padded number to the given string buffer.

This is an internal helper method which doesn't + * perform any validation on the given arguments. * * @param buf String buffer to append to * @param n number to append diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/IndexType.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/IndexType.java index 2c989b47..a503d6cf 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/IndexType.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/IndexType.java @@ -48,5 +48,4 @@ public static int valueFromName(String name) { throw new IllegalArgumentException("unknown index type: " + name); } } - } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/JahiaCndReader.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/JahiaCndReader.java index a5c1e411..b660a491 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/JahiaCndReader.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/JahiaCndReader.java @@ -15,28 +15,25 @@ */ package org.jahia.modules.javascript.modules.engine.jshandler.parsers.cnd; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.collections.Transformer; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; - +import java.io.IOException; +import java.io.Reader; +import java.util.*; +import java.util.regex.Pattern; import javax.jcr.PropertyType; import javax.jcr.RepositoryException; import javax.jcr.Value; import javax.jcr.nodetype.NoSuchNodeTypeException; import javax.jcr.query.qom.QueryObjectModelConstants; import javax.jcr.version.OnParentVersionAction; -import java.io.IOException; -import java.io.Reader; -import java.util.*; -import java.util.regex.Pattern; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.Transformer; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; /** - * JahiaCndReader. Parses node type definitions written in the compact - * node type definition format and returns a list of JahiaNodeTypeDef objects that - * can then be used to register node types. - *

- * The EBNF grammar of the compact node type definition:
+ * JahiaCndReader. Parses node type definitions written in the compact node type definition format and returns a list of + * JahiaNodeTypeDef objects that can then be used to register node types.

The EBNF grammar of the compact node type + * definition:
*

  * cnd ::= ns_mapping* node_type_def+
  *
@@ -109,9 +106,8 @@
  * unquoted_string ::= [A-Za-z0-9:_]+
  * 
* - * TEMPORARY WORKAROUND - DO NOT USE - * This class duplicates poor legacy code to provide backward compatibility. - * Marked for immediate replacement and removal. + * TEMPORARY WORKAROUND - DO NOT USE This class duplicates poor legacy code to provide backward compatibility. Marked + * for immediate replacement and removal. * * @deprecated since 1.0.0 Technical debt. Will be removed in next major version. */ @@ -142,12 +138,10 @@ public class JahiaCndReader { */ protected String currentToken; - protected boolean doRegister = true; /** - * Checks if the provided token is semantically equal to the given - * argument. + * Checks if the provided token is semantically equal to the given argument. * * @param token the tokens to be compared * @param s the tokens to compare with @@ -165,8 +159,7 @@ protected static boolean tokenEquals(String token, String[] s) { /** * Returns the parsed property type or -1 if the type is not recognized. * - * @param token - * the token to parse property type from + * @param token the token to parse property type from * @return the parsed property type or -1 if the type is not recognized */ public static int getPropertyType(String token) { @@ -204,8 +197,7 @@ public static int getPropertyType(String token) { /** * Returns the parsed selector type or -1 if the selector is not recognized. * - * @param token - * the token to parse property type from + * @param token the token to parse property type from * @return the parsed selector type or -1 if the selector is not recognized */ public static int getSelectorType(String token) { @@ -287,27 +279,27 @@ public void parse() throws ParseException, IOException { doItemDefs(ntd); if (doRegister) { - registry.addNodeType(ntd.getNameObject(),ntd); + registry.addNodeType(ntd.getNameObject(), ntd); } nodeTypesList.add(ntd); } /* - for (ExtendedNodeType type : nodeTypesList) { - try { - type.validate(); - if (!type.getPrefix().equals("nt") && !type.isMixin() && !type.isNodeType(Constants.MIX_REFERENCEABLE)) { - int length = type.getDeclaredSupertypeNames().length; - String[] newTypes = new String[length + 1]; - System.arraycopy(type.getDeclaredSupertypeNames(), 0, newTypes, 0, length); - newTypes[length] = Constants.MIX_REFERENCEABLE; - type.setDeclaredSupertypes(newTypes); - type.validate(); - } - } catch (NoSuchNodeTypeException e) { - throw new ParseException("Cannot validate supertypes for : "+type.getName(),e,0,0,filename); - } - } - */ + * for (ExtendedNodeType type : nodeTypesList) { + * try { + * type.validate(); + * if (!type.getPrefix().equals("nt") && !type.isMixin() && !type.isNodeType(Constants.MIX_REFERENCEABLE)) { + * int length = type.getDeclaredSupertypeNames().length; + * String[] newTypes = new String[length + 1]; + * System.arraycopy(type.getDeclaredSupertypeNames(), 0, newTypes, 0, length); + * newTypes[length] = Constants.MIX_REFERENCEABLE; + * type.setDeclaredSupertypes(newTypes); + * type.validate(); + * } + * } catch (NoSuchNodeTypeException e) { + * throw new ParseException("Cannot validate supertypes for : "+type.getName(),e,0,0,filename); + * } + * } + */ } /** @@ -355,19 +347,21 @@ private boolean doNameSpace() throws ParseException, IOException { * @param ntd * @throws ParseException */ - private void doNodeTypeName(ExtendedNodeType ntd) throws ParseException,IOException { + private void doNodeTypeName(ExtendedNodeType ntd) throws ParseException, IOException { if (!currentTokenEquals(Lexer.BEGIN_NODE_TYPE_NAME)) { - lexer.fail("Unexpected token '" + currentToken +"'"); + lexer.fail("Unexpected token '" + currentToken + "'"); } nextToken(); Name name = parseName(currentToken); ntd.setName(name); nextToken(); if (!currentTokenEquals(Lexer.END_NODE_TYPE_NAME)) { - lexer.fail("Missing '" + Lexer.END_NODE_TYPE_NAME + "' delimiter for end of node type name, found " + currentToken); + lexer.fail("Missing '" + + Lexer.END_NODE_TYPE_NAME + + "' delimiter for end of node type name, found " + + currentToken); } nextToken(); - } /** @@ -450,9 +444,9 @@ private void doOptions(ExtendedNodeType ntd) throws ParseException, IOException } else { lexer.fail("Invalid validator"); } -// } else if (currentTokenEquals(Lexer.LIVECONTENT)) { -// nextToken(); -// ntd.setLiveContent(true); + // } else if (currentTokenEquals(Lexer.LIVECONTENT)) { + // nextToken(); + // ntd.setLiveContent(true); } else { hasOption = false; } @@ -548,7 +542,7 @@ private void doPropertySelector(ExtendedPropertyDefinition pdi) throws ParseExce } if (currentTokenEquals(Lexer.END_TYPE)) { nextToken(); - } else{ + } else { lexer.fail("Missing '" + Lexer.END_TYPE + "' delimiter for end of property type"); } } @@ -560,7 +554,8 @@ private void doPropertySelector(ExtendedPropertyDefinition pdi) throws ParseExce * @param ntd * @throws ParseException */ - private void doPropertyAttributes(ExtendedPropertyDefinition pdi, ExtendedNodeType ntd) throws ParseException, IOException { + private void doPropertyAttributes(ExtendedPropertyDefinition pdi, ExtendedNodeType ntd) + throws ParseException, IOException { while (currentTokenEquals(Lexer.PROP_ATTRIBUTE)) { if (currentTokenEquals(Lexer.PRIMARY)) { ntd.setPrimaryItemName(pdi.getName()); @@ -595,7 +590,7 @@ private void doPropertyAttributes(ExtendedPropertyDefinition pdi, ExtendedNodeTy } else if (currentTokenEquals(Lexer.UNTOKENIZED)) { pdi.setIndex(ExtendedPropertyDefinition.INDEXED_UNTOKENIZED); } else { - lexer.fail("Invalid value for indexed [ no | tokenized | untokenized ] "+currentToken); + lexer.fail("Invalid value for indexed [ no | tokenized | untokenized ] " + currentToken); } } else { lexer.fail("Invalid value for indexed " + currentToken); @@ -607,7 +602,7 @@ private void doPropertyAttributes(ExtendedPropertyDefinition pdi, ExtendedNodeTy try { pdi.setScoreboost(Double.parseDouble(currentToken)); } catch (NumberFormatException e) { - lexer.fail("Invalid value for score boost "+currentToken); + lexer.fail("Invalid value for score boost " + currentToken); } } else { lexer.fail("Invalid value for score boost " + currentToken); @@ -675,7 +670,6 @@ private void doPropertyAttributes(ExtendedPropertyDefinition pdi, ExtendedNodeTy doPropertyQueryOperators(pdi); } - nextToken(); } } @@ -686,8 +680,7 @@ private void doPropertyAttributes(ExtendedPropertyDefinition pdi, ExtendedNodeTy * @param pd the property definition builder * @throws ParseException if an error occurs */ - private void doPropertyQueryOperators(ExtendedPropertyDefinition pd) - throws ParseException { + private void doPropertyQueryOperators(ExtendedPropertyDefinition pd) throws ParseException { if (!currentTokenEquals(Lexer.QUERYOPS)) { return; } @@ -809,7 +802,7 @@ private void doChildNodeRequiredTypes(ExtendedNodeDefinition ndi) throws ParseEx } if (currentTokenEquals(Lexer.END_TYPE)) { nextToken(); - } else{ + } else { lexer.fail("Missing '" + Lexer.END_TYPE + "' delimiter for end of child node type"); } ndi.setRequiredPrimaryTypes(types.toArray(new String[types.size()])); @@ -831,7 +824,7 @@ private void doChildNodeSelector(ExtendedNodeDefinition ndi) throws ParseExcepti } if (currentTokenEquals(Lexer.END_TYPE)) { nextToken(); - } else{ + } else { lexer.fail("Missing '" + Lexer.END_TYPE + "' delimiter for end of property type"); } } @@ -859,7 +852,8 @@ private void doChildNodeDefaultType(ExtendedNodeDefinition ndi) throws ParseExce * @param ntd * @throws ParseException */ - private void doChildNodeAttributes(ExtendedNodeDefinition ndi, ExtendedNodeType ntd) throws ParseException, IOException { + private void doChildNodeAttributes(ExtendedNodeDefinition ndi, ExtendedNodeType ntd) + throws ParseException, IOException { while (currentTokenEquals(Lexer.NODE_ATTRIBUTE)) { if (currentTokenEquals(Lexer.PRIMARY)) { ntd.setPrimaryItemName(ndi.getName()); @@ -871,7 +865,7 @@ private void doChildNodeAttributes(ExtendedNodeDefinition ndi, ExtendedNodeType ndi.setHidden(true); } else if (currentTokenEquals(Lexer.PROTECTED)) { ndi.setProtected(true); - } else if (currentTokenEquals(Lexer.MULTIPLE) /*|| currentTokenEquals(Lexer.SNS)*/) { + } else if (currentTokenEquals(Lexer.MULTIPLE)/*|| currentTokenEquals(Lexer.SNS) */) { ndi.setAllowsSameNameSiblings(true); } else if (currentTokenEquals(Lexer.COPY)) { ndi.setOnParentVersion(OnParentVersionAction.COPY); @@ -901,11 +895,11 @@ private void doChildNodeAttributes(ExtendedNodeDefinition ndi, ExtendedNodeType } else { lexer.fail("Invalid value for workflow " + currentToken); } -// } else if (currentTokenEquals(Lexer.LIVECONTENT)) { -// ndi.setLiveContent(true); + // } else if (currentTokenEquals(Lexer.LIVECONTENT)) { + // ndi.setLiveContent(true); } - //todo : handle new attributes + // todo : handle new attributes nextToken(); } @@ -913,7 +907,7 @@ private void doChildNodeAttributes(ExtendedNodeDefinition ndi, ExtendedNodeType private void doSelectorOptions(ExtendedItemDefinition pdi) throws ParseException, IOException { nextToken(); - Map options = new LinkedHashMap(); + Map options = new LinkedHashMap(); while (true) { String key = currentToken; String value = ""; @@ -928,7 +922,7 @@ private void doSelectorOptions(ExtendedItemDefinition pdi) throws ParseException try { registry.getNodeType(s); } catch (NoSuchNodeTypeException e) { - lexer.fail("Cannot find type : "+s); + lexer.fail("Cannot find type : " + s); } } } @@ -956,8 +950,7 @@ protected void nextToken() throws ParseException { } /** - * Checks if the {@link #currentToken} is semantically equal to the given - * argument. + * Checks if the {@link #currentToken} is semantically equal to the given argument. * * @param s the tokens to compare with * @return true if equals; false otherwise. @@ -967,8 +960,7 @@ protected boolean currentTokenEquals(String[] s) { } /** - * Checks if the {@link #currentToken} is semantically equal to the given - * argument. + * Checks if the {@link #currentToken} is semantically equal to the given argument. * * @param c the tokens to compare with * @return true if equals; false otherwise. @@ -978,8 +970,7 @@ protected boolean currentTokenEquals(char c) { } /** - * Checks if the {@link #currentToken} is semantically equal to the given - * argument. + * Checks if the {@link #currentToken} is semantically equal to the given argument. * * @param s the tokens to compare with * @return true if equals; false otherwise. @@ -1001,54 +992,61 @@ private Logger getLog() { return logger; } - public void getDefinitionsAndReferences(Set contentTypeDefinitions, Set contentTypeReferences) throws RepositoryException { + public void getDefinitionsAndReferences(Set contentTypeDefinitions, Set contentTypeReferences) + throws RepositoryException { for (ExtendedNodeType extendedNodeType : getNodeTypesList()) { - getLog().debug(filename+ " Nodetype definition " + extendedNodeType.getName()); + getLog().debug(filename + " Nodetype definition " + extendedNodeType.getName()); contentTypeDefinitions.add(extendedNodeType.getName()); for (String superTypeName : extendedNodeType.getDeclaredSupertypeNames()) { - getLog().debug(filename+ " node type super type reference " + superTypeName); + getLog().debug(filename + " node type super type reference " + superTypeName); contentTypeReferences.add(superTypeName); } for (String mixinExtendName : extendedNodeType.getMixinExtendNames()) { - getLog().debug(filename+ " node type mixin type reference " + mixinExtendName); + getLog().debug(filename + " node type mixin type reference " + mixinExtendName); contentTypeReferences.add(mixinExtendName); } ExtendedNodeDefinition[] childNodeDefinitions = extendedNodeType.getDeclaredChildNodeDefinitions(); for (ExtendedNodeDefinition childNodeDefinition : childNodeDefinitions) { if (childNodeDefinition.getDefaultPrimaryTypeName() != null) { - getLog().debug(filename+ " child node default type reference " + childNodeDefinition.getDefaultPrimaryTypeName()); + getLog() + .debug(filename + + " child node default type reference " + + childNodeDefinition.getDefaultPrimaryTypeName()); contentTypeReferences.add(childNodeDefinition.getDefaultPrimaryTypeName()); } String[] requiredPrimaryTypeNames = childNodeDefinition.getRequiredPrimaryTypeNames(); for (String requiredPrimaryTypeName : requiredPrimaryTypeNames) { - getLog().debug(filename+ " child node required type reference " + requiredPrimaryTypeName); + getLog().debug(filename + " child node required type reference " + requiredPrimaryTypeName); contentTypeReferences.add(requiredPrimaryTypeName); } - Map selectorOptions = childNodeDefinition.getSelectorOptions(); + Map selectorOptions = childNodeDefinition.getSelectorOptions(); if (selectorOptions.size() > 0) { - getLog().debug(filename+ "Found child node selector options !!!!!!!!!!!!!!!!!!"); + getLog().debug(filename + "Found child node selector options !!!!!!!!!!!!!!!!!!"); } } ExtendedPropertyDefinition[] propertyDefinitions = extendedNodeType.getPropertyDefinitions(); for (ExtendedPropertyDefinition propertyDefinition : propertyDefinitions) { - if (ExtendedPropertyType.REFERENCE == propertyDefinition.getRequiredType() || - ExtendedPropertyType.WEAKREFERENCE == propertyDefinition.getRequiredType()) { + if (ExtendedPropertyType.REFERENCE == propertyDefinition.getRequiredType() + || ExtendedPropertyType.WEAKREFERENCE == propertyDefinition.getRequiredType()) { String[] valueConstraints = propertyDefinition.getValueConstraints(); for (String valueConstraint : valueConstraints) { if (valueConstraint != null) { - getLog().debug(filename+ " reference property value contraints " + valueConstraint); + getLog().debug(filename + " reference property value contraints " + valueConstraint); contentTypeReferences.add(valueConstraint); } } Value[] defaultValues = propertyDefinition.getDefaultValues(); for (Value defaultValue : defaultValues) { if (defaultValue != null) { - getLog().debug(filename+ " found reference property default value " + defaultValue.getString()); + getLog() + .debug(filename + + " found reference property default value " + + defaultValue.getString()); contentTypeReferences.add(defaultValue.getString()); } } } - Map selectorOptions = propertyDefinition.getSelectorOptions(); + Map selectorOptions = propertyDefinition.getSelectorOptions(); if (selectorOptions.size() > 0) { if (selectorOptions.containsKey("nodes")) { String nodeSelector = selectorOptions.get("nodes"); @@ -1056,7 +1054,7 @@ public void getDefinitionsAndReferences(Set contentTypeDefinitions, Set< String[] nodeSelectorOptions = nodeSelectorItem.split(";"); if (nodeSelectorOptions.length > 1) { if (StringUtils.isNotEmpty(nodeSelectorOptions[1])) { - getLog().debug(filename+ " found choicelist node type " + nodeSelectorOptions[1]); + getLog().debug(filename + " found choicelist node type " + nodeSelectorOptions[1]); contentTypeReferences.add(nodeSelectorOptions[1]); } } @@ -1064,14 +1062,9 @@ public void getDefinitionsAndReferences(Set contentTypeDefinitions, Set< } if (selectorOptions.containsKey("nodetypes")) { String param = selectorOptions.get("nodetypes"); - if (param.indexOf(";fromDependencies") > -1) { - } - if (param.startsWith("MIXIN")) { - } else if (param.startsWith("PRIMARY")) { - } else if (param.startsWith("ALL")) { - } else if (StringUtils.isEmpty(param)) { - } else { - getLog().debug(filename+ " found choicelist nodetype type " + param); + if (param.indexOf(";fromDependencies") > -1) {} + if (param.startsWith("MIXIN")) {} else if (param.startsWith("PRIMARY")) {} else if (param.startsWith("ALL")) {} else if (StringUtils.isEmpty(param)) {} else { + getLog().debug(filename + " found choicelist nodetype type " + param); contentTypeReferences.add(param); } } @@ -1084,31 +1077,34 @@ public void getDefinitionsAndReferences(Set contentTypeDefinitions, Set< Set excludedTypes = new HashSet(); String exclusion = StringUtils.substringAfter(param, ";"); if (StringUtils.isNotBlank(exclusion)) { - excludedTypes.addAll(CollectionUtils.collect(Arrays.asList(Patterns.COMMA.split(StringUtils.substringAfter(param, ";"))), new Transformer() { - public Object transform(Object input) { - return ((String) input).trim(); - } - })); + excludedTypes.addAll(CollectionUtils.collect( + Arrays.asList(Patterns.COMMA.split(StringUtils.substringAfter(param, ";"))), + new Transformer() { + public Object transform(Object input) { + return ((String) input).trim(); + } + })); } for (String nodeTypeName : Patterns.COMMA.split(includedTypes)) { if (StringUtils.isNotEmpty(nodeTypeName)) { - getLog().debug(filename+ " found choicelist subnodetype included type " + nodeTypeName); + getLog() + .debug(filename + " found choicelist subnodetype included type " + nodeTypeName); contentTypeReferences.add(nodeTypeName); } } for (String nodeTypeName : excludedTypes) { if (StringUtils.isNotEmpty(nodeTypeName)) { - getLog().debug(filename+ " found choicelist subnodetype excluded type " + nodeTypeName); + getLog() + .debug(filename + " found choicelist subnodetype excluded type " + nodeTypeName); contentTypeReferences.add(nodeTypeName); } } } if (selectorOptions.containsKey("componenttypes")) { String param = selectorOptions.get("componenttypes"); - Set DEF_INCLUDES = new TreeSet( - Arrays.asList("jmix:editorialContent")); + Set DEF_INCLUDES = new TreeSet(Arrays.asList("jmix:editorialContent")); Set includeTypes = DEF_INCLUDES; Set excludeTypes = new TreeSet(); @@ -1119,14 +1115,20 @@ public Object transform(Object input) { for (String nodeTypeName : includeTypes) { if (StringUtils.isNotEmpty(nodeTypeName)) { - getLog().debug(filename+ " found choicelist component type included type " + nodeTypeName); + getLog() + .debug(filename + + " found choicelist component type included type " + + nodeTypeName); contentTypeReferences.add(nodeTypeName); } } for (String nodeTypeName : excludeTypes) { if (StringUtils.isNotEmpty(nodeTypeName)) { - getLog().debug(filename+ " found choicelist component type included type " + nodeTypeName); + getLog() + .debug(filename + + " found choicelist component type included type " + + nodeTypeName); contentTypeReferences.add(nodeTypeName); } } @@ -1151,5 +1153,4 @@ public Set getNodeTypes(String typesString) { return types; } - } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/Lexer.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/Lexer.java index 50fa0a6a..12549e98 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/Lexer.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/Lexer.java @@ -15,12 +15,12 @@ */ package org.jahia.modules.javascript.modules.engine.jshandler.parsers.cnd; -import javax.jcr.query.qom.QueryObjectModelConstants; import java.io.IOException; import java.io.Reader; import java.io.StreamTokenizer; import java.util.ArrayList; import java.util.Arrays; +import javax.jcr.query.qom.QueryObjectModelConstants; /** * Lexer @@ -40,73 +40,66 @@ class Lexer { public static final char CONSTRAINT = '<'; public static final String[] ORDERABLE = new String[] {"orderable", "ord", "o"}; - public static final String[] MIXIN = new String[]{"mixin", "mix", "m"}; - public static final String[] ABSTRACT = new String[]{"abstract", "abs", "a"}; - public static final String[] NOQUERY = new String[]{"noquery", "nq"}; - public static final String[] QUERY = new String[]{"query", "q"}; - public static final String[] PRIMARYITEM = new String[]{"primaryitem", "!"}; - public static final String[] MIXIN_EXTENDS = new String[]{"extends"}; - - public static final String[] VALIDATOR = new String[]{"validator", "val", "v"}; - - public static final String[] PRIMARY = new String[]{"primary", "pri", "!"}; - public static final String[] AUTOCREATED = new String[]{"autocreated", "aut", "a"}; - public static final String[] MANDATORY = new String[]{"mandatory", "man", "m"}; - public static final String[] PROTECTED = new String[]{"protected", "pro", "p"}; - public static final String[] MULTIPLE = new String[]{"multiple", "mul", "*"}; - public static final String[] SNS = new String[]{"sns", "*", "multiple"}; - public static final String[] INTERNATIONALIZED = new String[]{"internationalized", "i15d", "i18n", "i"}; - - public static final String[] ITEMTYPE = new String[]{"itemtype", "type"}; - public static final String[] INDEXED = new String[]{"indexed", "ind", "x"}; - public static final String[] SCOREBOOST = new String[]{"scoreboost", "boost", "b"}; - public static final String[] NO = new String[]{"no","n"}; - public static final String[] YES = new String[]{"yes","y"}; - public static final String[] TOKENIZED = new String[]{"tokenized","tok","t"}; - public static final String[] UNTOKENIZED = new String[]{"untokenized","untok","u"}; - public static final String[] ANALYZER = new String[]{"analyzer"}; - public static final String[] FACETABLE = new String[]{"facetable"}; - public static final String[] HIERARCHICAL = new String[]{"hierarchical"}; - - public static final String[] SORTABLE = new String[]{"sortable"}; - public static final String[] FULLTEXTSEARCHABLE = new String[]{"fulltextsearchable", "fts"}; - - public static final String[] QUERYOPS = new String[]{"queryops", "qop"}; - public static final String[] NOFULLTEXT = new String[]{"nofulltext", "nof"}; - public static final String[] NOQUERYORDER = new String[]{"noqueryorder", "nqord"}; - - public static final String[] HIDDEN = new String[]{"hidden", "Hidden", "HIDDEN"}; - - public static final String[] ONCONFLICT = new String[]{"onconflict"}; - public static final String[] USE_LATEST = new String[]{"latest"}; - public static final String[] USE_OLDEST = new String[]{"oldest"}; - public static final String[] NUMERIC_USE_MIN = new String[]{"min"}; - public static final String[] NUMERIC_USE_MAX = new String[]{"max"}; - public static final String[] NUMERIC_SUM = new String[]{"sum"}; - - public static final String[] COPY = new String[]{"copy", "Copy", "COPY"}; - public static final String[] VERSION = new String[]{"version", "Version", "VERSION"}; - public static final String[] INITIALIZE = new String[]{"initialize", "Initialize", "INITIALIZE"}; - public static final String[] COMPUTE = new String[]{"compute", "Compute", "COMPUTE"}; - public static final String[] IGNORE = new String[]{"ignore", "Ignore", "IGNORE"}; - public static final String[] ABORT = new String[]{"abort", "Abort", "ABORT"}; - -// public static final String[] LIVECONTENT = new String[]{"livecontent", "LiveContent", "LIVECONTENT"}; - - public static final String[] WORKFLOW = new String[]{"workflow", "Workflow", "WORKFLOW"}; + public static final String[] MIXIN = new String[] {"mixin", "mix", "m"}; + public static final String[] ABSTRACT = new String[] {"abstract", "abs", "a"}; + public static final String[] NOQUERY = new String[] {"noquery", "nq"}; + public static final String[] QUERY = new String[] {"query", "q"}; + public static final String[] PRIMARYITEM = new String[] {"primaryitem", "!"}; + public static final String[] MIXIN_EXTENDS = new String[] {"extends"}; + + public static final String[] VALIDATOR = new String[] {"validator", "val", "v"}; + + public static final String[] PRIMARY = new String[] {"primary", "pri", "!"}; + public static final String[] AUTOCREATED = new String[] {"autocreated", "aut", "a"}; + public static final String[] MANDATORY = new String[] {"mandatory", "man", "m"}; + public static final String[] PROTECTED = new String[] {"protected", "pro", "p"}; + public static final String[] MULTIPLE = new String[] {"multiple", "mul", "*"}; + public static final String[] SNS = new String[] {"sns", "*", "multiple"}; + public static final String[] INTERNATIONALIZED = new String[] {"internationalized", "i15d", "i18n", "i"}; + + public static final String[] ITEMTYPE = new String[] {"itemtype", "type"}; + public static final String[] INDEXED = new String[] {"indexed", "ind", "x"}; + public static final String[] SCOREBOOST = new String[] {"scoreboost", "boost", "b"}; + public static final String[] NO = new String[] {"no", "n"}; + public static final String[] YES = new String[] {"yes", "y"}; + public static final String[] TOKENIZED = new String[] {"tokenized", "tok", "t"}; + public static final String[] UNTOKENIZED = new String[] {"untokenized", "untok", "u"}; + public static final String[] ANALYZER = new String[] {"analyzer"}; + public static final String[] FACETABLE = new String[] {"facetable"}; + public static final String[] HIERARCHICAL = new String[] {"hierarchical"}; + + public static final String[] SORTABLE = new String[] {"sortable"}; + public static final String[] FULLTEXTSEARCHABLE = new String[] {"fulltextsearchable", "fts"}; + + public static final String[] QUERYOPS = new String[] {"queryops", "qop"}; + public static final String[] NOFULLTEXT = new String[] {"nofulltext", "nof"}; + public static final String[] NOQUERYORDER = new String[] {"noqueryorder", "nqord"}; + + public static final String[] HIDDEN = new String[] {"hidden", "Hidden", "HIDDEN"}; + + public static final String[] ONCONFLICT = new String[] {"onconflict"}; + public static final String[] USE_LATEST = new String[] {"latest"}; + public static final String[] USE_OLDEST = new String[] {"oldest"}; + public static final String[] NUMERIC_USE_MIN = new String[] {"min"}; + public static final String[] NUMERIC_USE_MAX = new String[] {"max"}; + public static final String[] NUMERIC_SUM = new String[] {"sum"}; + + public static final String[] COPY = new String[] {"copy", "Copy", "COPY"}; + public static final String[] VERSION = new String[] {"version", "Version", "VERSION"}; + public static final String[] INITIALIZE = new String[] {"initialize", "Initialize", "INITIALIZE"}; + public static final String[] COMPUTE = new String[] {"compute", "Compute", "COMPUTE"}; + public static final String[] IGNORE = new String[] {"ignore", "Ignore", "IGNORE"}; + public static final String[] ABORT = new String[] {"abort", "Abort", "ABORT"}; + + // public static final String[] LIVECONTENT = new String[]{"livecontent", "LiveContent", "LIVECONTENT"}; + + public static final String[] WORKFLOW = new String[] {"workflow", "Workflow", "WORKFLOW"}; public static final String[] PROP_ATTRIBUTE; public static final String[] NODE_ATTRIBUTE; - public static final String[] ALL_OPERATORS = new String[]{ - QueryObjectModelConstants.JCR_OPERATOR_EQUAL_TO, - QueryObjectModelConstants.JCR_OPERATOR_NOT_EQUAL_TO, - QueryObjectModelConstants.JCR_OPERATOR_GREATER_THAN, - QueryObjectModelConstants.JCR_OPERATOR_GREATER_THAN_OR_EQUAL_TO, - QueryObjectModelConstants.JCR_OPERATOR_LESS_THAN, - QueryObjectModelConstants.JCR_OPERATOR_LESS_THAN_OR_EQUAL_TO, - QueryObjectModelConstants.JCR_OPERATOR_LIKE - }; + public static final String[] ALL_OPERATORS = + new String[] {QueryObjectModelConstants.JCR_OPERATOR_EQUAL_TO, QueryObjectModelConstants.JCR_OPERATOR_NOT_EQUAL_TO, QueryObjectModelConstants.JCR_OPERATOR_GREATER_THAN, QueryObjectModelConstants.JCR_OPERATOR_GREATER_THAN_OR_EQUAL_TO, QueryObjectModelConstants.JCR_OPERATOR_LESS_THAN, QueryObjectModelConstants.JCR_OPERATOR_LESS_THAN_OR_EQUAL_TO, QueryObjectModelConstants.JCR_OPERATOR_LIKE}; static { ArrayList attr = new ArrayList(); @@ -152,7 +145,7 @@ class Lexer { attr.addAll(Arrays.asList(WORKFLOW)); attr.addAll(Arrays.asList(HIDDEN)); attr.addAll(Arrays.asList(ITEMTYPE)); -// attr.addAll(Arrays.asList(LIVECONTENT)); + // attr.addAll(Arrays.asList(LIVECONTENT)); NODE_ATTRIBUTE = attr.toArray(new String[attr.size()]); } @@ -192,7 +185,7 @@ class Lexer { public static final String[] CRON = {"cron", "Cron", "CRON"}; public static final String[] TAG = {"tag", "Tag", "TAG"}; - public static final String[] UNDEFINED = new String[]{"undefined", "Undefined", "UNDEFINED", "*"}; + public static final String[] UNDEFINED = new String[] {"undefined", "Undefined", "UNDEFINED", "*"}; public static final String EOF = "eof"; @@ -246,9 +239,7 @@ public String getNextToken() throws ParseException { int tokenType = st.nextToken(); if (tokenType == StreamTokenizer.TT_EOF) { return EOF; - } else if (tokenType == StreamTokenizer.TT_WORD - || tokenType == SINGLE_QUOTE - || tokenType == DOUBLE_QUOTE) { + } else if (tokenType == StreamTokenizer.TT_WORD || tokenType == SINGLE_QUOTE || tokenType == DOUBLE_QUOTE) { return st.sval; } else if (tokenType == StreamTokenizer.TT_NUMBER) { return String.valueOf(st.nval); @@ -280,12 +271,12 @@ public void fail(String message, Throwable e) throws ParseException { throw new ParseException(message, e, st.lineno(), -1, filename); } - /** + /** * Creates a failure exception including the current line number and systemid. * @param e root cause * @throws ParseException the created exception */ - public void fail(Throwable e) throws ParseException { + public void fail(Throwable e) throws ParseException { throw new ParseException(e, st.lineno(), -1, filename); } } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/Name.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/Name.java index 400fc5ac..bcdc7443 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/Name.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/Name.java @@ -15,16 +15,12 @@ */ package org.jahia.modules.javascript.modules.engine.jshandler.parsers.cnd; -import org.apache.commons.lang3.StringUtils; - import java.util.Map; +import org.apache.commons.lang3.StringUtils; /** * - * User: toto - * Date: 14 mars 2008 - * Time: 18:43:40 - * + * User: toto Date: 14 mars 2008 Time: 18:43:40 */ class Name { private String localName; @@ -40,7 +36,7 @@ public Name(String localName, String prefix, String uri) { this.uri = uri; } - public Name(String qualifiedName, Map namespaceMapping) { + public Name(String qualifiedName, Map namespaceMapping) { if (qualifiedName.startsWith("{")) { int endUri = qualifiedName.indexOf("}"); if (endUri != -1 && qualifiedName.length() > endUri) { diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/NodeTypeIteratorImpl.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/NodeTypeIteratorImpl.java index acf0ded3..816d352f 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/NodeTypeIteratorImpl.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/NodeTypeIteratorImpl.java @@ -15,16 +15,13 @@ */ package org.jahia.modules.javascript.modules.engine.jshandler.parsers.cnd; +import java.util.Iterator; import javax.jcr.nodetype.NodeType; import javax.jcr.nodetype.NodeTypeIterator; -import java.util.Iterator; /** * - * User: toto - * Date: Sep 21, 2009 - * Time: 5:32:24 PM - * + * User: toto Date: Sep 21, 2009 Time: 5:32:24 PM */ class NodeTypeIteratorImpl extends RangeIteratorAdapter implements NodeTypeIterator { @@ -35,5 +32,4 @@ public NodeTypeIteratorImpl(Iterator iterator, long size) { public NodeType nextNodeType() { return (NodeType) next(); } - } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/NodeTypeRegistry.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/NodeTypeRegistry.java index ab6ead78..23bbce3f 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/NodeTypeRegistry.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/NodeTypeRegistry.java @@ -15,27 +15,22 @@ */ package org.jahia.modules.javascript.modules.engine.jshandler.parsers.cnd; -import org.apache.commons.io.IOUtils; -import org.slf4j.Logger; - -import javax.jcr.RepositoryException; -import javax.jcr.UnsupportedRepositoryOperationException; -import javax.jcr.nodetype.*; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.*; +import javax.jcr.RepositoryException; +import javax.jcr.UnsupportedRepositoryOperationException; +import javax.jcr.nodetype.*; +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; /** - * Jahia implementation of the {@link NodeTypeManager}. - * User: toto - * Date: 4 janv. 2008 - * Time: 15:08:56 + * Jahia implementation of the {@link NodeTypeManager} . User: toto Date: 4 janv. 2008 Time: 15:08:56 * - * TEMPORARY WORKAROUND - DO NOT USE - * This class duplicates poor legacy code to provide backward compatibility. - * Marked for immediate replacement and removal. + * TEMPORARY WORKAROUND - DO NOT USE This class duplicates poor legacy code to provide backward compatibility. Marked + * for immediate replacement and removal. * * @deprecated since 1.0.0 Technical debt. Will be removed in next major version. */ @@ -47,10 +42,11 @@ public class NodeTypeRegistry implements NodeTypeManager { private List nodeTypesList = new ArrayList(); private Map nodetypes = new HashMap(); - private Map namespaces = new HashMap(); + private Map namespaces = new HashMap(); - private Map> mixinExtensions = new HashMap>(); - private Map> typedItems = new HashMap>(); + private Map> mixinExtensions = + new HashMap>(); + private Map> typedItems = new HashMap>(); private boolean propertiesLoaded = false; private final Properties deploymentProperties = new Properties(); @@ -73,7 +69,8 @@ public void flushLabels() { } } - public List getDefinitionsFromFile(File resource, String systemId) throws ParseException, IOException { + public List getDefinitionsFromFile(File resource, String systemId) + throws ParseException, IOException { String ext = resource.getPath().substring(resource.getPath().lastIndexOf('.')); if (ext.equalsIgnoreCase(".cnd")) { Reader resourceReader = null; @@ -99,12 +96,12 @@ public ExtendedNodeType getNodeType(String name) throws NoSuchNodeTypeException } public NodeTypeIterator getAllNodeTypes() { - return new JahiaNodeTypeIterator(nodeTypesList.iterator(),nodeTypesList.size()); + return new JahiaNodeTypeIterator(nodeTypesList.iterator(), nodeTypesList.size()); } public NodeTypeIterator getAllNodeTypes(List systemIds) { List res = new ArrayList(); - for (Iterator iterator = nodetypes.values().iterator(); iterator.hasNext();) { + for (Iterator iterator = nodetypes.values().iterator(); iterator.hasNext(); ) { ExtendedNodeType nt = iterator.next(); if (systemIds == null || systemIds.contains(nt.getSystemId())) { res.add(nt); @@ -120,19 +117,20 @@ public NodeTypeIterator getNodeTypes(String systemId) { l.add(nt); } } - return new JahiaNodeTypeIterator(l.iterator(),l.size()); + return new JahiaNodeTypeIterator(l.iterator(), l.size()); } public Map getNamespaces() { return namespaces; } + public NodeTypeIterator getPrimaryNodeTypes() throws RepositoryException { return getPrimaryNodeTypes(null); } public NodeTypeIterator getPrimaryNodeTypes(List systemIds) throws RepositoryException { List res = new ArrayList(); - for (Iterator iterator = nodetypes.values().iterator(); iterator.hasNext();) { + for (Iterator iterator = nodetypes.values().iterator(); iterator.hasNext(); ) { ExtendedNodeType nt = iterator.next(); if (!nt.isMixin() && (systemIds == null || systemIds.contains(nt.getSystemId()))) { res.add(nt); @@ -147,7 +145,7 @@ public NodeTypeIterator getMixinNodeTypes() throws RepositoryException { public NodeTypeIterator getMixinNodeTypes(List systemIds) throws RepositoryException { List res = new ArrayList(); - for (Iterator iterator = nodetypes.values().iterator(); iterator.hasNext();) { + for (Iterator iterator = nodetypes.values().iterator(); iterator.hasNext(); ) { ExtendedNodeType nt = iterator.next(); if (nt.isMixin() && (systemIds == null || systemIds.contains(nt.getSystemId()))) { res.add(nt); @@ -203,7 +201,7 @@ public void unregisterNodeTypes(String systemId) { class JahiaNodeTypeIterator implements NodeTypeIterator { private long size; - private long pos=0; + private long pos = 0; private Iterator iterator; JahiaNodeTypeIterator(Iterator it, long size) { @@ -218,11 +216,14 @@ public NodeType nextNodeType() { public void skip(long l) { if ((pos + l + 1) > size) { - throw new NoSuchElementException("Tried to skip past " + l + - " elements, which with current pos (" + pos + - ") brings us past total size=" + size); + throw new NoSuchElementException("Tried to skip past " + + l + + " elements, which with current pos (" + + pos + + ") brings us past total size=" + + size); } - for (int i=0; i < l; i++) { + for (int i = 0; i < l; i++) { next(); } } @@ -254,27 +255,33 @@ public boolean hasNodeType(String name) { return nodetypes.get(new Name(name, namespaces)) != null; } - public NodeTypeTemplate createNodeTypeTemplate() throws UnsupportedRepositoryOperationException, RepositoryException { + public NodeTypeTemplate createNodeTypeTemplate() + throws UnsupportedRepositoryOperationException, RepositoryException { throw new UnsupportedRepositoryOperationException(); } - public NodeTypeTemplate createNodeTypeTemplate(NodeTypeDefinition ntd) throws UnsupportedRepositoryOperationException, RepositoryException { + public NodeTypeTemplate createNodeTypeTemplate(NodeTypeDefinition ntd) + throws UnsupportedRepositoryOperationException, RepositoryException { throw new UnsupportedRepositoryOperationException(); } - public NodeDefinitionTemplate createNodeDefinitionTemplate() throws UnsupportedRepositoryOperationException, RepositoryException { + public NodeDefinitionTemplate createNodeDefinitionTemplate() + throws UnsupportedRepositoryOperationException, RepositoryException { throw new UnsupportedRepositoryOperationException(); } - public PropertyDefinitionTemplate createPropertyDefinitionTemplate() throws UnsupportedRepositoryOperationException, RepositoryException { + public PropertyDefinitionTemplate createPropertyDefinitionTemplate() + throws UnsupportedRepositoryOperationException, RepositoryException { throw new UnsupportedRepositoryOperationException(); } - public NodeType registerNodeType(NodeTypeDefinition ntd, boolean allowUpdate) throws InvalidNodeTypeDefinitionException, NodeTypeExistsException, UnsupportedRepositoryOperationException, RepositoryException { + public NodeType registerNodeType(NodeTypeDefinition ntd, boolean allowUpdate) throws InvalidNodeTypeDefinitionException, NodeTypeExistsException, UnsupportedRepositoryOperationException, + RepositoryException { throw new UnsupportedRepositoryOperationException(); } - public NodeTypeIterator registerNodeTypes(NodeTypeDefinition[] ntds, boolean allowUpdate) throws InvalidNodeTypeDefinitionException, NodeTypeExistsException, UnsupportedRepositoryOperationException, RepositoryException { + public NodeTypeIterator registerNodeTypes(NodeTypeDefinition[] ntds, boolean allowUpdate) throws InvalidNodeTypeDefinitionException, NodeTypeExistsException, UnsupportedRepositoryOperationException, + RepositoryException { throw new UnsupportedRepositoryOperationException(); } @@ -285,17 +292,29 @@ public void unregisterNodeType(String name) throws ConstraintViolationException if (!type.getName().equals(name)) { for (ExtendedNodeType nt : type.getSupertypes()) { if (nt.getName().equals(name)) { - throw new ConstraintViolationException("Cannot unregister node type " + name + " because " + type.getName() + " extends it."); + throw new ConstraintViolationException("Cannot unregister node type " + + name + + " because " + + type.getName() + + " extends it."); } } for (ExtendedNodeDefinition ntd : type.getChildNodeDefinitions()) { if (Arrays.asList(ntd.getRequiredPrimaryTypeNames()).contains(name)) { - throw new ConstraintViolationException("Cannot unregister node type " + name + " because a child node definition of " + type.getName() + " requires it."); + throw new ConstraintViolationException("Cannot unregister node type " + + name + + " because a child node definition of " + + type.getName() + + " requires it."); } } for (ExtendedNodeDefinition ntd : type.getUnstructuredChildNodeDefinitions().values()) { if (Arrays.asList(ntd.getRequiredPrimaryTypeNames()).contains(name)) { - throw new ConstraintViolationException("Cannot unregister node type " + name + " because a child node definition of " + type.getName() + " requires it."); + throw new ConstraintViolationException("Cannot unregister node type " + + name + + " because a child node definition of " + + type.getName() + + " requires it."); } } } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/OnConflictAction.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/OnConflictAction.java index 1df8578e..adb9f6c4 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/OnConflictAction.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/OnConflictAction.java @@ -17,10 +17,7 @@ /** * - * User: toto - * Date: Feb 4, 2010 - * Time: 8:24:09 PM - * + * User: toto Date: Feb 4, 2010 Time: 8:24:09 PM */ class OnConflictAction { public static final int IGNORE = 0; @@ -44,13 +41,11 @@ class OnConflictAction { public static final String ACTIONNAME_NUMERIC_SUM = "sum"; /** - * Returns the name of the specified action, as used in - * serialization. + * Returns the name of the specified action, as used in serialization. * * @param action the on-conflict action * @return the name of the specified action - * @throws IllegalArgumentException if action is not a valid - * on-conflict action. + * @throws IllegalArgumentException if action is not a valid on-conflict action. */ public static String nameFromValue(int action) { switch (action) { @@ -70,13 +65,11 @@ public static String nameFromValue(int action) { } /** - * Returns the numeric constant value of the on-conflict action with the - * specified name. + * Returns the numeric constant value of the on-conflict action with the specified name. * * @param name the name of the on-conflict action * @return the numeric constant value - * @throws IllegalArgumentException if name is not a valid - * on-conflict action name. + * @throws IllegalArgumentException if name is not a valid on-conflict action name. */ public static int valueFromName(String name) { if (name.equals(ACTIONNAME_USE_OLDEST)) { diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ParseException.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ParseException.java index 2af6a45c..dc9ac07d 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ParseException.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ParseException.java @@ -18,9 +18,8 @@ /** * ParseException * - * TEMPORARY WORKAROUND - DO NOT USE - * This class duplicates poor legacy code to provide backward compatibility. - * Marked for immediate replacement and removal. + * TEMPORARY WORKAROUND - DO NOT USE This class duplicates poor legacy code to provide backward compatibility. Marked + * for immediate replacement and removal. * * @deprecated since 1.0.0 Technical debt. Will be removed in next major version. */ @@ -42,10 +41,8 @@ public class ParseException extends Exception { */ private final String filename; - /** - * Constructs a new instance of this class with null as its - * detail message. + * Constructs a new instance of this class with null as its detail message. */ public ParseException(int lineNumber, int colNumber, String filename) { super(); @@ -55,11 +52,10 @@ public ParseException(int lineNumber, int colNumber, String filename) { } /** - * Constructs a new instance of this class with the specified detail - * message. + * Constructs a new instance of this class with the specified detail message. * - * @param message the detail message. The detail message is saved for - * later retrieval by the {@link #getMessage()} method. + * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} + * method. */ public ParseException(String message, int lineNumber, int colNumber, String filename) { super(message); @@ -69,11 +65,10 @@ public ParseException(String message, int lineNumber, int colNumber, String file } /** - * Constructs a new instance of this class with the specified detail - * message and root cause. + * Constructs a new instance of this class with the specified detail message and root cause. * - * @param message the detail message. The detail message is saved for - * later retrieval by the {@link #getMessage()} method. + * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} + * method. * @param rootCause root failure cause */ public ParseException(String message, Throwable rootCause, int lineNumber, int colNumber, String filename) { @@ -130,5 +125,4 @@ public String getMessage() { public String toString() { return super.toString(); // + " (" + systemId + ", line " + lineNumber +", col " + colNumber +")"; } - } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/Patterns.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/Patterns.java index d7a1d5e9..17778271 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/Patterns.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/Patterns.java @@ -18,16 +18,12 @@ import java.util.regex.Pattern; /** - * Created with IntelliJ IDEA. - * User: loom - * Date: 27.02.13 - * Time: 10:39 - * To change this template use File | Settings | File Templates. + * Created with IntelliJ IDEA. User: loom Date: 27.02.13 Time: 10:39 To change this template use File | Settings | File + * Templates. */ class Patterns { public static final Pattern COLON = Pattern.compile(":", Pattern.LITERAL); public static final Pattern COMMA = Pattern.compile(",", Pattern.LITERAL); - } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/RangeIteratorAdapter.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/RangeIteratorAdapter.java index e38a04e4..8301d0cb 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/RangeIteratorAdapter.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/RangeIteratorAdapter.java @@ -16,24 +16,22 @@ */ package org.jahia.modules.javascript.modules.engine.jshandler.parsers.cnd; -import javax.jcr.RangeIterator; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.NoSuchElementException; +import javax.jcr.RangeIterator; /** - * Adapter for turning normal {@link Iterator}s into {@link RangeIterator}s. - * This helper class is used by the adapter classes in this package to - * implement the JCR iterator interfaces on top of normal Java iterators. + * Adapter for turning normal {@link Iterator} s into {@link RangeIterator} s. This helper class is used by the adapter + * classes in this package to implement the JCR iterator interfaces on top of normal Java iterators. */ class RangeIteratorAdapter implements RangeIterator { /** - * Static instance of an empty {@link RangeIterator}. + * Static instance of an empty {@link RangeIterator} . */ - public static final RangeIterator EMPTY = - new RangeIteratorAdapter(Collections.EMPTY_LIST); + public static final RangeIterator EMPTY = new RangeIteratorAdapter(Collections.EMPTY_LIST); /** * The adapted iterator instance. @@ -80,7 +78,7 @@ public RangeIteratorAdapter(Collection collection) { this(collection.iterator(), collection.size()); } - //-------------------------------------------------------< RangeIterator > + // -------------------------------------------------------< RangeIterator > /** * Returns the current position of the iterator. @@ -107,8 +105,7 @@ public long getSize() { * @throws IllegalArgumentException if n is negative * @throws NoSuchElementException if skipped past the last element */ - public void skip(long n) - throws IllegalArgumentException, NoSuchElementException { + public void skip(long n) throws IllegalArgumentException, NoSuchElementException { if (n < 0) { throw new IllegalArgumentException("skip(" + n + ")"); } @@ -117,15 +114,13 @@ public void skip(long n) } } - //------------------------------------------------------------< Iterator > + // ------------------------------------------------------------< Iterator > /** - * Checks if this iterator has more elements. If there are no more - * elements and the size of the iterator is unknown, then the size is - * set to the current position. + * Checks if this iterator has more elements. If there are no more elements and the size of the iterator is unknown, + * then the size is set to the current position. * - * @return true if this iterator has more elements, - * false otherwise + * @return true if this iterator has more elements, false otherwise */ public boolean hasNext() { if (iterator.hasNext()) { @@ -139,9 +134,8 @@ public boolean hasNext() { } /** - * Returns the next element in this iterator and advances the iterator - * position. If there are no more elements and the size of the iterator - * is unknown, then the size is set to the current position. + * Returns the next element in this iterator and advances the iterator position. If there are no more elements and + * the size of the iterator is unknown, then the size is set to the current position. * * @return next element * @throws NoSuchElementException if there are no more elements @@ -160,19 +154,16 @@ public Object next() throws NoSuchElementException { } /** - * Removes the previously retrieved element. Decreases the current - * position and size of this iterator. + * Removes the previously retrieved element. Decreases the current position and size of this iterator. * * @throws UnsupportedOperationException if removes are not permitted * @throws IllegalStateException if there is no previous element to remove */ - public void remove() - throws UnsupportedOperationException, IllegalStateException { + public void remove() throws UnsupportedOperationException, IllegalStateException { iterator.remove(); position--; if (size != -1) { size--; } } - } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/SelectorType.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/SelectorType.java index a67b755b..9968c6ab 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/SelectorType.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/SelectorType.java @@ -15,16 +15,13 @@ */ package org.jahia.modules.javascript.modules.engine.jshandler.parsers.cnd; -import javax.jcr.PropertyType; import java.util.HashMap; import java.util.Map; +import javax.jcr.PropertyType; /** * - * User: toto - * Date: 14 mars 2008 - * Time: 17:06:46 - * + * User: toto Date: 14 mars 2008 Time: 17:06:46 */ class SelectorType { public static final int SMALLTEXT = 1; diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ValueImpl.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ValueImpl.java index 7569575b..37ae241c 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ValueImpl.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ValueImpl.java @@ -15,19 +15,17 @@ */ package org.jahia.modules.javascript.modules.engine.jshandler.parsers.cnd; -import org.slf4j.Logger; - -import javax.jcr.*; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.util.Calendar; import java.util.regex.Pattern; +import javax.jcr.*; +import org.slf4j.Logger; /** - * Implementation of the JCR's {@link Value} interface for holding property - * values of different types. + * Implementation of the JCR's {@link Value} interface for holding property values of different types. * * @author Thomas Draier */ @@ -68,7 +66,7 @@ public ValueImpl(String v, int type, boolean isConstraint) { if (value != null && !isConstraint) { switch (type) { - case PropertyType.LONG : + case PropertyType.LONG: this.value = Long.toString(new Double(value).longValue()); break; } @@ -77,14 +75,13 @@ public ValueImpl(String v, int type, boolean isConstraint) { if (value != null && isConstraint) { switch (type) { // handle constant constraint - case PropertyType.LONG : - case PropertyType.DOUBLE : - case PropertyType.DATE : - case PropertyType.BINARY : - if (value.indexOf(',') == -1) value = "["+value+","+value+"]"; + case PropertyType.LONG: + case PropertyType.DOUBLE: + case PropertyType.DATE: + case PropertyType.BINARY: + if (value.indexOf(',') == -1) value = "[" + value + "," + value + "]"; } } - } public String getString() throws ValueFormatException, IllegalStateException, RepositoryException { @@ -139,7 +136,8 @@ public int getType() { return type; } - public boolean checkConstraint(String value) throws ValueFormatException, IllegalStateException, RepositoryException { + public boolean checkConstraint(String value) + throws ValueFormatException, IllegalStateException, RepositoryException { if (value == null || value.length() == 0) { return true; } @@ -153,22 +151,22 @@ public boolean checkConstraint(String value) throws ValueFormatException, Illega case PropertyType.DATE: String s = getString(); boolean lowerBoundIncluded = s.charAt(0) == '['; - boolean upperBoundIncluded = s.charAt(s.length()-1) == ']'; - String lowerBound = s.substring(1,s.indexOf(',')); - String upperBound = s.substring(s.indexOf(',')+1, s.length()-1); + boolean upperBoundIncluded = s.charAt(s.length() - 1) == ']'; + String lowerBound = s.substring(1, s.indexOf(',')); + String upperBound = s.substring(s.indexOf(',') + 1, s.length() - 1); switch (type) { case PropertyType.LONG: case PropertyType.DOUBLE: { double v = Double.parseDouble(value); double l = Double.parseDouble(lowerBound); double u = Double.parseDouble(upperBound); - return (lowerBoundIncluded?v>=l:v>l) && (upperBoundIncluded?v<=u:v= l : v > l) && (upperBoundIncluded ? v <= u : v < u); } case PropertyType.DATE: { long v = Long.parseLong(value); long l = ISO8601.parse(lowerBound).getTimeInMillis(); long u = ISO8601.parse(upperBound).getTimeInMillis(); - return (lowerBoundIncluded?v>=l:v>l) && (upperBoundIncluded?v<=u:v= l : v > l) && (upperBoundIncluded ? v <= u : v < u); } } } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ValueInitializer.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ValueInitializer.java index 687c85a0..cdebd136 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ValueInitializer.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/jshandler/parsers/cnd/ValueInitializer.java @@ -15,18 +15,13 @@ */ package org.jahia.modules.javascript.modules.engine.jshandler.parsers.cnd; - -import javax.jcr.Value; import java.util.List; +import javax.jcr.Value; /** - * Defines a property value initializer. - * User: toto - * Date: Apr 3, 2008 - * Time: 4:09:58 PM + * Defines a property value initializer. User: toto Date: Apr 3, 2008 Time: 4:09:58 PM */ - interface ValueInitializer { - - Value[] getValues(ExtendedPropertyDefinition declaringPropertyDefinition, List params); +interface ValueInitializer { + Value[] getValues(ExtendedPropertyDefinition declaringPropertyDefinition, List params); } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/registrars/RenderFilterRegistrar.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/registrars/RenderFilterRegistrar.java index 6a522109..a713956b 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/registrars/RenderFilterRegistrar.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/registrars/RenderFilterRegistrar.java @@ -15,6 +15,7 @@ */ package org.jahia.modules.javascript.modules.engine.registrars; +import java.util.*; import org.graalvm.polyglot.Value; import org.jahia.modules.javascript.modules.engine.jsengine.ContextProvider; import org.jahia.modules.javascript.modules.engine.jsengine.GraalVMEngine; @@ -32,8 +33,6 @@ import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; -import java.util.*; - @Component(service = Registrar.class, immediate = true) public class RenderFilterRegistrar implements Registrar { @@ -120,16 +119,22 @@ public RenderFilterBridge(Map value, GraalVMEngine engine) { } @Override - public String execute(String s, RenderContext renderContext, Resource resource, RenderChain renderChain) throws Exception { + public String execute(String s, RenderContext renderContext, Resource resource, RenderChain renderChain) + throws Exception { return engine.doWithContext(contextProvider -> { - return Value.asValue(getJsFilter(contextProvider).get("execute")).execute(s, renderContext, resource, renderChain).asString(); + return Value.asValue(getJsFilter(contextProvider).get("execute")) + .execute(s, renderContext, resource, renderChain) + .asString(); }); } @Override - public String prepare(RenderContext renderContext, Resource resource, RenderChain renderChain) throws Exception { + public String prepare(RenderContext renderContext, Resource resource, RenderChain renderChain) + throws Exception { return engine.doWithContext(contextProvider -> { - return Value.asValue(getJsFilter(contextProvider).get("prepare")).execute(renderContext, resource, renderChain).asString(); + return Value.asValue(getJsFilter(contextProvider).get("prepare")) + .execute(renderContext, resource, renderChain) + .asString(); }); } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/registrars/ViewsRegistrar.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/registrars/ViewsRegistrar.java index 281423a6..80f6ed49 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/registrars/ViewsRegistrar.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/registrars/ViewsRegistrar.java @@ -15,6 +15,11 @@ */ package org.jahia.modules.javascript.modules.engine.registrars; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; +import javax.jcr.RepositoryException; +import javax.jcr.nodetype.NoSuchNodeTypeException; import org.jahia.modules.javascript.modules.engine.jsengine.ContextProvider; import org.jahia.modules.javascript.modules.engine.jsengine.GraalVMEngine; import org.jahia.modules.javascript.modules.engine.views.JSScript; @@ -33,22 +38,20 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.jcr.RepositoryException; -import javax.jcr.nodetype.NoSuchNodeTypeException; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.stream.Collectors; - -@Component(immediate = true, service = {ViewsRegistrar.class, Registrar.class, ScriptResolver.class, JahiaEventListener.class}) +@Component( + immediate = true, + service = { + ViewsRegistrar.class, + Registrar.class, + ScriptResolver.class, + JahiaEventListener.class + }) public class ViewsRegistrar implements ScriptResolver, TemplateResolver, Registrar, JahiaEventListener { private static final Logger logger = LoggerFactory.getLogger(ViewsRegistrar.class); - private static final Class[] ACCEPTED_EVENT_TYPES = new Class[] { - JahiaTemplateManagerService.TemplatePackageRedeployedEvent.class, - JahiaTemplateManagerService.ModuleDeployedOnSiteEvent.class, - JahiaTemplateManagerService.ModuleDependenciesEvent.class - }; + private static final Class[] ACCEPTED_EVENT_TYPES = + new Class[] {JahiaTemplateManagerService.TemplatePackageRedeployedEvent.class, JahiaTemplateManagerService.ModuleDeployedOnSiteEvent.class, JahiaTemplateManagerService.ModuleDependenciesEvent.class}; private RenderService renderService; private GraalVMEngine graalVMEngine; @@ -91,6 +94,7 @@ public void deactivate(BundleContext context) { renderService.setTemplateResolvers(templateResolvers); logger.info("Unregistered ViewsRegistrar"); } + @Override public void register(Bundle bundle) { Set views = new HashSet<>(); @@ -130,7 +134,8 @@ public Script resolveScript(Resource resource, RenderContext renderContext) thro } @Override - public boolean hasTemplate(String templateName, ExtendedNodeType nodeType, Set templatePackages) throws RepositoryException { + public boolean hasTemplate(String templateName, ExtendedNodeType nodeType, Set templatePackages) + throws RepositoryException { Set involvedJSModules = filterModulesWithJSViews(templatePackages); if (involvedJSModules.isEmpty()) { return false; @@ -146,7 +151,12 @@ public Template resolveTemplate(Resource resource, RenderContext renderContext) // JS templates are just JS views, so we just read already resolved script for resource. Script script = resource.getScript(renderContext); if (script != null && script.getView() instanceof JSView && ((JSView) script.getView()).isTemplate()) { - Template template = new Template(script.getView().getKey(), null, null, resource.getResolvedTemplate(), ((JSView) script.getView()).getPriority()); + Template template = new Template( + script.getView().getKey(), + null, + null, + resource.getResolvedTemplate(), + ((JSView) script.getView()).getPriority()); template.setExternal(true); return template; } @@ -154,7 +164,8 @@ public Template resolveTemplate(Resource resource, RenderContext renderContext) return null; } - private JSView resolveView(Resource resource, RenderContext renderContext) throws RepositoryException, TemplateNotFoundException { + private JSView resolveView(Resource resource, RenderContext renderContext) + throws RepositoryException, TemplateNotFoundException { ExtendedNodeType nt = resource.getNode().getPrimaryNodeType(); List nodeTypeList = getNodeTypeList(nt); for (ExtendedNodeType type : resource.getNode().getMixinNodeTypes()) { @@ -180,7 +191,8 @@ private List getNodeTypeList(ExtendedNodeType nt) throws NoSuc return nodeTypeList; } - private JSView resolveView(Resource resource, List nodeTypeList, RenderContext renderContext) throws RepositoryException, TemplateNotFoundException { + private JSView resolveView(Resource resource, List nodeTypeList, RenderContext renderContext) + throws RepositoryException, TemplateNotFoundException { // Are we rendering the page level node (main resource) ? boolean pageRendering = "page".equals(resource.getContextConfiguration()) && !renderContext.isAjaxRequest(); @@ -197,8 +209,10 @@ private JSView resolveView(Resource resource, List nodeTypeLis template = resource.getResolvedTemplate(); } - JCRSiteNode site = renderContext.getSite() != null ? renderContext.getSite() : resource.getNode().getResolveSite(); - return (JSView) nodeTypeList.stream().flatMap(nodeType -> getViewsSet(nodeType, site, resource.getTemplateType(), pageRendering).stream()) + JCRSiteNode site = + renderContext.getSite() != null ? renderContext.getSite() : resource.getNode().getResolveSite(); + return (JSView) nodeTypeList.stream() + .flatMap(nodeType -> getViewsSet(nodeType, site, resource.getTemplateType(), pageRendering).stream()) .filter(v -> { JSView jsv = (JSView) v; // pageRendering -> JSView should be a template @@ -218,12 +232,15 @@ public boolean hasView(ExtendedNodeType nt, String viewName, JCRSiteNode site, S } @Override - public SortedSet getViewsSet(ExtendedNodeType extendedNodeType, JCRSiteNode jcrSiteNode, String templateType) { + public SortedSet getViewsSet( + ExtendedNodeType extendedNodeType, JCRSiteNode jcrSiteNode, String templateType) { return getViewsSet(extendedNodeType, jcrSiteNode, templateType, false); } - public SortedSet getViewsSet(ExtendedNodeType extendedNodeType, JCRSiteNode jcrSiteNode, String templateType, boolean pageRendering) { - Set involvedJSModules = siteJSModulesCache.computeIfAbsent(jcrSiteNode.getPath(), + public SortedSet getViewsSet( + ExtendedNodeType extendedNodeType, JCRSiteNode jcrSiteNode, String templateType, boolean pageRendering) { + Set involvedJSModules = siteJSModulesCache.computeIfAbsent( + jcrSiteNode.getPath(), k -> filterModulesWithJSViews(jcrSiteNode.getInstalledModulesWithAllDependencies())); // If no JS module involved in the site, return empty set @@ -234,24 +251,35 @@ public SortedSet getViewsSet(ExtendedNodeType extendedNodeType, JCRSiteNod return getViewsSet(extendedNodeType, involvedJSModules, templateType, pageRendering); } - private SortedSet getViewsSet(ExtendedNodeType extendedNodeType, Set moduleNames, String templateType, boolean pageRendering) { + private SortedSet getViewsSet( + ExtendedNodeType extendedNodeType, Set moduleNames, String templateType, boolean pageRendering) { return moduleNames.stream() .filter(viewsPerBundle::containsKey) .flatMap(moduleName -> { - String cacheKey = extendedNodeType.getName() + "_" + moduleName + "_" + templateType + "_" + pageRendering; - return viewSetCache.computeIfAbsent(cacheKey, key -> viewsPerBundle.get(moduleName).stream() - .filter(v -> extendedNodeType.isNodeType(v.getNodeType())) - .filter(v -> templateType.equals(v.getTemplateType())) - .filter(v -> pageRendering == v.isTemplate()) - .collect(Collectors.toCollection(TreeSet::new))).stream(); + String cacheKey = extendedNodeType.getName() + + "_" + + moduleName + + "_" + + templateType + + "_" + + pageRendering; + return viewSetCache + .computeIfAbsent( + cacheKey, + key -> viewsPerBundle + .get(moduleName) + .stream() + .filter(v -> extendedNodeType.isNodeType(v.getNodeType())) + .filter(v -> templateType.equals(v.getTemplateType())) + .filter(v -> pageRendering == v.isTemplate()) + .collect(Collectors.toCollection(TreeSet::new))) + .stream(); }) .collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> (JSView) o)))); } private Set filterModulesWithJSViews(Set moduleNames) { - return moduleNames.stream() - .filter(viewsPerBundle::containsKey) - .collect(Collectors.toSet()); + return moduleNames.stream().filter(viewsPerBundle::containsKey).collect(Collectors.toSet()); } private void clearCache() { diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/views/JSScript.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/views/JSScript.java index 8c79c04e..03b22724 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/views/JSScript.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/views/JSScript.java @@ -15,6 +15,7 @@ */ package org.jahia.modules.javascript.modules.engine.views; +import java.util.Map; import org.graalvm.polyglot.Value; import org.graalvm.polyglot.proxy.ProxyObject; import org.jahia.modules.javascript.modules.engine.jsengine.GraalVMEngine; @@ -27,8 +28,6 @@ import org.slf4j.LoggerFactory; import pl.touk.throwing.ThrowingFunction; -import java.util.Map; - public class JSScript implements Script { private static final Logger logger = LoggerFactory.getLogger(JSScript.class); @@ -52,7 +51,8 @@ public String execute(Resource resource, RenderContext renderContext) throws Ren String viewRendererStr = viewValues.get("viewRenderer").toString(); Map viewRenderer = contextProvider.getRegistry().get("viewRenderer", viewRendererStr); if (viewRenderer == null) { - throw new RenderException(String.format("Unknown view renderer: %s for view: %s", viewRendererStr, jsView.getRegistryKey())); + throw new RenderException(String.format( + "Unknown view renderer: %s for view: %s", viewRendererStr, jsView.getRegistryKey())); } if (logger.isDebugEnabled()) { @@ -60,7 +60,8 @@ public String execute(Resource resource, RenderContext renderContext) throws Ren } viewValues.put("bundle", Value.asValue(jsView.getModule().getBundle())); - Object executionResult = Value.asValue(viewRenderer.get("render")).execute(resource, renderContext, ProxyObject.fromMap(viewValues)); + Object executionResult = Value.asValue(viewRenderer.get("render")) + .execute(resource, renderContext, ProxyObject.fromMap(viewValues)); Value value = Value.asValue(executionResult); return value.asString(); })); diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/views/JSView.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/views/JSView.java index e741df57..6ae782a8 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/views/JSView.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/views/JSView.java @@ -15,6 +15,10 @@ */ package org.jahia.modules.javascript.modules.engine.views; +import java.util.Map; +import java.util.Objects; +import java.util.Properties; +import javax.annotation.Nonnull; import org.jahia.data.templates.JahiaTemplatesPackage; import org.jahia.modules.javascript.modules.engine.jsengine.ContextProvider; import org.jahia.registries.ServicesRegistry; @@ -23,11 +27,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.annotation.Nonnull; -import java.util.Map; -import java.util.Objects; -import java.util.Properties; - public class JSView implements View, Comparable { private JahiaTemplatesPackage module; @@ -53,7 +52,10 @@ public JSView(Map jsValues, Bundle bundle) { // init some system info, like componentType: template or view String componentType = jsValues.containsKey("componentType") ? jsValues.get("componentType").toString() : null; if ((!"template".equals(componentType) && !"view".equals(componentType))) { - logger.warn("Unrecognized componentType '{}' for view '{}', will be considered as a view", componentType, this.getKey()); + logger.warn( + "Unrecognized componentType '{}' for view '{}', will be considered as a view", + componentType, + this.getKey()); } this.isTemplate = "template".equals(componentType); @@ -78,7 +80,9 @@ public String getKey() { @Override public JahiaTemplatesPackage getModule() { if (module == null) { - this.module = ServicesRegistry.getInstance().getJahiaTemplateManagerService().getTemplatePackageById(bundle.getSymbolicName()); + this.module = ServicesRegistry.getInstance() + .getJahiaTemplateManagerService() + .getTemplatePackageById(bundle.getSymbolicName()); } return module; } @@ -147,18 +151,19 @@ public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof JSView)) return false; JSView jsView = (JSView) o; - return getRegistryKey().equals(jsView.getRegistryKey()) && - getKey().equals(jsView.getKey()) && - getModule().equals(jsView.getModule()) && - Objects.equals(path, jsView.path) && - getNodeType().equals(jsView.getNodeType()) && - getTemplateType().equals(jsView.getTemplateType()) && - isTemplate() == jsView.isTemplate(); + return getRegistryKey().equals(jsView.getRegistryKey()) + && getKey().equals(jsView.getKey()) + && getModule().equals(jsView.getModule()) + && Objects.equals(path, jsView.path) + && getNodeType().equals(jsView.getNodeType()) + && getTemplateType().equals(jsView.getTemplateType()) + && isTemplate() == jsView.isTemplate(); } @Override public int hashCode() { - return Objects.hash(getRegistryKey(), getKey(), getModule(), path, getNodeType(), getTemplateType(), isTemplate()); + return Objects.hash( + getRegistryKey(), getKey(), getModule(), path, getNodeType(), getTemplateType(), isTemplate()); } @Override @@ -181,5 +186,4 @@ public int compareTo(@Nonnull View otherView) { } return getKey().compareTo(otherView.getKey()); } - } diff --git a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/views/JavascriptTemplatesNodeChoiceListInitializer.java b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/views/JavascriptTemplatesNodeChoiceListInitializer.java index 9f7d2995..07bc2da4 100644 --- a/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/views/JavascriptTemplatesNodeChoiceListInitializer.java +++ b/javascript-modules-engine-java/src/main/java/org/jahia/modules/javascript/modules/engine/views/JavascriptTemplatesNodeChoiceListInitializer.java @@ -15,6 +15,12 @@ */ package org.jahia.modules.javascript.modules.engine.views; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; +import javax.jcr.RepositoryException; import org.apache.commons.lang3.StringUtils; import org.jahia.bin.Jahia; import org.jahia.modules.javascript.modules.engine.registrars.ViewsRegistrar; @@ -34,16 +40,10 @@ import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; -import javax.jcr.RepositoryException; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.stream.Collectors; - @Component(immediate = true) public class JavascriptTemplatesNodeChoiceListInitializer implements ChoiceListInitializer { - private static final Logger logger = org.slf4j.LoggerFactory.getLogger(JavascriptTemplatesNodeChoiceListInitializer.class); + private static final Logger logger = + org.slf4j.LoggerFactory.getLogger(JavascriptTemplatesNodeChoiceListInitializer.class); private ChoiceListInitializerService service; @@ -73,7 +73,12 @@ public void deactivate() { } @Override - public List getChoiceListValues(ExtendedPropertyDefinition epd, String param, List previousValues, Locale locale, Map context) { + public List getChoiceListValues( + ExtendedPropertyDefinition epd, + String param, + List previousValues, + Locale locale, + Map context) { List values = oldInitializer.getChoiceListValues(epd, param, previousValues, locale, context); try { @@ -91,15 +96,19 @@ public List getChoiceListValues(ExtendedPropertyDefinition epd, final JCRSessionWrapper session = site.getSession(); // get default template - String defaultTemplate = site.hasProperty("j:defaultTemplateName") ? site.getProperty("j:defaultTemplateName").getString() : null; + String defaultTemplate = site.hasProperty("j:defaultTemplateName") + ? site.getProperty("j:defaultTemplateName").getString() + : null; - List newValues = addTemplates(site, session, nodetype, defaultTemplate, epd, locale, context); + List newValues = + addTemplates(site, session, nodetype, defaultTemplate, epd, locale, context); if (values.isEmpty()) { values.addAll(newValues); } else { // in case of page mode, the templates are rendered in a separate subsection - String templatesTitle = Messages.getInternal("org.jahia.services.content.nodetypes.initializers.templates.title", locale); + String templatesTitle = Messages.getInternal( + "org.jahia.services.content.nodetypes.initializers.templates.title", locale); int insertIndex = 0; for (int i = 0; i < values.size(); i++) { if (templatesTitle.equals(values.get(i).getDisplayName())) { @@ -116,10 +125,22 @@ public List getChoiceListValues(ExtendedPropertyDefinition epd, return values; } - private List addTemplates(JCRSiteNode site, JCRSessionWrapper session, ExtendedNodeType nodetype, String defaultTemplate, ExtendedPropertyDefinition propertyDefinition, Locale locale, Map context) throws RepositoryException { - return viewsRegistrar.getViewsSet(nodetype, site, "html", true).stream() + private List addTemplates( + JCRSiteNode site, + JCRSessionWrapper session, + ExtendedNodeType nodetype, + String defaultTemplate, + ExtendedPropertyDefinition propertyDefinition, + Locale locale, + Map context) throws RepositoryException { + return viewsRegistrar + .getViewsSet(nodetype, site, "html", true) + .stream() .filter(v -> v instanceof JSView && ((JSView) v).isTemplate()) - .map(v -> new ChoiceListValue(v.getDisplayName(), getProperties(v, defaultTemplate), session.getValueFactory().createValue(v.getKey()))) + .map(v -> new ChoiceListValue( + v.getDisplayName(), + getProperties(v, defaultTemplate), + session.getValueFactory().createValue(v.getKey()))) .sorted() .collect(Collectors.toList()); } @@ -132,9 +153,14 @@ private Map getProperties(View view, String defaultTemplate) { String imageName = StringUtils.substringAfterLast(view.getPath(), "/").replace(".hbs", ".png"); if (view.getModule().getBundle().findEntries("images", imageName, false) != null) { - props.put("image", Jahia.getContextPath() + "/modules/" + view.getModule().getBundle().getSymbolicName() + "/images/" + imageName); + props.put( + "image", + Jahia.getContextPath() + + "/modules/" + + view.getModule().getBundle().getSymbolicName() + + "/images/" + + imageName); } return props; } - } diff --git a/javascript-modules-engine-java/src/test/java/org/jahia/modules/javascript/modules/engine/js/server/RenderHelperTest.java b/javascript-modules-engine-java/src/test/java/org/jahia/modules/javascript/modules/engine/js/server/RenderHelperTest.java index 2687f198..8782d79f 100644 --- a/javascript-modules-engine-java/src/test/java/org/jahia/modules/javascript/modules/engine/js/server/RenderHelperTest.java +++ b/javascript-modules-engine-java/src/test/java/org/jahia/modules/javascript/modules/engine/js/server/RenderHelperTest.java @@ -10,22 +10,23 @@ public class RenderHelperTest extends TestCase { @Test - @Parameters({ - // siblings: - "/home, /about, ../about", - "/sites/mysite/home, /sites/mysite/about, ../about", - // identical: - "/home, /home, .", - // parents: - "/home/sub-level-1, /home, ../", - "/home/sub-level-1/sub-level-2, /home, ../../", - "/home/sub-level-1/sub-level-2, /home/sub-level-1, ../", - // children: - "/home, /home/sub-level-1, sub-level-1", - "/home, /home/sub-level-1, sub-level-1", - "/home, /home/sub-level-1/sub-level-2, sub-level-1/sub-level-2" - }) + @Parameters( + { + // siblings: + "/home, /about, ../about", + "/sites/mysite/home, /sites/mysite/about, ../about", + // identical: + "/home, /home, .", + // parents: + "/home/sub-level-1, /home, ../", + "/home/sub-level-1/sub-level-2, /home, ../../", + "/home/sub-level-1/sub-level-2, /home/sub-level-1, ../", + // children: + "/home, /home/sub-level-1, sub-level-1", + "/home, /home/sub-level-1, sub-level-1", + "/home, /home/sub-level-1/sub-level-2, sub-level-1/sub-level-2" + }) public void testCalculateRelativePath(String currentPath, String basePath, String expectedRelativePath) { assertEquals(expectedRelativePath, RenderHelper.calculateRelativePath(currentPath, basePath)); } -} \ No newline at end of file +} diff --git a/javascript-modules-engine-java/src/test/java/org/jahia/modules/javascript/modules/engine/jshandler/JavascriptProtocolConnectionTest.java b/javascript-modules-engine-java/src/test/java/org/jahia/modules/javascript/modules/engine/jshandler/JavascriptProtocolConnectionTest.java index d550094f..17bbfbdb 100644 --- a/javascript-modules-engine-java/src/test/java/org/jahia/modules/javascript/modules/engine/jshandler/JavascriptProtocolConnectionTest.java +++ b/javascript-modules-engine-java/src/test/java/org/jahia/modules/javascript/modules/engine/jshandler/JavascriptProtocolConnectionTest.java @@ -1,64 +1,76 @@ package org.jahia.modules.javascript.modules.engine.jshandler; -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; - -import static org.junit.Assert.assertEquals; +import org.junit.Test; public class JavascriptProtocolConnectionTest { - public static final String PACKAGE_VERSION = "1.2.3"; @Test - public void GIVEN_the_snapshot_mode_is_enabled_with_a_boolean_WHEN_getting_the_bundle_version_THEN_the_snapshot_suffix_is_present() { - String version = JavascriptProtocolConnection.getBundleVersion(createPackageProperties(), createJahiaProps(true)); + public void GIVEN_the_snapshot_mode_is_enabled_with_a_boolean_WHEN_getting_the_bundle_version_THEN_the_snapshot_suffix_is_present( + ) { + String version = + JavascriptProtocolConnection.getBundleVersion(createPackageProperties(), createJahiaProps(true)); assertEquals("The version should be suffixed with SNAPSHOT", PACKAGE_VERSION + ".SNAPSHOT", version); } @Test - public void GIVEN_the_snapshot_mode_is_enabled_with_a_string_WHEN_getting_the_bundle_version_THEN_the_snapshot_suffix_is_present() { - String version = JavascriptProtocolConnection.getBundleVersion(createPackageProperties(), createJahiaProps("TrUe")); + public void GIVEN_the_snapshot_mode_is_enabled_with_a_string_WHEN_getting_the_bundle_version_THEN_the_snapshot_suffix_is_present( + ) { + String version = + JavascriptProtocolConnection.getBundleVersion(createPackageProperties(), createJahiaProps("TrUe")); assertEquals("The version should be suffixed with SNAPSHOT", PACKAGE_VERSION + ".SNAPSHOT", version); } @Test - public void GIVEN_the_snapshot_mode_is_disabled_WHEN_getting_the_bundle_version_THEN_the_snapshot_suffix_is_absent() { - String version = JavascriptProtocolConnection.getBundleVersion(createPackageProperties(), createJahiaProps(false)); + public void GIVEN_the_snapshot_mode_is_disabled_WHEN_getting_the_bundle_version_THEN_the_snapshot_suffix_is_absent( + ) { + String version = + JavascriptProtocolConnection.getBundleVersion(createPackageProperties(), createJahiaProps(false)); assertEquals("The version should not be suffixed with SNAPSHOT", PACKAGE_VERSION, version); } @Test - public void GIVEN_the_snapshot_mode_is_not_set_WHEN_getting_the_bundle_version_THEN_the_snapshot_suffix_is_absent() { + public void GIVEN_the_snapshot_mode_is_not_set_WHEN_getting_the_bundle_version_THEN_the_snapshot_suffix_is_absent( + ) { String version = JavascriptProtocolConnection.getBundleVersion(createPackageProperties(), new HashMap<>()); assertEquals("The version should not be suffixed with SNAPSHOT", PACKAGE_VERSION, version); } - @Test - public void GIVEN_the_snapshot_mode_is_enabled_with_a_boolean_WHEN_getting_the_implementation_version_THEN_the_snapshot_suffix_is_present() { - String version = JavascriptProtocolConnection.getImplementationVersion(createPackageProperties(), createJahiaProps(true)); + public void GIVEN_the_snapshot_mode_is_enabled_with_a_boolean_WHEN_getting_the_implementation_version_THEN_the_snapshot_suffix_is_present( + ) { + String version = + JavascriptProtocolConnection.getImplementationVersion(createPackageProperties(), createJahiaProps(true)); assertEquals("The version should be suffixed with SNAPSHOT", PACKAGE_VERSION + "-SNAPSHOT", version); } @Test - public void GIVEN_the_snapshot_mode_is_enabled_with_a_string_WHEN_getting_the_implementation_version_THEN_the_snapshot_suffix_is_present() { - String version = JavascriptProtocolConnection.getImplementationVersion(createPackageProperties(), createJahiaProps("TrUe")); + public void GIVEN_the_snapshot_mode_is_enabled_with_a_string_WHEN_getting_the_implementation_version_THEN_the_snapshot_suffix_is_present( + ) { + String version = JavascriptProtocolConnection.getImplementationVersion( + createPackageProperties(), createJahiaProps("TrUe")); assertEquals("The version should be suffixed with SNAPSHOT", PACKAGE_VERSION + "-SNAPSHOT", version); } @Test - public void GIVEN_the_snapshot_mode_is_disabled_WHEN_getting_the_implementation_version_THEN_the_snapshot_suffix_is_absent() { - String version = JavascriptProtocolConnection.getImplementationVersion(createPackageProperties(), createJahiaProps(false)); + public void GIVEN_the_snapshot_mode_is_disabled_WHEN_getting_the_implementation_version_THEN_the_snapshot_suffix_is_absent( + ) { + String version = JavascriptProtocolConnection.getImplementationVersion( + createPackageProperties(), createJahiaProps(false)); assertEquals("The version should not be suffixed with SNAPSHOT", PACKAGE_VERSION, version); } @Test - public void GIVEN_the_snapshot_mode_is_not_set_WHEN_getting_the_implementation_version_THEN_the_snapshot_suffix_is_absent() { - String version = JavascriptProtocolConnection.getImplementationVersion(createPackageProperties(), new HashMap<>()); + public void GIVEN_the_snapshot_mode_is_not_set_WHEN_getting_the_implementation_version_THEN_the_snapshot_suffix_is_absent( + ) { + String version = + JavascriptProtocolConnection.getImplementationVersion(createPackageProperties(), new HashMap<>()); assertEquals("The version should not be suffixed with SNAPSHOT", PACKAGE_VERSION, version); } @@ -74,4 +86,3 @@ private static Map createJahiaProps(Object snapshotModeValue) { return jahiaProps; } } - diff --git a/javascript-modules-engine/rollup.config.mjs b/javascript-modules-engine/rollup.config.mjs index 52eab4b7..397b8d09 100644 --- a/javascript-modules-engine/rollup.config.mjs +++ b/javascript-modules-engine/rollup.config.mjs @@ -48,7 +48,7 @@ const plugins = [ ]; export default defineConfig([ - //#region Client build + // #region Client build // Bundle the shared libraries for browser use (exposed by an importmap) // They are used by both the main client script and client-side module scripts { @@ -83,9 +83,9 @@ export default defineConfig([ buildEnv === "production" && terser(), ], }, - //#endregion + // #endregion - //#region Server build + // #region Server build // Bundle the shared libraries for server use { input: serverLibs, @@ -120,8 +120,9 @@ export default defineConfig([ if (id === "virtual:shared-lib-files") return `\0shared-lib-files`; }, load(id) { - if (id === "\0shared-lib-files") + if (id === "\0shared-lib-files") { return `export default ${JSON.stringify(sharedLibFiles)};`; + } }, }, ...plugins, @@ -137,5 +138,5 @@ export default defineConfig([ external: Object.keys(serverLibs), plugins, }, - //#endregion + // #endregion ]); diff --git a/javascript-modules-engine/src/client/i18next.ts b/javascript-modules-engine/src/client/i18next.ts index b2231e6b..6f624f05 100644 --- a/javascript-modules-engine/src/client/i18next.ts +++ b/javascript-modules-engine/src/client/i18next.ts @@ -1,6 +1,6 @@ +import * as devalue from "devalue"; import i18n from "i18next"; import { initReactI18next } from "react-i18next"; -import * as devalue from "devalue"; i18n.use(initReactI18next).init({ fallbackLng: "en", diff --git a/javascript-modules-engine/src/server/init-i18next.ts b/javascript-modules-engine/src/server/init-i18next.ts index 7843b71f..37a2e10f 100644 --- a/javascript-modules-engine/src/server/init-i18next.ts +++ b/javascript-modules-engine/src/server/init-i18next.ts @@ -2,31 +2,33 @@ import i18n, { type BackendModule } from "i18next"; import { initReactI18next } from "react-i18next"; i18n - .use({ - type: "backend", + .use( + { + type: "backend", - init() {}, + init() {}, - read(language, namespace, callback) { - const bundle = server.osgi.getBundle(namespace); - if (bundle) { - // See JavascriptProtocolConnection.java that is moving the settings/locales to META-INF/locales - // (Maybe we will move locales registration in the src and make the registration programmatically like JS views, - // using the registry. But for now, we are using the META-INF/locales folder and .json files) - const content = server.osgi.loadResource(bundle, `META-INF/locales/${language}.json`, true); - if (content) { - callback(null, JSON.parse(content)); + read(language, namespace, callback) { + const bundle = server.osgi.getBundle(namespace); + if (bundle) { + // See JavascriptProtocolConnection.java that is moving the settings/locales to META-INF/locales + // (Maybe we will move locales registration in the src and make the registration programmatically like JS views, + // using the registry. But for now, we are using the META-INF/locales folder and .json files) + const content = server.osgi.loadResource(bundle, `META-INF/locales/${language}.json`, true); + if (content) { + callback(null, JSON.parse(content)); + } else { + // No locales found + callback(null, {}); + } } else { - // No locales found - callback(null, {}); + callback(`Cannot find bundle: ${namespace}`, null); } - } else { - callback(`Cannot find bundle: ${namespace}`, null); - } - }, + }, - create() {}, - } satisfies BackendModule) + create() {}, + } satisfies BackendModule, + ) .use(initReactI18next) .init({ fallbackLng: "en", diff --git a/javascript-modules-engine/src/server/init-react.tsx b/javascript-modules-engine/src/server/init-react.tsx index 4c525f66..6458ef42 100644 --- a/javascript-modules-engine/src/server/init-react.tsx +++ b/javascript-modules-engine/src/server/init-react.tsx @@ -47,13 +47,13 @@ server.registry.add("viewRenderer", "react", { return ( // In page mode, prepend the rendered HTML with the HTML5 doctype - (currentResource.getContextConfiguration() === "page" ? "" : "") + + (currentResource.getContextConfiguration() === "page" ? "" : "") // We use a `` element to wrap raw HTML output because React does not allow // directly returning raw HTML strings. These elements are removed there, to avoid // having them in the final output. // `` SHOULD NOT be used in userland code, it is an internal implementation // detail. - ReactDOMServer.renderToString(element).replaceAll(/<\/?jsm-raw-html>/g, "") + + ReactDOMServer.renderToString(element).replaceAll(/<\/?jsm-raw-html>/g, "") ); }, }); diff --git a/javascript-modules-engine/src/shared/react-dom.ts b/javascript-modules-engine/src/shared/react-dom.ts index 1e987059..fbb6389a 100644 --- a/javascript-modules-engine/src/shared/react-dom.ts +++ b/javascript-modules-engine/src/shared/react-dom.ts @@ -1,5 +1,7 @@ export { createPortal, + // Default export too + default, flushSync, preconnect, prefetchDNS, @@ -11,6 +13,4 @@ export { unstable_batchedUpdates, useFormState, useFormStatus, - // Default export too - default, } from "react-dom"; diff --git a/javascript-modules-engine/src/shared/react.ts b/javascript-modules-engine/src/shared/react.ts index f6e61fd5..02f19d09 100644 --- a/javascript-modules-engine/src/shared/react.ts +++ b/javascript-modules-engine/src/shared/react.ts @@ -1,24 +1,26 @@ // Until https://github.com/facebook/react/issues/10021 is fixed, // we have to list every single export export { - Children, - Component, - Fragment, - Profiler, - PureComponent, - StrictMode, - Suspense, act, cache, + Children, cloneElement, + Component, createContext, createElement, createRef, + // Default export too + default, forwardRef, + Fragment, isValidElement, lazy, memo, + Profiler, + PureComponent, startTransition, + StrictMode, + Suspense, use, useActionState, useCallback, @@ -38,6 +40,4 @@ export { useSyncExternalStore, useTransition, version, - // Default export too - default, } from "react"; diff --git a/javascript-modules-library/src/components/render/Island.tsx b/javascript-modules-library/src/components/render/Island.tsx index 258b69bc..651ec5b2 100644 --- a/javascript-modules-library/src/components/render/Island.tsx +++ b/javascript-modules-library/src/components/render/Island.tsx @@ -1,7 +1,7 @@ import * as devalue from "devalue"; import i18n from "i18next"; import { clientLibs } from "javascript-modules-engine/shared-libs.mjs"; -import { createElement, type ComponentType, type ReactNode } from "react"; +import { type ComponentType, createElement, type ReactNode } from "react"; import { I18nextProvider } from "react-i18next"; import sharedLibFiles from "virtual:shared-lib-files"; import { useServerContext } from "../../hooks/useServerContext.js"; @@ -29,80 +29,82 @@ import { AddResources } from "../AddResources.js"; */ // @ts-expect-error TS complains that the signature does not match the implementation, but it does export function Island( - props: { - /** The React component to render. */ - component: ComponentType; - } & (keyof Omit extends never - ? { + props: + & { + /** The React component to render. */ + component: ComponentType; + } + & (keyof Omit extends never ? { // If the component has no properties (other than children), none can be passed props?: never; } - : Partial> extends Omit - ? { + : Partial> extends Omit ? { // If all properties of component are optional, they may be passed or not, // props will default to an empty object if omitted /** Props to forward to the component. */ props?: Omit; } : { - // If at least one property is required, providing props is mandatory - /** Props to forward to the component. */ - props: Omit; - }) & - (Props extends { children: infer Children } - ? // If the component has mandatory children, it cannot be client-only - { + // If at least one property is required, providing props is mandatory + /** Props to forward to the component. */ + props: Omit; + }) + & (Props extends { children: infer Children } + // If the component has mandatory children, it cannot be client-only + ? { + /** + * If false or undefined, the component will be rendered on the server. If true, + * server-side rendering will be skipped. + */ + clientOnly?: false; + /** The children to render inside the component. */ + children: Children; + } + : "children" extends keyof Props + // If the component has optional children, it may be client-only or not + ? + | { + // In SSR mode, the children are passed to the component and must be of the correct type + /** + * If false or undefined, the component will be rendered on the server. If true, + * server-side rendering will be skipped. + */ + clientOnly?: false; + /** The children to render inside the component. */ + children?: Props["children"]; + } + | { + // In CSR mode, the children are used as a placeholder and may be of any type + /** + * If false or undefined, the component will be rendered on the server. If true, + * server-side rendering will be skipped. + */ + clientOnly: true; + /** Placeholder content until the component is rendered on the client. */ + children?: ReactNode; + } + // If the component has no children, it may be client-only or not + : + | { + // In SSR mode, the component cannot have children /** * If false or undefined, the component will be rendered on the server. If true, * server-side rendering will be skipped. */ clientOnly?: false; - /** The children to render inside the component. */ - children: Children; + // Prevent children from being passed to the component + children?: never; } - : "children" extends keyof Props - ? // If the component has optional children, it may be client-only or not - | { - // In SSR mode, the children are passed to the component and must be of the correct type - /** - * If false or undefined, the component will be rendered on the server. If true, - * server-side rendering will be skipped. - */ - clientOnly?: false; - /** The children to render inside the component. */ - children?: Props["children"]; - } - | { - // In CSR mode, the children are used as a placeholder and may be of any type - /** - * If false or undefined, the component will be rendered on the server. If true, - * server-side rendering will be skipped. - */ - clientOnly: true; - /** Placeholder content until the component is rendered on the client. */ - children?: ReactNode; - } - : // If the component has no children, it may be client-only or not - | { - // In SSR mode, the component cannot have children - /** - * If false or undefined, the component will be rendered on the server. If true, - * server-side rendering will be skipped. - */ - clientOnly?: false; - // Prevent children from being passed to the component - children?: never; - } - | { - // In CSR mode, the children are used as a placeholder and may be of any type - /** - * If false or undefined, the component will be rendered on the server. If true, - * server-side rendering will be skipped. - */ - clientOnly: true; - /** Placeholder content until the component is rendered on the client. */ - children?: ReactNode; - }), + | { + // In CSR mode, the children are used as a placeholder and may be of any type + /** + * If false or undefined, the component will be rendered on the server. If true, + * server-side rendering will be skipped. + */ + clientOnly: true; + /** Placeholder content until the component is rendered on the client. */ + children?: ReactNode; + }), ): ReactNode; // We use an overload rather than a single function because some props (e.g. children) are not always defined @@ -139,33 +141,32 @@ export function Island({ key="jsm-island-head" insert // Insert the resource at the top of the pile targetTag="head" - inlineResource={ - /* HTML */ ` ${ - /** - * Module preload hints for shared libraries, deep in the dependency tree. - * - * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/rel/modulepreload - */ - sharedLibFiles - .map((file) => ``) - .join("") - }` - } + /** + * Module preload hints for shared libraries, deep in the dependency tree. + * + * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/rel/modulepreload + */ + sharedLibFiles + .map((file) => ``) + .join("")}`} /> + inlineResource={/* HTML */ `` - } + `} /> )} {devalue.stringify(props)} - ), - clientOnly ? ( - children - ) : ( + props !== undefined && , + clientOnly ? children : ( node.isNodeType(filter) : filter, - ).map((node) => ( - - ))} + ).map((node) => )} ); diff --git a/javascript-modules-library/src/framework/jahiaComponent.tsx b/javascript-modules-library/src/framework/jahiaComponent.tsx index 6e2add95..9feaa663 100644 --- a/javascript-modules-library/src/framework/jahiaComponent.tsx +++ b/javascript-modules-library/src/framework/jahiaComponent.tsx @@ -57,7 +57,9 @@ export const jahiaComponent = ; - /** - * The mode to use to build the URL. Defines the mode or override the one provided by the - * renderContext. - */ - mode?: "edit" | "preview" | "live"; - /** - * The language to use to build the URL. Defines the languages or overrides the one provided - * by the current resource - */ - language?: string; - /** - * The extension to use to build the URL. Defines the extension or overrides the one - * provided by the current resource - */ - extension?: string; - } + /** The query string parameters to append to the URL */ + parameters?: Record; + /** + * The mode to use to build the URL. Defines the mode or override the one provided by the + * renderContext. + */ + mode?: "edit" | "preview" | "live"; + /** + * The language to use to build the URL. Defines the languages or overrides the one provided + * by the current resource + */ + language?: string; + /** + * The extension to use to build the URL. Defines the extension or overrides the one + * provided by the current resource + */ + extension?: string; + } | { - /** The query string parameters to append to the URL */ - parameters?: Record; - /** Additional arguments used for building the URL, through `node.getUrl` overloads. */ - args?: Record; - }, + /** The query string parameters to append to the URL */ + parameters?: Record; + /** Additional arguments used for building the URL, through `node.getUrl` overloads. */ + args?: Record; + }, context?: { /** Provided in react context, but you need to provide one otherwise. * */ renderContext?: RenderContext; @@ -84,8 +84,7 @@ export function buildNodeUrl( const mode = config.mode ?? context.renderContext?.getMode(); const language = config.language ?? context.currentResource?.getLocale().toString(); - const extension = - config.extension ?? `.${context.currentResource?.getTemplateType() ?? "html"}`; + const extension = config.extension ?? `.${context.currentResource?.getTemplateType() ?? "html"}`; if (!mode) throw new Error("buildNodeUrl: mode is not defined and cannot be inferred."); if (!language) throw new Error("buildNodeUrl: language is not defined and cannot be inferred."); @@ -94,11 +93,11 @@ export function buildNodeUrl( (mode === "edit" ? "/cms/edit/default/" : mode === "preview" - ? "/cms/render/default/" - : "/cms/render/live/") + - language + - node.getPath() + - extension, + ? "/cms/render/default/" + : "/cms/render/live/") + + language + + node.getPath() + + extension, { parameters: config.parameters }, context, ); diff --git a/package.json b/package.json index 92560dd6..7cafce5a 100644 --- a/package.json +++ b/package.json @@ -11,19 +11,17 @@ "vite-plugin" ], "scripts": { - "format": "prettier --write --list-different $INIT_CWD", + "format": "dprint fmt", "lint": "eslint $INIT_CWD" }, "devDependencies": { "@eslint-react/eslint-plugin": "^2.3.13", "@eslint/compat": "^2.0.0", "@eslint/js": "^9.39.2", + "dprint": "^0.52.0", "eslint": "^9.39.2", "eslint-plugin-cypress": "^5.2.0", "globals": "^16.5.0", - "prettier": "^3.7.4", - "prettier-plugin-jsdoc": "^1.8.0", - "prettier-plugin-packagejson": "^2.5.20", "typescript": "^5.9.3", "typescript-eslint": "^8.50.0" }, diff --git a/prettier.config.js b/prettier.config.js deleted file mode 100644 index be951e48..00000000 --- a/prettier.config.js +++ /dev/null @@ -1,9 +0,0 @@ -/** - * @type {import("prettier").Config} - * @see https://prettier.io/docs/en/configuration.html - */ -export default { - quoteProps: "consistent", - printWidth: 100, - plugins: ["prettier-plugin-jsdoc", "prettier-plugin-packagejson"], -}; diff --git a/samples/hydrogen/.prettierignore b/samples/hydrogen/.prettierignore deleted file mode 100644 index 6eb19d7f..00000000 --- a/samples/hydrogen/.prettierignore +++ /dev/null @@ -1 +0,0 @@ -# This file inherits .gitignore, there is no need to copy its content here diff --git a/samples/hydrogen/eslint.config.js b/samples/hydrogen/eslint.config.js index 55f99439..d89b4fc3 100644 --- a/samples/hydrogen/eslint.config.js +++ b/samples/hydrogen/eslint.config.js @@ -1,10 +1,10 @@ // @ts-check +import eslintReact from "@eslint-react/eslint-plugin"; import { includeIgnoreFile } from "@eslint/compat"; import eslint from "@eslint/js"; -import tseslint from "typescript-eslint"; -import path from "node:path"; import globals from "globals"; -import eslintReact from "@eslint-react/eslint-plugin"; +import path from "node:path"; +import tseslint from "typescript-eslint"; export default tseslint.config( { @@ -12,14 +12,11 @@ export default tseslint.config( globals: { ...globals.browser, ...globals.node }, }, }, - // JS/TS recommended eslint.configs.recommended, { files: ["**/*.ts", "**/*.tsx"], extends: tseslint.configs.recommended }, - // React eslintReact.configs["recommended-typescript"], - // Ignore the same files as .gitignore includeIgnoreFile(path.resolve(import.meta.dirname, ".gitignore")), ); diff --git a/samples/hydrogen/package.json b/samples/hydrogen/package.json index 11337db2..b487b5fc 100644 --- a/samples/hydrogen/package.json +++ b/samples/hydrogen/package.json @@ -12,7 +12,7 @@ "build": "tsc --noEmit && vite build && run package", "clean": "rm -rf dist/", "deploy": "jahia-deploy", - "format": "prettier --write --list-different .", + "format": "dprint fmt", "lint": "eslint .", "package": "yarn pack --out dist/package.tgz", "dev": "vite build --watch", @@ -35,7 +35,6 @@ "eslint": "^9.39.2", "globals": "^16.5.0", "i18next": "^25.7.3", - "prettier": "^3.7.4", "react": "^19.2.3", "react-i18next": "^16.5.0", "typescript": "^5.9.3", diff --git a/samples/hydrogen/prettier.config.js b/samples/hydrogen/prettier.config.js deleted file mode 100644 index 3f4fc0a9..00000000 --- a/samples/hydrogen/prettier.config.js +++ /dev/null @@ -1,8 +0,0 @@ -/** - * @type {import("prettier").Config} - * @see https://prettier.io/docs/en/configuration.html - */ -export default { - quoteProps: "consistent", - printWidth: 100, -}; diff --git a/samples/hydrogen/src/components/BlogPost/default.server.tsx b/samples/hydrogen/src/components/BlogPost/default.server.tsx index 304d4c69..4a4b1787 100644 --- a/samples/hydrogen/src/components/BlogPost/default.server.tsx +++ b/samples/hydrogen/src/components/BlogPost/default.server.tsx @@ -1,6 +1,6 @@ import { buildNodeUrl, jahiaComponent } from "@jahia/javascript-modules-library"; -import type { Props } from "./types.js"; import classes from "./component.module.css"; +import type { Props } from "./types.js"; jahiaComponent( { @@ -20,11 +20,10 @@ jahiaComponent(

{subtitle}

- Written {authors && authors.length > 0 && <>by {authors.join(", ")} } + Written {authors && authors.length > 0 && <>by {authors.join(", ")}} {publicationDate && ( <> - on{" "} - {new Date(publicationDate).toLocaleDateString( + on {new Date(publicationDate).toLocaleDateString( currentResource.getLocale().toString(), { dateStyle: "long", diff --git a/samples/hydrogen/src/components/BlogPost/fullPage.server.tsx b/samples/hydrogen/src/components/BlogPost/fullPage.server.tsx index 30c19d68..c0c81ebe 100644 --- a/samples/hydrogen/src/components/BlogPost/fullPage.server.tsx +++ b/samples/hydrogen/src/components/BlogPost/fullPage.server.tsx @@ -1,8 +1,8 @@ import { AbsoluteArea, jahiaComponent } from "@jahia/javascript-modules-library"; -import type { Props } from "./types.js"; -import classes from "./component.module.css"; -import { SmallHeroSection } from "../Hero/Section/small.server.jsx"; import { buildNodeUrl } from "@jahia/javascript-modules-library"; +import { SmallHeroSection } from "../Hero/Section/small.server.jsx"; +import classes from "./component.module.css"; +import type { Props } from "./types.js"; jahiaComponent( { @@ -20,11 +20,10 @@ jahiaComponent(

- Written {authors && authors.length > 0 && <>by {authors.join(", ")} } + Written {authors && authors.length > 0 && <>by {authors.join(", ")}} {publicationDate && ( <> - on{" "} - {new Date(publicationDate).toLocaleDateString( + on {new Date(publicationDate).toLocaleDateString( currentResource.getLocale().toString(), { dateStyle: "long" }, )} diff --git a/samples/hydrogen/src/components/HelloWorld/Celebrate.client.tsx b/samples/hydrogen/src/components/HelloWorld/Celebrate.client.tsx index 019959ad..e87206ea 100644 --- a/samples/hydrogen/src/components/HelloWorld/Celebrate.client.tsx +++ b/samples/hydrogen/src/components/HelloWorld/Celebrate.client.tsx @@ -1,9 +1,9 @@ import clsx from "clsx"; import { useEffect, useState } from "react"; -import classes from "./component.module.css"; import { useTranslation } from "react-i18next"; +import classes from "./component.module.css"; -export default function () { +export default function() { const [confetti, setConfetti] = useState(); const [isClient, setIsClient] = useState(false); diff --git a/samples/hydrogen/src/components/HelloWorld/default.server.tsx b/samples/hydrogen/src/components/HelloWorld/default.server.tsx index 7ee4c143..bddb5250 100644 --- a/samples/hydrogen/src/components/HelloWorld/default.server.tsx +++ b/samples/hydrogen/src/components/HelloWorld/default.server.tsx @@ -1,9 +1,4 @@ -import { - buildModuleFileUrl, - Island, - jahiaComponent, - RenderChildren, -} from "@jahia/javascript-modules-library"; +import { buildModuleFileUrl, Island, jahiaComponent, RenderChildren } from "@jahia/javascript-modules-library"; import { Trans, useTranslation } from "react-i18next"; import Celebrate from "./Celebrate.client.jsx"; import classes from "./component.module.css"; diff --git a/samples/hydrogen/src/components/Hero/CallToAction/default.server.tsx b/samples/hydrogen/src/components/Hero/CallToAction/default.server.tsx index 980aa2d6..0daa2d64 100644 --- a/samples/hydrogen/src/components/Hero/CallToAction/default.server.tsx +++ b/samples/hydrogen/src/components/Hero/CallToAction/default.server.tsx @@ -2,13 +2,15 @@ import { buildNodeUrl, jahiaComponent } from "@jahia/javascript-modules-library" import type { JCRNodeWrapper } from "org.jahia.services.content"; import classes from "./component.module.css"; -type Props = { - title: string; -} & ( // Reflect the three possible values of j:linkType - | { "j:linkType": "none" } - | { "j:linkType": "external"; "j:url": string; "j:linkTitle": string } - | { "j:linkType": "internal"; "j:linknode": JCRNodeWrapper } -); +type Props = + & { + title: string; + } + & ( // Reflect the three possible values of j:linkType + | { "j:linkType": "none" } + | { "j:linkType": "external"; "j:url": string; "j:linkTitle": string } + | { "j:linkType": "internal"; "j:linknode": JCRNodeWrapper } + ); jahiaComponent( { diff --git a/samples/hydrogen/src/components/LanguageSwitcher/default.server.tsx b/samples/hydrogen/src/components/LanguageSwitcher/default.server.tsx index d8b42799..d656b1e5 100644 --- a/samples/hydrogen/src/components/LanguageSwitcher/default.server.tsx +++ b/samples/hydrogen/src/components/LanguageSwitcher/default.server.tsx @@ -1,7 +1,7 @@ import { buildNodeUrl, getSiteLocales, jahiaComponent } from "@jahia/javascript-modules-library"; import { Fragment } from "react"; -import classes from "./component.module.css"; import { useTranslation } from "react-i18next"; +import classes from "./component.module.css"; jahiaComponent( { @@ -19,8 +19,7 @@ jahiaComponent( const currentLanguage = currentResource.getLocale().toString(); return (

- {t("JI87mYV8J5pAEST4RIUcb")}{" "} - {Object.entries(getSiteLocales()).map(([language, locale], i, { length }) => { + {t("JI87mYV8J5pAEST4RIUcb")} {Object.entries(getSiteLocales()).map(([language, locale], i, { length }) => { const href = buildNodeUrl(mainNode, { language }); return ( diff --git a/samples/hydrogen/src/components/NavBar/default.server.tsx b/samples/hydrogen/src/components/NavBar/default.server.tsx index 8e45a40d..21f68d74 100644 --- a/samples/hydrogen/src/components/NavBar/default.server.tsx +++ b/samples/hydrogen/src/components/NavBar/default.server.tsx @@ -3,8 +3,7 @@ import type { JCRNodeWrapper } from "org.jahia.services.content"; import classes from "./component.module.css"; /** Get all child pages of a node. */ -const getChildPages = (node: JCRNodeWrapper) => - getChildNodes(node, -1, 0, (node) => node.isNodeType("jnt:page")); +const getChildPages = (node: JCRNodeWrapper) => getChildNodes(node, -1, 0, (node) => node.isNodeType("jnt:page")); jahiaComponent( { diff --git a/samples/hydrogen/src/templates/Layout.tsx b/samples/hydrogen/src/templates/Layout.tsx index d6f318f0..363f9e7e 100644 --- a/samples/hydrogen/src/templates/Layout.tsx +++ b/samples/hydrogen/src/templates/Layout.tsx @@ -1,8 +1,4 @@ -import { - AddResources, - buildModuleFileUrl, - useServerContext, -} from "@jahia/javascript-modules-library"; +import { AddResources, buildModuleFileUrl, useServerContext } from "@jahia/javascript-modules-library"; import type { ReactNode } from "react"; import "modern-normalize/modern-normalize.css"; diff --git a/samples/hydrogen/src/templates/Page/singleColumn.server.tsx b/samples/hydrogen/src/templates/Page/singleColumn.server.tsx index 3fd2027a..2bb537e4 100644 --- a/samples/hydrogen/src/templates/Page/singleColumn.server.tsx +++ b/samples/hydrogen/src/templates/Page/singleColumn.server.tsx @@ -1,6 +1,6 @@ import { AbsoluteArea, Area, jahiaComponent } from "@jahia/javascript-modules-library"; -import { Layout } from "../Layout.jsx"; import { Render } from "@jahia/javascript-modules-library"; +import { Layout } from "../Layout.jsx"; jahiaComponent( { diff --git a/samples/hydrogen/vite.config.mjs b/samples/hydrogen/vite.config.mjs index 7fb6347e..52ceeb83 100644 --- a/samples/hydrogen/vite.config.mjs +++ b/samples/hydrogen/vite.config.mjs @@ -1,7 +1,7 @@ // @ts-check -import { defineConfig } from "vite"; import jahia from "@jahia/vite-plugin"; import { spawnSync } from "node:child_process"; +import { defineConfig } from "vite"; export default defineConfig({ plugins: [ diff --git a/samples/simple-osgi-service/src/main/java/org/example/services/SimpleService.java b/samples/simple-osgi-service/src/main/java/org/example/services/SimpleService.java index 9b84e0ea..213d84f4 100644 --- a/samples/simple-osgi-service/src/main/java/org/example/services/SimpleService.java +++ b/samples/simple-osgi-service/src/main/java/org/example/services/SimpleService.java @@ -3,10 +3,11 @@ import java.util.List; /** - * This interface defines the SimpleService contract, and it can be used - * in JavaScript Modules to refere to "SimpleServiceImpl" methods. + * This interface defines the SimpleService contract, and it can be used in JavaScript Modules to refere to + * "SimpleServiceImpl" methods. */ public interface SimpleService { String sayHello(String name); + List sortNumbers(List list); } diff --git a/samples/simple-osgi-service/src/main/java/org/example/services/internal/SimpleServiceImpl.java b/samples/simple-osgi-service/src/main/java/org/example/services/internal/SimpleServiceImpl.java index 3956ff06..5daaa72d 100644 --- a/samples/simple-osgi-service/src/main/java/org/example/services/internal/SimpleServiceImpl.java +++ b/samples/simple-osgi-service/src/main/java/org/example/services/internal/SimpleServiceImpl.java @@ -3,15 +3,16 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; - import org.example.services.SimpleService; import org.osgi.service.component.annotations.Component; - @Component(service = SimpleService.class, configurationPid = "org.example.services.simple") public class SimpleServiceImpl implements SimpleService { - /** Configurable in org.example.services.simple.cfg */ + /** + * Configurable in org.example.services.simple.cfg + */ private String greeting = "Hello"; + public void activate(Map props) { if (props.containsKey("greeting")) { greeting = (String) props.get("greeting"); diff --git a/tests/cypress/e2e/engine/graalvmEngineTest.cy.ts b/tests/cypress/e2e/engine/graalvmEngineTest.cy.ts index e8f6b9bd..c6d79c93 100644 --- a/tests/cypress/e2e/engine/graalvmEngineTest.cy.ts +++ b/tests/cypress/e2e/engine/graalvmEngineTest.cy.ts @@ -3,7 +3,7 @@ describe("Check that GraalVM debugger can be enabled", () => { const ports = [9229, 10229]; ports.forEach((port) => { - it(`Check that GraalVM debugger can be enabled on port ${port}`, function () { + it(`Check that GraalVM debugger can be enabled on port ${port}`, function() { // extract the host from the JAHIA_URL env var const host = Cypress.env("JAHIA_URL").split("//")[1].split(":")[0]; @@ -51,10 +51,9 @@ function waitForCurlExitCode( const actualCode = result.code; if (expectedCodes.includes(actualCode)) { - const msg = - actualCode === 0 - ? `Connection successful (HTTP ${result.stdout})` - : `Got expected connection error (exit code: ${actualCode})`; + const msg = actualCode === 0 + ? `Connection successful (HTTP ${result.stdout})` + : `Got expected connection error (exit code: ${actualCode})`; Cypress.log({ message: msg }); return true; } diff --git a/tests/cypress/e2e/hydrogen-tutorial/3-about-us-page.cy.ts b/tests/cypress/e2e/hydrogen-tutorial/3-about-us-page.cy.ts index e85b55df..dedea4e6 100644 --- a/tests/cypress/e2e/hydrogen-tutorial/3-about-us-page.cy.ts +++ b/tests/cypress/e2e/hydrogen-tutorial/3-about-us-page.cy.ts @@ -1,17 +1,17 @@ import { HYDROGEN_SITE_KEY, JAHIA_CONTEXT } from "../../support/constants"; -describe('Validate the concepts of the tutorial: 3 - The "About Us" Page', () => { +describe("Validate the concepts of the tutorial: 3 - The \"About Us\" Page", () => { it("a node type can be rendered using different views", () => { cy.login(); // on the home page, a new CTA can be added cy.visit(`/jahia/jcontent/${HYDROGEN_SITE_KEY}/en/pages/home`); cy.iframe("#page-builder-frame-1").within(() => { - cy.get('button[data-sel-role="hydrogen:heroCallToAction"]').should("be.visible"); + cy.get("button[data-sel-role=\"hydrogen:heroCallToAction\"]").should("be.visible"); }); // but can't be added on the about-us page cy.visit(`/jahia/jcontent/${HYDROGEN_SITE_KEY}/en/pages/about-us`); cy.iframe("#page-builder-frame-1").within(() => { - cy.get('button[data-sel-role="hydrogen:heroCallToAction"]').should("not.exist"); + cy.get("button[data-sel-role=\"hydrogen:heroCallToAction\"]").should("not.exist"); }); }); const pagesWithFooter = [ diff --git a/tests/cypress/e2e/hydrogen-tutorial/4-making-a-blog.cy.ts b/tests/cypress/e2e/hydrogen-tutorial/4-making-a-blog.cy.ts index 7e23d296..927445d2 100644 --- a/tests/cypress/e2e/hydrogen-tutorial/4-making-a-blog.cy.ts +++ b/tests/cypress/e2e/hydrogen-tutorial/4-making-a-blog.cy.ts @@ -1,4 +1,4 @@ -import { HYDROGEN_SITE_KEY, HYDROGEN_POSTS, JAHIA_CONTEXT } from "../../support/constants"; +import { HYDROGEN_POSTS, HYDROGEN_SITE_KEY, JAHIA_CONTEXT } from "../../support/constants"; describe("Validate the concepts of the tutorial: 4 - Making a Blog", () => { it("the blog home page should only list published posts in the right order", () => { diff --git a/tests/cypress/e2e/hydrogen-tutorial/5-view-content-in-full-page.cy.ts b/tests/cypress/e2e/hydrogen-tutorial/5-view-content-in-full-page.cy.ts index 58894f7d..c08b4d00 100644 --- a/tests/cypress/e2e/hydrogen-tutorial/5-view-content-in-full-page.cy.ts +++ b/tests/cypress/e2e/hydrogen-tutorial/5-view-content-in-full-page.cy.ts @@ -1,4 +1,4 @@ -import { HYDROGEN_SITE_KEY, HYDROGEN_POSTS, JAHIA_CONTEXT } from "../../support/constants"; +import { HYDROGEN_POSTS, HYDROGEN_SITE_KEY, JAHIA_CONTEXT } from "../../support/constants"; describe("Validate the concepts of the tutorial: 5 - View Content in Full Page", () => { HYDROGEN_POSTS.forEach(({ page, title, subTitle, details, extract }) => { diff --git a/tests/cypress/e2e/module/moduleRegistrationTest.cy.ts b/tests/cypress/e2e/module/moduleRegistrationTest.cy.ts index 555cdcb2..50b964db 100644 --- a/tests/cypress/e2e/module/moduleRegistrationTest.cy.ts +++ b/tests/cypress/e2e/module/moduleRegistrationTest.cy.ts @@ -1,9 +1,9 @@ import { addNode, getNodeTypes, publishAndWaitJobEnding } from "@jahia/cypress"; -import { addSimplePage } from "../../utils/helpers"; import { GENERIC_SITE_KEY, JAHIA_CONTEXT } from "../../support/constants"; +import { addSimplePage } from "../../utils/helpers"; describe("Check that components of a module are correctly registered", () => { - it("Create a page with .hbs template", function () { + it("Create a page with .hbs template", function() { cy.login(); addSimplePage(`/sites/${GENERIC_SITE_KEY}/home`, "simple", "Simple page", "en", "simple", [ @@ -26,7 +26,7 @@ describe("Check that components of a module are correctly registered", () => { cy.logout(); }); - it("Verify nodeTypes and icons are registered", function () { + it("Verify nodeTypes and icons are registered", function() { cy.login(); getNodeTypes({ includeTypes: ["javascriptExample:test"] }) .its("data.jcr.nodeTypes.nodes") diff --git a/tests/cypress/e2e/module/moduleSettingsTest.cy.ts b/tests/cypress/e2e/module/moduleSettingsTest.cy.ts index 151e1040..9e21b811 100644 --- a/tests/cypress/e2e/module/moduleSettingsTest.cy.ts +++ b/tests/cypress/e2e/module/moduleSettingsTest.cy.ts @@ -1,12 +1,7 @@ +import { addNode, Collapsible, getComponentBySelector, publishAndWaitJobEnding } from "@jahia/cypress"; import { JContent, JContentPageBuilder } from "@jahia/jcontent-cypress/dist/page-object/jcontent"; -import { - addNode, - Collapsible, - getComponentBySelector, - publishAndWaitJobEnding, -} from "@jahia/cypress"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; describe("Check that Javascript module settings (UI extensions, rules, configs) are correctly deployed", () => { before("Create test page and contents", () => { @@ -40,7 +35,7 @@ describe("Check that Javascript module settings (UI extensions, rules, configs) }); }); - it("Ensure Content editor UI extension is correctly registered", function () { + it("Ensure Content editor UI extension is correctly registered", function() { cy.login(); const jcontent = new JContentPageBuilder( JContent.visit(GENERIC_SITE_KEY, "en", "pages/home/testModuleSettings"), @@ -56,23 +51,23 @@ describe("Check that Javascript module settings (UI extensions, rules, configs) .doubleClick(); getComponentBySelector( Collapsible, - '[data-sel-content-editor-fields-group="metadata"]', + "[data-sel-content-editor-fields-group=\"metadata\"]", ).shouldBeExpanded(); cy.logout(); }); - it("Ensure Jahia rule is correctly registered and working", function () { + it("Ensure Jahia rule is correctly registered and working", function() { cy.login(); cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testModuleSettings.html`); - cy.get('div[data-testid="testRule_triggerProp"]').should("contain", "Trigger prop set"); - cy.get('div[data-testid="testRule_resultProp"]').should("contain", "It works"); + cy.get("div[data-testid=\"testRule_triggerProp\"]").should("contain", "Trigger prop set"); + cy.get("div[data-testid=\"testRule_resultProp\"]").should("contain", "It works"); cy.logout(); }); - it("Ensure Jahia URLRewrite rule is correctly registered and working", function () { + it("Ensure Jahia URLRewrite rule is correctly registered and working", function() { cy.login(); cy.visit("/javascriptModuleURLRewriteTest"); - cy.get('div[data-testid="testRule_triggerProp"]').should("contain", "Trigger prop set"); + cy.get("div[data-testid=\"testRule_triggerProp\"]").should("contain", "Trigger prop set"); cy.logout(); }); }); diff --git a/tests/cypress/e2e/module/moduleTransformationTest.cy.ts b/tests/cypress/e2e/module/moduleTransformationTest.cy.ts index f8237cf4..72cb1fd5 100644 --- a/tests/cypress/e2e/module/moduleTransformationTest.cy.ts +++ b/tests/cypress/e2e/module/moduleTransformationTest.cy.ts @@ -6,15 +6,15 @@ describe("Check that the Javascript module has been transformed properly and has console.log(result); expect(result).to.contain("Bundle-Category: jahia-javascript-module"); expect(result).to.contain( - "Bundle-Description: Test module for Javascript Module Engine" + "Bundle-Description: Test module for Javascript Module Engine", ); expect(result).to.contain("Jahia-GroupId: org.jahia.test"); expect(result).to.contain("Bundle-License: MIT"); expect(result).to.contain( - "Bundle-Name: JS Modules Engine Test Module (javascript module)" + "Bundle-Name: JS Modules Engine Test Module (javascript module)", ); expect(result).to.contain( - "Bundle-SymbolicName: javascript-modules-engine-test-module" + "Bundle-SymbolicName: javascript-modules-engine-test-module", ); expect(result).to.contain("Bundle-Vendor: Jahia Solutions Group SA"); expect(result).to.contain("Bundle-Version: "); @@ -22,33 +22,36 @@ describe("Check that the Javascript module has been transformed properly and has // expect(result).to.contain('Jahia-Depends: default,legacy-default-components,javascript-modules-engine') expect(result).to.contain("Jahia-Module-Type: templatesSet"); expect(result).to.contain( - "Jahia-javascript-InitScript: dist/server/index.js" + "Jahia-javascript-InitScript: dist/server/index.js", ); expect(result).to.contain("Jahia-Required-Version: 8.2.0.0-SNAPSHOT"); expect(result).to.contain( - "Jahia-Static-Resources: /css,/javascript,/icons,/dist/client,/static" + "Jahia-Static-Resources: /css,/javascript,/icons,/dist/client,/static", ); // expect for Provide-Capability expect(result).to.contain("Provide-Capability:"); expect(result).to.contain("com.jahia.services.content;nodetypes:List"); - expect(result).to.contain('moduleIdentifier="javascript-modules-engine-test-module"'); - expect(result).to.contain('moduleIdentifier="JS Modules Engine Test Module (javascript module)"'); + expect(result).to.contain("moduleIdentifier=\"javascript-modules-engine-test-module\""); + expect(result).to.contain("moduleIdentifier=\"JS Modules Engine Test Module (javascript module)\""); expect(result).to.contain("javascriptExample:simpleText"); expect(result).to.contain("javascriptExample:testReactClientSide"); expect(result).to.contain("javascriptExampleMix:javascriptExampleComponent"); // expect for Require-Capability expect(result).to.contain("Require-Capability:"); // nodetypes from cnd file - expect(result).to.contain('com.jahia.services.content;filter:="(nodetypes=jmix:accessControllableContent)"'); - expect(result).to.contain('com.jahia.services.content;filter:="(nodetypes=jmix:bindedComponent)"'); - expect(result).to.contain('com.jahia.services.content;filter:="(nodetypes=jmix:droppableContent)"'); - expect(result).to.contain('com.jahia.services.content;filter:="(nodetypes=jnt:content)"'); + expect(result).to.contain("com.jahia.services.content;filter:=\"(nodetypes=jmix:accessControllableContent)\""); + expect(result).to.contain("com.jahia.services.content;filter:=\"(nodetypes=jmix:bindedComponent)\""); + expect(result).to.contain("com.jahia.services.content;filter:=\"(nodetypes=jmix:droppableContent)\""); + expect(result).to.contain("com.jahia.services.content;filter:=\"(nodetypes=jnt:content)\""); // Node types from import.xml - expect(result).to.contain('com.jahia.services.content;filter:="(nodetypes=jnt:page)"'); - expect(result).to.contain('com.jahia.modules.dependencies;filter:="(moduleIdentifier=default)"'); - expect(result).to.contain('com.jahia.modules.dependencies;filter:="(moduleIdentifier=legacy-default-components)"'); - expect(result).to.contain('com.jahia.modules.dependencies;filter:="(moduleIdentifier=javascript-modules-engine)"'); - + expect(result).to.contain("com.jahia.services.content;filter:=\"(nodetypes=jnt:page)\""); + expect(result).to.contain("com.jahia.modules.dependencies;filter:=\"(moduleIdentifier=default)\""); + expect(result).to.contain( + "com.jahia.modules.dependencies;filter:=\"(moduleIdentifier=legacy-default-components)\"", + ); + expect(result).to.contain( + "com.jahia.modules.dependencies;filter:=\"(moduleIdentifier=javascript-modules-engine)\"", + ); }); }); }); diff --git a/tests/cypress/e2e/ui/absoluteAreaTest.cy.ts b/tests/cypress/e2e/ui/absoluteAreaTest.cy.ts index 50724a8e..5c8d846d 100644 --- a/tests/cypress/e2e/ui/absoluteAreaTest.cy.ts +++ b/tests/cypress/e2e/ui/absoluteAreaTest.cy.ts @@ -1,6 +1,6 @@ import { addNode, enableModule } from "@jahia/cypress"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; import "cypress-wait-until"; describe("Absolute Area test", () => { @@ -66,7 +66,7 @@ describe("Absolute Area test", () => { primaryNodeType: "jnt:contentList", }); addSimplePage(`/sites/${GENERIC_SITE_KEY}`, "custom", "Custom", "en", "simple").then(() => - addSimplePage(`/sites/${GENERIC_SITE_KEY}/custom`, "sub-level", "Sub level", "en", "simple"), + addSimplePage(`/sites/${GENERIC_SITE_KEY}/custom`, "sub-level", "Sub level", "en", "simple") ); }); @@ -79,20 +79,20 @@ describe("Absolute Area test", () => { it(`${pageName}: Basic Area test`, () => { cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="basicArea"]').find('div[type="absoluteArea"]').should("be.visible"); + cy.get("div[data-testid=\"basicArea\"]").find("div[type=\"absoluteArea\"]").should("be.visible"); }); }); it(`${pageName}: Allowed types area`, () => { cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="allowedTypesArea"]') - .find('div[type="placeholder"]') + cy.get("div[data-testid=\"allowedTypesArea\"]") + .find("div[type=\"placeholder\"]") .then((buttons) => { const selector = `div[data-jahia-id="${buttons.attr("id")}"]`; - cy.get(selector).find('button[data-sel-role="jnt:bigText"]').should("be.visible"); - cy.get(selector).find('button[data-sel-role="jnt:event"]').should("be.visible"); + cy.get(selector).find("button[data-sel-role=\"jnt:bigText\"]").should("be.visible"); + cy.get(selector).find("button[data-sel-role=\"jnt:event\"]").should("be.visible"); cy.get(selector) - .find('button[data-sel-role!="jnt:event"][data-sel-role!="jnt:bigText"]') + .find("button[data-sel-role!=\"jnt:event\"][data-sel-role!=\"jnt:bigText\"]") .should("not.exist"); }); }); @@ -111,21 +111,21 @@ describe("Absolute Area test", () => { }); cy.reload(); cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="numberOfItemsArea"]') - .find('div[type="placeholder"]') + cy.get("div[data-testid=\"numberOfItemsArea\"]") + .find("div[type=\"placeholder\"]") .should("not.be.visible"); }); }); it(`${pageName}: areaView Area`, () => { cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="areaViewArea"]').find('ul[class*="dropdown"]').should("be.visible"); + cy.get("div[data-testid=\"areaViewArea\"]").find("ul[class*=\"dropdown\"]").should("be.visible"); }); }); it(`${pageName}: absolute Area home page`, () => { cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="absoluteAreaHomePage"] div[data-testid="row-twoColumns"]').should( + cy.get("div[data-testid=\"absoluteAreaHomePage\"] div[data-testid=\"row-twoColumns\"]").should( "exist", ); }); @@ -133,44 +133,44 @@ describe("Absolute Area test", () => { it(`${pageName}: absolute Area site root`, () => { cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="absoluteAreaCustomPage"]') - .find('div[type="absoluteArea"]') + cy.get("div[data-testid=\"absoluteAreaCustomPage\"]") + .find("div[type=\"absoluteArea\"]") .should("be.visible"); }); }); it(`${pageName}: absolute Area custom page (sub-level)`, () => { cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="absoluteAreaCustomPage"]') - .find('div[type="absoluteArea"]') + cy.get("div[data-testid=\"absoluteAreaCustomPage\"]") + .find("div[type=\"absoluteArea\"]") .should("be.visible"); }); }); it(`${pageName}: non editable Area`, () => { cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="nonEditableArea"]').should("be.empty"); + cy.get("div[data-testid=\"nonEditableArea\"]").should("be.empty"); }); }); it(`${pageName}: Area type`, () => { cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="areaType"]').find('div[data-testid="row-areaType"]').should("exist"); + cy.get("div[data-testid=\"areaType\"]").find("div[data-testid=\"row-areaType\"]").should("exist"); }); }); it(`${pageName}: Limited absolute area editing`, () => { cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="limitedAbsoluteAreaEdit"]') - .find('div[type="existingNode"]') + cy.get("div[data-testid=\"limitedAbsoluteAreaEdit\"]") + .find("div[type=\"existingNode\"]") .should("not.exist"); }); }); - it(`${pageName}: should render absolute area with parameters`, function () { + it(`${pageName}: should render absolute area with parameters`, function() { cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="areaParam-string1"]').should("contain", "stringParam1=stringValue1"); - cy.get('div[data-testid="areaParam-string2"]').should("contain", "stringParam2=stringValue2"); + cy.get("div[data-testid=\"areaParam-string1\"]").should("contain", "stringParam1=stringValue1"); + cy.get("div[data-testid=\"areaParam-string2\"]").should("contain", "stringParam2=stringValue2"); }); }); }); diff --git a/tests/cypress/e2e/ui/addResources.cy.ts b/tests/cypress/e2e/ui/addResources.cy.ts index 0785f967..e7319266 100644 --- a/tests/cypress/e2e/ui/addResources.cy.ts +++ b/tests/cypress/e2e/ui/addResources.cy.ts @@ -1,6 +1,6 @@ import { addNode } from "@jahia/cypress"; +import { GENERIC_SITE_KEY, JAHIA_CONTEXT } from "../../support/constants"; import { addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY, JAHIA_CONTEXT } from '../../support/constants'; describe("Test on add resources component/helper", () => { const pageName = "testAddResources"; @@ -22,15 +22,19 @@ describe("Test on add resources component/helper", () => { { name: "propMultiple", values: ["value 1", "value 2", "value 3"] }, { name: "propRichText", - value: '

Hello this is a sample rich text

', + value: "

Hello this is a sample rich text

", }, ], }); }); }); - beforeEach("Login", () => { cy.login(); }); - afterEach('Logout', () => { cy.logout(); }); + beforeEach("Login", () => { + cy.login(); + }); + afterEach("Logout", () => { + cy.logout(); + }); it(`${pageName}: should not contain a div in the head tag in the page source code`, () => { cy.request(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/${pageName}.html`) @@ -43,7 +47,7 @@ describe("Test on add resources component/helper", () => { it(`${pageName} : should contain a link tag in the head tag to load the CSS styles`, () => { cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/${pageName}.html`); cy.get( - `head link[href="${JAHIA_CONTEXT}/modules/javascript-modules-engine-test-module/css/styles.css"]` + `head link[href="${JAHIA_CONTEXT}/modules/javascript-modules-engine-test-module/css/styles.css"]`, ).then(($link: JQuery) => { expect($link.attr("id")).to.match(/^staticAssetCSS/); }); diff --git a/tests/cypress/e2e/ui/areaTest.cy.ts b/tests/cypress/e2e/ui/areaTest.cy.ts index f805c7c7..030d5cfb 100644 --- a/tests/cypress/e2e/ui/areaTest.cy.ts +++ b/tests/cypress/e2e/ui/areaTest.cy.ts @@ -1,13 +1,13 @@ import { addNode, enableModule } from "@jahia/cypress"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; import "cypress-wait-until"; describe("Area test", () => { const pageName = "testJArea"; before("Create test page and contents", () => { - enableModule('event', GENERIC_SITE_KEY); + enableModule("event", GENERIC_SITE_KEY); addSimplePage(`/sites/${GENERIC_SITE_KEY}/home`, pageName, pageName, "en", "simple", [ { @@ -23,29 +23,29 @@ describe("Area test", () => { }); }); - beforeEach('Login and visit test page', () => { + beforeEach("Login and visit test page", () => { cy.login(); cy.visit(`/jahia/jcontent/${GENERIC_SITE_KEY}/en/pages/home/${pageName}`); }); - afterEach('Logout', () => cy.logout()); + afterEach("Logout", () => cy.logout()); it(`${pageName}: Basic Area test`, () => { cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="basicArea"]').find('div[type="area"]').should("be.visible"); + cy.get("div[data-testid=\"basicArea\"]").find("div[type=\"area\"]").should("be.visible"); }); }); it(`${pageName}: Allowed types area`, () => { cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="allowedTypesArea"]') - .find('div[type="placeholder"]') + cy.get("div[data-testid=\"allowedTypesArea\"]") + .find("div[type=\"placeholder\"]") .then((buttons) => { const selector = `div[data-jahia-id="${buttons.attr("id")}"]`; - cy.get(selector).find('button[data-sel-role="jnt:bigText"]').should("be.visible"); - cy.get(selector).find('button[data-sel-role="jnt:event"]').should("be.visible"); + cy.get(selector).find("button[data-sel-role=\"jnt:bigText\"]").should("be.visible"); + cy.get(selector).find("button[data-sel-role=\"jnt:event\"]").should("be.visible"); cy.get(selector) - .find('button[data-sel-role!="jnt:event"][data-sel-role!="jnt:bigText"]') + .find("button[data-sel-role!=\"jnt:event\"][data-sel-role!=\"jnt:bigText\"]") .should("not.exist"); }); }); @@ -64,40 +64,40 @@ describe("Area test", () => { }); cy.reload(); cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="numberOfItemsArea"]') - .find('div[type="placeholder"]') + cy.get("div[data-testid=\"numberOfItemsArea\"]") + .find("div[type=\"placeholder\"]") .should("not.be.visible"); }); }); it(`${pageName}: areaView Area`, () => { cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="areaViewArea"]').find('ul[class*="dropdown"]').should("be.visible"); + cy.get("div[data-testid=\"areaViewArea\"]").find("ul[class*=\"dropdown\"]").should("be.visible"); }); }); it(`${pageName}: path Area`, () => { cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="parentArea"]').find('div[type="area"]').should("exist"); + cy.get("div[data-testid=\"parentArea\"]").find("div[type=\"area\"]").should("exist"); }); }); it(`${pageName}: non editable Area`, () => { cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="nonEditableArea"]').should("be.empty"); + cy.get("div[data-testid=\"nonEditableArea\"]").should("be.empty"); }); }); it(`${pageName}: Area type`, () => { cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="areaType"]').find('div[data-testid="row-areaType"]').should("exist"); + cy.get("div[data-testid=\"areaType\"]").find("div[data-testid=\"row-areaType\"]").should("exist"); }); }); - it(`${pageName}: should render area with parameters`, function () { + it(`${pageName}: should render area with parameters`, function() { cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="areaParam-string1"]').should("contain", "stringParam1=stringValue1"); - cy.get('div[data-testid="areaParam-string2"]').should("contain", "stringParam2=stringValue2"); + cy.get("div[data-testid=\"areaParam-string1\"]").should("contain", "stringParam1=stringValue1"); + cy.get("div[data-testid=\"areaParam-string2\"]").should("contain", "stringParam2=stringValue2"); }); }); }); diff --git a/tests/cypress/e2e/ui/boundComponentTest.cy.ts b/tests/cypress/e2e/ui/boundComponentTest.cy.ts index 50a1d285..48b51aea 100644 --- a/tests/cypress/e2e/ui/boundComponentTest.cy.ts +++ b/tests/cypress/e2e/ui/boundComponentTest.cy.ts @@ -1,6 +1,6 @@ import { enableModule, publishAndWaitJobEnding } from "@jahia/cypress"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addEvent, addEventPageAndEvents, addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; describe("Check on bound components", () => { before(() => { @@ -18,14 +18,18 @@ describe("Check on bound components", () => { }); }); - beforeEach('Login', () => { cy.login(); }); - afterEach('Logout', () => { cy.logout(); }); + beforeEach("Login", () => { + cy.login(); + }); + afterEach("Logout", () => { + cy.logout(); + }); const validateNumberOfEventInCalendar = (expectedNumber: number) => { cy.get(`span[class*="fc-event-title"]:contains("${expectedNumber}")`).should("exist"); }; - it("Verify calendar (.jsp content in the template) is correctly bound to the events list", function () { + it("Verify calendar (.jsp content in the template) is correctly bound to the events list", function() { const pageName = "test1"; const pageTemplate = "events"; addEventPageAndEvents(GENERIC_SITE_KEY, pageTemplate, pageName, () => { @@ -35,7 +39,7 @@ describe("Check on bound components", () => { }); }); - it("Verify that the calendar is correctly refreshed once a new event is added", function () { + it("Verify that the calendar is correctly refreshed once a new event is added", function() { const pageName = "test2"; const pageTemplate = "events"; addEventPageAndEvents(GENERIC_SITE_KEY, pageTemplate, pageName, () => { @@ -61,7 +65,7 @@ describe("Check on bound components", () => { }); }); - it("Verify that the facets is working correctly", function () { + it("Verify that the facets is working correctly", function() { const pageName = "test3"; const pageTemplate = "events"; addEventPageAndEvents(GENERIC_SITE_KEY, pageTemplate, pageName, () => { @@ -90,41 +94,41 @@ describe("Check on bound components", () => { // Check facets display cy.visit(`/sites/${GENERIC_SITE_KEY}/home/${pageName}.html`, { failOnStatusCode: false }); cy.get(".eventsListItem").should("have.length", 4); - cy.get('div[class*="facetsList"] a:contains("consumerShow")').should("exist"); - cy.get('div[class*="facetsList"] a:contains("meeting")').should("exist"); + cy.get("div[class*=\"facetsList\"] a:contains(\"consumerShow\")").should("exist"); + cy.get("div[class*=\"facetsList\"] a:contains(\"meeting\")").should("exist"); // Activate consumerShow facet - cy.get('div[class*="facetsList"] a:contains("consumerShow")').click(); + cy.get("div[class*=\"facetsList\"] a:contains(\"consumerShow\")").click(); cy.get(".eventsListItem").should("have.length", 1); // Deactivate consumerShow facet - cy.get('a:contains("remove")').click(); + cy.get("a:contains(\"remove\")").click(); cy.get(".eventsListItem").should("have.length", 4); // Activate meeting facet - cy.get('div[class*="facetsList"] a:contains("meeting")').click(); + cy.get("div[class*=\"facetsList\"] a:contains(\"meeting\")").click(); cy.get(".eventsListItem").should("have.length", 3); // Deactivate consumerShow facet - cy.get('a:contains("remove")').click(); + cy.get("a:contains(\"remove\")").click(); cy.get(".eventsListItem").should("have.length", 4); }); }); - it("Test boundComponent behavior with area/list creation by edit mode", function () { + it("Test boundComponent behavior with area/list creation by edit mode", function() { // The page have been published without rendering in edit mode, list for area won't be created yet, check live: cy.visit(`/sites/${GENERIC_SITE_KEY}/home/testBoundComponent.html`, { failOnStatusCode: false }); - cy.get('[data-testid="boundComponent_path"]').should("contain", "null"); + cy.get("[data-testid=\"boundComponent_path\"]").should("contain", "null"); // Check preview: cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testBoundComponent.html`); - cy.get('[data-testid="boundComponent_path"]').should("contain", "null"); + cy.get("[data-testid=\"boundComponent_path\"]").should("contain", "null"); // Go to edit mode to trigger the area/list creation cy.visit(`/jahia/jcontent/${GENERIC_SITE_KEY}/en/pages/home/testBoundComponent`); - cy.iframe('[data-sel-role="page-builder-frame-active"]', { timeout: 90000, log: true }).within( + cy.iframe("[data-sel-role=\"page-builder-frame-active\"]", { timeout: 90000, log: true }).within( () => { // The list should have been created - cy.get('[data-testid="boundComponent_path"]').should( + cy.get("[data-testid=\"boundComponent_path\"]").should( "contain", `/${GENERIC_SITE_KEY}/home/testBoundComponent/events`, ); @@ -132,18 +136,18 @@ describe("Check on bound components", () => { ); // Retest preview that should now be correct cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testBoundComponent.html`); - cy.get('[data-testid="boundComponent_path"]').should( + cy.get("[data-testid=\"boundComponent_path\"]").should( "contain", `/${GENERIC_SITE_KEY}/home/testBoundComponent/events`, ); // Retest live that should still not be correct, since we didn't publish the changes cy.visit(`/sites/${GENERIC_SITE_KEY}/home/testBoundComponent.html`, { failOnStatusCode: false }); - cy.get('[data-testid="boundComponent_path"]').should("contain", "null"); + cy.get("[data-testid=\"boundComponent_path\"]").should("contain", "null"); // Publish the changes, and retest live that should be correct publishAndWaitJobEnding(`/sites/${GENERIC_SITE_KEY}/home/testBoundComponent`); cy.visit(`/sites/${GENERIC_SITE_KEY}/home/testBoundComponent.html`, { failOnStatusCode: false }); - cy.get('[data-testid="boundComponent_path"]').should( + cy.get("[data-testid=\"boundComponent_path\"]").should( "contain", `/${GENERIC_SITE_KEY}/home/testBoundComponent/events`, ); diff --git a/tests/cypress/e2e/ui/configTest.cy.ts b/tests/cypress/e2e/ui/configTest.cy.ts index 2b4a4104..89c811d9 100644 --- a/tests/cypress/e2e/ui/configTest.cy.ts +++ b/tests/cypress/e2e/ui/configTest.cy.ts @@ -1,6 +1,6 @@ import { addNode, publishAndWaitJobEnding } from "@jahia/cypress"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; describe("Test OSGi configuration in views", () => { const pageName = "testConfig"; @@ -22,44 +22,44 @@ describe("Test OSGi configuration in views", () => { }); const testConfigEntries = () => { - cy.get('p[data-testid="configKey1"]').should("contain", "configKey1=configValue1"); - cy.get('p[data-testid="configValues.configKey1"]').should( + cy.get("p[data-testid=\"configKey1\"]").should("contain", "configKey1=configValue1"); + cy.get("p[data-testid=\"configValues.configKey1\"]").should( "contain", "configValues.configKey1=configValue1", ); - cy.get('p[data-testid="configValues.configKey2"]').should( + cy.get("p[data-testid=\"configValues.configKey2\"]").should( "contain", "configValues.configKey2=configValue2", ); - cy.get('p[data-testid="defaultFactoryConfigs.configKey1"]').should( + cy.get("p[data-testid=\"defaultFactoryConfigs.configKey1\"]").should( "contain", "defaultFactoryConfigs.configKey1=configValue1", ); - cy.get('p[data-testid="defaultFactoryConfigs.configKey2"]').should( + cy.get("p[data-testid=\"defaultFactoryConfigs.configKey2\"]").should( "contain", "defaultFactoryConfigs.configKey2=configValue2", ); - cy.get('p[data-testid="testModuleFactoryIdentifiers"]').should( + cy.get("p[data-testid=\"testModuleFactoryIdentifiers\"]").should( "contain", "testModuleFactoryIdentifiers=default,id1,id2", ); - cy.get('div[data-testid="complexObject_metadata.name"]').should( + cy.get("div[data-testid=\"complexObject_metadata.name\"]").should( "contain", "metadata.name: my-app", ); }; - it(`${pageName}: test config in preview`, function () { + it(`${pageName}: test config in preview`, function() { cy.login(); cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/${pageName}.html`); testConfigEntries(); cy.logout(); }); - it(`${pageName}: test config in edit`, function () { + it(`${pageName}: test config in edit`, function() { cy.login(); cy.visit(`/jahia/jcontent/${GENERIC_SITE_KEY}/en/pages/home/${pageName}`); - cy.iframe('[data-sel-role="page-builder-frame-active"]', { timeout: 90000, log: true }).within( + cy.iframe("[data-sel-role=\"page-builder-frame-active\"]", { timeout: 90000, log: true }).within( () => { testConfigEntries(); }, @@ -67,19 +67,19 @@ describe("Test OSGi configuration in views", () => { cy.logout(); }); - it(`${pageName}: test config in live guest`, function () { + it(`${pageName}: test config in live guest`, function() { cy.visit(`/sites/${GENERIC_SITE_KEY}/home/${pageName}.html`); testConfigEntries(); }); - it(`${pageName}: test config in live logged`, function () { + it(`${pageName}: test config in live logged`, function() { cy.login(); cy.visit(`/sites/${GENERIC_SITE_KEY}/home/${pageName}.html`); testConfigEntries(); cy.logout(); }); - it(`${pageName}: test config in ajax rendered content`, function () { + it(`${pageName}: test config in ajax rendered content`, function() { cy.visit(`/sites/${GENERIC_SITE_KEY}/home/${pageName}/pagecontent/test.html.ajax`); testConfigEntries(); }); diff --git a/tests/cypress/e2e/ui/contentTemplate.cy.ts b/tests/cypress/e2e/ui/contentTemplate.cy.ts index b8c865ce..9239a0e2 100644 --- a/tests/cypress/e2e/ui/contentTemplate.cy.ts +++ b/tests/cypress/e2e/ui/contentTemplate.cy.ts @@ -1,6 +1,6 @@ import { addNode, enableModule } from "@jahia/cypress"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addEventPageAndEvents, addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; describe("Content templates resolution testsuite", () => { before("Create test page and contents", () => { @@ -79,35 +79,39 @@ describe("Content templates resolution testsuite", () => { }); }); - beforeEach('Login', () => { cy.login(); }); - afterEach('Logout', () => { cy.logout(); }); + beforeEach("Login", () => { + cy.login(); + }); + afterEach("Logout", () => { + cy.logout(); + }); - it("Verify content template for jnt:event is correctly displayed", function () { + it("Verify content template for jnt:event is correctly displayed", function() { cy.visit( `/jahia/page-composer/default/en/sites/${GENERIC_SITE_KEY}/home/testEvents/events/event-a.full.html`, ); cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testEvents/events/event-a.full.html`); // Check template is good: - cy.get('div[class="header"]').should("be.visible"); - cy.get('div[class="main"]').should("be.visible"); - cy.get('div[class="footer"]').should("be.visible"); + cy.get("div[class=\"header\"]").should("be.visible"); + cy.get("div[class=\"main\"]").should("be.visible"); + cy.get("div[class=\"footer\"]").should("be.visible"); // Check main resource display is correct: - cy.get('div[class="eventsBody"]').should("be.visible"); - cy.get('div[class="eventsBody"]').contains("The first event"); + cy.get("div[class=\"eventsBody\"]").should("be.visible"); + cy.get("div[class=\"eventsBody\"]").contains("The first event"); }); - it("Verify findDisplayableNode is correctly resolving jnt:event that is using a JS content template", function () { + it("Verify findDisplayableNode is correctly resolving jnt:event that is using a JS content template", function() { cy.visit(`/jahia/page-composer/default/en/sites/${GENERIC_SITE_KEY}/home/testFindDisplayableNode.html`); cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testFindDisplayableNode.html`); - cy.get('p[data-testid="displayableContent"]').contains( + cy.get("p[data-testid=\"displayableContent\"]").contains( `Found displayable content: /sites/${GENERIC_SITE_KEY}/home/testEvents/events/event-a`, ); }); - it("Test default content template is working properly when content doesn't have specific view", function () { + it("Test default content template is working properly when content doesn't have specific view", function() { cy.visit( `/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testContentTemplate/pagecontent/content.html`, ); @@ -117,7 +121,7 @@ describe("Content templates resolution testsuite", () => { cy.contains("Just a normal view").should("be.visible"); }); - it("Test default content template is working properly when content have specific view", function () { + it("Test default content template is working properly when content have specific view", function() { cy.visit( `/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testContentTemplateWithView/pagecontent/content.html`, ); diff --git a/tests/cypress/e2e/ui/currentContent.cy.ts b/tests/cypress/e2e/ui/currentContent.cy.ts index 1e4409e2..13544370 100644 --- a/tests/cypress/e2e/ui/currentContent.cy.ts +++ b/tests/cypress/e2e/ui/currentContent.cy.ts @@ -1,6 +1,6 @@ import { addNode } from "@jahia/cypress"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; describe("Test on currentContent injected data", () => { const pageName = "testCurrentContent"; @@ -22,53 +22,57 @@ describe("Test on currentContent injected data", () => { { name: "propMultiple", values: ["value 1", "value 2", "value 3"] }, { name: "propRichText", - value: '

Hello this is a sample rich text

', + value: "

Hello this is a sample rich text

", }, ], }); }); }); - beforeEach("Login", () => { cy.login(); }); - afterEach('Logout', () => { cy.logout(); }); + beforeEach("Login", () => { + cy.login(); + }); + afterEach("Logout", () => { + cy.logout(); + }); - it(`${pageName}: Check currentContent injected JSON node in current view`, function () { + it(`${pageName}: Check currentContent injected JSON node in current view`, function() { cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/${pageName}.html`); - cy.get('div[data-testid="currentContent_resourcePath"]').should( + cy.get("div[data-testid=\"currentContent_resourcePath\"]").should( "contain", `/sites/${GENERIC_SITE_KEY}/home/${pageName}/pagecontent/test`, ); - cy.get('div[data-testid="currentContent_nodePath"]').should( + cy.get("div[data-testid=\"currentContent_nodePath\"]").should( "contain", `/sites/${GENERIC_SITE_KEY}/home/${pageName}/pagecontent/test`, ); - cy.get('div[data-testid="currentContent_mainNodePath"]').should( + cy.get("div[data-testid=\"currentContent_mainNodePath\"]").should( "contain", `/sites/${GENERIC_SITE_KEY}/home/${pageName}`, ); - cy.get('div[data-testid="currentContent_properties_prop1"]').should("contain", "prop1 value"); - cy.get('div[data-testid="currentContent_properties_jcr:title"]').should( + cy.get("div[data-testid=\"currentContent_properties_prop1\"]").should("contain", "prop1 value"); + cy.get("div[data-testid=\"currentContent_properties_jcr:title\"]").should( "contain", "test component", ); - cy.get('div[data-testid="currentContent_properties_propMultiple"]').should( + cy.get("div[data-testid=\"currentContent_properties_propMultiple\"]").should( "contain", "value 1,value 2,value 3", ); - cy.get('p[data-testid="propRichTextValue"]').should( + cy.get("p[data-testid=\"propRichTextValue\"]").should( "contain", "Hello this is a sample rich text", ); - cy.get('div[data-testid="currentContent_name"]').should("contain", "test"); - cy.get('div[data-testid="currentContent_path"]').should( + cy.get("div[data-testid=\"currentContent_name\"]").should("contain", "test"); + cy.get("div[data-testid=\"currentContent_path\"]").should( "contain", `/sites/${GENERIC_SITE_KEY}/home/${pageName}/pagecontent/test`, ); - cy.get('div[data-testid="currentContent_parent"]').should( + cy.get("div[data-testid=\"currentContent_parent\"]").should( "contain", `/sites/${GENERIC_SITE_KEY}/home/${pageName}/pagecontent`, ); - cy.get('div[data-testid="currentContent_nodeType"]').should( + cy.get("div[data-testid=\"currentContent_nodeType\"]").should( "contain", "javascriptExample:test", ); diff --git a/tests/cypress/e2e/ui/getChildNodesTest.cy.ts b/tests/cypress/e2e/ui/getChildNodesTest.cy.ts index 698b331a..5d36f7ab 100644 --- a/tests/cypress/e2e/ui/getChildNodesTest.cy.ts +++ b/tests/cypress/e2e/ui/getChildNodesTest.cy.ts @@ -1,6 +1,6 @@ import { addNode } from "@jahia/cypress"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; describe("getChildNodes function test", () => { before("Create test page and contents", () => { @@ -47,191 +47,195 @@ describe("getChildNodes function test", () => { }); }); - beforeEach('Login', () => { cy.login(); }); - afterEach('Logout', () => { cy.logout(); }); + beforeEach("Login", () => { + cy.login(); + }); + afterEach("Logout", () => { + cy.logout(); + }); - it("Verify all children returned", function () { + it("Verify all children returned", function() { cy.visit( `/jahia/page-composer/default/en/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes.html`, ); cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes.html`); - cy.get('div[data-testid="getChildNodes_all_1"]').contains( + cy.get("div[data-testid=\"getChildNodes_all_1\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes/pagecontent/getChildNodesTest/child1`, ); - cy.get('div[data-testid="getChildNodes_all_2"]').contains( + cy.get("div[data-testid=\"getChildNodes_all_2\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes/pagecontent/getChildNodesTest/child2`, ); - cy.get('div[data-testid="getChildNodes_all_3"]').contains( + cy.get("div[data-testid=\"getChildNodes_all_3\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes/pagecontent/getChildNodesTest/filtered`, ); - cy.get('div[data-testid="getChildNodes_all_4"]').contains( + cy.get("div[data-testid=\"getChildNodes_all_4\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes/pagecontent/getChildNodesTest/filtered2`, ); - cy.get('div[data-testid="getChildNodes_all_5"]').contains( + cy.get("div[data-testid=\"getChildNodes_all_5\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes/pagecontent/getChildNodesTest/filtered3`, ); }); - it("Verify filtered children returned", function () { + it("Verify filtered children returned", function() { cy.visit( `/jahia/page-composer/default/en/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes.html`, ); cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes.html`); - cy.get('div[data-testid="getChildNodes_filtered_1"]').contains( + cy.get("div[data-testid=\"getChildNodes_filtered_1\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes/pagecontent/getChildNodesTest/filtered`, ); - cy.get('div[data-testid="getChildNodes_filtered_2"]').contains( + cy.get("div[data-testid=\"getChildNodes_filtered_2\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes/pagecontent/getChildNodesTest/filtered2`, ); - cy.get('div[data-testid="getChildNodes_filtered_3"]').contains( + cy.get("div[data-testid=\"getChildNodes_filtered_3\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes/pagecontent/getChildNodesTest/filtered3`, ); - cy.get('div[data-testid="getChildNodes_filtered_4"]').should("not.exist"); - cy.get('div[data-testid="getChildNodes_filtered_5"]').should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_filtered_4\"]").should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_filtered_5\"]").should("not.exist"); }); - it("Verify filtered + offset children returned", function () { + it("Verify filtered + offset children returned", function() { cy.visit( `/jahia/page-composer/default/en/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes.html`, ); cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes.html`); - cy.get('div[data-testid="getChildNodes_filteredOffset_1"]').contains( + cy.get("div[data-testid=\"getChildNodes_filteredOffset_1\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes/pagecontent/getChildNodesTest/filtered2`, ); - cy.get('div[data-testid="getChildNodes_filteredOffset_2"]').contains( + cy.get("div[data-testid=\"getChildNodes_filteredOffset_2\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes/pagecontent/getChildNodesTest/filtered3`, ); - cy.get('div[data-testid="getChildNodes_filteredOffset_3"]').should("not.exist"); - cy.get('div[data-testid="getChildNodes_filteredOffset_4"]').should("not.exist"); - cy.get('div[data-testid="getChildNodes_filteredOffset_5"]').should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_filteredOffset_3\"]").should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_filteredOffset_4\"]").should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_filteredOffset_5\"]").should("not.exist"); }); - it("Verify filtered + limit children returned", function () { + it("Verify filtered + limit children returned", function() { cy.login(); cy.visit( `/jahia/page-composer/default/en/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes.html`, ); cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes.html`); - cy.get('div[data-testid="getChildNodes_filteredLimit_1"]').contains( + cy.get("div[data-testid=\"getChildNodes_filteredLimit_1\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes/pagecontent/getChildNodesTest/filtered`, ); - cy.get('div[data-testid="getChildNodes_filteredLimit_2"]').should("not.exist"); - cy.get('div[data-testid="getChildNodes_filteredLimit_3"]').should("not.exist"); - cy.get('div[data-testid="getChildNodes_filteredLimit_4"]').should("not.exist"); - cy.get('div[data-testid="getChildNodes_filteredLimit_5"]').should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_filteredLimit_2\"]").should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_filteredLimit_3\"]").should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_filteredLimit_4\"]").should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_filteredLimit_5\"]").should("not.exist"); }); - it("Verify filtered + limit + offset children returned", function () { + it("Verify filtered + limit + offset children returned", function() { cy.visit( `/jahia/page-composer/default/en/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes.html`, ); cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes.html`); - cy.get('div[data-testid="getChildNodes_filteredLimitOffset_1"]').contains( + cy.get("div[data-testid=\"getChildNodes_filteredLimitOffset_1\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes/pagecontent/getChildNodesTest/filtered2`, ); - cy.get('div[data-testid="getChildNodes_filteredLimitOffset_2"]').should("not.exist"); - cy.get('div[data-testid="getChildNodes_filteredLimitOffset_3"]').should("not.exist"); - cy.get('div[data-testid="getChildNodes_filteredLimitOffset_4"]').should("not.exist"); - cy.get('div[data-testid="getChildNodes_filteredLimitOffset_5"]').should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_filteredLimitOffset_2\"]").should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_filteredLimitOffset_3\"]").should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_filteredLimitOffset_4\"]").should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_filteredLimitOffset_5\"]").should("not.exist"); }); - it("Verify limited children returned", function () { + it("Verify limited children returned", function() { cy.visit( `/jahia/page-composer/default/en/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes.html`, ); cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes.html`); - cy.get('div[data-testid="getChildNodes_limit_1"]').contains( + cy.get("div[data-testid=\"getChildNodes_limit_1\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes/pagecontent/getChildNodesTest/child1`, ); - cy.get('div[data-testid="getChildNodes_limit_2"]').contains( + cy.get("div[data-testid=\"getChildNodes_limit_2\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes/pagecontent/getChildNodesTest/child2`, ); - cy.get('div[data-testid="getChildNodes_limit_3"]').should("not.exist"); - cy.get('div[data-testid="getChildNodes_limit_4"]').should("not.exist"); - cy.get('div[data-testid="getChildNodes_limit_5"]').should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_limit_3\"]").should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_limit_4\"]").should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_limit_5\"]").should("not.exist"); }); - it("Verify limited + offset children returned", function () { + it("Verify limited + offset children returned", function() { cy.visit( `/jahia/page-composer/default/en/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes.html`, ); cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes.html`); - cy.get('div[data-testid="getChildNodes_limitOffset_1"]').contains( + cy.get("div[data-testid=\"getChildNodes_limitOffset_1\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes/pagecontent/getChildNodesTest/filtered`, ); - cy.get('div[data-testid="getChildNodes_limitOffset_2"]').contains( + cy.get("div[data-testid=\"getChildNodes_limitOffset_2\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes/pagecontent/getChildNodesTest/filtered2`, ); - cy.get('div[data-testid="getChildNodes_limitOffset_3"]').should("not.exist"); - cy.get('div[data-testid="getChildNodes_limitOffset_4"]').should("not.exist"); - cy.get('div[data-testid="getChildNodes_limitOffset_5"]').should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_limitOffset_3\"]").should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_limitOffset_4\"]").should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_limitOffset_5\"]").should("not.exist"); }); - it("Verify limit is mandatory", function () { + it("Verify limit is mandatory", function() { cy.visit( `/jahia/page-composer/default/en/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes.html`, ); cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes.html`); - cy.get('div[data-testid="getChildNodes_limitMandatory_1"]').should("not.exist"); - cy.get('div[data-testid="getChildNodes_limitMandatory_2"]').should("not.exist"); - cy.get('div[data-testid="getChildNodes_limitMandatory_3"]').should("not.exist"); - cy.get('div[data-testid="getChildNodes_limitMandatory_4"]').should("not.exist"); - cy.get('div[data-testid="getChildNodes_limitMandatory_5"]').should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_limitMandatory_1\"]").should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_limitMandatory_2\"]").should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_limitMandatory_3\"]").should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_limitMandatory_4\"]").should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_limitMandatory_5\"]").should("not.exist"); }); - it("Verify offset", function () { + it("Verify offset", function() { cy.visit( `/jahia/page-composer/default/en/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes.html`, ); cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes.html`); - cy.get('div[data-testid="getChildNodes_offset_1"]').contains( + cy.get("div[data-testid=\"getChildNodes_offset_1\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes/pagecontent/getChildNodesTest/filtered`, ); - cy.get('div[data-testid="getChildNodes_offset_2"]').contains( + cy.get("div[data-testid=\"getChildNodes_offset_2\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes/pagecontent/getChildNodesTest/filtered2`, ); - cy.get('div[data-testid="getChildNodes_offset_3"]').contains( + cy.get("div[data-testid=\"getChildNodes_offset_3\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes/pagecontent/getChildNodesTest/filtered3`, ); - cy.get('div[data-testid="getChildNodes_offset_4"]').should("not.exist"); - cy.get('div[data-testid="getChildNodes_offset_5"]').should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_offset_4\"]").should("not.exist"); + cy.get("div[data-testid=\"getChildNodes_offset_5\"]").should("not.exist"); }); - it("Verify RenderChildren", function () { + it("Verify RenderChildren", function() { cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes.html`); for (const child of ["child1", "child2", "filtered", "filtered2", "filtered3"]) { - cy.get('div[data-testid="renderAllChildren"]').contains( + cy.get("div[data-testid=\"renderAllChildren\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes/pagecontent/getChildNodesTest/${child}`, ); } for (const child of ["filtered", "filtered2", "filtered3"]) { - cy.get('div[data-testid="renderFilteredChildren"]').contains( + cy.get("div[data-testid=\"renderFilteredChildren\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes/pagecontent/getChildNodesTest/${child}`, ); } for (const child of ["child2", "filtered"]) { - cy.get('div[data-testid="renderPaginatedChildren"]').contains( + cy.get("div[data-testid=\"renderPaginatedChildren\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes/pagecontent/getChildNodesTest/${child}`, ); } }); - it("Verify RenderChild", function () { + it("Verify RenderChild", function() { cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes.html`); - cy.get('div[data-testid="renderChild"]').contains( + cy.get("div[data-testid=\"renderChild\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetChildNodes/pagecontent/getChildNodesTest/child1`, ); }); diff --git a/tests/cypress/e2e/ui/getNodePropsTest.cy.ts b/tests/cypress/e2e/ui/getNodePropsTest.cy.ts index 3b424672..c40fcb07 100644 --- a/tests/cypress/e2e/ui/getNodePropsTest.cy.ts +++ b/tests/cypress/e2e/ui/getNodePropsTest.cy.ts @@ -1,6 +1,6 @@ import { addNode } from "@jahia/cypress"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; describe("getNodeProps function test", () => { before("Create test page and contents", () => { @@ -39,7 +39,7 @@ describe("getNodeProps function test", () => { }, { name: "bigtext", - value: '
bigtext value
', + value: "
bigtext value
", }, { name: "date", value: "2023-12-26T01:30:25.243Z", type: "DATE" }, { name: "decimal", value: "4535353.55665775", type: "DECIMAL" }, @@ -63,8 +63,8 @@ describe("getNodeProps function test", () => { { name: "multipleBigtext", values: [ - '
bigtext value1
', - '
bigtext value2
', + "
bigtext value1
", + "
bigtext value2
", ], }, { @@ -97,70 +97,72 @@ describe("getNodeProps function test", () => { cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testGetNodeProps.html`); }); - afterEach("Logout", () => { cy.logout(); }); + afterEach("Logout", () => { + cy.logout(); + }); - it("Verify property values from getNodeProps", function () { - cy.get('div[data-testid="getNodeProps_smallText"]').contains("smallTextValue"); - cy.get('div[data-testid="getNodeProps_textarea"]').contains("textareaValue"); - cy.get('div[data-testid="getNodeProps_choicelist"]').contains("choice2"); - cy.get('div[data-testid="getNodeProps_long"]').contains("2"); - cy.get('div[data-testid="getNodeProps_double"]').contains("3.6"); - cy.get('div[data-testid="getNodeProps_boolean"]').contains("true"); - cy.get('div[data-testid="getNodeProps_weakreference"]').contains( + it("Verify property values from getNodeProps", function() { + cy.get("div[data-testid=\"getNodeProps_smallText\"]").contains("smallTextValue"); + cy.get("div[data-testid=\"getNodeProps_textarea\"]").contains("textareaValue"); + cy.get("div[data-testid=\"getNodeProps_choicelist\"]").contains("choice2"); + cy.get("div[data-testid=\"getNodeProps_long\"]").contains("2"); + cy.get("div[data-testid=\"getNodeProps_double\"]").contains("3.6"); + cy.get("div[data-testid=\"getNodeProps_boolean\"]").contains("true"); + cy.get("div[data-testid=\"getNodeProps_weakreference\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetNodeProps/pagecontent`, ); - cy.get('div[data-testid="getNodeProps_bigtext_inner"]').contains("bigtext value"); - cy.get('div[data-testid="getNodeProps_date"]').contains("2023-12-26T01:30:25.243Z"); - cy.get('div[data-testid="getNodeProps_decimal"]').contains("4535353.55665775"); - cy.get('div[data-testid="getNodeProps_uri"]').contains("https://www.jahia.com"); - cy.get('div[data-testid="getNodeProps_name"]').contains("nameValue"); - cy.get('div[data-testid="getNodeProps_path"]').contains( + cy.get("div[data-testid=\"getNodeProps_bigtext_inner\"]").contains("bigtext value"); + cy.get("div[data-testid=\"getNodeProps_date\"]").contains("2023-12-26T01:30:25.243Z"); + cy.get("div[data-testid=\"getNodeProps_decimal\"]").contains("4535353.55665775"); + cy.get("div[data-testid=\"getNodeProps_uri\"]").contains("https://www.jahia.com"); + cy.get("div[data-testid=\"getNodeProps_name\"]").contains("nameValue"); + cy.get("div[data-testid=\"getNodeProps_path\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetNodeProps/pagecontent`, ); }); - it("Verify property values from getNodeProps (multiple)", function () { - cy.get('div[data-testid="getNodeProps_multipleSmallText_1"]').contains("smallTextValue1"); - cy.get('div[data-testid="getNodeProps_multipleSmallText_2"]').contains("smallTextValue2"); - cy.get('div[data-testid="getNodeProps_multipleTextarea_1"]').contains("textareaValue1"); - cy.get('div[data-testid="getNodeProps_multipleTextarea_2"]').contains("textareaValue2"); - cy.get('div[data-testid="getNodeProps_multipleChoicelist_1"]').contains("choice1"); - cy.get('div[data-testid="getNodeProps_multipleChoicelist_2"]').contains("choice2"); - cy.get('div[data-testid="getNodeProps_multipleLong_1"]').contains("1"); - cy.get('div[data-testid="getNodeProps_multipleLong_2"]').contains("2"); - cy.get('div[data-testid="getNodeProps_multipleDouble_1"]').contains("1.5"); - cy.get('div[data-testid="getNodeProps_multipleDouble_2"]').contains("2.5"); - cy.get('div[data-testid="getNodeProps_multipleBoolean_1"]').contains("true"); - cy.get('div[data-testid="getNodeProps_multipleBoolean_2"]').contains("false"); - cy.get('div[data-testid="getNodeProps_multipleWeakreference_1"]').contains( + it("Verify property values from getNodeProps (multiple)", function() { + cy.get("div[data-testid=\"getNodeProps_multipleSmallText_1\"]").contains("smallTextValue1"); + cy.get("div[data-testid=\"getNodeProps_multipleSmallText_2\"]").contains("smallTextValue2"); + cy.get("div[data-testid=\"getNodeProps_multipleTextarea_1\"]").contains("textareaValue1"); + cy.get("div[data-testid=\"getNodeProps_multipleTextarea_2\"]").contains("textareaValue2"); + cy.get("div[data-testid=\"getNodeProps_multipleChoicelist_1\"]").contains("choice1"); + cy.get("div[data-testid=\"getNodeProps_multipleChoicelist_2\"]").contains("choice2"); + cy.get("div[data-testid=\"getNodeProps_multipleLong_1\"]").contains("1"); + cy.get("div[data-testid=\"getNodeProps_multipleLong_2\"]").contains("2"); + cy.get("div[data-testid=\"getNodeProps_multipleDouble_1\"]").contains("1.5"); + cy.get("div[data-testid=\"getNodeProps_multipleDouble_2\"]").contains("2.5"); + cy.get("div[data-testid=\"getNodeProps_multipleBoolean_1\"]").contains("true"); + cy.get("div[data-testid=\"getNodeProps_multipleBoolean_2\"]").contains("false"); + cy.get("div[data-testid=\"getNodeProps_multipleWeakreference_1\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetNodeProps/pagecontent`, ); - cy.get('div[data-testid="getNodeProps_multipleWeakreference_2"]').contains( + cy.get("div[data-testid=\"getNodeProps_multipleWeakreference_2\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetNodeProps/header`, ); - cy.get('div[data-testid="getNodeProps_multipleBigtext_inner1"]').contains("bigtext value1"); - cy.get('div[data-testid="getNodeProps_multipleBigtext_inner2"]').contains("bigtext value2"); - cy.get('div[data-testid="getNodeProps_multipleDate_1"]').contains("2023-12-26T01:30:25.243Z"); - cy.get('div[data-testid="getNodeProps_multipleDate_2"]').contains("2023-12-27T01:30:25.243Z"); - cy.get('div[data-testid="getNodeProps_multipleDecimal_1"]').contains("4535353.55665775"); - cy.get('div[data-testid="getNodeProps_multipleDecimal_2"]').contains("4535353.55665776"); - cy.get('div[data-testid="getNodeProps_multipleUri_1"]').contains("https://www.jahia.com"); - cy.get('div[data-testid="getNodeProps_multipleUri_2"]').contains("https://www.google.com"); - cy.get('div[data-testid="getNodeProps_multipleName_1"]').contains("nameValue1"); - cy.get('div[data-testid="getNodeProps_multipleName_2"]').contains("nameValue2"); - cy.get('div[data-testid="getNodeProps_multiplePath_1"]').contains( + cy.get("div[data-testid=\"getNodeProps_multipleBigtext_inner1\"]").contains("bigtext value1"); + cy.get("div[data-testid=\"getNodeProps_multipleBigtext_inner2\"]").contains("bigtext value2"); + cy.get("div[data-testid=\"getNodeProps_multipleDate_1\"]").contains("2023-12-26T01:30:25.243Z"); + cy.get("div[data-testid=\"getNodeProps_multipleDate_2\"]").contains("2023-12-27T01:30:25.243Z"); + cy.get("div[data-testid=\"getNodeProps_multipleDecimal_1\"]").contains("4535353.55665775"); + cy.get("div[data-testid=\"getNodeProps_multipleDecimal_2\"]").contains("4535353.55665776"); + cy.get("div[data-testid=\"getNodeProps_multipleUri_1\"]").contains("https://www.jahia.com"); + cy.get("div[data-testid=\"getNodeProps_multipleUri_2\"]").contains("https://www.google.com"); + cy.get("div[data-testid=\"getNodeProps_multipleName_1\"]").contains("nameValue1"); + cy.get("div[data-testid=\"getNodeProps_multipleName_2\"]").contains("nameValue2"); + cy.get("div[data-testid=\"getNodeProps_multiplePath_1\"]").contains( "/sites/javascriptTestSite/home/testGetNodeProps/pagecontent", ); - cy.get('div[data-testid="getNodeProps_multiplePath_2"]').contains( + cy.get("div[data-testid=\"getNodeProps_multiplePath_2\"]").contains( `/sites/${GENERIC_SITE_KEY}/home/testGetNodeProps/header`, ); }); - it("Verify property values from getNodeProps (Types and safety)", function () { - cy.get('div[data-testid="getNodeProps_propNotSet"]').should("be.empty"); - cy.get('div[data-testid="getNodeProps_propNotExists"]').should("be.empty"); - cy.get('div[data-testid="getNodeProps_checkBooleanType"]').contains("true"); - cy.get('div[data-testid="getNodeProps_checkLongType"]').contains("true"); - cy.get('div[data-testid="getNodeProps_checkDoubleType"]').contains("true"); + it("Verify property values from getNodeProps (Types and safety)", function() { + cy.get("div[data-testid=\"getNodeProps_propNotSet\"]").should("be.empty"); + cy.get("div[data-testid=\"getNodeProps_propNotExists\"]").should("be.empty"); + cy.get("div[data-testid=\"getNodeProps_checkBooleanType\"]").contains("true"); + cy.get("div[data-testid=\"getNodeProps_checkLongType\"]").contains("true"); + cy.get("div[data-testid=\"getNodeProps_checkDoubleType\"]").contains("true"); }); }); diff --git a/tests/cypress/e2e/ui/getNodesByJCRQueryTest.cy.ts b/tests/cypress/e2e/ui/getNodesByJCRQueryTest.cy.ts index 7be33648..1f0f387f 100644 --- a/tests/cypress/e2e/ui/getNodesByJCRQueryTest.cy.ts +++ b/tests/cypress/e2e/ui/getNodesByJCRQueryTest.cy.ts @@ -1,6 +1,6 @@ import { addNode } from "@jahia/cypress"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addEvent, addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; describe("getNodesByJCRQuery function test", () => { const initEvent = (index: number) => { @@ -50,9 +50,13 @@ describe("getNodesByJCRQuery function test", () => { }); }); }); - - beforeEach("Login", () => { cy.login(); }); - afterEach("Logout", () => { cy.logout(); }); + + beforeEach("Login", () => { + cy.login(); + }); + afterEach("Logout", () => { + cy.logout(); + }); // dynmically generated test cases [ @@ -101,7 +105,7 @@ describe("getNodesByJCRQuery function test", () => { ], }, ].forEach((test) => { - it(`Test getNodesByJCRQuery, case: ${test.testCase}`, function () { + it(`Test getNodesByJCRQuery, case: ${test.testCase}`, function() { cy.visit( `/jahia/page-composer/default/en/sites/${GENERIC_SITE_KEY}/home/getNodesByJCRQuery.html`, ); diff --git a/tests/cypress/e2e/ui/gqlTest.cy.ts b/tests/cypress/e2e/ui/gqlTest.cy.ts index a490c8b5..9be25317 100644 --- a/tests/cypress/e2e/ui/gqlTest.cy.ts +++ b/tests/cypress/e2e/ui/gqlTest.cy.ts @@ -1,6 +1,6 @@ import { addNode } from "@jahia/cypress"; -import { addSimplePage } from "../../utils/helpers"; import { GENERIC_SITE_KEY } from "../../support/constants"; +import { addSimplePage } from "../../utils/helpers"; describe("Test GQL", () => { before("Create test page and contents", () => { @@ -20,7 +20,7 @@ describe("Test GQL", () => { { name: "prop2", value: "prop2 value !@#$%ˆ//{}È" }, { name: "propRichText", - value: '

Hello this is a sample rich text

', + value: "

Hello this is a sample rich text

", }, ], }); @@ -34,18 +34,18 @@ describe("Test GQL", () => { cy.logout(); }); - it("Check GQL execution in current view", function () { + it("Check GQL execution in current view", function() { cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testJGQL.html`); - cy.get('li[data-testid="j:nodename"]').should("contain", "test"); - cy.get('li[data-testid="jcr:title"]').should("contain", "test component"); - cy.get('li[data-testid="prop1"]').should("contain", "prop1 value"); - cy.get('li[data-testid="prop2"]').should("contain", "prop2 value !@#$%ˆ//{}È"); - cy.get('li[data-testid="propRichText"]').should("contain", "Hello this is a sample rich text"); - cy.get('li[data-testid="j:nodename-from-document"]').should("contain", "test"); - cy.get('li[data-testid="jcr:title-from-document"]').should("contain", "test component"); - cy.get('li[data-testid="prop1-from-document"]').should("contain", "prop1 value"); - cy.get('li[data-testid="prop2-from-document"]').should("contain", "prop2 value !@#$%ˆ//{}È"); - cy.get('li[data-testid="propRichText-from-document"]').should( + cy.get("li[data-testid=\"j:nodename\"]").should("contain", "test"); + cy.get("li[data-testid=\"jcr:title\"]").should("contain", "test component"); + cy.get("li[data-testid=\"prop1\"]").should("contain", "prop1 value"); + cy.get("li[data-testid=\"prop2\"]").should("contain", "prop2 value !@#$%ˆ//{}È"); + cy.get("li[data-testid=\"propRichText\"]").should("contain", "Hello this is a sample rich text"); + cy.get("li[data-testid=\"j:nodename-from-document\"]").should("contain", "test"); + cy.get("li[data-testid=\"jcr:title-from-document\"]").should("contain", "test component"); + cy.get("li[data-testid=\"prop1-from-document\"]").should("contain", "prop1 value"); + cy.get("li[data-testid=\"prop2-from-document\"]").should("contain", "prop2 value !@#$%ˆ//{}È"); + cy.get("li[data-testid=\"propRichText-from-document\"]").should( "contain", "Hello this is a sample rich text", ); diff --git a/tests/cypress/e2e/ui/osgiTest.cy.ts b/tests/cypress/e2e/ui/osgiTest.cy.ts index b170f544..c20ede40 100644 --- a/tests/cypress/e2e/ui/osgiTest.cy.ts +++ b/tests/cypress/e2e/ui/osgiTest.cy.ts @@ -1,6 +1,6 @@ import { addNode, publishAndWaitJobEnding } from "@jahia/cypress"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; describe("Test OSGi configuration in views", () => { const pageName = "testOSGi"; @@ -21,12 +21,16 @@ describe("Test OSGi configuration in views", () => { publishAndWaitJobEnding(`/sites/${GENERIC_SITE_KEY}`); }); - beforeEach("Login", () => { cy.login(); }); - afterEach("Logout", () => { cy.logout(); }); + beforeEach("Login", () => { + cy.login(); + }); + afterEach("Logout", () => { + cy.logout(); + }); - it(`is polite, says hello and sorts numbers`, function () { + it(`is polite, says hello and sorts numbers`, function() { cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/${pageName}.html`); - cy.get('p[data-testid="hello"]').should("contain", "Good morning World!"); - cy.get('p[data-testid="numbers"]').should("contain", "1, 2, 3, 4"); + cy.get("p[data-testid=\"hello\"]").should("contain", "Good morning World!"); + cy.get("p[data-testid=\"numbers\"]").should("contain", "1, 2, 3, 4"); }); }); diff --git a/tests/cypress/e2e/ui/priorityOnTemplatesTest.cy.ts b/tests/cypress/e2e/ui/priorityOnTemplatesTest.cy.ts index 8e491455..e50f1dff 100644 --- a/tests/cypress/e2e/ui/priorityOnTemplatesTest.cy.ts +++ b/tests/cypress/e2e/ui/priorityOnTemplatesTest.cy.ts @@ -1,6 +1,6 @@ import { deleteNode } from "@jahia/cypress"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; import "cypress-wait-until"; describe("Test priority parameter on templates", () => { @@ -15,7 +15,9 @@ describe("Test priority parameter on templates", () => { }, ]; - beforeEach('Login', () => { cy.login(); }); + beforeEach("Login", () => { + cy.login(); + }); afterEach("Delete the test page after each test", () => { deleteNode(`/sites/${GENERIC_SITE_KEY}/${pageName}`); @@ -35,7 +37,7 @@ describe("Test priority parameter on templates", () => { ); cy.visit(`/jahia/jcontent/${GENERIC_SITE_KEY}/en/pages/${pageName}`); cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="testPriorityTemplate"] span[data-testid="priorityValue"]').should( + cy.get("div[data-testid=\"testPriorityTemplate\"] span[data-testid=\"priorityValue\"]").should( "have.text", expectedPriority, ); diff --git a/tests/cypress/e2e/ui/priorityOnViewsTest.cy.ts b/tests/cypress/e2e/ui/priorityOnViewsTest.cy.ts index 6ca83970..56f7ee12 100644 --- a/tests/cypress/e2e/ui/priorityOnViewsTest.cy.ts +++ b/tests/cypress/e2e/ui/priorityOnViewsTest.cy.ts @@ -1,6 +1,6 @@ import { addNode, deleteNode } from "@jahia/cypress"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; import "cypress-wait-until"; describe("Test priority parameter on views", () => { @@ -24,7 +24,7 @@ describe("Test priority parameter on views", () => { afterEach("Delete the test page after each test", () => { deleteNode(`/sites/${GENERIC_SITE_KEY}/${pageName}`); - cy.logout(); + cy.logout(); }); examples.forEach(({ nodeType, expectedPriority }) => { @@ -36,7 +36,7 @@ describe("Test priority parameter on views", () => { }); cy.visit(`/jahia/jcontent/${GENERIC_SITE_KEY}/en/pages/${pageName}`); cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="testPriorityView"] span[data-testid="priorityValue"]').should( + cy.get("div[data-testid=\"testPriorityView\"] span[data-testid=\"priorityValue\"]").should( "have.text", expectedPriority, ); diff --git a/tests/cypress/e2e/ui/proxyPropsTest.cy.ts b/tests/cypress/e2e/ui/proxyPropsTest.cy.ts index a44b2c4c..0eacb68f 100644 --- a/tests/cypress/e2e/ui/proxyPropsTest.cy.ts +++ b/tests/cypress/e2e/ui/proxyPropsTest.cy.ts @@ -1,6 +1,6 @@ import { addNode, publishAndWaitJobEnding } from "@jahia/cypress"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; describe("proxyProps function test", () => { before("Create test page and contents", () => { @@ -33,16 +33,16 @@ describe("proxyProps function test", () => { }); }); - it("Verify property values from getNodeProps", function () { + it("Verify property values from getNodeProps", function() { cy.visit(`/sites/${GENERIC_SITE_KEY}/home/testProxyProps.html`); - cy.get('div[data-testid="proxyProps_myFirstProp"]').contains("First prop value"); - cy.get('div[data-testid="proxyProps_mySecondProp"]').contains("Second prop value"); - cy.get('div[data-testid="proxyProps_restOfProps_in"]').contains("true"); - cy.get('div[data-testid="proxyProps_restOfProps_items_myFirstProp"]').should("not.exist"); - cy.get('div[data-testid="proxyProps_restOfProps_items_mySecondProp"]').should("not.exist"); - cy.get('div[data-testid="proxyProps_restOfProps_items_myThirdProp"]').should("exist"); - cy.get('div[data-testid="proxyProps_restOfProps_items_myFourthProp"]').should("exist"); - cy.get('div[data-testid="proxyProps_restOfProps_items_jcr:uuid"]').should("exist"); + cy.get("div[data-testid=\"proxyProps_myFirstProp\"]").contains("First prop value"); + cy.get("div[data-testid=\"proxyProps_mySecondProp\"]").contains("Second prop value"); + cy.get("div[data-testid=\"proxyProps_restOfProps_in\"]").contains("true"); + cy.get("div[data-testid=\"proxyProps_restOfProps_items_myFirstProp\"]").should("not.exist"); + cy.get("div[data-testid=\"proxyProps_restOfProps_items_mySecondProp\"]").should("not.exist"); + cy.get("div[data-testid=\"proxyProps_restOfProps_items_myThirdProp\"]").should("exist"); + cy.get("div[data-testid=\"proxyProps_restOfProps_items_myFourthProp\"]").should("exist"); + cy.get("div[data-testid=\"proxyProps_restOfProps_items_jcr:uuid\"]").should("exist"); }); }); diff --git a/tests/cypress/e2e/ui/reactClientSideTest.cy.ts b/tests/cypress/e2e/ui/reactClientSideTest.cy.ts index ea1ac00e..8c21d5fa 100644 --- a/tests/cypress/e2e/ui/reactClientSideTest.cy.ts +++ b/tests/cypress/e2e/ui/reactClientSideTest.cy.ts @@ -1,6 +1,6 @@ import { addNode, publishAndWaitJobEnding } from "@jahia/cypress"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; describe("Verify client side component are rehydrated as expected", () => { before("Create test contents", () => { @@ -36,35 +36,35 @@ describe("Verify client side component are rehydrated as expected", () => { `/cms/render/${workspace}/en/sites/${GENERIC_SITE_KEY}/home/testHydrateInBrowser.html`, ); // Check children - cy.get('[data-testid="ssr-child"]').should("exist"); - cy.get('[data-testid="ssr-child"]').should("contain", "Server-side rendered"); - cy.get('[data-testid="ssr-placeholder"]').should("exist"); - cy.get('[data-testid="ssr-placeholder"]').should("contain", "Server-side placeholder"); + cy.get("[data-testid=\"ssr-child\"]").should("exist"); + cy.get("[data-testid=\"ssr-child\"]").should("contain", "Server-side rendered"); + cy.get("[data-testid=\"ssr-placeholder\"]").should("exist"); + cy.get("[data-testid=\"ssr-placeholder\"]").should("contain", "Server-side placeholder"); - cy.get('p[data-testid="count"]').should("exist"); - cy.get('p[data-testid="count"]').should("contain", "Count: 9"); - cy.get('p[data-testid="set"]').should("contain", "Set: a, b, c"); + cy.get("p[data-testid=\"count\"]").should("exist"); + cy.get("p[data-testid=\"count\"]").should("contain", "Count: 9"); + cy.get("p[data-testid=\"set\"]").should("contain", "Set: a, b, c"); // Wait for the component to be declared as hydrated to avoid flakiness - cy.get('[data-hydrated="true"]').should("exist"); + cy.get("[data-hydrated=\"true\"]").should("exist"); // Check that CSR place holder is removed after hydration - cy.get('[data-testid="ssr-placeholder"]').should("not.exist"); + cy.get("[data-testid=\"ssr-placeholder\"]").should("not.exist"); - cy.get('button[data-testid="count-button"]').click(); - cy.get('button[data-testid="count-button"]').click(); - cy.get('p[data-testid="count"]').should("contain", "Count: 11"); + cy.get("button[data-testid=\"count-button\"]").click(); + cy.get("button[data-testid=\"count-button\"]").click(); + cy.get("p[data-testid=\"count\"]").should("contain", "Count: 11"); - cy.get('span[data-testid="path"]').should("exist"); - cy.get('span[data-testid="path"]').should( + cy.get("span[data-testid=\"path\"]").should("exist"); + cy.get("span[data-testid=\"path\"]").should( "contain", `/sites/${GENERIC_SITE_KEY}/home/testHydrateInBrowser/pagecontent/test`, ); - cy.get('span[data-testid="counter"]').should("exist"); - cy.get('span[data-testid="counter"]').should("not.contain", "0"); - cy.get('span[data-testid="counter"]').should("contain", "0"); + cy.get("span[data-testid=\"counter\"]").should("exist"); + cy.get("span[data-testid=\"counter\"]").should("not.contain", "0"); + cy.get("span[data-testid=\"counter\"]").should("contain", "0"); - cy.get('[data-testid="ssr-child"]').should("contain", "Server-side rendered"); + cy.get("[data-testid=\"ssr-child\"]").should("contain", "Server-side rendered"); }); } }); diff --git a/tests/cypress/e2e/ui/registerJahiaComponentsTest.cy.ts b/tests/cypress/e2e/ui/registerJahiaComponentsTest.cy.ts index 9f8aef00..1b1a606d 100644 --- a/tests/cypress/e2e/ui/registerJahiaComponentsTest.cy.ts +++ b/tests/cypress/e2e/ui/registerJahiaComponentsTest.cy.ts @@ -1,6 +1,6 @@ import { addNode } from "@jahia/cypress"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; describe("Verify that registerJahiaComponents behaves as expected", () => { before("Create test contents", () => { @@ -34,12 +34,12 @@ describe("Verify that registerJahiaComponents behaves as expected", () => { it("Check that components are properly registered", () => { cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="standardViewRegistration"]').should("exist"); - cy.get('div[data-testid="standardViewRegistration"]').contains("default"); - cy.get('div[data-testid="customViewRegistration"]').should("exist"); - cy.get('div[data-testid="customViewRegistration"]').contains("default"); - cy.get('div[data-testid="noRegistration"]').should("exist"); - cy.get('div[data-testid="noRegistration"]').contains("null"); + cy.get("div[data-testid=\"standardViewRegistration\"]").should("exist"); + cy.get("div[data-testid=\"standardViewRegistration\"]").contains("default"); + cy.get("div[data-testid=\"customViewRegistration\"]").should("exist"); + cy.get("div[data-testid=\"customViewRegistration\"]").contains("default"); + cy.get("div[data-testid=\"noRegistration\"]").should("exist"); + cy.get("div[data-testid=\"noRegistration\"]").contains("null"); }); }); }); diff --git a/tests/cypress/e2e/ui/renderShouldBeEditableTest.cy.ts b/tests/cypress/e2e/ui/renderShouldBeEditableTest.cy.ts index 629c7cd9..3b7bbeb4 100644 --- a/tests/cypress/e2e/ui/renderShouldBeEditableTest.cy.ts +++ b/tests/cypress/e2e/ui/renderShouldBeEditableTest.cy.ts @@ -1,6 +1,6 @@ import { addNode } from "@jahia/cypress"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; describe("Render should be editable", () => { before("Create test contents", () => { @@ -44,24 +44,24 @@ describe("Render should be editable", () => { it("Without parameter, text should be editable", () => { cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="react-render-editable-default"]') - .find('div[class="childs"]>div[jahiatype="module"]') + cy.get("div[data-testid=\"react-render-editable-default\"]") + .find("div[class=\"childs\"]>div[jahiatype=\"module\"]") .should("exist"); }); }); it("With parameter set to false, text should not be editable", () => { cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="react-render-not-editable"]') - .find('div[class="childs"]>div[jahiatype="module"]') + cy.get("div[data-testid=\"react-render-not-editable\"]") + .find("div[class=\"childs\"]>div[jahiatype=\"module\"]") .should("not.exist"); }); }); it("With parameter set to true, text should be editable", () => { cy.iframe("#page-builder-frame-1").within(() => { - cy.get('div[data-testid="react-render-editable"]') - .find('div[class="childs"]>div[jahiatype="module"]') + cy.get("div[data-testid=\"react-render-editable\"]") + .find("div[class=\"childs\"]>div[jahiatype=\"module\"]") .should("exist"); }); }); diff --git a/tests/cypress/e2e/ui/renderTest.cy.ts b/tests/cypress/e2e/ui/renderTest.cy.ts index 142d472c..4c015e58 100644 --- a/tests/cypress/e2e/ui/renderTest.cy.ts +++ b/tests/cypress/e2e/ui/renderTest.cy.ts @@ -1,6 +1,6 @@ import { addNode, enableModule } from "@jahia/cypress"; -import { addSimplePage } from "../../utils/helpers"; import { GENERIC_SITE_KEY } from "../../support/constants"; +import { addSimplePage } from "../../utils/helpers"; describe("Test on render and createContentButtons helpers", () => { const pageName = "testRender"; @@ -30,81 +30,81 @@ describe("Test on render and createContentButtons helpers", () => { cy.logout(); }); - it(`${pageName}: should display page composer create button correctly using createContentButtons helper`, function () { + it(`${pageName}: should display page composer create button correctly using createContentButtons helper`, function() { cy.visit(`/jahia/jcontent/${GENERIC_SITE_KEY}/en/pages/home/${pageName}`); - cy.iframe('[data-sel-role="page-builder-frame-active"]', { timeout: 90000, log: true }).within( + cy.iframe("[data-sel-role=\"page-builder-frame-active\"]", { timeout: 90000, log: true }).within( () => { - cy.get('button[data-sel-role="jnt:text"]').should("exist"); + cy.get("button[data-sel-role=\"jnt:text\"]").should("exist"); }, ); }); - it(`${pageName}: should render jnt:text JSON node`, function () { + it(`${pageName}: should render jnt:text JSON node`, function() { cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/${pageName}.html`); - cy.get('div[data-testid="component-text-json-node"]').should("contain", "JSON node rendered"); + cy.get("div[data-testid=\"component-text-json-node\"]").should("contain", "JSON node rendered"); cy.get("jsm-raw-html").should("not.exist"); }); - it(`${pageName}: should render jnt:text JSON node in config: OPTION`, function () { + it(`${pageName}: should render jnt:text JSON node in config: OPTION`, function() { cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/${pageName}.html`); - cy.get('div[data-testid="component-text-json-node-option"]').should( + cy.get("div[data-testid=\"component-text-json-node-option\"]").should( "contain", "JSON node rendered with option config", ); cy.get("jsm-raw-html").should("not.exist"); }); - it(`${pageName}: should render javascriptExample:test JSON node in config: OPTION with view: sub`, function () { + it(`${pageName}: should render javascriptExample:test JSON node in config: OPTION with view: sub`, function() { cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/${pageName}.html`); - cy.get('div[data-testid="component-react-json-node-option"]').should( + cy.get("div[data-testid=\"component-react-json-node-option\"]").should( "contain", "prop1 value it is", ); cy.get("jsm-raw-html").should("not.exist"); }); - it(`${pageName}: should render JSON node with INCLUDE config`, function () { + it(`${pageName}: should render JSON node with INCLUDE config`, function() { cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/${pageName}.html`); - cy.get('div[data-testid="component-react-node-include"]').should("contain", "prop1 value"); + cy.get("div[data-testid=\"component-react-node-include\"]").should("contain", "prop1 value"); cy.get("jsm-raw-html").should("not.exist"); }); - it(`${pageName}: should render JSON node with mixin`, function () { + it(`${pageName}: should render JSON node with mixin`, function() { cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/${pageName}.html`); - cy.get('div[data-testid="component-json-node-with-mixin"]').should("contain", "tag1"); - cy.get('div[data-testid="component-json-node-with-mixin"]').should("contain", "tag2"); + cy.get("div[data-testid=\"component-json-node-with-mixin\"]").should("contain", "tag1"); + cy.get("div[data-testid=\"component-json-node-with-mixin\"]").should("contain", "tag2"); cy.get("jsm-raw-html").should("not.exist"); }); - it(`${pageName}: should render JSON node with parameters passed to render`, function () { + it(`${pageName}: should render JSON node with parameters passed to render`, function() { cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/${pageName}.html`); cy.get( - 'div[data-testid="component-json-node-with-parameters"] div[data-testid="renderParam-string1"]', + "div[data-testid=\"component-json-node-with-parameters\"] div[data-testid=\"renderParam-string1\"]", ).should("contain", "stringParam=stringValue"); cy.get( - 'div[data-testid="component-json-node-with-parameters"] div[data-testid="renderParam-string2"]', + "div[data-testid=\"component-json-node-with-parameters\"] div[data-testid=\"renderParam-string2\"]", ).should("contain", "stringParam2=stringValue2"); cy.get( - 'div[data-testid="component-json-node-with-parameters"] div[data-testid="renderParam-notString-notSupported"]', + "div[data-testid=\"component-json-node-with-parameters\"] div[data-testid=\"renderParam-notString-notSupported\"]", ).should("contain", "objectParam not supported="); cy.get("jsm-raw-html").should("not.exist"); }); - it(`${pageName}: should render node with parameters passed to render`, function () { + it(`${pageName}: should render node with parameters passed to render`, function() { cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/${pageName}.html`); cy.get( - 'div[data-testid="component-react-node-with-parameters"] div[data-testid="renderParam-string1"]', + "div[data-testid=\"component-react-node-with-parameters\"] div[data-testid=\"renderParam-string1\"]", ).should("contain", "stringParam=stringValue"); cy.get( - 'div[data-testid="component-react-node-with-parameters"] div[data-testid="renderParam-string2"]', + "div[data-testid=\"component-react-node-with-parameters\"] div[data-testid=\"renderParam-string2\"]", ).should("contain", "stringParam2=stringValue2"); cy.get( - 'div[data-testid="component-react-node-with-parameters"] div[data-testid="renderParam-notString-notSupported"]', + "div[data-testid=\"component-react-node-with-parameters\"] div[data-testid=\"renderParam-notString-notSupported\"]", ).should("contain", "objectParam not supported="); cy.get("jsm-raw-html").should("not.exist"); }); - it(`${pageName}: should render existing child node using relative path`, function () { + it(`${pageName}: should render existing child node using relative path`, function() { addNode({ parentPathOrId: `/sites/${GENERIC_SITE_KEY}/home/${pageName}/pagecontent/test`, name: "simpletext", @@ -114,7 +114,7 @@ describe("Test on render and createContentButtons helpers", () => { ], }); cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/${pageName}.html`); - cy.get('div[data-testid="component-text-child-node"]').should( + cy.get("div[data-testid=\"component-text-child-node\"]").should( "contain", "Child node rendered using relative path", ); diff --git a/tests/cypress/e2e/ui/templatePickerCorrectOrderTest.cy.ts b/tests/cypress/e2e/ui/templatePickerCorrectOrderTest.cy.ts index 0f9eb751..d1dae7b6 100644 --- a/tests/cypress/e2e/ui/templatePickerCorrectOrderTest.cy.ts +++ b/tests/cypress/e2e/ui/templatePickerCorrectOrderTest.cy.ts @@ -1,6 +1,6 @@ import { JContent } from "@jahia/jcontent-cypress/dist/page-object/jcontent"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; describe("Template Picker Correct Order Test", () => { before("Create page", () => { @@ -16,8 +16,12 @@ describe("Template Picker Correct Order Test", () => { ); }); - beforeEach('Login', () => { cy.login(); }); - afterEach('Logout', () => { cy.logout(); }); + beforeEach("Login", () => { + cy.login(); + }); + afterEach("Logout", () => { + cy.logout(); + }); it("should display the correct order of templates", () => { const templatesValues = [ @@ -40,9 +44,9 @@ describe("Template Picker Correct Order Test", () => { ]; const jContent = JContent.visit("javascriptTestSite", "en", "pages/home").switchToPageBuilder(); jContent.getCreatePage(); - cy.get('[id="select-jmix:hasTemplateNode_j:templateName"]').click(); + cy.get("[id=\"select-jmix:hasTemplateNode_j:templateName\"]").click(); let i = 0; - cy.get('[id="select-jmix:hasTemplateNode_j:templateName"] menu li').each((el) => { + cy.get("[id=\"select-jmix:hasTemplateNode_j:templateName\"] menu li").each((el) => { cy.wrap(el).should("have.text", templatesValues[i]); i++; }); diff --git a/tests/cypress/e2e/ui/templateTest.cy.ts b/tests/cypress/e2e/ui/templateTest.cy.ts index 98c508d1..95b7ff8f 100644 --- a/tests/cypress/e2e/ui/templateTest.cy.ts +++ b/tests/cypress/e2e/ui/templateTest.cy.ts @@ -1,12 +1,12 @@ import { publishAndWaitJobEnding } from "@jahia/cypress"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; import "cypress-iframe"; const checkSectionsPresence = () => { - cy.get('div[class="header"]').should("be.visible"); - cy.get('div[class="main"]').should("be.visible"); - cy.get('div[class="footer"]').should("be.visible"); + cy.get("div[class=\"header\"]").should("be.visible"); + cy.get("div[class=\"main\"]").should("be.visible"); + cy.get("div[class=\"footer\"]").should("be.visible"); }; describe("Template testsuite", () => { @@ -26,7 +26,9 @@ describe("Template testsuite", () => { cy.visit(`/jahia/jcontent/${GENERIC_SITE_KEY}/en/pages/home/${pageName}`); }); - afterEach("Logout", () => { cy.logout(); }); + afterEach("Logout", () => { + cy.logout(); + }); it(`${pageName}: Verify 3 sections presence`, () => { cy.iframe("#page-builder-frame-1").within(() => { @@ -36,10 +38,10 @@ describe("Template testsuite", () => { it(`${pageName}: Check grouping components`, () => { cy.iframe("#page-builder-frame-1").within(() => { - cy.get('button[data-sel-role="createContent"]:first').click(); + cy.get("button[data-sel-role=\"createContent\"]:first").click(); }); - cy.get('li[role="treeitem"]:contains("javascriptExampleComponent")').click(); - cy.get('li[role="treeitem"]:contains("test")').should("be.visible"); + cy.get("li[role=\"treeitem\"]:contains(\"javascriptExampleComponent\")").click(); + cy.get("li[role=\"treeitem\"]:contains(\"test\")").should("be.visible"); }); it(`${pageName}: Check 3 sections presence in LIVE workspace`, () => { diff --git a/tests/cypress/e2e/ui/testCurrentUser.cy.ts b/tests/cypress/e2e/ui/testCurrentUser.cy.ts index 37b70184..52aa39b1 100644 --- a/tests/cypress/e2e/ui/testCurrentUser.cy.ts +++ b/tests/cypress/e2e/ui/testCurrentUser.cy.ts @@ -1,6 +1,6 @@ import { addNode } from "@jahia/cypress"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; describe("Test current user", () => { before("Create tests contents", () => { @@ -25,12 +25,16 @@ describe("Test current user", () => { }); }); -beforeEach('Login', () => { cy.login(); }); -afterEach('Logout', () => { cy.logout(); }); + beforeEach("Login", () => { + cy.login(); + }); + afterEach("Logout", () => { + cy.logout(); + }); it("should display the current user as root", () => { cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testCurrentUser.html`); - cy.get('div[data-testid="currentUser_username"]').should("exist").contains("root"); - cy.get('div[data-testid="currentUser_isRoot"]').should("exist").contains("true"); + cy.get("div[data-testid=\"currentUser_username\"]").should("exist").contains("root"); + cy.get("div[data-testid=\"currentUser_isRoot\"]").should("exist").contains("true"); }); }); diff --git a/tests/cypress/e2e/ui/testHasPermission.cy.ts b/tests/cypress/e2e/ui/testHasPermission.cy.ts index 28c70366..0d21280f 100644 --- a/tests/cypress/e2e/ui/testHasPermission.cy.ts +++ b/tests/cypress/e2e/ui/testHasPermission.cy.ts @@ -1,6 +1,6 @@ import { addNode } from "@jahia/cypress"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; describe("Test has permission", () => { before("Create test contents", () => { @@ -25,12 +25,16 @@ describe("Test has permission", () => { }); }); - beforeEach('Login', () => { cy.login(); }); - afterEach('Logout', () => { cy.logout(); }); + beforeEach("Login", () => { + cy.login(); + }); + afterEach("Logout", () => { + cy.logout(); + }); it("should display the permission", () => { cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testHasPermission.html`); - cy.get('div[data-testid="currentNode_hasPermission"]').should("exist").contains("true"); - cy.get('div[data-testid="currentNode_hasNotPermission"]').should("exist").contains("false"); + cy.get("div[data-testid=\"currentNode_hasPermission\"]").should("exist").contains("true"); + cy.get("div[data-testid=\"currentNode_hasNotPermission\"]").should("exist").contains("false"); }); }); diff --git a/tests/cypress/e2e/ui/testI18n.cy.ts b/tests/cypress/e2e/ui/testI18n.cy.ts index a793b49a..3d275143 100644 --- a/tests/cypress/e2e/ui/testI18n.cy.ts +++ b/tests/cypress/e2e/ui/testI18n.cy.ts @@ -1,10 +1,4 @@ -import { - addNode, - createSite, - deleteSite, - enableModule, - publishAndWaitJobEnding, -} from "@jahia/cypress"; +import { addNode, createSite, deleteSite, enableModule, publishAndWaitJobEnding } from "@jahia/cypress"; import { addSimplePage } from "../../utils/helpers"; const testData = { @@ -87,21 +81,21 @@ describe("Test i18n", () => { ["live", "default"].forEach((workspace) => { ["en", "fr_LU", "fr", "de"].forEach((locale) => { cy.visit(`/cms/render/${workspace}/${locale}/sites/${siteKey}/home/testPageI18N.html`); - testI18n(locale, 'div[data-testid="i18n-server-side"]', "We are server side !", false); + testI18n(locale, "div[data-testid=\"i18n-server-side\"]", "We are server side !", false); testI18n( locale, - 'div[data-testid="i18n-hydrated-client-side"]', + "div[data-testid=\"i18n-hydrated-client-side\"]", "We are hydrated client side !", true, ); testI18n( locale, - 'div[data-testid="i18n-rendered-client-side"]', + "div[data-testid=\"i18n-rendered-client-side\"]", "We are rendered client side !", true, ); }); - cy.get('[data-testid="getSiteLocales"]').should("contain", "de,en,fr,fr_LU"); + cy.get("[data-testid=\"getSiteLocales\"]").should("contain", "de,en,fr,fr_LU"); }); cy.logout(); @@ -123,8 +117,7 @@ describe("Test i18n", () => { testData.translations[locale].composed.replace("{{placeholder}}", placeholderIntialValue), ); - const newPlaceholderValue = - "Updated placeholder to test dynamic client side placeholder in i18n translation !"; + const newPlaceholderValue = "Updated placeholder to test dynamic client side placeholder in i18n translation !"; cy.get(`${mainSelector} input[data-testid="i18n-edit-placeholder"]`).clear(); cy.get(`${mainSelector} input[data-testid="i18n-edit-placeholder"]`).type(newPlaceholderValue); if (placeholderShouldBeDynamic) { @@ -165,8 +158,8 @@ describe("Test i18n", () => { cy.visit(`/cms/render/${workspace}/en/sites/${siteKey}/home/testPageI18N.html`); // make sure the 2 modules are present on the page with their i18n store - cy.get('script[data-i18n-store="javascript-modules-engine-test-module"]').should("exist"); - cy.get('script[data-i18n-store="hydrogen"]').should("exist"); + cy.get("script[data-i18n-store=\"javascript-modules-engine-test-module\"]").should("exist"); + cy.get("script[data-i18n-store=\"hydrogen\"]").should("exist"); cy.get("jsm-island").then(($islands) => { // get unique "data-bundle" values from all islands elements const bundles = new Set($islands.get().map((el) => el.getAttribute("data-bundle"))); @@ -178,21 +171,21 @@ describe("Test i18n", () => { // make sure the translations are rendered server-side // - for hydrogen:helloWorld : cy.get( - 'p:contains("Welcome to Jahia! You successfully created a new JavaScript Module and a Jahia Website built with it. Here are a few things you can do now:")', + "p:contains(\"Welcome to Jahia! You successfully created a new JavaScript Module and a Jahia Website built with it. Here are a few things you can do now:\")", ).should("have.length", 2); // - for javascriptExample:testI18n : - cy.get('div[data-testid="i18n-server-side"] div[data-testid="i18n-simple"]') + cy.get("div[data-testid=\"i18n-server-side\"] div[data-testid=\"i18n-simple\"]") .should("contain", testData.translations.en.simple) .should("have.length", 2); // make sure the translations are rendered client-side cy.get( - 'div[data-testid="i18n-hydrated-client-side"] jsm-island[data-bundle="javascript-modules-engine-test-module"]' + - ' [data-testid="i18n-simple"]', + "div[data-testid=\"i18n-hydrated-client-side\"] jsm-island[data-bundle=\"javascript-modules-engine-test-module\"]" + + " [data-testid=\"i18n-simple\"]", ) .should("contain", testData.translations.en.simple) .should("have.length", 2); - cy.get('jsm-island[data-bundle="hydrogen"] [data-testid="i18n-client-only"]') + cy.get("jsm-island[data-bundle=\"hydrogen\"] [data-testid=\"i18n-client-only\"]") .should( "contain", "Rendered client-side only", // the translated content diff --git a/tests/cypress/e2e/ui/testIsNodeType.cy.ts b/tests/cypress/e2e/ui/testIsNodeType.cy.ts index 9d8c6a11..26f0b5f4 100644 --- a/tests/cypress/e2e/ui/testIsNodeType.cy.ts +++ b/tests/cypress/e2e/ui/testIsNodeType.cy.ts @@ -1,6 +1,6 @@ import { addNode } from "@jahia/cypress"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; describe("test isNodeType", () => { before("Create test contents", () => { @@ -25,12 +25,16 @@ describe("test isNodeType", () => { }); }); - beforeEach('Login', () => { cy.login(); }); - afterEach('Logout', () => { cy.logout(); }); + beforeEach("Login", () => { + cy.login(); + }); + afterEach("Logout", () => { + cy.logout(); + }); it("should display the node type", () => { cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testIsNodeType.html`); - cy.get('div[data-testid="currentNode_isNodeType"]').should("exist").contains("true"); - cy.get('div[data-testid="currentNode_isNotNodeType"]').should("exist").contains("false"); + cy.get("div[data-testid=\"currentNode_isNodeType\"]").should("exist").contains("true"); + cy.get("div[data-testid=\"currentNode_isNotNodeType\"]").should("exist").contains("false"); }); }); diff --git a/tests/cypress/e2e/ui/testLocale.cy.ts b/tests/cypress/e2e/ui/testLocale.cy.ts index a6a96a53..400112c2 100644 --- a/tests/cypress/e2e/ui/testLocale.cy.ts +++ b/tests/cypress/e2e/ui/testLocale.cy.ts @@ -1,6 +1,6 @@ import { addNode } from "@jahia/cypress"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; describe("Test locale", () => { before("Create tests contents", () => { @@ -18,12 +18,16 @@ describe("Test locale", () => { }); }); - beforeEach('Login', () => { cy.login(); }); - afterEach('Logout', () => { cy.logout(); }); + beforeEach("Login", () => { + cy.login(); + }); + afterEach("Logout", () => { + cy.logout(); + }); it("should display the locale", () => { cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testLocale.html`); - cy.get('div[test-shouldbeEn="true"]').each(($el) => { + cy.get("div[test-shouldbeEn=\"true\"]").each(($el) => { cy.wrap($el).should("exist").contains("en"); }); }); diff --git a/tests/cypress/e2e/ui/testUrlParameters.cy.ts b/tests/cypress/e2e/ui/testUrlParameters.cy.ts index 8e349b73..7153fa7a 100644 --- a/tests/cypress/e2e/ui/testUrlParameters.cy.ts +++ b/tests/cypress/e2e/ui/testUrlParameters.cy.ts @@ -1,6 +1,6 @@ import { addNode } from "@jahia/cypress"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; describe("Test url parameters", () => { before("Create tests contents", () => { @@ -25,21 +25,25 @@ describe("Test url parameters", () => { }); }); - beforeEach('Login', () => { cy.login(); }); - afterEach('Logout', () => { cy.logout(); }); + beforeEach("Login", () => { + cy.login(); + }); + afterEach("Logout", () => { + cy.logout(); + }); it("should display the url parameters", () => { cy.visit( `/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testUrlParameters.html?test=root`, ); - cy.get('div[data-testid="renderContext_urlParameters"]').should("exist").contains("root"); + cy.get("div[data-testid=\"renderContext_urlParameters\"]").should("exist").contains("root"); }); it("should display the url parameters with special chars", () => { - const param = '(root,user,:./" \\)'; + const param = "(root,user,:./\" \\)"; cy.visit( `/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testUrlParameters.html?test=` + param, ); - cy.get('div[data-testid="renderContext_urlParameters"]').should("exist").contains(param); + cy.get("div[data-testid=\"renderContext_urlParameters\"]").should("exist").contains(param); }); }); diff --git a/tests/cypress/e2e/ui/urlHelperTest.cy.ts b/tests/cypress/e2e/ui/urlHelperTest.cy.ts index 582569f2..0447898c 100644 --- a/tests/cypress/e2e/ui/urlHelperTest.cy.ts +++ b/tests/cypress/e2e/ui/urlHelperTest.cy.ts @@ -1,6 +1,6 @@ import { addNode, addVanityUrl, deleteNode, publishAndWaitJobEnding } from "@jahia/cypress"; -import { addSimplePage } from "../../utils/helpers"; import { GENERIC_SITE_KEY, JAHIA_CONTEXT } from "../../support/constants"; +import { addSimplePage } from "../../utils/helpers"; describe("Test on url helper", () => { before("Create test page and contents", () => { @@ -79,7 +79,7 @@ describe("Test on url helper", () => { } }; - it("Generated URLs should be correct", function () { + it("Generated URLs should be correct", function() { cy.login(); cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testUrl.html`); @@ -173,7 +173,8 @@ describe("Test on url helper", () => { dataTestId: "fragment_link", tag: "a", attribute: "href", - expectedURL: `${JAHIA_CONTEXT}/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testUrl/pagecontent/test.html.ajax`, + expectedURL: + `${JAHIA_CONTEXT}/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testUrl/pagecontent/test.html.ajax`, }, ]); @@ -269,7 +270,7 @@ describe("Test on url helper", () => { cy.logout(); }); - it("Generated URLs should be correct with vanity", function () { + it("Generated URLs should be correct with vanity", function() { // Add a vanity url addVanityUrl(`/sites/${GENERIC_SITE_KEY}/home/linkedPage`, "en", "/vanityUrlTest"); publishAndWaitJobEnding(`/sites/${GENERIC_SITE_KEY}/home/linkedPage`); @@ -361,7 +362,8 @@ describe("Test on url helper", () => { dataTestId: "fragment_link", tag: "a", attribute: "href", - expectedURL: `${JAHIA_CONTEXT}/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testUrl/pagecontent/test.html.ajax`, + expectedURL: + `${JAHIA_CONTEXT}/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/testUrl/pagecontent/test.html.ajax`, }, ]); diff --git a/tests/cypress/e2e/ui/virtualNodeTest.cy.ts b/tests/cypress/e2e/ui/virtualNodeTest.cy.ts index dda9ddd6..1d0a8ddc 100644 --- a/tests/cypress/e2e/ui/virtualNodeTest.cy.ts +++ b/tests/cypress/e2e/ui/virtualNodeTest.cy.ts @@ -1,6 +1,6 @@ import { addNode, createUser, deleteUser } from "@jahia/cypress"; +import { GENERIC_SITE_KEY } from "../../support/constants"; import { addSimplePage } from "../../utils/helpers"; -import { GENERIC_SITE_KEY } from '../../support/constants'; describe("Test virtual nodes", () => { const pageName = "testVirtualNode"; @@ -21,29 +21,33 @@ describe("Test virtual nodes", () => { }); }); - beforeEach('Login', () => { cy.login(); }); - afterEach('Logout', () => { cy.logout(); }); + beforeEach("Login", () => { + cy.login(); + }); + afterEach("Logout", () => { + cy.logout(); + }); - it(`${pageName}: Check virtual nodes are correctly rendered in preview mode`, function () { + it(`${pageName}: Check virtual nodes are correctly rendered in preview mode`, function() { cy.visit(`/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/${pageName}.html`); - cy.get('div[data-testid="testVirtualNodeSample_myProperty"]').contains( + cy.get("div[data-testid=\"testVirtualNodeSample_myProperty\"]").contains( "this is a virtual node property", ); - cy.get('div[data-testid="virtualNode_aliasedUser"]').should("be.empty"); // logged as root, no alias + cy.get("div[data-testid=\"virtualNode_aliasedUser\"]").should("be.empty"); // logged as root, no alias }); - it(`${pageName}: Check virtual nodes are correctly rendered in customized preview mode`, function () { + it(`${pageName}: Check virtual nodes are correctly rendered in customized preview mode`, function() { const users = ["fooUser", "barUser"]; users.forEach((user) => { createUser(user, "testPassword"); cy.visit( `/cms/render/default/en/sites/${GENERIC_SITE_KEY}/home/${pageName}.html?alias=${user}`, ); - cy.get('div[data-testid="testVirtualNodeSample_myProperty"]').should( + cy.get("div[data-testid=\"testVirtualNodeSample_myProperty\"]").should( "have.text", "this is a virtual node property", ); - cy.get('div[data-testid="virtualNode_aliasedUser"]').should("have.text", user); + cy.get("div[data-testid=\"virtualNode_aliasedUser\"]").should("have.text", user); deleteUser("testUser"); }); }); diff --git a/tests/cypress/support/constants.ts b/tests/cypress/support/constants.ts index 220d5e56..f9c22d67 100644 --- a/tests/cypress/support/constants.ts +++ b/tests/cypress/support/constants.ts @@ -1,23 +1,24 @@ -export const GENERIC_SITE_KEY = 'javascriptTestSite'; -export const HYDROGEN_SITE_KEY = 'hydrogen'; -export const HYDROGEN_PREPACKAGED_SITE='jar:mvn:org.jahia.samples/javascript-modules-samples-hydrogen-prepackaged/LATEST/zip!/site.zip'; +export const GENERIC_SITE_KEY = "javascriptTestSite"; +export const HYDROGEN_SITE_KEY = "hydrogen"; +export const HYDROGEN_PREPACKAGED_SITE = + "jar:mvn:org.jahia.samples/javascript-modules-samples-hydrogen-prepackaged/LATEST/zip!/site.zip"; export const HYDROGEN_POSTS = [ { - page: 'a-second-article', - title: 'A second Article', - subTitle: 'We love writing articles!', - details: 'Written by Alice, Bob on March 28, 2025', - extract: 'This is a great article', + page: "a-second-article", + title: "A second Article", + subTitle: "We love writing articles!", + details: "Written by Alice, Bob on March 28, 2025", + extract: "This is a great article", }, { - page: 'welcome-to-hydrogen-blog', - title: 'Welcome to Hydrogen Blog', - subTitle: 'This blog will keep you up to date with the latest news from our company', - details: 'Written by Gautier on March 26, 2025', + page: "welcome-to-hydrogen-blog", + title: "Welcome to Hydrogen Blog", + subTitle: "This blog will keep you up to date with the latest news from our company", + details: "Written by Gautier on March 26, 2025", extract: - 'Hydrogen is a chemical element;', + "Hydrogen is a chemical element;", }, ]; export const JAHIA_CONTEXT = new URL( - Cypress.env('JAHIA_URL') ?? "http://localhost:8080" + Cypress.env("JAHIA_URL") ?? "http://localhost:8080", ).pathname.replace(/\/$/, ""); diff --git a/tests/cypress/support/e2e.js b/tests/cypress/support/e2e.js index 958d24c6..d1a05634 100644 --- a/tests/cypress/support/e2e.js +++ b/tests/cypress/support/e2e.js @@ -14,39 +14,39 @@ // *********************************************************** // Import commands.js using ES2015 syntax: -import './commands'; -import { createHydrogenSite, createTestSite } from '../utils/helpers'; +import "./commands"; import { deleteSite } from "@jahia/cypress"; -import { GENERIC_SITE_KEY, HYDROGEN_SITE_KEY, HYDROGEN_PREPACKAGED_SITE } from "./constants"; +import { createHydrogenSite, createTestSite } from "../utils/helpers"; +import { GENERIC_SITE_KEY, HYDROGEN_PREPACKAGED_SITE, HYDROGEN_SITE_KEY } from "./constants"; -require('cypress-terminal-report/src/installLogsCollector')({ +require("cypress-terminal-report/src/installLogsCollector")({ xhr: { printHeaderData: true, printRequestData: true, }, enableExtendedCollector: true, collectTypes: [ - 'cons:log', - 'cons:info', - 'cons:warn', - 'cons:error', - 'cy:log', - 'cy:xhr', - 'cy:request', - 'cy:intercept', - 'cy:command', + "cons:log", + "cons:info", + "cons:warn", + "cons:error", + "cy:log", + "cy:xhr", + "cy:request", + "cy:intercept", + "cy:command", ], }); -require('@jahia/cypress/dist/support/registerSupport').registerSupport(); -Cypress.on('uncaught:exception', () => { +require("@jahia/cypress/dist/support/registerSupport").registerSupport(); +Cypress.on("uncaught:exception", () => { // Returning false here prevents Cypress from failing the test return false; }); -before('Create test site', () => { +before("Create test site", () => { // use separate hooks for hydrogen and generic sites to avoid creating unnecessary data - if (Cypress.spec.relative.includes('hydrogen-tutorial')) { + if (Cypress.spec.relative.includes("hydrogen-tutorial")) { deleteSite(HYDROGEN_SITE_KEY); createHydrogenSite(HYDROGEN_SITE_KEY, HYDROGEN_PREPACKAGED_SITE); } else { diff --git a/tests/cypress/utils/helpers.ts b/tests/cypress/utils/helpers.ts index b8962a00..19072419 100644 --- a/tests/cypress/utils/helpers.ts +++ b/tests/cypress/utils/helpers.ts @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ -import { createSite, deleteSite, addNode, publishAndWaitJobEnding } from "@jahia/cypress"; +import { addNode, createSite, deleteSite, publishAndWaitJobEnding } from "@jahia/cypress"; export const addSimplePage = ( parentPathOrId: string, @@ -121,42 +121,42 @@ export const createHydrogenSite = (siteKey: string, prepackagedSiteURL: string) cy.log(`Publishing site '${siteKey}'...`); publishAndWaitJobEnding(`/sites/${siteKey}`, ["en"]); }); - } -} + } +}; export const createTestSite = (siteKey: string) => { - cy.step('Cleanup previous state: delete site', () => { + cy.step("Cleanup previous state: delete site", () => { deleteSite(siteKey); }); cy.step(`Create test site: ${siteKey}`, () => { createSite(siteKey, { - languages: 'en', - templateSet: 'javascript-modules-engine-test-module', - locale: 'en', - serverName: 'localhost', + languages: "en", + templateSet: "javascript-modules-engine-test-module", + locale: "en", + serverName: "localhost", }); - addSimplePage(`/sites/${siteKey}/home`, 'testPage', 'testPage', 'en', 'simple', [ + addSimplePage(`/sites/${siteKey}/home`, "testPage", "testPage", "en", "simple", [ { - name: 'pagecontent', - primaryNodeType: 'jnt:contentList', + name: "pagecontent", + primaryNodeType: "jnt:contentList", }, ]).then(() => { addNode({ parentPathOrId: `/sites/${siteKey}/home/testPage/pagecontent`, - name: 'test', - primaryNodeType: 'javascriptExample:test', + name: "test", + primaryNodeType: "javascriptExample:test", properties: [ - { name: 'jcr:title', value: 'test component' }, - { name: 'prop1', value: 'prop1 value' }, - { name: 'propMultiple', values: ['value 1', 'value 2', 'value 3'] }, + { name: "jcr:title", value: "test component" }, + { name: "prop1", value: "prop1 value" }, + { name: "propMultiple", values: ["value 1", "value 2", "value 3"] }, { - name: 'propRichText', - value: '

Hello this is a sample rich text

', + name: "propRichText", + value: "

Hello this is a sample rich text

", }, ], }); }); }); -} +}; diff --git a/tests/reporter/base.js b/tests/reporter/base.js index 755f9b83..43f03d7b 100644 --- a/tests/reporter/base.js +++ b/tests/reporter/base.js @@ -33,8 +33,7 @@ var consoleLog = console.log; /** Enable coloring by default, except in the browser interface. */ -exports.useColors = - !utils.isBrowser() && (supportsColor.stdout || process.env.MOCHA_COLORS !== undefined); +exports.useColors = !utils.isBrowser() && (supportsColor.stdout || process.env.MOCHA_COLORS !== undefined); /** Inline diffs instead of +/- */ @@ -92,7 +91,7 @@ if (process.platform === "win32") { * @param {string} str * @returns {string} */ -var color = (exports.color = function (type, str) { +var color = (exports.color = function(type, str) { if (!exports.useColors) { return String(str); } @@ -117,23 +116,23 @@ if (isatty) { /** Expose some basic cursor interactions that are common among reporters. */ exports.cursor = { - hide: function () { + hide: function() { isatty && process.stdout.write("\u001b[?25l"); }, - show: function () { + show: function() { isatty && process.stdout.write("\u001b[?25h"); }, - deleteLine: function () { + deleteLine: function() { isatty && process.stdout.write("\u001b[2K"); }, - beginningOfLine: function () { + beginningOfLine: function() { isatty && process.stdout.write("\u001b[0G"); }, - CR: function () { + CR: function() { if (isatty) { exports.cursor.deleteLine(); exports.cursor.beginningOfLine(); @@ -143,12 +142,12 @@ exports.cursor = { }, }; -var showDiff = (exports.showDiff = function (err) { +var showDiff = (exports.showDiff = function(err) { return ( - err && - err.showDiff !== false && - sameType(err.actual, err.expected) && - err.expected !== undefined + err + && err.showDiff !== false + && sameType(err.actual, err.expected) + && err.expected !== undefined ); }); @@ -168,16 +167,15 @@ function stringifyDiffObjs(err) { * @param {string} expected * @returns {string} Diff */ -var generateDiff = (exports.generateDiff = function (actual, expected) { +var generateDiff = (exports.generateDiff = function(actual, expected) { try { return exports.inlineDiffs ? inlineDiff(actual, expected) : unifiedDiff(actual, expected); } catch { - var msg = - "\n " + - color("diff added", "+ expected") + - " " + - color("diff removed", "- actual: failed to generate Mocha diff") + - "\n"; + var msg = "\n " + + color("diff added", "+ expected") + + " " + + color("diff removed", "- actual: failed to generate Mocha diff") + + "\n"; return msg; } }); @@ -190,16 +188,15 @@ var generateDiff = (exports.generateDiff = function (actual, expected) { * @public * @variation 1 */ -exports.list = function (failures) { +exports.list = function(failures) { var multipleErr; var multipleTest; Base.consoleLog(); - failures.forEach(function (test, i) { + failures.forEach(function(test, i) { // Format - var fmt = - color("error title", " %s) %s:\n") + - color("error message", " %s") + - color("error stack", "\n%s\n"); + var fmt = color("error title", " %s) %s:\n") + + color("error message", " %s") + + color("error stack", "\n%s\n"); // Msg var msg; @@ -256,7 +253,7 @@ exports.list = function (failures) { // Indented test title var testTitle = ""; - test.titlePath().forEach(function (str, index) { + test.titlePath().forEach(function(str, index) { if (index !== 0) { testTitle += "\n "; } @@ -294,7 +291,7 @@ function Base(runner, options) { this.runner = runner; this.stats = runner.stats; // Assigned so Reporters keep a closer reference - runner.on(EVENT_TEST_PASS, function (test) { + runner.on(EVENT_TEST_PASS, function(test) { if (test.duration > test.slow()) { test.speed = "slow"; } else if (test.duration > test.slow() / 2) { @@ -304,7 +301,7 @@ function Base(runner, options) { } }); - runner.on(EVENT_TEST_FAIL, function (test, err) { + runner.on(EVENT_TEST_FAIL, function(test, err) { if (showDiff(err)) { stringifyDiffObjs(err); } @@ -326,7 +323,7 @@ function Base(runner, options) { * @memberof Mocha.reporters * @public */ -Base.prototype.epilogue = function () { +Base.prototype.epilogue = function() { var stats = this.stats; var fmt; @@ -386,21 +383,20 @@ function inlineDiff(actual, expected) { if (lines.length > 4) { var width = String(lines.length).length; msg = lines - .map(function (str, i) { + .map(function(str, i) { return pad(++i, width) + " |" + " " + str; }) .join("\n"); } // Legend - msg = - "\n" + - color("diff removed inline", "actual") + - " " + - color("diff added inline", "expected") + - "\n\n" + - msg + - "\n"; + msg = "\n" + + color("diff removed inline", "actual") + + " " + + color("diff added inline", "expected") + + "\n\n" + + msg + + "\n"; // Indent msg = msg.replace(/^/gm, " "); @@ -444,12 +440,12 @@ function unifiedDiff(actual, expected) { var msg = diff.createPatch("string", actual, expected); var lines = msg.split("\n").splice(5); return ( - "\n " + - colorLines("diff added", "+ expected") + - " " + - colorLines("diff removed", "- actual") + - "\n\n" + - lines.map(cleanUp).filter(notBlank).join("\n") + "\n " + + colorLines("diff added", "+ expected") + + " " + + colorLines("diff removed", "- actual") + + "\n\n" + + lines.map(cleanUp).filter(notBlank).join("\n") ); } @@ -464,7 +460,7 @@ function unifiedDiff(actual, expected) { function errorDiff(actual, expected) { return diff .diffWordsWithSpace(actual, expected) - .map(function (str) { + .map(function(str) { if (str.added) { return colorLines("diff added inline", str.value); } @@ -489,7 +485,7 @@ function errorDiff(actual, expected) { function colorLines(name, str) { return str .split("\n") - .map(function (str) { + .map(function(str) { return color(name, str); }) .join("\n"); diff --git a/tests/reporter/json.js b/tests/reporter/json.js index 31bc4cf7..a1f65ce2 100644 --- a/tests/reporter/json.js +++ b/tests/reporter/json.js @@ -33,23 +33,23 @@ function JSONReporter(runner, options) { var failures = []; var passes = []; - runner.on(EVENT_TEST_END, function (test) { + runner.on(EVENT_TEST_END, function(test) { tests.push(test); }); - runner.on(EVENT_TEST_PASS, function (test) { + runner.on(EVENT_TEST_PASS, function(test) { passes.push(test); }); - runner.on(EVENT_TEST_FAIL, function (test) { + runner.on(EVENT_TEST_FAIL, function(test) { failures.push(test); }); - runner.on(EVENT_TEST_PENDING, function (test) { + runner.on(EVENT_TEST_PENDING, function(test) { pending.push(test); }); - runner.once(EVENT_RUN_END, function () { + runner.once(EVENT_RUN_END, function() { var obj = { stats: self.stats, tests: tests.map(clean), @@ -76,7 +76,7 @@ function JSONReporter(runner, options) { reportsPath + fileName + ".json", JSON.stringify(obj, null, 2), "utf8", - function (err) { + function(err) { if (err) { console.log("An error occured while writing JSON Object to File."); return console.log(err); @@ -123,7 +123,7 @@ function clean(test) { function cleanCycles(obj) { var cache = []; return JSON.parse( - JSON.stringify(obj, function (key, value) { + JSON.stringify(obj, function(key, value) { if (typeof value === "object" && value !== null) { if (cache.indexOf(value) !== -1) { // Instead of going in a circle, we'll print [object Object] @@ -147,7 +147,7 @@ function cleanCycles(obj) { */ function errorJSON(err) { var res = {}; - Object.getOwnPropertyNames(err).forEach(function (key) { + Object.getOwnPropertyNames(err).forEach(function(key) { res[key] = err[key]; }, err); return res; diff --git a/tests/reporter/utils.js b/tests/reporter/utils.js index 9770d677..895c4f23 100644 --- a/tests/reporter/utils.js +++ b/tests/reporter/utils.js @@ -30,7 +30,7 @@ exports.inherits = util.inherits; * @param {string} html * @returns {string} */ -exports.escape = function (html) { +exports.escape = function(html) { return he.encode(String(html), { useNamedReferences: false }); }; @@ -41,7 +41,7 @@ exports.escape = function (html) { * @param {Object} obj * @returns {boolean} */ -exports.isString = function (obj) { +exports.isString = function(obj) { return typeof obj === "string"; }; @@ -52,7 +52,7 @@ exports.isString = function (obj) { * @param {string} str * @returns {string} */ -exports.slug = function (str) { +exports.slug = function(str) { return str .toLowerCase() .replace(/\s+/g, "-") @@ -66,7 +66,7 @@ exports.slug = function (str) { * @param {string} str * @returns {string} */ -exports.clean = function (str) { +exports.clean = function(str) { str = str .replace(/\r\n?|[\n\u2028\u2029]/g, "\n") .replace(/^\uFEFF/, "") @@ -166,7 +166,7 @@ var type = (exports.type = function type(value) { * @returns {string} * @see exports.type */ -exports.stringify = function (value) { +exports.stringify = function(value) { var typeHint = type(value); if (!~["object", "array", "function"].indexOf(typeHint)) { @@ -179,7 +179,7 @@ exports.stringify = function (value) { // IE7/IE8 has a bizarre String constructor; needs to be coerced // into an array and back to obj. if (typeHint === "string" && typeof value === "object") { - value = value.split("").reduce(function (acc, char, idx) { + value = value.split("").reduce(function(acc, char, idx) { acc[idx] = char; return acc; }, {}); @@ -240,10 +240,9 @@ function jsonStringify(object, spaces, depth) { case "regexp": case "symbol": case "number": - val = - val === 0 && 1 / val === -Infinity // `-0` - ? "-0" - : val.toString(); + val = val === 0 && 1 / val === -Infinity // `-0` + ? "-0" + : val.toString(); break; case "date": var sDate = isNaN(val.getTime()) ? val.toString() : val.toISOString(); @@ -268,18 +267,17 @@ function jsonStringify(object, spaces, depth) { } --length; - str += - "\n " + - repeat(" ", space) + - (Array.isArray(object) ? "" : '"' + i + '": ') + // Key - _stringify(object[i]) + // Value - (length ? "," : ""); // Comma + str += "\n " + + repeat(" ", space) + + (Array.isArray(object) ? "" : "\"" + i + "\": ") // Key + + _stringify(object[i]) // Value + + (length ? "," : ""); // Comma } return ( - str + + str // [], {} - (str.length !== 1 ? "\n" + repeat(" ", --space) + end : end) + + (str.length !== 1 ? "\n" + repeat(" ", --space) + end : end) ); } @@ -329,8 +327,8 @@ exports.canonicalize = function canonicalize(value, stack, typeHint) { canonicalizedObj = value; break; case "array": - withStack(value, function () { - canonicalizedObj = value.map(function (item) { + withStack(value, function() { + canonicalizedObj = value.map(function(item) { return exports.canonicalize(item, stack); }); }); @@ -350,10 +348,10 @@ exports.canonicalize = function canonicalize(value, stack, typeHint) { /* Falls through */ case "object": canonicalizedObj = canonicalizedObj || {}; - withStack(value, function () { + withStack(value, function() { Object.keys(value) .sort() - .forEach(function (key) { + .forEach(function(key) { canonicalizedObj[key] = exports.canonicalize(value[key], stack); }); }); @@ -382,7 +380,7 @@ function emitWarning(msg, type) { if (process.emitWarning) { process.emitWarning(msg, type); } else { - process.nextTick(function () { + process.nextTick(function() { console.warn(type + ": " + msg); }); } @@ -424,7 +422,7 @@ exports.warn = function warn(msg) { * @summary * This Filter based on `mocha-clean` module.(see: `github.com/rstacruz/mocha-clean`) */ -exports.stackTraceFilter = function () { +exports.stackTraceFilter = function() { // TODO: Replace with `process.browser` var is = typeof document === "undefined" ? { node: true } : { browser: true }; var slash = path.sep; @@ -441,27 +439,27 @@ exports.stackTraceFilter = function () { function isMochaInternal(line) { return ( - ~line.indexOf("node_modules" + slash + "mocha" + slash) || - ~line.indexOf(slash + "mocha.js") || - ~line.indexOf(slash + "mocha.min.js") + ~line.indexOf("node_modules" + slash + "mocha" + slash) + || ~line.indexOf(slash + "mocha.js") + || ~line.indexOf(slash + "mocha.min.js") ); } function isNodeInternal(line) { return ( - ~line.indexOf("(timers.js:") || - ~line.indexOf("(events.js:") || - ~line.indexOf("(node.js:") || - ~line.indexOf("(module.js:") || - ~line.indexOf("GeneratorFunctionPrototype.next (native)") || - false + ~line.indexOf("(timers.js:") + || ~line.indexOf("(events.js:") + || ~line.indexOf("(node.js:") + || ~line.indexOf("(module.js:") + || ~line.indexOf("GeneratorFunctionPrototype.next (native)") + || false ); } - return function (stack) { + return function(stack) { stack = stack.split("\n"); - stack = stack.reduce(function (list, line) { + stack = stack.reduce(function(list, line) { if (isMochaInternal(line)) { return list; } @@ -520,7 +518,7 @@ exports.clamp = function clamp(value, range) { * @param {string} str - Value to be quoted. * @returns {string} Quoted value */ -exports.sQuote = function (str) { +exports.sQuote = function(str) { return "'" + str + "'"; }; @@ -539,8 +537,8 @@ exports.sQuote = function (str) { * @param {string} str - Value to be quoted. * @returns {string} Quoted value */ -exports.dQuote = function (str) { - return '"' + str + '"'; +exports.dQuote = function(str) { + return "\"" + str + "\""; }; /** @@ -548,7 +546,7 @@ exports.dQuote = function (str) { * * @public */ -exports.noop = function () {}; +exports.noop = function() {}; /** * Creates a map-like object. @@ -564,7 +562,7 @@ exports.noop = function () {}; * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Custom_and_Null_objects|MDN:Object.create - Custom objects} * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign|MDN:Object.assign} */ -exports.createMap = function () { +exports.createMap = function() { return assign.apply(null, [Object.create(null)].concat(Array.prototype.slice.call(arguments))); }; @@ -579,7 +577,7 @@ exports.createMap = function () { * @throws {TypeError} If argument is not a non-empty object. * @see {@link module:utils.createMap createMap} */ -exports.defineConstants = function (obj) { +exports.defineConstants = function(obj) { if (type(obj) !== "object" || !Object.keys(obj).length) { throw new TypeError("Invalid argument; expected a non-empty object"); } @@ -599,7 +597,7 @@ exports.defineConstants = function (obj) { * @returns {Boolean} Whether the current version of Node.JS supports ES Modules in a way that is * compatible with Mocha */ -exports.supportsEsModules = function (partialSupport) { +exports.supportsEsModules = function(partialSupport) { if (!exports.isBrowser() && process.versions && process.versions.node) { var versionFields = process.versions.node.split("."); var major = Number(versionFields[0]); diff --git a/vite-plugin/bin/jahia-deploy.js b/vite-plugin/bin/jahia-deploy.js index 005c132d..2bf07763 100755 --- a/vite-plugin/bin/jahia-deploy.js +++ b/vite-plugin/bin/jahia-deploy.js @@ -12,7 +12,7 @@ if (deployMethod !== "curl") { console.warn( styleText( "yellow", - 'JAHIA_DEPLOY_METHOD environment is now ignored and will always be "curl". You can safely remove it from your .env file.', + "JAHIA_DEPLOY_METHOD environment is now ignored and will always be \"curl\". You can safely remove it from your .env file.", ), ); } diff --git a/vite-plugin/fixtures/expected/client/foo.client.tsx.js b/vite-plugin/fixtures/expected/client/foo.client.tsx.js index 3f468abd..1ac89d54 100644 --- a/vite-plugin/fixtures/expected/client/foo.client.tsx.js +++ b/vite-plugin/fixtures/expected/client/foo.client.tsx.js @@ -1 +1,10 @@ -import{jsx as o}from"react/jsx-runtime";import{useEffect as e}from"react";const r="_pre_1cbxx_3",s={pre:r};function n(){return e(()=>{console.log("Foo component mounted")}),o("pre",{className:s.pre,children:"Hello World!"})}export{n as default}; +import { useEffect as e } from "react"; +import { jsx as o } from "react/jsx-runtime"; +const r = "_pre_1cbxx_3", s = { pre: r }; +function n() { + return e(() => { + console.log("Foo component mounted"); + }), + o("pre", { className: s.pre, children: "Hello World!" }); +} +export { n as default }; diff --git a/vite-plugin/fixtures/expected/server/index.js b/vite-plugin/fixtures/expected/server/index.js index e9ea9fb5..b74fadd0 100644 --- a/vite-plugin/fixtures/expected/server/index.js +++ b/vite-plugin/fixtures/expected/server/index.js @@ -1,21 +1,25 @@ -import { jsxs, jsx } from "react/jsx-runtime"; -import { AddResources, buildModuleFileUrl, jahiaComponent, Island } from "@jahia/javascript-modules-library"; +import { AddResources, buildModuleFileUrl, Island, jahiaComponent } from "@jahia/javascript-modules-library"; +import { jsx, jsxs } from "react/jsx-runtime"; import "react"; const vite = "dist/assets/vite-DrFLeNov.png"; -const Layout = ({ children }) => /* @__PURE__ */ jsxs("body", { children: [ - children, - /* @__PURE__ */ jsx(AddResources, { type: "css", resources: buildModuleFileUrl("dist/assets/style.css") }) -] }); +const Layout = ({ children }) => + /* @__PURE__ */ jsxs("body", { + children: [ + children, + /* @__PURE__ */ jsx(AddResources, { type: "css", resources: buildModuleFileUrl("dist/assets/style.css") }), + ], + }); const pre = "_pre_1cbxx_3"; const classes = { - pre + pre, }; const Foo = (function(v) { - if (typeof v === "function" || typeof v === "object" && v) + if (typeof v === "function" || typeof v === "object" && v) { Object.defineProperty(v, "__filename", { value: "dist/client/foo.client.tsx", - enumerable: false + enumerable: false, }); + } return v; })(function Foo2() { return /* @__PURE__ */ jsx("pre", { className: classes.pre, children: "Hello World!" }); @@ -23,21 +27,27 @@ const Foo = (function(v) { jahiaComponent( { componentType: "view", - nodeType: "fixtures:foo" + nodeType: "fixtures:foo", }, - () => /* @__PURE__ */ jsxs(Layout, { children: [ - /* @__PURE__ */ jsx("img", { src: buildModuleFileUrl(vite), alt: "Vite logo" }), - /* @__PURE__ */ jsx(Island, { component: Foo }) - ] }) + () => + /* @__PURE__ */ jsxs(Layout, { + children: [ + /* @__PURE__ */ jsx("img", { src: buildModuleFileUrl(vite), alt: "Vite logo" }), + /* @__PURE__ */ jsx(Island, { component: Foo }), + ], + }), ); jahiaComponent( { componentType: "view", - nodeType: "process:env" + nodeType: "process:env", }, - () => /* @__PURE__ */ jsxs("h1", { children: [ - "Mode: ", - "production" - ] }) + () => + /* @__PURE__ */ jsxs("h1", { + children: [ + "Mode: ", + "production", + ], + }), ); -//# sourceMappingURL=index.js.map +// # sourceMappingURL=index.js.map diff --git a/vite-plugin/fixtures/index.test.js b/vite-plugin/fixtures/index.test.js index 0d9e762f..a42afe67 100644 --- a/vite-plugin/fixtures/index.test.js +++ b/vite-plugin/fixtures/index.test.js @@ -1,7 +1,7 @@ -import test from "node:test"; import assert from "node:assert/strict"; import fs from "node:fs"; import path from "node:path"; +import test from "node:test"; test("@jahia/vite-plugin output snapshot", () => { for (const entry of fs.readdirSync("expected", { recursive: true, withFileTypes: true })) { diff --git a/vite-plugin/fixtures/src/foo.server.tsx b/vite-plugin/fixtures/src/foo.server.tsx index 5afed394..b84069f7 100644 --- a/vite-plugin/fixtures/src/foo.server.tsx +++ b/vite-plugin/fixtures/src/foo.server.tsx @@ -1,7 +1,7 @@ import { buildModuleFileUrl, Island, jahiaComponent } from "@jahia/javascript-modules-library"; -import vite from "./vite.png"; -import { Layout } from "./Layout.tsx"; import Foo from "./foo.client.tsx"; +import { Layout } from "./Layout.tsx"; +import vite from "./vite.png"; jahiaComponent( { diff --git a/vite-plugin/fixtures/vite.config.js b/vite-plugin/fixtures/vite.config.js index f6934431..f832e4df 100644 --- a/vite-plugin/fixtures/vite.config.js +++ b/vite-plugin/fixtures/vite.config.js @@ -1,6 +1,6 @@ // @ts-check -import { defineConfig } from "vite"; import jahia from "@jahia/vite-plugin"; +import { defineConfig } from "vite"; import inspect from "vite-plugin-inspect"; export default defineConfig({ diff --git a/vite-plugin/src/index.ts b/vite-plugin/src/index.ts index 424c0e84..0b375933 100644 --- a/vite-plugin/src/index.ts +++ b/vite-plugin/src/index.ts @@ -106,7 +106,9 @@ export default function jahia( • If this is the intended behavior, you can safely ignore this message • Otherwise, ensure that your client files are properly configured in the plugin options Client base directory: ${styleText("cyanBright", options.inputDir ?? "src (default value)")} - Client glob pattern: ${styleText("cyanBright", String(options.client?.inputGlob ?? "**/*.client.{jsx,tsx} (default value)"))}`, + Client glob pattern: ${ + styleText("cyanBright", String(options.client?.inputGlob ?? "**/*.client.{jsx,tsx} (default value)")) + }`, ); } @@ -175,9 +177,9 @@ export default function jahia( }, }, // Only add the callback plugin in watch mode - config.build?.watch && - options.watchCallback && - buildSuccessful(options.watchCallback), + config.build?.watch + && options.watchCallback + && buildSuccessful(options.watchCallback), ], }, }, @@ -216,9 +218,9 @@ export default function jahia( plugins: [ multiEntry(options.server?.outputFile ?? "server/index.js"), // Only add the callback plugin in watch mode - config.build?.watch && - options.watchCallback && - buildSuccessful(options.watchCallback), + config.build?.watch + && options.watchCallback + && buildSuccessful(options.watchCallback), // Insert filenames in client-side components insertFilename( clientBaseDir, @@ -264,7 +266,9 @@ export default function jahia( resolveId(id, importer) { if (this.environment.name === "client" && id === "@jahia/javascript-modules-library") { this.error( - `\n\tCannot import @jahia/javascript-modules-library in the client bundle\n\tin ${importer}\n\t${styleText("bgRedBright", "This module is only available on the server.")}`, + `\n\tCannot import @jahia/javascript-modules-library in the client bundle\n\tin ${importer}\n\t${ + styleText("bgRedBright", "This module is only available on the server.") + }`, ); } }, diff --git a/vite-plugin/src/multi-entry.ts b/vite-plugin/src/multi-entry.ts index 01efd934..277fb19a 100644 --- a/vite-plugin/src/multi-entry.ts +++ b/vite-plugin/src/multi-entry.ts @@ -1,5 +1,5 @@ -import { globSync } from "tinyglobby"; import type { Plugin } from "rollup"; +import { globSync } from "tinyglobby"; const VIRTUAL_ENTRY_ID = "\0virtual:entry"; diff --git a/yarn.lock b/yarn.lock index 51f4fcb8..d31cc5a9 100644 --- a/yarn.lock +++ b/yarn.lock @@ -79,6 +79,83 @@ __metadata: languageName: node linkType: hard +"@dprint/darwin-arm64@npm:0.52.0": + version: 0.52.0 + resolution: "@dprint/darwin-arm64@npm:0.52.0" + conditions: os=darwin & cpu=arm64 + languageName: node + linkType: hard + +"@dprint/darwin-x64@npm:0.52.0": + version: 0.52.0 + resolution: "@dprint/darwin-x64@npm:0.52.0" + conditions: os=darwin & cpu=x64 + languageName: node + linkType: hard + +"@dprint/linux-arm64-glibc@npm:0.52.0": + version: 0.52.0 + resolution: "@dprint/linux-arm64-glibc@npm:0.52.0" + conditions: os=linux & cpu=arm64 & libc=glibc + languageName: node + linkType: hard + +"@dprint/linux-arm64-musl@npm:0.52.0": + version: 0.52.0 + resolution: "@dprint/linux-arm64-musl@npm:0.52.0" + conditions: os=linux & cpu=arm64 & libc=musl + languageName: node + linkType: hard + +"@dprint/linux-loong64-glibc@npm:0.52.0": + version: 0.52.0 + resolution: "@dprint/linux-loong64-glibc@npm:0.52.0" + conditions: os=linux & cpu=loong64 & libc=glibc + languageName: node + linkType: hard + +"@dprint/linux-loong64-musl@npm:0.52.0": + version: 0.52.0 + resolution: "@dprint/linux-loong64-musl@npm:0.52.0" + conditions: os=linux & cpu=loong64 & libc=musl + languageName: node + linkType: hard + +"@dprint/linux-riscv64-glibc@npm:0.52.0": + version: 0.52.0 + resolution: "@dprint/linux-riscv64-glibc@npm:0.52.0" + conditions: os=linux & cpu=riscv64 & libc=glibc + languageName: node + linkType: hard + +"@dprint/linux-x64-glibc@npm:0.52.0": + version: 0.52.0 + resolution: "@dprint/linux-x64-glibc@npm:0.52.0" + conditions: os=linux & cpu=x64 & libc=glibc + languageName: node + linkType: hard + +"@dprint/linux-x64-musl@npm:0.52.0": + version: 0.52.0 + resolution: "@dprint/linux-x64-musl@npm:0.52.0" + conditions: os=linux & cpu=x64 & libc=musl + languageName: node + linkType: hard + +"@dprint/win32-arm64@npm:0.52.0": + version: 0.52.0 + resolution: "@dprint/win32-arm64@npm:0.52.0" + conditions: os=win32 & cpu=arm64 + languageName: node + linkType: hard + +"@dprint/win32-x64@npm:0.52.0": + version: 0.52.0 + resolution: "@dprint/win32-x64@npm:0.52.0" + conditions: os=win32 & cpu=x64 + languageName: node + linkType: hard + "@esbuild/aix-ppc64@npm:0.26.0": version: 0.26.0 resolution: "@esbuild/aix-ppc64@npm:0.26.0" @@ -1391,15 +1468,6 @@ __metadata: languageName: node linkType: hard -"@types/debug@npm:^4.0.0": - version: 4.1.12 - resolution: "@types/debug@npm:4.1.12" - dependencies: - "@types/ms": "npm:*" - checksum: 10c0/5dcd465edbb5a7f226e9a5efd1f399c6172407ef5840686b73e3608ce135eeca54ae8037dcd9f16bdb2768ac74925b820a8b9ecc588a58ca09eca6acabe33e2f - languageName: node - linkType: hard - "@types/estree@npm:*, @types/estree@npm:1.0.8, @types/estree@npm:^1.0.0, @types/estree@npm:^1.0.6": version: 1.0.8 resolution: "@types/estree@npm:1.0.8" @@ -1414,22 +1482,6 @@ __metadata: languageName: node linkType: hard -"@types/mdast@npm:^4.0.0": - version: 4.0.4 - resolution: "@types/mdast@npm:4.0.4" - dependencies: - "@types/unist": "npm:*" - checksum: 10c0/84f403dbe582ee508fd9c7643ac781ad8597fcbfc9ccb8d4715a2c92e4545e5772cbd0dbdf18eda65789386d81b009967fdef01b24faf6640f817287f54d9c82 - languageName: node - linkType: hard - -"@types/ms@npm:*": - version: 2.1.0 - resolution: "@types/ms@npm:2.1.0" - checksum: 10c0/5ce692ffe1549e1b827d99ef8ff71187457e0eb44adbae38fdf7b9a74bae8d20642ee963c14516db1d35fa2652e65f47680fdf679dcbde52bbfadd021f497225 - languageName: node - linkType: hard - "@types/node@npm:^22.19.3": version: 22.19.11 resolution: "@types/node@npm:22.19.11" @@ -1482,13 +1534,6 @@ __metadata: languageName: node linkType: hard -"@types/unist@npm:*, @types/unist@npm:^3.0.0": - version: 3.0.3 - resolution: "@types/unist@npm:3.0.3" - checksum: 10c0/2b1e4adcab78388e088fcc3c0ae8700f76619dbcb4741d7d201f87e2cb346bfc29a89003cfea2d76c996e1061452e14fcd737e8b25aacf949c1f2d6b2bc3dd60 - languageName: node - linkType: hard - "@typescript-eslint/eslint-plugin@npm:8.51.0": version: 8.51.0 resolution: "@typescript-eslint/eslint-plugin@npm:8.51.0" @@ -1938,13 +1983,6 @@ __metadata: languageName: node linkType: hard -"binary-searching@npm:^2.0.5": - version: 2.0.5 - resolution: "binary-searching@npm:2.0.5" - checksum: 10c0/914ccf15d4c989a8900e5617e2b6ec77a016f894b3833eaa5720a310214420dbd5d8eb577c158f99d25769968225c522cc37580c8d2ed46cc469f9d0365b7f15 - languageName: node - linkType: hard - "birecord@npm:^0.1.1": version: 0.1.1 resolution: "birecord@npm:0.1.1" @@ -2047,13 +2085,6 @@ __metadata: languageName: node linkType: hard -"character-entities@npm:^2.0.0": - version: 2.0.2 - resolution: "character-entities@npm:2.0.2" - checksum: 10c0/b0c645a45bcc90ff24f0e0140f4875a8436b8ef13b6bcd31ec02cfb2ca502b680362aa95386f7815bdc04b6464d48cf191210b3840d7c04241a149ede591a308 - languageName: node - linkType: hard - "chokidar@npm:^4.0.0": version: 4.0.3 resolution: "chokidar@npm:4.0.3" @@ -2114,13 +2145,6 @@ __metadata: languageName: node linkType: hard -"comment-parser@npm:^1.4.0": - version: 1.4.1 - resolution: "comment-parser@npm:1.4.1" - checksum: 10c0/d6c4be3f5be058f98b24f2d557f745d8fe1cc9eb75bebbdccabd404a0e1ed41563171b16285f593011f8b6a5ec81f564fb1f2121418ac5cbf0f49255bf0840dd - languageName: node - linkType: hard - "commondir@npm:^1.0.1": version: 1.0.1 resolution: "commondir@npm:1.0.1" @@ -2178,7 +2202,7 @@ __metadata: languageName: node linkType: hard -"debug@npm:4, debug@npm:^4.0.0, debug@npm:^4.3.1, debug@npm:^4.3.2, debug@npm:^4.3.4, debug@npm:^4.4.1": +"debug@npm:4, debug@npm:^4.3.1, debug@npm:^4.3.2, debug@npm:^4.3.4, debug@npm:^4.4.1": version: 4.4.1 resolution: "debug@npm:4.4.1" dependencies: @@ -2190,15 +2214,6 @@ __metadata: languageName: node linkType: hard -"decode-named-character-reference@npm:^1.0.0": - version: 1.0.2 - resolution: "decode-named-character-reference@npm:1.0.2" - dependencies: - character-entities: "npm:^2.0.0" - checksum: 10c0/66a9fc5d9b5385a2b3675c69ba0d8e893393d64057f7dbbb585265bb4fc05ec513d76943b8e5aac7d8016d20eea4499322cbf4cd6d54b466976b78f3a7587a4c - languageName: node - linkType: hard - "deep-is@npm:^0.1.3": version: 0.1.4 resolution: "deep-is@npm:0.1.4" @@ -2237,20 +2252,6 @@ __metadata: languageName: node linkType: hard -"dequal@npm:^2.0.0": - version: 2.0.3 - resolution: "dequal@npm:2.0.3" - checksum: 10c0/f98860cdf58b64991ae10205137c0e97d384c3a4edc7f807603887b7c4b850af1224a33d88012009f150861cbee4fa2d322c4cc04b9313bee312e47f6ecaa888 - languageName: node - linkType: hard - -"detect-indent@npm:^7.0.2": - version: 7.0.2 - resolution: "detect-indent@npm:7.0.2" - checksum: 10c0/adb1334ca3fe516dc6817aff0a777540b88643ab92fe13a72d0f5d12721ca796ffdd0e5fedb7b45e6e82657156c6ad44f5d5758157f0439532ae7d07b595146b - languageName: node - linkType: hard - "detect-libc@npm:^1.0.3": version: 1.0.3 resolution: "detect-libc@npm:1.0.3" @@ -2260,13 +2261,6 @@ __metadata: languageName: node linkType: hard -"detect-newline@npm:^4.0.1": - version: 4.0.1 - resolution: "detect-newline@npm:4.0.1" - checksum: 10c0/1cc1082e88ad477f30703ae9f23bd3e33816ea2db6a35333057e087d72d466f5a777809b71f560118ecff935d2c712f5b59e1008a8b56a900909d8fd4621c603 - languageName: node - linkType: hard - "devalue@npm:5.6.3, devalue@npm:^5.6.1": version: 5.6.3 resolution: "devalue@npm:5.6.3" @@ -2274,15 +2268,6 @@ __metadata: languageName: node linkType: hard -"devlop@npm:^1.0.0": - version: 1.1.0 - resolution: "devlop@npm:1.1.0" - dependencies: - dequal: "npm:^2.0.0" - checksum: 10c0/e0928ab8f94c59417a2b8389c45c55ce0a02d9ac7fd74ef62d01ba48060129e1d594501b77de01f3eeafc7cb00773819b0df74d96251cf20b31c5b3071f45c0e - languageName: node - linkType: hard - "dotenv@npm:^16.4.2": version: 16.6.1 resolution: "dotenv@npm:16.6.1" @@ -2297,6 +2282,50 @@ __metadata: languageName: node linkType: hard +"dprint@npm:^0.52.0": + version: 0.52.0 + resolution: "dprint@npm:0.52.0" + dependencies: + "@dprint/darwin-arm64": "npm:0.52.0" + "@dprint/darwin-x64": "npm:0.52.0" + "@dprint/linux-arm64-glibc": "npm:0.52.0" + "@dprint/linux-arm64-musl": "npm:0.52.0" + "@dprint/linux-loong64-glibc": "npm:0.52.0" + "@dprint/linux-loong64-musl": "npm:0.52.0" + "@dprint/linux-riscv64-glibc": "npm:0.52.0" + "@dprint/linux-x64-glibc": "npm:0.52.0" + "@dprint/linux-x64-musl": "npm:0.52.0" + "@dprint/win32-arm64": "npm:0.52.0" + "@dprint/win32-x64": "npm:0.52.0" + dependenciesMeta: + "@dprint/darwin-arm64": + optional: true + "@dprint/darwin-x64": + optional: true + "@dprint/linux-arm64-glibc": + optional: true + "@dprint/linux-arm64-musl": + optional: true + "@dprint/linux-loong64-glibc": + optional: true + "@dprint/linux-loong64-musl": + optional: true + "@dprint/linux-riscv64-glibc": + optional: true + "@dprint/linux-x64-glibc": + optional: true + "@dprint/linux-x64-musl": + optional: true + "@dprint/win32-arm64": + optional: true + "@dprint/win32-x64": + optional: true + bin: + dprint: bin.js + checksum: 10c0/ed26b402514e0d424f18de4b23a2720da28c8546b6a7fbdce7e2fd75815a9cbe1f8197543c4a228e6301d94995072c3fc1765b17fc444326362e1311ae47bfda + languageName: node + linkType: hard + "eastasianwidth@npm:^0.2.0": version: 0.2.0 resolution: "eastasianwidth@npm:0.2.0" @@ -2972,13 +3001,6 @@ __metadata: languageName: node linkType: hard -"git-hooks-list@npm:^4.1.1": - version: 4.2.1 - resolution: "git-hooks-list@npm:4.2.1" - checksum: 10c0/c5cac4e0526dd186122739f87c9e687c62a5ae7daadc9852d1823435f18a21f43ee6938825b97ecbb53c8c45456d94cc081fd5a2cf7eb4ea7508e5d9fa5fb5f3 - languageName: node - linkType: hard - "glob-parent@npm:^5.1.2": version: 5.1.2 resolution: "glob-parent@npm:5.1.2" @@ -3133,7 +3155,6 @@ __metadata: globals: "npm:^16.5.0" i18next: "npm:^25.7.3" modern-normalize: "npm:^3.0.1" - prettier: "npm:^3.7.4" react: "npm:^19.2.3" react-i18next: "npm:^16.5.0" typescript: "npm:^5.9.3" @@ -3340,13 +3361,6 @@ __metadata: languageName: node linkType: hard -"is-plain-obj@npm:^4.1.0": - version: 4.1.0 - resolution: "is-plain-obj@npm:4.1.0" - checksum: 10c0/32130d651d71d9564dc88ba7e6fda0e91a1010a3694648e9f4f47bb6080438140696d3e3e15c741411d712e47ac9edc1a8a9de1fe76f3487b0d90be06ac9975e - languageName: node - linkType: hard - "is-reference@npm:1.2.1": version: 1.2.1 resolution: "is-reference@npm:1.2.1" @@ -3444,12 +3458,10 @@ __metadata: "@eslint-react/eslint-plugin": "npm:^2.3.13" "@eslint/compat": "npm:^2.0.0" "@eslint/js": "npm:^9.39.2" + dprint: "npm:^0.52.0" eslint: "npm:^9.39.2" eslint-plugin-cypress: "npm:^5.2.0" globals: "npm:^16.5.0" - prettier: "npm:^3.7.4" - prettier-plugin-jsdoc: "npm:^1.8.0" - prettier-plugin-packagejson: "npm:^2.5.20" typescript: "npm:^5.9.3" typescript-eslint: "npm:^8.50.0" languageName: unknown @@ -3632,35 +3644,6 @@ __metadata: languageName: node linkType: hard -"mdast-util-from-markdown@npm:^2.0.0": - version: 2.0.2 - resolution: "mdast-util-from-markdown@npm:2.0.2" - dependencies: - "@types/mdast": "npm:^4.0.0" - "@types/unist": "npm:^3.0.0" - decode-named-character-reference: "npm:^1.0.0" - devlop: "npm:^1.0.0" - mdast-util-to-string: "npm:^4.0.0" - micromark: "npm:^4.0.0" - micromark-util-decode-numeric-character-reference: "npm:^2.0.0" - micromark-util-decode-string: "npm:^2.0.0" - micromark-util-normalize-identifier: "npm:^2.0.0" - micromark-util-symbol: "npm:^2.0.0" - micromark-util-types: "npm:^2.0.0" - unist-util-stringify-position: "npm:^4.0.0" - checksum: 10c0/76eb2bd2c6f7a0318087c73376b8af6d7561c1e16654e7667e640f391341096c56142618fd0ff62f6d39e5ab4895898b9789c84cd7cec2874359a437a0e1ff15 - languageName: node - linkType: hard - -"mdast-util-to-string@npm:^4.0.0": - version: 4.0.0 - resolution: "mdast-util-to-string@npm:4.0.0" - dependencies: - "@types/mdast": "npm:^4.0.0" - checksum: 10c0/2d3c1af29bf3fe9c20f552ee9685af308002488f3b04b12fa66652c9718f66f41a32f8362aa2d770c3ff464c034860b41715902ada2306bb0a055146cef064d7 - languageName: node - linkType: hard - "merge2@npm:^1.3.0": version: 1.4.1 resolution: "merge2@npm:1.4.1" @@ -3668,242 +3651,6 @@ __metadata: languageName: node linkType: hard -"micromark-core-commonmark@npm:^2.0.0": - version: 2.0.2 - resolution: "micromark-core-commonmark@npm:2.0.2" - dependencies: - decode-named-character-reference: "npm:^1.0.0" - devlop: "npm:^1.0.0" - micromark-factory-destination: "npm:^2.0.0" - micromark-factory-label: "npm:^2.0.0" - micromark-factory-space: "npm:^2.0.0" - micromark-factory-title: "npm:^2.0.0" - micromark-factory-whitespace: "npm:^2.0.0" - micromark-util-character: "npm:^2.0.0" - micromark-util-chunked: "npm:^2.0.0" - micromark-util-classify-character: "npm:^2.0.0" - micromark-util-html-tag-name: "npm:^2.0.0" - micromark-util-normalize-identifier: "npm:^2.0.0" - micromark-util-resolve-all: "npm:^2.0.0" - micromark-util-subtokenize: "npm:^2.0.0" - micromark-util-symbol: "npm:^2.0.0" - micromark-util-types: "npm:^2.0.0" - checksum: 10c0/87c7a75cd339189eb6f1d6323037f7d108d1331d953b84fe839b37fd385ee2292b27222327c1ceffda46ba5d5d4dee703482475e5ee8744be40c9e308d8acb77 - languageName: node - linkType: hard - -"micromark-factory-destination@npm:^2.0.0": - version: 2.0.1 - resolution: "micromark-factory-destination@npm:2.0.1" - dependencies: - micromark-util-character: "npm:^2.0.0" - micromark-util-symbol: "npm:^2.0.0" - micromark-util-types: "npm:^2.0.0" - checksum: 10c0/bbafcf869cee5bf511161354cb87d61c142592fbecea051000ff116068dc85216e6d48519d147890b9ea5d7e2864a6341c0c09d9948c203bff624a80a476023c - languageName: node - linkType: hard - -"micromark-factory-label@npm:^2.0.0": - version: 2.0.1 - resolution: "micromark-factory-label@npm:2.0.1" - dependencies: - devlop: "npm:^1.0.0" - micromark-util-character: "npm:^2.0.0" - micromark-util-symbol: "npm:^2.0.0" - micromark-util-types: "npm:^2.0.0" - checksum: 10c0/0137716b4ecb428114165505e94a2f18855c8bbea21b07a8b5ce514b32a595ed789d2b967125718fc44c4197ceaa48f6609d58807a68e778138d2e6b91b824e8 - languageName: node - linkType: hard - -"micromark-factory-space@npm:^2.0.0": - version: 2.0.1 - resolution: "micromark-factory-space@npm:2.0.1" - dependencies: - micromark-util-character: "npm:^2.0.0" - micromark-util-types: "npm:^2.0.0" - checksum: 10c0/f9ed43f1c0652d8d898de0ac2be3f77f776fffe7dd96bdbba1e02d7ce33d3853c6ff5daa52568fc4fa32cdf3a62d86b85ead9b9189f7211e1d69ff2163c450fb - languageName: node - linkType: hard - -"micromark-factory-title@npm:^2.0.0": - version: 2.0.1 - resolution: "micromark-factory-title@npm:2.0.1" - dependencies: - micromark-factory-space: "npm:^2.0.0" - micromark-util-character: "npm:^2.0.0" - micromark-util-symbol: "npm:^2.0.0" - micromark-util-types: "npm:^2.0.0" - checksum: 10c0/e72fad8d6e88823514916890099a5af20b6a9178ccf78e7e5e05f4de99bb8797acb756257d7a3a57a53854cb0086bf8aab15b1a9e9db8982500dd2c9ff5948b6 - languageName: node - linkType: hard - -"micromark-factory-whitespace@npm:^2.0.0": - version: 2.0.1 - resolution: "micromark-factory-whitespace@npm:2.0.1" - dependencies: - micromark-factory-space: "npm:^2.0.0" - micromark-util-character: "npm:^2.0.0" - micromark-util-symbol: "npm:^2.0.0" - micromark-util-types: "npm:^2.0.0" - checksum: 10c0/20a1ec58698f24b766510a309b23a10175034fcf1551eaa9da3adcbed3e00cd53d1ebe5f030cf873f76a1cec3c34eb8c50cc227be3344caa9ed25d56cf611224 - languageName: node - linkType: hard - -"micromark-util-character@npm:^2.0.0": - version: 2.1.1 - resolution: "micromark-util-character@npm:2.1.1" - dependencies: - micromark-util-symbol: "npm:^2.0.0" - micromark-util-types: "npm:^2.0.0" - checksum: 10c0/d3fe7a5e2c4060fc2a076f9ce699c82a2e87190a3946e1e5eea77f563869b504961f5668d9c9c014724db28ac32fa909070ea8b30c3a39bd0483cc6c04cc76a1 - languageName: node - linkType: hard - -"micromark-util-chunked@npm:^2.0.0": - version: 2.0.1 - resolution: "micromark-util-chunked@npm:2.0.1" - dependencies: - micromark-util-symbol: "npm:^2.0.0" - checksum: 10c0/b68c0c16fe8106949537bdcfe1be9cf36c0ccd3bc54c4007003cb0984c3750b6cdd0fd77d03f269a3382b85b0de58bde4f6eedbe7ecdf7244759112289b1ab56 - languageName: node - linkType: hard - -"micromark-util-classify-character@npm:^2.0.0": - version: 2.0.1 - resolution: "micromark-util-classify-character@npm:2.0.1" - dependencies: - micromark-util-character: "npm:^2.0.0" - micromark-util-symbol: "npm:^2.0.0" - micromark-util-types: "npm:^2.0.0" - checksum: 10c0/8a02e59304005c475c332f581697e92e8c585bcd45d5d225a66c1c1b14ab5a8062705188c2ccec33cc998d33502514121478b2091feddbc751887fc9c290ed08 - languageName: node - linkType: hard - -"micromark-util-combine-extensions@npm:^2.0.0": - version: 2.0.1 - resolution: "micromark-util-combine-extensions@npm:2.0.1" - dependencies: - micromark-util-chunked: "npm:^2.0.0" - micromark-util-types: "npm:^2.0.0" - checksum: 10c0/f15e282af24c8372cbb10b9b0b3e2c0aa681fea0ca323a44d6bc537dc1d9382c819c3689f14eaa000118f5a163245358ce6276b2cda9a84439cdb221f5d86ae7 - languageName: node - linkType: hard - -"micromark-util-decode-numeric-character-reference@npm:^2.0.0": - version: 2.0.2 - resolution: "micromark-util-decode-numeric-character-reference@npm:2.0.2" - dependencies: - micromark-util-symbol: "npm:^2.0.0" - checksum: 10c0/9c8a9f2c790e5593ffe513901c3a110e9ec8882a08f466da014112a25e5059b51551ca0aeb7ff494657d86eceb2f02ee556c6558b8d66aadc61eae4a240da0df - languageName: node - linkType: hard - -"micromark-util-decode-string@npm:^2.0.0": - version: 2.0.1 - resolution: "micromark-util-decode-string@npm:2.0.1" - dependencies: - decode-named-character-reference: "npm:^1.0.0" - micromark-util-character: "npm:^2.0.0" - micromark-util-decode-numeric-character-reference: "npm:^2.0.0" - micromark-util-symbol: "npm:^2.0.0" - checksum: 10c0/f24d75b2e5310be6e7b6dee532e0d17d3bf46996841d6295f2a9c87a2046fff4ab603c52ab9d7a7a6430a8b787b1574ae895849c603d262d1b22eef71736b5cb - languageName: node - linkType: hard - -"micromark-util-encode@npm:^2.0.0": - version: 2.0.1 - resolution: "micromark-util-encode@npm:2.0.1" - checksum: 10c0/b2b29f901093845da8a1bf997ea8b7f5e061ffdba85070dfe14b0197c48fda64ffcf82bfe53c90cf9dc185e69eef8c5d41cae3ba918b96bc279326921b59008a - languageName: node - linkType: hard - -"micromark-util-html-tag-name@npm:^2.0.0": - version: 2.0.1 - resolution: "micromark-util-html-tag-name@npm:2.0.1" - checksum: 10c0/ae80444db786fde908e9295f19a27a4aa304171852c77414516418650097b8afb401961c9edb09d677b06e97e8370cfa65638dde8438ebd41d60c0a8678b85b9 - languageName: node - linkType: hard - -"micromark-util-normalize-identifier@npm:^2.0.0": - version: 2.0.1 - resolution: "micromark-util-normalize-identifier@npm:2.0.1" - dependencies: - micromark-util-symbol: "npm:^2.0.0" - checksum: 10c0/5299265fa360769fc499a89f40142f10a9d4a5c3dd8e6eac8a8ef3c2e4a6570e4c009cf75ea46dce5ee31c01f25587bde2f4a5cc0a935584ae86dd857f2babbd - languageName: node - linkType: hard - -"micromark-util-resolve-all@npm:^2.0.0": - version: 2.0.1 - resolution: "micromark-util-resolve-all@npm:2.0.1" - dependencies: - micromark-util-types: "npm:^2.0.0" - checksum: 10c0/bb6ca28764696bb479dc44a2d5b5fe003e7177aeae1d6b0d43f24cc223bab90234092d9c3ce4a4d2b8df095ccfd820537b10eb96bb7044d635f385d65a4c984a - languageName: node - linkType: hard - -"micromark-util-sanitize-uri@npm:^2.0.0": - version: 2.0.1 - resolution: "micromark-util-sanitize-uri@npm:2.0.1" - dependencies: - micromark-util-character: "npm:^2.0.0" - micromark-util-encode: "npm:^2.0.0" - micromark-util-symbol: "npm:^2.0.0" - checksum: 10c0/60e92166e1870fd4f1961468c2651013ff760617342918e0e0c3c4e872433aa2e60c1e5a672bfe5d89dc98f742d6b33897585cf86ae002cda23e905a3c02527c - languageName: node - linkType: hard - -"micromark-util-subtokenize@npm:^2.0.0": - version: 2.0.4 - resolution: "micromark-util-subtokenize@npm:2.0.4" - dependencies: - devlop: "npm:^1.0.0" - micromark-util-chunked: "npm:^2.0.0" - micromark-util-symbol: "npm:^2.0.0" - micromark-util-types: "npm:^2.0.0" - checksum: 10c0/d1d19c6ede87e5d3778aa7f6c56ad736a48404556757abf71ea87bd2baac71927d18db3c9a1f76c4b3f42f32d6032aea97d1de739b49872daf168c6f8f373f39 - languageName: node - linkType: hard - -"micromark-util-symbol@npm:^2.0.0": - version: 2.0.1 - resolution: "micromark-util-symbol@npm:2.0.1" - checksum: 10c0/f2d1b207771e573232436618e78c5e46cd4b5c560dd4a6d63863d58018abbf49cb96ec69f7007471e51434c60de3c9268ef2bf46852f26ff4aacd10f9da16fe9 - languageName: node - linkType: hard - -"micromark-util-types@npm:^2.0.0": - version: 2.0.1 - resolution: "micromark-util-types@npm:2.0.1" - checksum: 10c0/872ec9334bb42afcc91c5bed8b7ee03b75654b36c6f221ab4d2b1bb0299279f00db948bf38ec6bc1ec03d0cf7842c21ab805190bf676157ba587eb0386d38b71 - languageName: node - linkType: hard - -"micromark@npm:^4.0.0": - version: 4.0.1 - resolution: "micromark@npm:4.0.1" - dependencies: - "@types/debug": "npm:^4.0.0" - debug: "npm:^4.0.0" - decode-named-character-reference: "npm:^1.0.0" - devlop: "npm:^1.0.0" - micromark-core-commonmark: "npm:^2.0.0" - micromark-factory-space: "npm:^2.0.0" - micromark-util-character: "npm:^2.0.0" - micromark-util-chunked: "npm:^2.0.0" - micromark-util-combine-extensions: "npm:^2.0.0" - micromark-util-decode-numeric-character-reference: "npm:^2.0.0" - micromark-util-encode: "npm:^2.0.0" - micromark-util-normalize-identifier: "npm:^2.0.0" - micromark-util-resolve-all: "npm:^2.0.0" - micromark-util-sanitize-uri: "npm:^2.0.0" - micromark-util-subtokenize: "npm:^2.0.0" - micromark-util-symbol: "npm:^2.0.0" - micromark-util-types: "npm:^2.0.0" - checksum: 10c0/b5d950c84664ce209575e5a54946488f0a1e1240d080544e657b65074c9b08208a5315d9db066b93cbc199ec05f68552ba8b09fd5e716c726f4a4712275a7c5c - languageName: node - linkType: hard - "micromatch@npm:^4.0.5, micromatch@npm:^4.0.8": version: 4.0.8 resolution: "micromatch@npm:4.0.8" @@ -4464,42 +4211,6 @@ __metadata: languageName: node linkType: hard -"prettier-plugin-jsdoc@npm:^1.8.0": - version: 1.8.0 - resolution: "prettier-plugin-jsdoc@npm:1.8.0" - dependencies: - binary-searching: "npm:^2.0.5" - comment-parser: "npm:^1.4.0" - mdast-util-from-markdown: "npm:^2.0.0" - peerDependencies: - prettier: ^3.0.0 - checksum: 10c0/c42a90793c8397a51e90692c7c8ffdd30e63b66cd6db5f7c044bfd99e40ca251f407b2052fc8f61fc569912e8b7b255daecf7d1777c46dab8527dbb11e4946ea - languageName: node - linkType: hard - -"prettier-plugin-packagejson@npm:^2.5.20": - version: 2.5.22 - resolution: "prettier-plugin-packagejson@npm:2.5.22" - dependencies: - sort-package-json: "npm:3.6.0" - peerDependencies: - prettier: ">= 1.16.0" - peerDependenciesMeta: - prettier: - optional: true - checksum: 10c0/a4c8d671c5c453c3c33414ac3c28ae61c11fce4494b5a82a442343cb26e13b86e70fd9335b2c6c19c3065bb299ad48765b220ec17d3e85942a2b6ea370597f67 - languageName: node - linkType: hard - -"prettier@npm:^3.7.4": - version: 3.7.4 - resolution: "prettier@npm:3.7.4" - bin: - prettier: bin/prettier.cjs - checksum: 10c0/9675d2cd08eacb1faf1d1a2dbfe24bfab6a912b059fc9defdb380a408893d88213e794a40a2700bd29b140eb3172e0b07c852853f6e22f16f3374659a1a13389 - languageName: node - linkType: hard - "proc-log@npm:^3.0.0": version: 3.0.0 resolution: "proc-log@npm:3.0.0" @@ -4868,15 +4579,6 @@ __metadata: languageName: node linkType: hard -"semver@npm:^7.7.3": - version: 7.7.3 - resolution: "semver@npm:7.7.3" - bin: - semver: bin/semver.js - checksum: 10c0/4afe5c986567db82f44c8c6faef8fe9df2a9b1d98098fc1721f57c696c4c21cebd572f297fc21002f81889492345b8470473bc6f4aff5fb032a6ea59ea2bc45e - languageName: node - linkType: hard - "serialize-javascript@npm:^6.0.1": version: 6.0.2 resolution: "serialize-javascript@npm:6.0.2" @@ -4962,30 +4664,6 @@ __metadata: languageName: node linkType: hard -"sort-object-keys@npm:^2.0.1": - version: 2.1.0 - resolution: "sort-object-keys@npm:2.1.0" - checksum: 10c0/3e10c4892c379800a920c83f943fd98b3d7cf3eb3db67b0470ead95f180c3fb95146e22ef176c4c71395537597deb8320a80ace8025c39eadc8da4b38ae26b5f - languageName: node - linkType: hard - -"sort-package-json@npm:3.6.0": - version: 3.6.0 - resolution: "sort-package-json@npm:3.6.0" - dependencies: - detect-indent: "npm:^7.0.2" - detect-newline: "npm:^4.0.1" - git-hooks-list: "npm:^4.1.1" - is-plain-obj: "npm:^4.1.0" - semver: "npm:^7.7.3" - sort-object-keys: "npm:^2.0.1" - tinyglobby: "npm:^0.2.15" - bin: - sort-package-json: cli.js - checksum: 10c0/977621b4541e6a107612524c8838a516425786b1d85fad9366416d3736989b1075d40511a28f0b3c47b9a0d7c1197f828af0cc3e350cdf793d1301d427178968 - languageName: node - linkType: hard - "source-map-js@npm:>=0.6.2 <2.0.0, source-map-js@npm:^1.0.2, source-map-js@npm:^1.2.1": version: 1.2.1 resolution: "source-map-js@npm:1.2.1" @@ -5368,15 +5046,6 @@ __metadata: languageName: node linkType: hard -"unist-util-stringify-position@npm:^4.0.0": - version: 4.0.0 - resolution: "unist-util-stringify-position@npm:4.0.0" - dependencies: - "@types/unist": "npm:^3.0.0" - checksum: 10c0/dfe1dbe79ba31f589108cb35e523f14029b6675d741a79dea7e5f3d098785045d556d5650ec6a8338af11e9e78d2a30df12b1ee86529cded1098da3f17ee999e - languageName: node - linkType: hard - "unplugin-utils@npm:^0.3.0": version: 0.3.0 resolution: "unplugin-utils@npm:0.3.0"