Search in sources :

Example 6 with SCRDescriptorException

use of org.apache.felix.scrplugin.SCRDescriptorException in project felix by apache.

the class SCRDescriptorTask method execute.

@Override
public void execute() throws BuildException {
    // ensure we know the source
    if (getImplicitFileSet().getDir() == null) {
        throw new BuildException("srcdir attribute must be set!", getLocation());
    }
    // while debugging
    final org.apache.felix.scrplugin.Log scrLog = new AntLog(this);
    scrLog.debug("SCRDescriptorTask Configuration");
    scrLog.debug("  implicitFileset: " + getImplicitFileSet());
    scrLog.debug("  outputDirectory: " + destdir);
    scrLog.debug("  classpath: " + classpath);
    scrLog.debug("  generateAccessors: " + generateAccessors);
    scrLog.debug("  strictMode: " + strictMode);
    scrLog.debug("  specVersion: " + specVersion);
    try {
        final Path classPath = createClasspath();
        final org.apache.felix.scrplugin.Project project = new org.apache.felix.scrplugin.Project();
        project.setClassLoader(getClassLoader(this.getClass().getClassLoader()));
        project.setDependencies(getDependencies(classPath));
        project.setSources(getSourceFiles(getImplicitFileSet()));
        project.setClassesDirectory(destdir.getAbsolutePath());
        // create options
        final Options options = new Options();
        options.setOutputDirectory(destdir);
        options.setGenerateAccessors(generateAccessors);
        options.setStrictMode(strictMode);
        options.setProperties(new HashMap<String, String>());
        options.setSpecVersion(SpecVersion.fromName(specVersion));
        if (specVersion != null && options.getSpecVersion() == null) {
            throw new BuildException("Unknown spec version specified: " + specVersion);
        }
        final SCRDescriptorGenerator generator = new SCRDescriptorGenerator(scrLog);
        // setup from plugin configuration
        generator.setOptions(options);
        generator.setProject(project);
        generator.execute();
    } catch (final SCRDescriptorException sde) {
        if (sde.getSourceLocation() != null) {
            final Location loc = new Location(sde.getSourceLocation(), -1, 0);
            throw new BuildException(sde.getMessage(), sde.getCause(), loc);
        }
        throw new BuildException(sde.getMessage(), sde.getCause());
    } catch (SCRDescriptorFailureException sdfe) {
        throw new BuildException(sdfe.getMessage(), sdfe.getCause());
    }
}
Also used : Path(org.apache.tools.ant.types.Path) Options(org.apache.felix.scrplugin.Options) SCRDescriptorFailureException(org.apache.felix.scrplugin.SCRDescriptorFailureException) SCRDescriptorGenerator(org.apache.felix.scrplugin.SCRDescriptorGenerator) Project(org.apache.tools.ant.Project) BuildException(org.apache.tools.ant.BuildException) SCRDescriptorException(org.apache.felix.scrplugin.SCRDescriptorException) Location(org.apache.tools.ant.Location)

Example 7 with SCRDescriptorException

use of org.apache.felix.scrplugin.SCRDescriptorException in project felix by apache.

the class SCRDescriptorMojo method execute.

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    final String projectType = project.getArtifact().getType();
    // ignore unsupported project types, useful when bundleplugin is configured in parent pom
    if (!supportedProjectTypes.contains(projectType)) {
        getLog().debug("Ignoring project type " + projectType + " - supportedProjectTypes = " + supportedProjectTypes);
        return;
    }
    // create the log for the generator
    final org.apache.felix.scrplugin.Log scrLog = new MavenLog(getLog(), buildContext);
    // create project
    final MavenProjectScanner scanner = new MavenProjectScanner(this.buildContext, this.project, this.sourceIncludes, this.sourceExcludes, this.scanClasses, scrLog);
    final Project project = new Project();
    // create the class loader
    project.setClassLoader(new URLClassLoader(getClassPath(), this.getClass().getClassLoader()));
    project.setDependencies(scanner.getDependencies());
    project.setSources(scanner.getSources());
    project.setClassesDirectory(this.project.getBuild().getOutputDirectory());
    // create options
    final Options options = new Options();
    options.setOutputDirectory(outputDirectory);
    options.setGenerateAccessors(generateAccessors);
    options.setStrictMode(strictMode);
    options.setProperties(properties);
    options.setSpecVersion(SpecVersion.fromName(specVersion));
    options.setIncremental(this.buildContext.isIncremental());
    options.setSkipVolatileCheck(this.skipVolatileCheck);
    if (specVersion != null && options.getSpecVersion() == null) {
        throw new MojoExecutionException("Unknown spec version specified: " + specVersion);
    }
    try {
        final SCRDescriptorGenerator generator = new SCRDescriptorGenerator(scrLog);
        // setup from plugin configuration
        generator.setOptions(options);
        generator.setProject(project);
        this.removePossiblyStaleFiles(scanner.getSources(), options);
        final Result result = generator.execute();
        this.setServiceComponentHeader(options);
        if (!this.updateProjectResources()) {
            this.setIncludeResourceHeader(options);
        }
        this.cleanUpDeletedSources(scanner.getDeletedSources(), options);
        this.refreshMessages(result.getProcessedSourceFiles());
        this.updateBuildContext(result);
    } catch (final SCRDescriptorException sde) {
        throw new MojoExecutionException(sde.getSourceLocation() + " : " + sde.getMessage(), sde);
    } catch (final SCRDescriptorFailureException sdfe) {
        throw (MojoFailureException) new MojoFailureException(sdfe.getMessage()).initCause(sdfe);
    }
}
Also used : Options(org.apache.felix.scrplugin.Options) SCRDescriptorFailureException(org.apache.felix.scrplugin.SCRDescriptorFailureException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) SCRDescriptorGenerator(org.apache.felix.scrplugin.SCRDescriptorGenerator) Result(org.apache.felix.scrplugin.Result) Project(org.apache.felix.scrplugin.Project) MavenProject(org.apache.maven.project.MavenProject) URLClassLoader(java.net.URLClassLoader) SCRDescriptorException(org.apache.felix.scrplugin.SCRDescriptorException)

Example 8 with SCRDescriptorException

use of org.apache.felix.scrplugin.SCRDescriptorException in project felix by apache.

the class ClassModifier method addMethods.

/**
 * Add bind/unbind methods
 * @param className       The class name in which the methods are injected
 * @param referenceName   Name of the reference
 * @param referenceType   Type of the reference
 * @param fieldName       Name of the field
 * @param fieldType       Type of the field
 * @param createBind      Name of the bind method or null
 * @param createUnbind    Name of the unbind method or null
 * @param outputDirectory Output directory where the class file is stored
 * @throws SCRDescriptorException
 */
public static void addMethods(final String className, final String referenceName, final String referenceType, final String fieldName, final String fieldType, final boolean createBind, final boolean createUnbind, final ClassLoader classLoader, final String outputDirectory, final Log logger) throws SCRDescriptorException {
    // now do byte code manipulation
    final String fileName = outputDirectory + File.separatorChar + className.replace('.', File.separatorChar) + ".class";
    final ClassNode cn = new ClassNode();
    try {
        final FileInputStream fis = new FileInputStream(fileName);
        try {
            final ClassReader reader = new ClassReader(fis);
            reader.accept(cn, 0);
        } finally {
            fis.close();
        }
        // For target Java7 and above use: ClassWriter.COMPUTE_MAXS  | ClassWriter.COMPUTE_FRAMES
        final int mask = (cn.version > 50 ? ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES : 0);
        final ClassWriter writer = new ClassWriter(mask) {

            @Override
            protected String getCommonSuperClass(final String type1, final String type2) {
                Class<?> c, d;
                try {
                    c = classLoader.loadClass(type1.replace('/', '.'));
                    d = classLoader.loadClass(type2.replace('/', '.'));
                } catch (final Exception e) {
                    throw new RuntimeException(e.toString(), e);
                }
                if (c.isAssignableFrom(d)) {
                    return type1;
                }
                if (d.isAssignableFrom(c)) {
                    return type2;
                }
                if (c.isInterface() || d.isInterface()) {
                    return "java/lang/Object";
                }
                do {
                    c = c.getSuperclass();
                } while (!c.isAssignableFrom(d));
                return c.getName().replace('.', '/');
            }
        };
        cn.accept(writer);
        if (createBind) {
            logger.debug("Adding bind " + className + " " + fieldName);
            createMethod(writer, className, referenceName, referenceType, fieldName, fieldType, true);
        }
        if (createUnbind) {
            logger.debug("Adding unbind " + className + " " + fieldName);
            createMethod(writer, className, referenceName, referenceType, fieldName, fieldType, false);
        }
        final FileOutputStream fos = new FileOutputStream(fileName);
        try {
            fos.write(writer.toByteArray());
        } finally {
            fos.close();
        }
    } catch (final Exception e) {
        throw new SCRDescriptorException("Unable to add methods to " + className, referenceType, e);
    }
}
Also used : ClassNode(org.objectweb.asm.tree.ClassNode) FileOutputStream(java.io.FileOutputStream) ClassReader(org.objectweb.asm.ClassReader) FileInputStream(java.io.FileInputStream) ClassWriter(org.objectweb.asm.ClassWriter) SCRDescriptorException(org.apache.felix.scrplugin.SCRDescriptorException) SCRDescriptorException(org.apache.felix.scrplugin.SCRDescriptorException)

Example 9 with SCRDescriptorException

use of org.apache.felix.scrplugin.SCRDescriptorException in project felix by apache.

the class ClassScanner method processClass.

/**
 * Scan a single class.
 */
private ClassDescription processClass(final Class<?> annotatedClass, final String location) throws SCRDescriptorFailureException, SCRDescriptorException {
    log.debug("Processing " + annotatedClass.getName());
    try {
        // get the class file for ASM
        final String pathToClassFile = annotatedClass.getName().replace('.', '/') + ".class";
        final InputStream input = project.getClassLoader().getResourceAsStream(pathToClassFile);
        final ClassReader classReader;
        try {
            classReader = new ClassReader(input);
        } finally {
            if (input != null) {
                input.close();
            }
        }
        final ClassNode classNode = new ClassNode();
        classReader.accept(classNode, SKIP_CODE | SKIP_DEBUG | SKIP_FRAMES);
        // create descriptions
        final List<ScannedAnnotation> annotations = extractAnnotation(classNode, annotatedClass);
        if (annotations.size() > 0) {
            // process annotations and create descriptions
            final ClassDescription desc = new ClassDescription(annotatedClass, location);
            aProcessor.process(new ScannedClass(annotations, annotatedClass), desc);
            log.debug("Found descriptions " + desc + " in " + annotatedClass.getName());
            return desc;
        }
    } catch (final IllegalArgumentException ioe) {
        throw new SCRDescriptorException("Unable to scan class files: " + annotatedClass.getName() + " (Class file format probably not supported by ASM ?)", location, ioe);
    } catch (final IOException ioe) {
        throw new SCRDescriptorException("Unable to scan class files: " + annotatedClass.getName(), location, ioe);
    }
    return null;
}
Also used : ClassNode(org.objectweb.asm.tree.ClassNode) FilterInputStream(java.io.FilterInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ClassReader(org.objectweb.asm.ClassReader) ScannedAnnotation(org.apache.felix.scrplugin.annotations.ScannedAnnotation) ClassDescription(org.apache.felix.scrplugin.description.ClassDescription) ScannedClass(org.apache.felix.scrplugin.annotations.ScannedClass) IOException(java.io.IOException) SCRDescriptorException(org.apache.felix.scrplugin.SCRDescriptorException)

Example 10 with SCRDescriptorException

use of org.apache.felix.scrplugin.SCRDescriptorException in project felix by apache.

the class ClassScanner method getComponentDescriptors.

/**
 * Returns a map of component descriptors which may be extended by the java
 * sources.
 * <p>
 * This method calls the {@link #getDependencies()} method and checks for
 * any Service-Component descriptors in the returned files.
 * <p>
 * This method may be overwritten by extensions of this class.
 *
 * @throws SCRDescriptorException May be thrown if an error occurs
 *             gathering the component descriptors.
 */
private Map<String, ClassDescription> getComponentDescriptors() throws SCRDescriptorException {
    if (loadedDependencies == null) {
        loadedDependencies = new HashMap<String, ClassDescription>();
        final Collection<File> dependencies = this.project.getDependencies();
        for (final File artifact : dependencies) {
            try {
                this.log.debug("Trying to get scrinfo from artifact " + artifact);
                // First try to read the private scr info file from previous scr generator versions
                InputStream scrInfoFile = null;
                try {
                    scrInfoFile = this.getFile(artifact, ABSTRACT_DESCRIPTOR_ARCHIV_PATH);
                    if (scrInfoFile != null) {
                        this.readServiceComponentDescriptor(scrInfoFile, artifact.toString() + ':' + ABSTRACT_DESCRIPTOR_ARCHIV_PATH);
                        continue;
                    }
                    this.log.debug("Artifact has no scrinfo file (it's optional): " + artifact);
                } catch (final IOException ioe) {
                    throw new SCRDescriptorException("Unable to get scrinfo from artifact", artifact.toString(), ioe);
                } finally {
                    if (scrInfoFile != null) {
                        try {
                            scrInfoFile.close();
                        } catch (final IOException ignore) {
                        }
                    }
                }
                this.log.debug("Trying to get manifest from artifact " + artifact);
                final Manifest manifest = this.getManifest(artifact);
                if (manifest != null) {
                    // read Service-Component entry
                    if (manifest.getMainAttributes().getValue(SERVICE_COMPONENT) != null) {
                        final String serviceComponent = manifest.getMainAttributes().getValue(SERVICE_COMPONENT);
                        this.log.debug("Found Service-Component: " + serviceComponent + " in artifact " + artifact);
                        final StringTokenizer st = new StringTokenizer(serviceComponent, ",");
                        while (st.hasMoreTokens()) {
                            final String entry = st.nextToken().trim();
                            if (entry.length() > 0) {
                                this.readServiceComponentDescriptor(artifact, entry);
                            }
                        }
                    } else {
                        this.log.debug("Artifact has no service component entry in manifest " + artifact);
                    }
                } else {
                    this.log.debug("Unable to get manifest from artifact " + artifact);
                }
            } catch (IOException ioe) {
                throw new SCRDescriptorException("Unable to get manifest from artifact", artifact.toString(), ioe);
            }
        }
    }
    return this.loadedDependencies;
}
Also used : StringTokenizer(java.util.StringTokenizer) FilterInputStream(java.io.FilterInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ClassDescription(org.apache.felix.scrplugin.description.ClassDescription) IOException(java.io.IOException) Manifest(java.util.jar.Manifest) JarFile(java.util.jar.JarFile) File(java.io.File) SCRDescriptorException(org.apache.felix.scrplugin.SCRDescriptorException)

Aggregations

SCRDescriptorException (org.apache.felix.scrplugin.SCRDescriptorException)14 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)5 FileInputStream (java.io.FileInputStream)4 File (java.io.File)3 FileOutputStream (java.io.FileOutputStream)3 FilterInputStream (java.io.FilterInputStream)3 InputStream (java.io.InputStream)3 TransformerException (javax.xml.transform.TransformerException)3 SCRDescriptorFailureException (org.apache.felix.scrplugin.SCRDescriptorFailureException)3 SpecVersion (org.apache.felix.scrplugin.SpecVersion)3 ClassDescription (org.apache.felix.scrplugin.description.ClassDescription)3 ComponentContainer (org.apache.felix.scrplugin.helper.ComponentContainer)3 Method (java.lang.reflect.Method)2 Options (org.apache.felix.scrplugin.Options)2 SCRDescriptorGenerator (org.apache.felix.scrplugin.SCRDescriptorGenerator)2 ScannedAnnotation (org.apache.felix.scrplugin.annotations.ScannedAnnotation)2 ComponentContainerContainer (org.apache.felix.scrplugin.helper.ComponentContainerUtil.ComponentContainerContainer)2 ClassReader (org.objectweb.asm.ClassReader)2 ClassNode (org.objectweb.asm.tree.ClassNode)2