incubator-sling-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From cziege...@apache.org
Subject svn commit: r687373 [2/2] - in /incubator/sling/trunk: ./ scripting/java/ scripting/java/src/ scripting/java/src/main/ scripting/java/src/main/java/ scripting/java/src/main/java/org/ scripting/java/src/main/java/org/apache/ scripting/java/src/main/java...
Date Wed, 20 Aug 2008 15:22:11 GMT
Added: incubator/sling/trunk/scripting/java/src/main/java/org/apache/sling/scripting/java/SlingIOProvider.java
URL: http://svn.apache.org/viewvc/incubator/sling/trunk/scripting/java/src/main/java/org/apache/sling/scripting/java/SlingIOProvider.java?rev=687373&view=auto
==============================================================================
--- incubator/sling/trunk/scripting/java/src/main/java/org/apache/sling/scripting/java/SlingIOProvider.java
(added)
+++ incubator/sling/trunk/scripting/java/src/main/java/org/apache/sling/scripting/java/SlingIOProvider.java
Wed Aug 20 08:22:10 2008
@@ -0,0 +1,369 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sling.scripting.java;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+import java.util.StringTokenizer;
+
+import javax.jcr.Item;
+import javax.jcr.Node;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
+import org.apache.sling.api.SlingException;
+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.jcr.api.SlingRepository;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * The <code>SlingIOProvider</code> TODO
+ */
+public class SlingIOProvider  {
+
+    /** default log */
+    private static final Logger log = LoggerFactory.getLogger(SlingIOProvider.class);
+
+    private final SlingRepository repository;
+
+    private ThreadLocal<ResourceResolver> requestResourceResolver;
+
+    // private session for write access
+    private ThreadLocal<Session> privateSession;
+
+    SlingIOProvider(SlingRepository repository) {
+        this.repository = repository;
+        this.requestResourceResolver = new ThreadLocal<ResourceResolver>();
+        this.privateSession = new ThreadLocal<Session>();
+    }
+
+    void setRequestResourceResolver(ResourceResolver resolver) {
+        requestResourceResolver.set(resolver);
+    }
+
+    void resetRequestResourceResolver() {
+        requestResourceResolver.remove();
+
+        // at the same time logout this thread's session
+        Session session = privateSession.get();
+        if (session != null) {
+            if (session.isLive()) {
+                session.logout();
+            }
+            privateSession.remove();
+        }
+    }
+
+    // ---------- IOProvider interface -----------------------------------------
+
+    /**
+     * Returns an InputStream for the file name which is looked up with the
+     * ResourceProvider and retrieved from the Resource if the StreamProvider
+     * interface is implemented.
+     */
+    public InputStream getInputStream(String fileName)
+    throws FileNotFoundException, IOException {
+
+        try {
+
+            Resource resource = getResourceInternal(fileName);
+            if (resource == null) {
+                throw new FileNotFoundException("Cannot find " + fileName);
+            }
+
+            InputStream stream = resource.adaptTo(InputStream.class);
+            if (stream == null) {
+                throw new FileNotFoundException("Cannot find " + fileName);
+            }
+
+            return stream;
+
+        } catch (SlingException se) {
+            throw (IOException) new IOException(
+                "Failed to get InputStream for " + fileName).initCause(se);
+        }
+    }
+
+    /**
+     * Returns the value of the last modified meta data field of the resource
+     * found at file name or zero if the meta data field is not set. If the
+     * resource does not exist or an error occurrs finding the resource, -1 is
+     * returned.
+     */
+    public long lastModified(String fileName) {
+        try {
+            Resource resource = getResourceInternal(fileName);
+            if (resource != null) {
+                ResourceMetadata meta = resource.getResourceMetadata();
+                long modTime = meta.getModificationTime();
+                return (modTime > 0) ? modTime : 0;
+            }
+
+        } catch (SlingException se) {
+            log.error("Cannot get last modification time for " + fileName, se);
+        }
+
+        // fallback to "non-existant" in case of problems
+        return -1;
+    }
+
+    /**
+     * Removes the named item from the repository.
+     */
+    public boolean delete(String fileName) {
+        Node parentNode = null;
+        try {
+            fileName = cleanPath(fileName);
+            Session session = getPrivateSession();
+            if (session.itemExists(fileName)) {
+                Item fileItem = session.getItem(fileName);
+                parentNode = fileItem.getParent();
+                fileItem.remove();
+                parentNode.save();
+                return true;
+            }
+        } catch (RepositoryException re) {
+            log.error("Cannot remove " + fileName, re);
+        } finally {
+            checkNode(parentNode, fileName);
+        }
+
+        // fall back to false if item does not exist or in case of error
+        return false;
+    }
+
+    /**
+     * Returns an output stream to write to the repository.
+     */
+    public OutputStream getOutputStream(String fileName) {
+        fileName = cleanPath(fileName);
+        return new RepositoryOutputStream(this, fileName);
+    }
+
+    /* package */URL getURL(String path) throws MalformedURLException {
+        try {
+            Resource resource = getResourceInternal(path);
+            return (resource != null) ? resource.adaptTo(URL.class) : null;
+        } catch (SlingException se) {
+            throw (MalformedURLException) new MalformedURLException(
+                "Cannot get URL for " + path).initCause(se);
+        }
+    }
+
+    /* package */Set<String> getResourcePaths(String path) {
+        Set<String> paths = new HashSet<String>();
+
+        ResourceResolver resolver = requestResourceResolver.get();
+        if (resolver != null) {
+            try {
+                Resource resource = resolver.getResource(cleanPath(path));
+                if (resource != null) {
+                    Iterator<Resource> entries = resolver.listChildren(resource);
+                    while (entries.hasNext()) {
+                        paths.add(entries.next().getPath());
+                    }
+                }
+            } catch (SlingException se) {
+                log.warn("getResourcePaths: Cannot list children of " + path,
+                    se);
+            }
+        }
+
+        return paths.isEmpty() ? null : paths;
+    }
+
+    private Resource getResourceInternal(String path) throws SlingException {
+        ResourceResolver resolver = requestResourceResolver.get();
+        if (resolver != null) {
+            return resolver.getResource(cleanPath(path));
+        }
+
+        return null;
+    }
+
+    // ---------- internal -----------------------------------------------------
+
+    private Session getPrivateSession() throws RepositoryException {
+        Session session = privateSession.get();
+        if (session == null) {
+            session = repository.loginAdministrative(null);
+            privateSession.set(session);
+        }
+
+        return session;
+    }
+
+    private static void checkNode(Node node, String path) {
+        if (node != null && node.isModified()) {
+            try {
+                node.refresh(false);
+            } catch (RepositoryException re) {
+                log.error("Cannot refresh node for " + path
+                    + " after failed save", re);
+            }
+        }
+    }
+
+    private String cleanPath(String path) {
+        // replace backslash by slash
+        path = path.replace('\\', '/');
+
+        // cut off trailing slash
+        while (path.endsWith("/")) {
+            path = path.substring(0, path.length() - 1);
+        }
+
+        return path;
+    }
+
+    private static class RepositoryOutputStream extends ByteArrayOutputStream {
+
+        private final SlingIOProvider repositoryOutputProvider;
+
+        private final String fileName;
+
+        RepositoryOutputStream(SlingIOProvider repositoryOutputProvider,
+                String fileName) {
+            this.repositoryOutputProvider = repositoryOutputProvider;
+            this.fileName = fileName;
+        }
+
+        public void close() throws IOException {
+            super.close();
+
+            Node parentNode = null;
+            try {
+                Session session = repositoryOutputProvider.getPrivateSession();
+                Node fileNode = null;
+                Node contentNode = null;
+                if (session.itemExists(fileName)) {
+                    Item item = session.getItem(fileName);
+                    if (item.isNode()) {
+                        Node node = item.isNode()
+                                ? (Node) item
+                                : item.getParent();
+                        if ("jcr:content".equals(node.getName())) {
+                            // replace the content properties of the jcr:content
+                            // node
+                            parentNode = node;
+                            contentNode = node;
+                        } else if (node.isNodeType("nt:file")) {
+                            // try to set the content properties of jcr:content
+                            // node
+                            parentNode = node;
+                            contentNode = node.getNode("jcr:content");
+                        } else { // fileName is a node
+                            // try to set the content properties of the node
+                            parentNode = node;
+                            contentNode = node;
+                        }
+                    } else {
+                        // replace property with an nt:file node (if possible)
+                        parentNode = item.getParent();
+                        String name = item.getName();
+                        fileNode = parentNode.addNode(name, "nt:file");
+                        item.remove();
+                    }
+                } else {
+                    fileNode = createPath(fileName, "nt:folder", "nt:file", session);
+                    parentNode = session.getRootNode();
+                }
+
+                // if we have a file node, create the contentNode
+                if (fileNode != null) {
+                    contentNode = fileNode.addNode("jcr:content", "nt:resource");
+                }
+
+                contentNode.setProperty("jcr:lastModified",
+                    System.currentTimeMillis());
+                contentNode.setProperty("jcr:data", new ByteArrayInputStream(
+                    buf, 0, size()));
+                contentNode.setProperty("jcr:mimeType",
+                    "application/octet-stream");
+
+                parentNode.save();
+            } catch (RepositoryException re) {
+                log.error("Cannot write file " + fileName, re);
+                throw new IOException("Cannot write file " + fileName
+                    + ", reason: " + re.toString());
+            } finally {
+                checkNode(parentNode, fileName);
+            }
+        }
+    }
+
+    /**
+     * Creates or gets the {@link javax.jcr.Node Node} at the given Path.
+     * In case it has to create the Node all non-existent intermediate path-elements
+     * will be create with the given intermediate node type and the returned node
+     * will be created with the given nodeType
+     *
+     * @param path to create
+     * @param intermediateNodeType to use for creation of intermediate nodes
+     * @param nodeType to use for creation of the final node
+     * @param session to use
+     * @return the Node at path
+     * @throws RepositoryException in case of exception accessing the Repository
+     */
+    private static Node createPath(String path,
+                                  String intermediateNodeType,
+                                  String nodeType,
+                                  Session session)
+            throws RepositoryException {
+        if (path == null || path.length() == 0 || "/".equals(path)) {
+            return session.getRootNode();
+        } else if (!session.itemExists(path)) {
+            Node node = session.getRootNode();
+            path = path.substring(1);
+            int pos = path.lastIndexOf('/');
+            if ( pos != -1 ) {
+                final StringTokenizer st = new StringTokenizer(path.substring(0, pos), "/");
+                while ( st.hasMoreTokens() ) {
+                    final String token = st.nextToken();
+                    if ( !node.hasNode(token) ) {
+                        try {
+                            node.addNode(token, intermediateNodeType);
+                        } catch (RepositoryException re) {
+                            // we ignore this as this folder might be created from a different
task
+                            node.refresh(false);
+                        }
+                    }
+                    node = node.getNode(token);
+                }
+                path = path.substring(pos + 1);
+            }
+            if ( !node.hasNode(path) ) {
+                node.addNode(path, nodeType);
+            }
+            return node.getNode(path);
+        } else {
+            return (Node) session.getItem(path);
+        }
+    }
+}

Propchange: incubator/sling/trunk/scripting/java/src/main/java/org/apache/sling/scripting/java/SlingIOProvider.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: incubator/sling/trunk/scripting/java/src/main/java/org/apache/sling/scripting/java/SlingIOProvider.java
------------------------------------------------------------------------------
    svn:keywords = author date id revision rev url

Propchange: incubator/sling/trunk/scripting/java/src/main/java/org/apache/sling/scripting/java/SlingIOProvider.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: incubator/sling/trunk/scripting/java/src/main/java/org/apache/sling/scripting/java/jdt/CompilationUnit.java
URL: http://svn.apache.org/viewvc/incubator/sling/trunk/scripting/java/src/main/java/org/apache/sling/scripting/java/jdt/CompilationUnit.java?rev=687373&view=auto
==============================================================================
--- incubator/sling/trunk/scripting/java/src/main/java/org/apache/sling/scripting/java/jdt/CompilationUnit.java
(added)
+++ incubator/sling/trunk/scripting/java/src/main/java/org/apache/sling/scripting/java/jdt/CompilationUnit.java
Wed Aug 20 08:22:10 2008
@@ -0,0 +1,282 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sling.scripting.java.jdt;
+
+import java.io.BufferedOutputStream;
+import java.io.BufferedReader;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.Reader;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.StringTokenizer;
+
+import org.apache.sling.scripting.java.CompilerError;
+import org.apache.sling.scripting.java.Options;
+import org.apache.sling.scripting.java.SlingIOProvider;
+import org.eclipse.jdt.core.compiler.IProblem;
+import org.eclipse.jdt.internal.compiler.ClassFile;
+import org.eclipse.jdt.internal.compiler.CompilationResult;
+import org.eclipse.jdt.internal.compiler.ICompilerRequestor;
+import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;
+import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
+import org.eclipse.jdt.internal.compiler.env.INameEnvironment;
+import org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer;
+
+
+public class CompilationUnit
+    implements ICompilationUnit, INameEnvironment, ICompilerRequestor {
+
+    private final Options options;
+    private final SlingIOProvider ioProvider;
+    private final String className;
+    private final String sourceFile;
+
+    /** The list of compile errors. */
+    private final List<CompilerError> errors = new LinkedList<CompilerError>();
+
+    public CompilationUnit(String sourceFile,
+                           String className,
+                           Options options,
+                           SlingIOProvider ioProvider) {
+        this.className = className;
+        this.sourceFile = sourceFile;
+        this.ioProvider = ioProvider;
+        this.options = options;
+    }
+
+    /**
+     * @see org.eclipse.jdt.internal.compiler.env.IDependent#getFileName()
+     */
+    public char[] getFileName() {
+        return className.concat(".java").toCharArray();
+    }
+
+    /**
+     * @see org.eclipse.jdt.internal.compiler.env.ICompilationUnit#getContents()
+     */
+    public char[] getContents() {
+        char[] result = null;
+        InputStream fr = null;
+        try {
+            fr = ioProvider.getInputStream(this.sourceFile);
+            final Reader reader = new BufferedReader(new InputStreamReader(fr, this.options.getJavaEncoding()));
+            try {
+                char[] chars = new char[8192];
+                StringBuffer buf = new StringBuffer();
+                int count;
+                while ((count = reader.read(chars, 0, chars.length)) > 0) {
+                    buf.append(chars, 0, count);
+                }
+                result = new char[buf.length()];
+                buf.getChars(0, result.length, result, 0);
+            } finally {
+                reader.close();
+            }
+        } catch (IOException e) {
+            handleError(-1, -1, e.getMessage());
+        }
+        return result;
+    }
+
+    /**
+     * @see org.eclipse.jdt.internal.compiler.env.ICompilationUnit#getMainTypeName()
+     */
+    public char[] getMainTypeName() {
+        int dot = className.lastIndexOf('.');
+        if (dot > 0) {
+            return className.substring(dot + 1).toCharArray();
+        }
+        return className.toCharArray();
+    }
+
+    /**
+     * @see org.eclipse.jdt.internal.compiler.env.ICompilationUnit#getPackageName()
+     */
+    public char[][] getPackageName() {
+        StringTokenizer izer = new StringTokenizer(className.replace('/', '.'), ".");
+        char[][] result = new char[izer.countTokens()-1][];
+        for (int i = 0; i < result.length; i++) {
+            String tok = izer.nextToken();
+            result[i] = tok.toCharArray();
+        }
+        return result;
+    }
+
+    /**
+     * @see org.eclipse.jdt.internal.compiler.env.INameEnvironment#findType(char[][])
+     */
+    public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
+        StringBuffer result = new StringBuffer();
+        for (int i = 0; i < compoundTypeName.length; i++) {
+            if (i > 0) {
+                result.append(".");
+            }
+            result.append(compoundTypeName[i]);
+        }
+        return findType(result.toString());
+    }
+
+    /**
+     * @see org.eclipse.jdt.internal.compiler.env.INameEnvironment#findType(char[], char[][])
+     */
+    public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) {
+        StringBuffer result = new StringBuffer();
+        for (int i = 0; i < packageName.length; i++) {
+            if (i > 0) {
+                result.append(".");
+            }
+            result.append(packageName[i]);
+        }
+        result.append(".");
+        result.append(typeName);
+        return findType(result.toString());
+    }
+
+    /**
+     * @param className
+     * @return
+     */
+    private NameEnvironmentAnswer findType(String className) {
+        try {
+            if (className.equals(this.className)) {
+                ICompilationUnit compilationUnit = this;
+                return new NameEnvironmentAnswer(compilationUnit, null);
+            }
+            String resourceName = className.replace('.', '/') + ".class";
+            InputStream is = options.getClassLoader().getResourceAsStream(resourceName);
+            if (is != null) {
+                byte[] classBytes;
+                byte[] buf = new byte[8192];
+                ByteArrayOutputStream baos =
+                    new ByteArrayOutputStream(buf.length);
+                int count;
+                while ((count = is.read(buf, 0, buf.length)) > 0) {
+                    baos.write(buf, 0, count);
+                }
+                baos.flush();
+                classBytes = baos.toByteArray();
+                char[] fileName = className.toCharArray();
+                ClassFileReader classFileReader =
+                    new ClassFileReader(classBytes, fileName,
+                                        true);
+                return
+                    new NameEnvironmentAnswer(classFileReader, null);
+            }
+        } catch (IOException exc) {
+            handleError(-1, -1, exc.getMessage());
+        } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) {
+            handleError(-1, -1, exc.getMessage());
+        }
+        return null;
+    }
+
+    private boolean isPackage(String result) {
+        if (result.equals(this.className)) {
+            return false;
+        }
+        String resourceName = result.replace('.', '/') + ".class";
+        InputStream is = options.getClassLoader().getResourceAsStream(resourceName);
+        return is == null;
+    }
+
+    /**
+     * @see org.eclipse.jdt.internal.compiler.env.INameEnvironment#isPackage(char[][], char[])
+     */
+    public boolean isPackage(char[][] parentPackageName, char[] packageName) {
+        StringBuffer result = new StringBuffer();
+        if (parentPackageName != null) {
+            for (int i = 0; i < parentPackageName.length; i++) {
+                if (i > 0) {
+                    result.append(".");
+                }
+                result.append(parentPackageName[i]);
+            }
+        }
+        String str = new String(packageName);
+        if (Character.isUpperCase(str.charAt(0)) && !isPackage(result.toString()))
{
+                return false;
+        }
+        result.append(".");
+        result.append(str);
+        return isPackage(result.toString());
+    }
+
+    /**
+     * @see org.eclipse.jdt.internal.compiler.env.INameEnvironment#cleanup()
+     */
+    public void cleanup() {
+        // EMPTY
+    }
+
+    /**
+     * @see org.eclipse.jdt.internal.compiler.ICompilerRequestor#acceptResult(org.eclipse.jdt.internal.compiler.CompilationResult)
+     */
+    public void acceptResult(CompilationResult result) {
+        try {
+            if (result.hasErrors()) {
+                IProblem[] errors = result.getErrors();
+                for (int i = 0; i < errors.length; i++) {
+                    IProblem error = errors[i];
+                    handleError(error.getSourceLineNumber(), -1, error.getMessage());
+                }
+            } else {
+                ClassFile[] classFiles = result.getClassFiles();
+                for (int i = 0; i < classFiles.length; i++) {
+                    ClassFile classFile = classFiles[i];
+                    char[][] compoundName = classFile.getCompoundName();
+                    StringBuffer className = new StringBuffer();
+                    for (int j = 0;  j < compoundName.length; j++) {
+                        if (j > 0) {
+                            className.append(".");
+                        }
+                        className.append(compoundName[j]);
+                    }
+                    byte[] bytes = classFile.getBytes();
+                    final StringBuffer b = new StringBuffer(this.options.getDestinationPath());
+                    b.append('/');
+                    b.append(className.toString().replace('.', '/'));
+                    b.append(".class");
+                    OutputStream fout = ioProvider.getOutputStream(b.toString());
+                    BufferedOutputStream bos = new BufferedOutputStream(fout);
+                    bos.write(bytes);
+                    bos.close();
+                }
+            }
+        } catch (IOException exc) {
+            exc.printStackTrace();
+        }
+    }
+
+    private void handleError(int line, int column, Object errorMessage) {
+        if (column < 0) column = 0;
+        errors.add(new CompilerError(this.sourceFile,
+                                     true,
+                                     line,
+                                     column,
+                                     line,
+                                     column,
+                                     errorMessage.toString()));
+    }
+
+    public List<CompilerError> getErrors() throws IOException {
+        return errors;
+    }
+}

Propchange: incubator/sling/trunk/scripting/java/src/main/java/org/apache/sling/scripting/java/jdt/CompilationUnit.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: incubator/sling/trunk/scripting/java/src/main/java/org/apache/sling/scripting/java/jdt/CompilationUnit.java
------------------------------------------------------------------------------
    svn:keywords = author date id revision rev url

Propchange: incubator/sling/trunk/scripting/java/src/main/java/org/apache/sling/scripting/java/jdt/CompilationUnit.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: incubator/sling/trunk/scripting/java/src/main/java/org/apache/sling/scripting/java/jdt/EclipseJavaCompiler.java
URL: http://svn.apache.org/viewvc/incubator/sling/trunk/scripting/java/src/main/java/org/apache/sling/scripting/java/jdt/EclipseJavaCompiler.java?rev=687373&view=auto
==============================================================================
--- incubator/sling/trunk/scripting/java/src/main/java/org/apache/sling/scripting/java/jdt/EclipseJavaCompiler.java
(added)
+++ incubator/sling/trunk/scripting/java/src/main/java/org/apache/sling/scripting/java/jdt/EclipseJavaCompiler.java
Wed Aug 20 08:22:10 2008
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sling.scripting.java.jdt;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+import org.apache.sling.scripting.java.CompilationContext;
+import org.apache.sling.scripting.java.CompilerError;
+import org.apache.sling.scripting.java.Options;
+import org.apache.sling.scripting.java.SlingIOProvider;
+import org.eclipse.jdt.internal.compiler.Compiler;
+import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
+import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy;
+import org.eclipse.jdt.internal.compiler.IProblemFactory;
+import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
+import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
+
+/**
+ * Eclipse Java Compiler
+ *
+ * @version $Id$
+ */
+public class EclipseJavaCompiler {
+
+    /** The io provider. */
+    private final SlingIOProvider ioProvider;
+
+    /** The compiler options. */
+    private final Options compilerOptions;
+
+    /** The compilation context. */
+    private final CompilationContext context;
+
+    /**
+     * Construct a new java compiler.
+     * @param context
+     */
+    public EclipseJavaCompiler(final CompilationContext context) {
+        this.ioProvider = context.getIOProvider();
+        this.compilerOptions = context.getCompilerOptions();
+        this.context = context;
+    }
+
+    private CompilerOptions getCompilerOptions() {
+        CompilerOptions options = new CompilerOptions();
+        final Map<String, String> settings = new HashMap<String, String>();
+        settings.put(CompilerOptions.OPTION_LineNumberAttribute,
+                CompilerOptions.GENERATE);
+        settings.put(CompilerOptions.OPTION_SourceFileAttribute,
+                CompilerOptions.GENERATE);
+        settings.put(CompilerOptions.OPTION_ReportDeprecation,
+                CompilerOptions.IGNORE);
+        settings.put(CompilerOptions.OPTION_ReportUnusedImport, CompilerOptions.IGNORE);
+        settings.put(CompilerOptions.OPTION_Encoding, this.compilerOptions.getJavaEncoding());
+        if (this.compilerOptions.getClassDebugInfo()) {
+            settings.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE);
+        }
+        if ( this.compilerOptions.getCompilerSourceVM().equals("1.6") ) {
+            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_6);
+        } else {
+            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
+        }
+        if ( this.compilerOptions.getCompilerTargetVM().equals("1.6") ) {
+            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_6);
+            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6);
+        } else {
+            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5);
+            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
+        }
+
+        options.set(settings);
+        return options;
+    }
+
+    /**
+     * Compile the java class.
+     * @return null if no error occured, a list of errors otherwise.
+     * @throws IOException
+     */
+    public List<CompilerError> compile() throws IOException {
+        final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
+        final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
+        final CompilationUnit unit = new CompilationUnit(this.context.getSourcePath(),
+                 this.context.getJavaClassName(),
+                 this.context.getCompilerOptions(),
+                 this.ioProvider);
+
+        final Compiler compiler = new Compiler(unit,
+                                         policy,
+                                         getCompilerOptions(),
+                                         unit,
+                                         problemFactory);
+        compiler.compile(new CompilationUnit[] {unit});
+        if ( unit.getErrors().size() == 0 ) {
+            return null;
+        }
+        return unit.getErrors();
+    }
+
+}

Propchange: incubator/sling/trunk/scripting/java/src/main/java/org/apache/sling/scripting/java/jdt/EclipseJavaCompiler.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: incubator/sling/trunk/scripting/java/src/main/java/org/apache/sling/scripting/java/jdt/EclipseJavaCompiler.java
------------------------------------------------------------------------------
    svn:keywords = author date id revision rev url

Propchange: incubator/sling/trunk/scripting/java/src/main/java/org/apache/sling/scripting/java/jdt/EclipseJavaCompiler.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain



Mime
View raw message