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 extends AccessMode> 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 extends AccessMode> 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 extends OpenOption> 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 extends OpenOption> 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 super Path> 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 super Path> 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