You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by ra...@apache.org on 2015/05/05 18:04:33 UTC
svn commit: r1677848 - in /sling/trunk/contrib/scripting/sightly: engine/
engine/src/main/java/org/apache/sling/scripting/sightly/impl/compiler/
engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/
engine/src/main/java/org/apache/sling/...
Author: radu
Date: Tue May 5 16:04:32 2015
New Revision: 1677848
URL: http://svn.apache.org/r1677848
Log:
SLING-4692 - Decouple Sightly from the JCR Compiler
* switched to using the JavaCompiler instead of the JcrJavaCompiler for generating Java classes
from Sightly scripts
Modified:
sling/trunk/contrib/scripting/sightly/engine/pom.xml
sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/compiler/SightlyJavaCompilerService.java
sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyScriptEngine.java
sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/UnitChangeMonitor.java
sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/UnitLoader.java
sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SourceIdentifier.java
sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/RenderUnitProvider.java
sling/trunk/contrib/scripting/sightly/engine/src/test/java/org/apache/sling/scripting/sightly/impl/compiler/SightlyJavaCompilerServiceTest.java
sling/trunk/contrib/scripting/sightly/testing/pom.xml
sling/trunk/contrib/scripting/sightly/testing/src/main/provisioning/model.txt
Modified: sling/trunk/contrib/scripting/sightly/engine/pom.xml
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/scripting/sightly/engine/pom.xml?rev=1677848&r1=1677847&r2=1677848&view=diff
==============================================================================
--- sling/trunk/contrib/scripting/sightly/engine/pom.xml (original)
+++ sling/trunk/contrib/scripting/sightly/engine/pom.xml Tue May 5 16:04:32 2015
@@ -184,8 +184,8 @@
</dependency>
<dependency>
<groupId>org.apache.sling</groupId>
- <artifactId>org.apache.sling.settings</artifactId>
- <version>1.0.0</version>
+ <artifactId>org.apache.sling.commons.compiler</artifactId>
+ <version>2.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
@@ -200,21 +200,8 @@
<version>2.2.8</version>
<scope>provided</scope>
</dependency>
- <dependency>
- <groupId>org.apache.sling</groupId>
- <artifactId>org.apache.sling.commons.compiler</artifactId>
- <version>2.0.0</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.sling</groupId>
- <artifactId>org.apache.sling.jcr.compiler</artifactId>
- <version>2.1.0</version>
- <scope>provided</scope>
- </dependency>
<!-- Dependency for expression parsing -->
-
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr4-runtime</artifactId>
Modified: sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/compiler/SightlyJavaCompilerService.java
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/compiler/SightlyJavaCompilerService.java?rev=1677848&r1=1677847&r2=1677848&view=diff
==============================================================================
--- sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/compiler/SightlyJavaCompilerService.java (original)
+++ sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/compiler/SightlyJavaCompilerService.java Tue May 5 16:04:32 2015
@@ -31,6 +31,7 @@ import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
+import org.apache.commons.io.IOUtils;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
@@ -41,8 +42,8 @@ import org.apache.sling.commons.classloa
import org.apache.sling.commons.compiler.CompilationResult;
import org.apache.sling.commons.compiler.CompilationUnit;
import org.apache.sling.commons.compiler.CompilerMessage;
+import org.apache.sling.commons.compiler.JavaCompiler;
import org.apache.sling.commons.compiler.Options;
-import org.apache.sling.jcr.compiler.JcrJavaCompiler;
import org.apache.sling.scripting.sightly.ResourceResolution;
import org.apache.sling.scripting.sightly.SightlyException;
import org.apache.sling.scripting.sightly.impl.engine.UnitChangeMonitor;
@@ -66,7 +67,7 @@ public class SightlyJavaCompilerService
private ClassLoaderWriter classLoaderWriter = null;
@Reference
- private JcrJavaCompiler jcrJavaCompiler = null;
+ private JavaCompiler javaCompiler = null;
@Reference
private UnitChangeMonitor unitChangeMonitor = null;
@@ -99,7 +100,11 @@ public class SightlyJavaCompilerService
if (pojoResource != null) {
// clear the cache as we need to recompile the POJO object
unitChangeMonitor.clearJavaUseObject(pojoPath);
- return compileSource(pojoResource, className);
+ try {
+ return compileSource(IOUtils.toString(pojoResource.adaptTo(InputStream.class), "UTF-8"), className);
+ } catch (IOException e) {
+ throw new SightlyException(String.format("Unable to compile class %s from %s.", className, pojoPath), e);
+ }
} else {
throw new SightlyException(String.format("Resource %s identifying class %s has been removed.", pojoPath, className));
}
@@ -111,7 +116,11 @@ public class SightlyJavaCompilerService
// the object definitely doesn't come from a bundle so we should attempt to compile it from the repo
Resource pojoResource = resolver.getResource(pojoPath);
if (pojoResource != null) {
- return compileSource(pojoResource, className);
+ try {
+ return compileSource(IOUtils.toString(pojoResource.adaptTo(InputStream.class), "UTF-8"), className);
+ } catch (IOException e) {
+ throw new SightlyException(String.format("Unable to compile class %s from %s.", className, pojoPath), e);
+ }
}
}
}
@@ -127,18 +136,17 @@ public class SightlyJavaCompilerService
}
/**
- * Compiles a class using the passed fully qualified classname and based on the resource that represents the class' source.
+ * Compiles a class using the passed fully qualified class name and its source code.
*
- * @param javaResource resource that constitutes the class' source
- * @param fqcn fully qualified name of the class to compile
+ * @param sourceCode the source code from which to generate the class
+ * @param fqcn fully qualified name of the class to compile
* @return object instance of the class to compile
* @throws CompilerException in case of any runtime exception
*/
- public Object compileSource(Resource javaResource, String fqcn) {
- LOG.debug("Compiling Sightly based Java class from resource: " + javaResource.getPath());
+ public Object compileSource(String sourceCode, String fqcn) {
try {
- CompilationUnit compilationUnit = new SightlyCompilationUnit(javaResource, fqcn);
- return compileJavaResource(compilationUnit, javaResource.getPath());
+ CompilationUnit compilationUnit = new SightlyCompilationUnit(sourceCode, fqcn);
+ return compileJavaResource(compilationUnit);
} catch (Exception e) {
throw new CompilerException(CompilerException.CompilerExceptionCause.COMPILER_ERRORS, e);
}
@@ -235,15 +243,14 @@ public class SightlyJavaCompilerService
* Compiles a class stored in the repository and returns an instance of the compiled class.
*
* @param compilationUnit a compilation unit
- * @param scriptPath the path of the script to compile
* @return instance of compiled class
* @throws Exception
*/
- private Object compileJavaResource(CompilationUnit compilationUnit, String scriptPath) throws Exception {
+ private Object compileJavaResource(CompilationUnit compilationUnit) throws Exception {
writeLock.lock();
try {
long start = System.currentTimeMillis();
- CompilationResult compilationResult = jcrJavaCompiler.compile(new String[]{scriptPath}, options);
+ CompilationResult compilationResult = javaCompiler.compile(new CompilationUnit[]{compilationUnit}, options);
long end = System.currentTimeMillis();
List<CompilerMessage> errors = compilationResult.getErrors();
if (errors != null && errors.size() > 0) {
@@ -329,36 +336,29 @@ public class SightlyJavaCompilerService
return buffer.toString();
}
- class SlingResourceCompilationUnit implements CompilationUnit {
- private final Resource resource;
+ class SightlyCompilationUnit implements CompilationUnit {
+
+ private String fqcn;
+ private String sourceCode;
- public SlingResourceCompilationUnit(Resource resource) {
- this.resource = resource;
+ SightlyCompilationUnit(String sourceCode, String fqcn) throws Exception {
+ this.sourceCode = sourceCode;
+ this.fqcn = fqcn;
}
+ @Override
public Reader getSource() throws IOException {
- return new InputStreamReader(resource.adaptTo(InputStream.class), "UTF-8");
+ return new InputStreamReader(IOUtils.toInputStream(sourceCode, "UTF-8"));
}
+ @Override
public String getMainClassName() {
- return getJavaNameFromPath(resource.getPath());
+ return fqcn;
}
+ @Override
public long getLastModified() {
- return resource.getResourceMetadata().getModificationTime();
- }
- }
-
- class SightlyCompilationUnit extends SlingResourceCompilationUnit {
- private String fqcn;
-
- public SightlyCompilationUnit(Resource resource, String fqcn) {
- super(resource);
- this.fqcn = fqcn;
- }
-
- public String getMainClassName() {
- return fqcn;
+ return System.currentTimeMillis();
}
}
@@ -372,7 +372,7 @@ public class SightlyJavaCompilerService
private Character symbol;
- private AmbiguousPathSymbol(Character symbol) {
+ AmbiguousPathSymbol(Character symbol) {
this.symbol = symbol;
}
Modified: sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyScriptEngine.java
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyScriptEngine.java?rev=1677848&r1=1677847&r2=1677848&view=diff
==============================================================================
--- sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyScriptEngine.java (original)
+++ sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyScriptEngine.java Tue May 5 16:04:32 2015
@@ -21,7 +21,6 @@ package org.apache.sling.scripting.sight
import java.io.Reader;
import java.util.Collections;
-
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngineFactory;
@@ -37,17 +36,13 @@ import org.apache.sling.api.scripting.Sl
import org.apache.sling.scripting.api.AbstractSlingScriptEngine;
import org.apache.sling.scripting.sightly.impl.engine.runtime.RenderContextImpl;
import org.apache.sling.scripting.sightly.impl.engine.runtime.RenderUnit;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
/**
* The Sightly Script engine
*/
public class SightlyScriptEngine extends AbstractSlingScriptEngine {
- private static final Logger LOG = LoggerFactory.getLogger(SightlyScriptEngine.class);
private static final Bindings EMPTY_BINDINGS = new SimpleBindings(Collections.<String, Object>emptyMap());
- private static final int MAX_CLASSLOADER_RETRIES = 5;
private final UnitLoader unitLoader;
private final ExtensionRegistryService extensionRegistryService;
@@ -81,6 +76,8 @@ public class SightlyScriptEngine extends
try {
request.setAttribute(SlingBindings.class.getName(), slingBindings);
evaluateScript(scriptResource, globalBindings, scriptResourceResolver);
+ } catch (Exception e) {
+ throw new ScriptException(e);
} finally {
request.setAttribute(SlingBindings.class.getName(), oldValue);
Thread.currentThread().setContextClassLoader(old);
@@ -89,7 +86,7 @@ public class SightlyScriptEngine extends
return null;
}
- private void evaluateScript(Resource scriptResource, Bindings bindings, ResourceResolver scriptResourceResolver) {
+ private void evaluateScript(Resource scriptResource, Bindings bindings, ResourceResolver scriptResourceResolver) throws Exception {
RenderContextImpl renderContext = new RenderContextImpl(bindings, extensionRegistryService.extensions(), scriptResourceResolver);
RenderUnit renderUnit = unitLoader.createUnit(scriptResource, bindings, renderContext);
renderUnit.render(renderContext, EMPTY_BINDINGS);
Modified: sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/UnitChangeMonitor.java
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/UnitChangeMonitor.java?rev=1677848&r1=1677847&r2=1677848&view=diff
==============================================================================
--- sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/UnitChangeMonitor.java (original)
+++ sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/UnitChangeMonitor.java Tue May 5 16:04:32 2015
@@ -32,7 +32,6 @@ import org.apache.sling.api.SlingConstan
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
-import org.apache.sling.settings.SlingSettingsService;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.event.Event;
@@ -48,17 +47,12 @@ public class UnitChangeMonitor {
private static final Logger LOG = LoggerFactory.getLogger(UnitChangeMonitor.class);
private Map<String, Long> slyScriptsMap = new ConcurrentHashMap<String, Long>();
- private Map<String, Long> slySourcesMap = new ConcurrentHashMap<String, Long>();
private Map<String, Long> slyJavaUseMap = new ConcurrentHashMap<String, Long>();
private ServiceRegistration eventHandlerServiceRegistration;
- private String[] searchPaths;
@Reference
private ResourceResolverFactory rrf = null;
- @Reference
- private SlingSettingsService slingSettings = null;
-
/**
* Returns the last modified date for a Sightly script.
*
@@ -74,20 +68,6 @@ public class UnitChangeMonitor {
}
/**
- * Returns the last modified date of a generated Java source file.
- *
- * @param file the full path of the generated source file
- * @return the file's last modified date or 0 if there's no information about the file
- */
- public long getLastModifiedDateForJavaSourceFile(String file) {
- if (file == null) {
- return 0;
- }
- Long date = slySourcesMap.get(file);
- return date != null ? date : 0;
- }
-
- /**
* Returns the last modified date for a Java Use-API object stored in the repository.
*
* @param path the full path of the file defining the Java Use-API object
@@ -113,12 +93,13 @@ public class UnitChangeMonitor {
}
@Activate
+ @SuppressWarnings(value = {"unused", "unchecked"})
protected void activate(ComponentContext componentContext) {
ResourceResolver adminResolver = null;
try {
adminResolver = rrf.getAdministrativeResourceResolver(null);
StringBuilder eventHandlerFilteredPaths = new StringBuilder("(|");
- searchPaths = adminResolver.getSearchPath();
+ String[] searchPaths = adminResolver.getSearchPath();
for (String sp : searchPaths) {
// Sightly script changes
eventHandlerFilteredPaths.append("(path=").append(sp).append("**/*.").append(SightlyScriptEngineFactory.EXTENSION).append(
@@ -126,8 +107,7 @@ public class UnitChangeMonitor {
// Sightly Java Use-API objects
eventHandlerFilteredPaths.append("(path=").append(sp).append("**/*.java").append(")");
}
- String basePath = UnitLoader.DEFAULT_REPO_BASE_PATH + "/" + slingSettings.getSlingId() + "/sightly/";
- eventHandlerFilteredPaths.append("(path=").append(basePath).append("**/*.java))");
+ eventHandlerFilteredPaths.append(")");
Dictionary eventHandlerProperties = new Hashtable();
eventHandlerProperties.put(EventConstants.EVENT_FILTER, eventHandlerFilteredPaths.toString());
eventHandlerProperties.put(EventConstants.EVENT_TOPIC, new String[]{SlingConstants.TOPIC_RESOURCE_ADDED, SlingConstants
@@ -153,6 +133,7 @@ public class UnitChangeMonitor {
}
@Deactivate
+ @SuppressWarnings("unused")
protected void deactivate(ComponentContext componentContext) {
if (eventHandlerServiceRegistration != null) {
eventHandlerServiceRegistration.unregister();
@@ -163,24 +144,16 @@ public class UnitChangeMonitor {
String path = (String) event.getProperty(SlingConstants.PROPERTY_PATH);
String topic = event.getTopic();
if (SlingConstants.TOPIC_RESOURCE_ADDED.equals(topic) || SlingConstants.TOPIC_RESOURCE_CHANGED.equals(topic)) {
- if (path.startsWith(UnitLoader.DEFAULT_REPO_BASE_PATH)) {
- slySourcesMap.put(path, System.currentTimeMillis());
- } else {
- if (path.endsWith(".java")) {
- slyJavaUseMap.put(path, System.currentTimeMillis());
- } else if (path.endsWith(SightlyScriptEngineFactory.EXTENSION)) {
- slyScriptsMap.put(path, System.currentTimeMillis());
- }
+ if (path.endsWith(".java")) {
+ slyJavaUseMap.put(path, System.currentTimeMillis());
+ } else if (path.endsWith(SightlyScriptEngineFactory.EXTENSION)) {
+ slyScriptsMap.put(path, System.currentTimeMillis());
}
} else if (SlingConstants.TOPIC_RESOURCE_REMOVED.equals(topic)) {
- if (path.startsWith(UnitLoader.DEFAULT_REPO_BASE_PATH)) {
- slySourcesMap.remove(path);
- } else {
- if (path.endsWith(".java")) {
- slyJavaUseMap.remove(path);
- } else if (path.endsWith(SightlyScriptEngineFactory.EXTENSION)) {
- slyScriptsMap.remove(path);
- }
+ if (path.endsWith(".java")) {
+ slyJavaUseMap.remove(path);
+ } else if (path.endsWith(SightlyScriptEngineFactory.EXTENSION)) {
+ slyScriptsMap.remove(path);
}
}
}
Modified: sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/UnitLoader.java
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/UnitLoader.java?rev=1677848&r1=1677847&r2=1677848&view=diff
==============================================================================
--- sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/UnitLoader.java (original)
+++ sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/UnitLoader.java Tue May 5 16:04:32 2015
@@ -18,16 +18,10 @@
******************************************************************************/
package org.apache.sling.scripting.sightly.impl.engine;
-import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
-import java.util.Calendar;
-import java.util.HashMap;
import java.util.Map;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-
import javax.script.Bindings;
import org.apache.commons.io.IOUtils;
@@ -38,13 +32,11 @@ import org.apache.felix.scr.annotations.
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletResponse;
-import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceMetadata;
import org.apache.sling.api.resource.ResourceResolver;
-import org.apache.sling.api.resource.ResourceResolverFactory;
-import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.api.scripting.SlingBindings;
+import org.apache.sling.commons.classloader.ClassLoaderWriter;
import org.apache.sling.scripting.sightly.SightlyException;
import org.apache.sling.scripting.sightly.impl.compiled.CompilationOutput;
import org.apache.sling.scripting.sightly.impl.compiled.JavaClassBackend;
@@ -56,7 +48,6 @@ import org.apache.sling.scripting.sightl
import org.apache.sling.scripting.sightly.impl.engine.compiled.SourceIdentifier;
import org.apache.sling.scripting.sightly.impl.engine.runtime.RenderContextImpl;
import org.apache.sling.scripting.sightly.impl.engine.runtime.RenderUnit;
-import org.apache.sling.settings.SlingSettingsService;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -68,25 +59,14 @@ import org.slf4j.LoggerFactory;
@Service(UnitLoader.class)
public class UnitLoader {
- public static final String DEFAULT_REPO_BASE_PATH = "/var/classes";
public static final String CLASS_NAME_PREFIX = "SightlyJava_";
private static final Logger log = LoggerFactory.getLogger(UnitLoader.class);
private static final String MAIN_TEMPLATE_PATH = "templates/compiled_unit_template.txt";
private static final String CHILD_TEMPLATE_PATH = "templates/subtemplate.txt";
- private static final String NT_FOLDER = "nt:folder";
- private static final String NT_FILE = "nt:file";
- private static final String NT_RESOURCE = "nt:resource";
- private static final String JCR_PRIMARY_TYPE = "jcr:primaryType";
- private static final String JCR_CONTENT = "jcr:content";
- private static final String JCR_DATA = "jcr:data";
- private static final String JCR_LASTMODIFIED = "jcr:lastModified";
-
private String mainTemplate;
private String childTemplate;
- private final Map<String, Lock> activeWrites = new HashMap<String, Lock>();
-
@Reference
private SightlyCompilerService sightlyCompilerService = null;
@@ -97,10 +77,7 @@ public class UnitLoader {
private SightlyEngineConfiguration sightlyEngineConfiguration = null;
@Reference
- private ResourceResolverFactory rrf = null;
-
- @Reference
- private SlingSettingsService slingSettings = null;
+ private ClassLoaderWriter classLoaderWriter = null;
@Reference
private UnitChangeMonitor unitChangeMonitor = null;
@@ -113,43 +90,28 @@ public class UnitLoader {
* @param renderContext the rendering context
* @return the render unit
*/
- public RenderUnit createUnit(Resource scriptResource, Bindings bindings, RenderContextImpl renderContext) {
- Lock lock = null;
- try {
- SourceIdentifier sourceIdentifier = obtainIdentifier(scriptResource);
- Object obj;
- ResourceMetadata resourceMetadata = scriptResource.getResourceMetadata();
- String encoding = resourceMetadata.getCharacterEncoding();
- if (encoding == null) {
- encoding = sightlyEngineConfiguration.getEncoding();
- }
- SlingHttpServletResponse response = (SlingHttpServletResponse) bindings.get(SlingBindings.RESPONSE);
- response.setCharacterEncoding(encoding);
- ResourceResolver adminResolver = renderContext.getScriptResourceResolver();
- if (needsUpdate(sourceIdentifier)) {
- synchronized (activeWrites) {
- String sourceFullPath = sourceIdentifier.getSourceFullPath();
- lock = activeWrites.get(sourceFullPath);
- if (lock == null) {
- lock = new ReentrantLock();
- activeWrites.put(sourceFullPath, lock);
- }
- lock.lock();
- }
- Resource javaClassResource = createClass(adminResolver, sourceIdentifier, bindings, encoding, renderContext);
- obj = sightlyJavaCompilerService.compileSource(javaClassResource, sourceIdentifier.getFullyQualifiedName());
- } else {
- obj = sightlyJavaCompilerService.getInstance(adminResolver, null, sourceIdentifier.getFullyQualifiedName());
- }
- if (!(obj instanceof RenderUnit)) {
- throw new SightlyException("Class is not a RenderUnit instance");
- }
- return (RenderUnit) obj;
- } finally {
- if (lock != null) {
- lock.unlock();
- }
+ public RenderUnit createUnit(Resource scriptResource, Bindings bindings, RenderContextImpl renderContext) throws Exception {
+ ResourceMetadata resourceMetadata = scriptResource.getResourceMetadata();
+ String encoding = resourceMetadata.getCharacterEncoding();
+ if (encoding == null) {
+ encoding = sightlyEngineConfiguration.getEncoding();
+ }
+ SlingHttpServletResponse response = (SlingHttpServletResponse) bindings.get(SlingBindings.RESPONSE);
+ response.setCharacterEncoding(encoding);
+ ResourceResolver adminResolver = renderContext.getScriptResourceResolver();
+ SourceIdentifier sourceIdentifier = obtainIdentifier(scriptResource);
+ Object obj;
+ if (needsUpdate(sourceIdentifier)) {
+ String sourceCode = getSourceCodeForScript(adminResolver, sourceIdentifier, bindings, encoding, renderContext);
+ obj = sightlyJavaCompilerService.compileSource(sourceCode, sourceIdentifier
+ .getFullyQualifiedName());
+ } else {
+ obj = sightlyJavaCompilerService.getInstance(adminResolver, null, sourceIdentifier.getFullyQualifiedName());
}
+ if (!(obj instanceof RenderUnit)) {
+ throw new SightlyException("Class is not a RenderUnit instance");
+ }
+ return (RenderUnit) obj;
}
@Activate
@@ -157,70 +119,20 @@ public class UnitLoader {
protected void activate(ComponentContext componentContext) {
mainTemplate = resourceFile(componentContext, MAIN_TEMPLATE_PATH);
childTemplate = resourceFile(componentContext, CHILD_TEMPLATE_PATH);
- String basePath =
- DEFAULT_REPO_BASE_PATH + "/" + slingSettings.getSlingId() + "/sightly/";
- ResourceResolver adminResolver = null;
- try {
- adminResolver = rrf.getAdministrativeResourceResolver(null);
- Resource basePathResource;
- if ((basePathResource = adminResolver.getResource(basePath)) != null) {
- for (Resource resource : basePathResource.getChildren()) {
- if (!resource.getName().equals(sightlyEngineConfiguration.getEngineVersion())) {
- adminResolver.delete(resource);
- }
- }
- if (adminResolver.hasChanges()) {
- adminResolver.commit();
- }
- }
- } catch (Exception e) {
- log.error("Cannot delete stale Sightly Java classes.", e);
- } finally {
- if (adminResolver != null) {
- adminResolver.close();
- }
- }
- }
-
- private synchronized Resource writeSource(ResourceResolver resolver, String sourceFullPath, String source) {
- Resource sourceResource;
- try {
- String sourceParentPath = ResourceUtil.getParent(sourceFullPath);
- Map<String, Object> sourceFolderProperties = new HashMap<String, Object>();
- sourceFolderProperties.put(JCR_PRIMARY_TYPE, NT_FOLDER);
- createResource(resolver, sourceParentPath, sourceFolderProperties, NT_FOLDER, true, false);
-
- Map<String, Object> sourceFileProperties = new HashMap<String, Object>();
- sourceFileProperties.put(JCR_PRIMARY_TYPE, NT_FILE);
- sourceResource = createResource(resolver, sourceFullPath, sourceFileProperties, null, false, false);
-
- Map<String, Object> ntResourceProperties = new HashMap<String, Object>();
- ntResourceProperties.put(JCR_PRIMARY_TYPE, NT_RESOURCE);
- ntResourceProperties.put(JCR_DATA, new ByteArrayInputStream(source.getBytes()));
- ntResourceProperties.put(JCR_LASTMODIFIED, Calendar.getInstance());
- createResource(resolver, sourceFullPath + "/" + JCR_CONTENT, ntResourceProperties, NT_RESOURCE, true, true);
- log.debug("Successfully written Java source file to repository: {}", sourceFullPath);
- } catch (PersistenceException e) {
- throw new SightlyException("Repository error while writing Java source file: " + sourceFullPath, e);
- }
- return sourceResource;
}
private SourceIdentifier obtainIdentifier(Resource resource) {
- String basePath =
- DEFAULT_REPO_BASE_PATH + "/" + slingSettings.getSlingId() + "/sightly/" + sightlyEngineConfiguration.getEngineVersion();
- return new SourceIdentifier(resource, CLASS_NAME_PREFIX, basePath);
+ return new SourceIdentifier(resource, CLASS_NAME_PREFIX);
}
- private Resource createClass(ResourceResolver resolver, SourceIdentifier identifier, Bindings bindings, String encoding,
+ private String getSourceCodeForScript(ResourceResolver resolver, SourceIdentifier identifier, Bindings bindings, String encoding,
RenderContextImpl renderContext) {
String scriptSource = null;
try {
Resource scriptResource = resolver.getResource(identifier.getResource().getPath());
if (scriptResource != null) {
scriptSource = IOUtils.toString(scriptResource.adaptTo(InputStream.class), encoding);
- String javaSourceCode = obtainResultSource(scriptSource, identifier, bindings, renderContext);
- return writeSource(resolver, identifier.getSourceFullPath(), javaSourceCode);
+ return obtainResultSource(scriptSource, identifier, bindings, renderContext);
}
} catch (SightlyParsingException e) {
String offendingInput = e.getOffendingInput();
@@ -312,8 +224,9 @@ public class UnitLoader {
return true;
}
String slyPath = sourceIdentifier.getResource().getPath();
- long javaFileDate = unitChangeMonitor.getLastModifiedDateForJavaSourceFile(sourceIdentifier.getSourceFullPath());
- if (javaFileDate != 0) {
+ String javaCompilerPath = "/" + sourceIdentifier.getFullyQualifiedName().replaceAll("\\.", "/") + ".class";
+ long javaFileDate = classLoaderWriter.getLastModified(javaCompilerPath);
+ if (javaFileDate > -1) {
long slyScriptChangeDate = unitChangeMonitor.getLastModifiedDateForScript(slyPath);
if (slyScriptChangeDate != 0) {
if (slyScriptChangeDate < javaFileDate) {
@@ -328,54 +241,4 @@ public class UnitLoader {
return true;
}
- private Resource createResource(ResourceResolver resolver, String path, Map<String, Object> resourceProperties, String intermediateType,
- boolean autoCommit, boolean forceOverwrite) throws PersistenceException {
- Resource rsrc = resolver.getResource(path);
- if (rsrc == null || forceOverwrite) {
- final int lastPos = path.lastIndexOf('/');
- final String name = path.substring(lastPos + 1);
-
- final Resource parentResource;
- if (lastPos == 0) {
- parentResource = resolver.getResource("/");
- } else {
- final String parentPath = path.substring(0, lastPos);
- Map<String, Object> parentProperties = new HashMap<String, Object>();
- parentProperties.put(JCR_PRIMARY_TYPE, intermediateType);
- parentResource = createResource(resolver, parentPath, parentProperties, intermediateType, autoCommit, false);
- }
- if (autoCommit) {
- resolver.refresh();
- }
- if (forceOverwrite) {
- Resource resource = resolver.getResource(parentResource, name);
- if (resource != null) {
- resolver.delete(resource);
- }
- }
- try {
- rsrc = resolver.create(parentResource, name, resourceProperties);
- if (autoCommit) {
- resolver.commit();
- resolver.refresh();
- rsrc = resolver.getResource(parentResource, name);
- }
- } catch (PersistenceException pe) {
- resolver.revert();
- resolver.refresh();
- rsrc = resolver.getResource(parentResource, name);
- if (rsrc == null) {
- rsrc = resolver.create(parentResource, name, resourceProperties);
- }
- } finally {
- if (autoCommit) {
- resolver.commit();
- resolver.refresh();
- rsrc = resolver.getResource(parentResource, name);
- }
- }
- }
- return rsrc;
- }
-
}
Modified: sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SourceIdentifier.java
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SourceIdentifier.java?rev=1677848&r1=1677847&r2=1677848&view=diff
==============================================================================
--- sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SourceIdentifier.java (original)
+++ sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SourceIdentifier.java Tue May 5 16:04:32 2015
@@ -31,16 +31,12 @@ public class SourceIdentifier {
private final String className;
private final Resource resource;
private final String packageName;
- private final String sourceFileName;
- private final String sourceFullPath;
private final String fullyQualifiedName;
- public SourceIdentifier(Resource resource, String classNamePrefix, String basePath) {
+ public SourceIdentifier(Resource resource, String classNamePrefix) {
this.resource = resource;
this.className = buildClassName(resource, classNamePrefix);
this.packageName = buildPackageName(resource);
- this.sourceFileName = buildSourceFileName(this.className);
- this.sourceFullPath = buildSourceFullPath(resource, basePath, this.sourceFileName);
this.fullyQualifiedName = buildFullyQualifiedName(packageName, className);
}
@@ -56,14 +52,6 @@ public class SourceIdentifier {
return packageName;
}
- public String getSourceFileName() {
- return sourceFileName;
- }
-
- public String getSourceFullPath() {
- return sourceFullPath;
- }
-
public String getFullyQualifiedName() {
return fullyQualifiedName;
}
@@ -86,15 +74,6 @@ public class SourceIdentifier {
.replaceAll("-", "_");
}
- private String buildSourceFileName(String className) {
- return className + ".java";
- }
-
- private String buildSourceFullPath(Resource resource, String basePath, String sourceFileName) {
- String sourceParentPath = basePath + ResourceUtil.getParent(resource.getPath());
- return sourceParentPath + "/" + sourceFileName;
- }
-
private String getExtension(String scriptName) {
if (StringUtils.isEmpty(scriptName)) {
return null;
Modified: sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/RenderUnitProvider.java
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/RenderUnitProvider.java?rev=1677848&r1=1677847&r2=1677848&view=diff
==============================================================================
--- sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/RenderUnitProvider.java (original)
+++ sling/trunk/contrib/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/RenderUnitProvider.java Tue May 5 16:04:32 2015
@@ -82,8 +82,12 @@ public class RenderUnitProvider implemen
errorMessage.append(".");
return ProviderOutcome.failure(new SightlyException(errorMessage.toString()));
}
- RenderUnit renderUnit = unitLoader.createUnit(renderUnitResource, globalBindings, (RenderContextImpl) renderContext);
- return ProviderOutcome.success(renderUnit);
+ try {
+ RenderUnit renderUnit = unitLoader.createUnit(renderUnitResource, globalBindings, (RenderContextImpl) renderContext);
+ return ProviderOutcome.success(renderUnit);
+ } catch (Exception e) {
+ return ProviderOutcome.failure(e);
+ }
}
return ProviderOutcome.failure();
}
Modified: sling/trunk/contrib/scripting/sightly/engine/src/test/java/org/apache/sling/scripting/sightly/impl/compiler/SightlyJavaCompilerServiceTest.java
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/scripting/sightly/engine/src/test/java/org/apache/sling/scripting/sightly/impl/compiler/SightlyJavaCompilerServiceTest.java?rev=1677848&r1=1677847&r2=1677848&view=diff
==============================================================================
--- sling/trunk/contrib/scripting/sightly/engine/src/test/java/org/apache/sling/scripting/sightly/impl/compiler/SightlyJavaCompilerServiceTest.java (original)
+++ sling/trunk/contrib/scripting/sightly/engine/src/test/java/org/apache/sling/scripting/sightly/impl/compiler/SightlyJavaCompilerServiceTest.java Tue May 5 16:04:32 2015
@@ -18,16 +18,19 @@
******************************************************************************/
package org.apache.sling.scripting.sightly.impl.compiler;
+import java.io.InputStream;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
+import org.apache.commons.io.IOUtils;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.commons.compiler.CompilationResult;
+import org.apache.sling.commons.compiler.CompilationUnit;
import org.apache.sling.commons.compiler.CompilerMessage;
+import org.apache.sling.commons.compiler.JavaCompiler;
import org.apache.sling.commons.compiler.Options;
-import org.apache.sling.jcr.compiler.JcrJavaCompiler;
import org.apache.sling.scripting.sightly.impl.engine.UnitChangeMonitor;
import org.junit.After;
import org.junit.Before;
@@ -38,6 +41,7 @@ import org.mockito.stubbing.Answer;
import org.powermock.reflect.Whitebox;
import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.any;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -97,17 +101,18 @@ public class SightlyJavaCompilerServiceT
Resource pojoResource = Mockito.mock(Resource.class);
ResourceResolver resolver = Mockito.mock(ResourceResolver.class);
when(resolver.getResource(pojoPath)).thenReturn(pojoResource);
- JcrJavaCompiler jcrJavaCompiler = Mockito.mock(JcrJavaCompiler.class);
+ when(pojoResource.adaptTo(InputStream.class)).thenReturn(IOUtils.toInputStream("DUMMY"));
+ JavaCompiler javaCompiler = Mockito.mock(JavaCompiler.class);
CompilationResult compilationResult = Mockito.mock(CompilationResult.class);
when(compilationResult.getErrors()).thenReturn(new ArrayList<CompilerMessage>());
- when(jcrJavaCompiler.compile(Mockito.any(String[].class), Mockito.any(Options.class))).thenReturn(compilationResult);
+ when(javaCompiler.compile(Mockito.any(CompilationUnit[].class), Mockito.any(Options.class))).thenReturn(compilationResult);
when(compilationResult.loadCompiledClass(className)).thenAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return MockPojo.class;
}
});
- Whitebox.setInternalState(compiler, "jcrJavaCompiler", jcrJavaCompiler);
+ Whitebox.setInternalState(compiler, "javaCompiler", javaCompiler);
Object obj = compiler.getInstance(resolver, null, className);
assertTrue("Expected to obtain a " + MockPojo.class.getName() + " object.", obj instanceof MockPojo);
}
Modified: sling/trunk/contrib/scripting/sightly/testing/pom.xml
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/scripting/sightly/testing/pom.xml?rev=1677848&r1=1677847&r2=1677848&view=diff
==============================================================================
--- sling/trunk/contrib/scripting/sightly/testing/pom.xml (original)
+++ sling/trunk/contrib/scripting/sightly/testing/pom.xml Tue May 5 16:04:32 2015
@@ -64,6 +64,14 @@
-->
<integration.test.wait>false</integration.test.wait>
+ <!--
+ if set to "true" this will start the launchpad with the following debug options:
+ -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000
+
+ otherwise you can provide your own debug settings
+ -->
+ <debug.options/>
+
<slf4j.version>1.7.7</slf4j.version>
<logback.version>1.1.2</logback.version>
</properties>
@@ -141,7 +149,7 @@
<plugin>
<groupId>org.apache.sling</groupId>
<artifactId>slingstart-maven-plugin</artifactId>
- <version>1.1.0</version>
+ <version>1.1.1-SNAPSHOT</version>
<extensions>true</extensions>
<executions>
<execution>
@@ -159,6 +167,7 @@
<controlPort>${sling.control.port}</controlPort>
<runmode>jackrabbit</runmode>
<contextPath>${http.base.path}</contextPath>
+ <debug>${debug.options}</debug>
</server>
</servers>
<!-- TODO
Modified: sling/trunk/contrib/scripting/sightly/testing/src/main/provisioning/model.txt
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/scripting/sightly/testing/src/main/provisioning/model.txt?rev=1677848&r1=1677847&r2=1677848&view=diff
==============================================================================
--- sling/trunk/contrib/scripting/sightly/testing/src/main/provisioning/model.txt (original)
+++ sling/trunk/contrib/scripting/sightly/testing/src/main/provisioning/model.txt Tue May 5 16:04:32 2015
@@ -20,8 +20,7 @@
# Dependencies
[artifacts]
org.apache.sling/org.apache.sling.launchpad/8-SNAPSHOT/slingstart
- org.apache.sling/org.apache.sling.launchpad.installer/1.2.2
- org.apache.sling/org.apache.sling.jcr.compiler/2.1.0
+ org.apache.sling/org.apache.sling.commons.fsclassloader/1.0.0
org.apache.sling/org.apache.sling.i18n/2.2.10
javax.mail/mail/1.4.7
org.apache.sling/org.apache.sling.xss/1.0.2