Search in sources :

Example 1 with ClassDescription

use of org.apache.felix.scrplugin.description.ClassDescription in project felix by apache.

the class SCRDescriptorGenerator method createComponent.

/**
 * Create the SCR objects based on the descriptions
 */
private ComponentContainer createComponent(final ClassDescription desc, final IssueLog iLog) throws SCRDescriptorException {
    final ComponentDescription componentDesc = desc.getDescription(ComponentDescription.class);
    final SpecVersion intitialComponentSpecVersion = componentDesc.getSpecVersion();
    // configuration pid in 1.2
    if (componentDesc.getConfigurationPid() != null && !componentDesc.getConfigurationPid().equals(componentDesc.getName())) {
        componentDesc.setSpecVersion(SpecVersion.VERSION_1_2);
    }
    final ComponentContainer container = new ComponentContainer(desc, componentDesc);
    // Create metatype (if required)
    final MetatypeContainer ocd;
    if (!componentDesc.isAbstract() && componentDesc.isCreateMetatype()) {
        // OCD
        ocd = new MetatypeContainer();
        container.setMetatypeContainer(ocd);
        ocd.setId(componentDesc.getName());
        if (componentDesc.getLabel() != null) {
            ocd.setName(componentDesc.getLabel());
        }
        if (componentDesc.getDescription() != null) {
            ocd.setDescription(componentDesc.getDescription());
        }
        // Factory pid
        if (componentDesc.isSetMetatypeFactoryPid()) {
            if (componentDesc.getFactory() == null) {
                ocd.setFactoryPid(componentDesc.getName());
            } else {
                iLog.addWarning("Component factory " + componentDesc.getName() + " should not set metatype factory pid.", desc.getSource());
            }
        }
    } else {
        ocd = null;
    }
    // metatype checks if metatype is not generated (FELIX-4033)
    if (!componentDesc.isAbstract() && !componentDesc.isCreateMetatype()) {
        if (componentDesc.getLabel() != null && componentDesc.getLabel().trim().length() > 0) {
            iLog.addWarning(" Component " + componentDesc.getName() + " has set a label. However metatype is set to false. This label is ignored.", desc.getSource());
        }
        if (componentDesc.getDescription() != null && componentDesc.getDescription().trim().length() > 0) {
            iLog.addWarning(" Component " + componentDesc.getName() + " has set a description. However metatype is set to false. This description is ignored.", desc.getSource());
        }
    }
    ClassDescription current = desc;
    boolean inherit;
    do {
        final ComponentDescription cd = current.getDescription(ComponentDescription.class);
        inherit = (cd == null ? true : cd.isInherit());
        if (cd != null) {
            if (current != desc) {
                iLog.addWarning(" Component " + componentDesc.getName() + " is using the " + "deprecated inheritance feature and inherits from " + current.getDescribedClass().getName() + ". This feature will be removed in future versions.", desc.getSource());
            }
            // handle enabled and immediate
            if (componentDesc.getEnabled() == null) {
                componentDesc.setEnabled(cd.getEnabled());
            }
            if (componentDesc.getImmediate() == null) {
                componentDesc.setImmediate(cd.getImmediate());
            }
            // lifecycle methods
            if (componentDesc.getActivate() == null && cd.getActivate() != null) {
                componentDesc.setActivate(cd.getActivate());
            }
            if (componentDesc.getDeactivate() == null && cd.getDeactivate() != null) {
                componentDesc.setDeactivate(cd.getDeactivate());
            }
            if (componentDesc.getModified() == null && cd.getModified() != null) {
                componentDesc.setModified(cd.getModified());
            }
            if (componentDesc.getActivate() != null || componentDesc.getDeactivate() != null || componentDesc.getModified() != null) {
                // spec version must be at least 1.1
                componentDesc.setSpecVersion(SpecVersion.VERSION_1_1);
            }
            if (componentDesc.getConfigurationPolicy() != ComponentConfigurationPolicy.OPTIONAL) {
                // policy requires 1.1
                componentDesc.setSpecVersion(SpecVersion.VERSION_1_1);
            }
        }
        // services, properties, references
        this.processServices(current, container);
        this.processProperties(current, container, ocd);
        this.processReferences(current, container);
        // go up in the class hierarchy
        if (!inherit || current.getDescribedClass().getSuperclass() == null) {
            current = null;
        } else {
            try {
                current = this.scanner.getDescription(current.getDescribedClass().getSuperclass());
            } catch (final SCRDescriptorFailureException sde) {
                this.logger.debug(sde.getMessage(), sde);
                iLog.addError(sde.getMessage(), current.getSource());
            } catch (final SCRDescriptorException sde) {
                this.logger.debug(sde.getSourceLocation() + " : " + sde.getMessage(), sde);
                iLog.addError(sde.getMessage(), sde.getSourceLocation());
            }
        }
    } while (current != null);
    // check service interfaces for properties
    if (container.getServiceDescription() != null) {
        for (final String interfaceName : container.getServiceDescription().getInterfaces()) {
            try {
                final Class<?> interfaceClass = project.getClassLoader().loadClass(interfaceName);
                final ClassDescription interfaceDesc = this.scanner.getDescription(interfaceClass);
                if (interfaceDesc != null) {
                    this.processProperties(interfaceDesc, container, ocd);
                }
            } catch (final SCRDescriptorFailureException sde) {
                this.logger.debug(sde.getMessage(), sde);
                iLog.addError(sde.getMessage(), interfaceName);
            } catch (final SCRDescriptorException sde) {
                this.logger.debug(sde.getSourceLocation() + " : " + sde.getMessage(), sde);
                iLog.addError(sde.getMessage(), sde.getSourceLocation());
            } catch (ClassNotFoundException e) {
                this.logger.debug(e.getMessage(), e);
                iLog.addError(e.getMessage(), interfaceName);
            }
        }
    }
    // global properties
    this.processGlobalProperties(desc, container.getProperties());
    // check lifecycle methods
    if (componentDesc.getActivate() == null) {
        final Validator.MethodResult result = Validator.findLifecycleMethod(project, container, "activate", true);
        if (result.method != null) {
            componentDesc.setSpecVersion(result.requiredSpecVersion);
        }
    }
    if (componentDesc.getDeactivate() == null) {
        final Validator.MethodResult result = Validator.findLifecycleMethod(project, container, "deactivate", false);
        if (result.method != null) {
            componentDesc.setSpecVersion(result.requiredSpecVersion);
        }
    }
    // check if component has spec version configured but requires a higher one
    if (intitialComponentSpecVersion != null && componentDesc.getSpecVersion().ordinal() > intitialComponentSpecVersion.ordinal()) {
        iLog.addError("Component " + container + " requires spec version " + container.getComponentDescription().getSpecVersion().name() + " but component is configured to use version " + intitialComponentSpecVersion.name(), desc.getSource());
    }
    return container;
}
Also used : ComponentDescription(org.apache.felix.scrplugin.description.ComponentDescription) MetatypeContainer(org.apache.felix.scrplugin.helper.MetatypeContainer) ClassDescription(org.apache.felix.scrplugin.description.ClassDescription) ComponentContainer(org.apache.felix.scrplugin.helper.ComponentContainer) Validator(org.apache.felix.scrplugin.helper.Validator)

Example 2 with ClassDescription

use of org.apache.felix.scrplugin.description.ClassDescription in project felix by apache.

the class SCRDescriptorGenerator method execute.

/**
 * Actually generates the Declarative Services and Metatype descriptors
 * scanning the java sources provided by the {@link #setProject(Project)}
 *
 * @return A list of generated file names, relative to the output directory
 *
 * @throws SCRDescriptorException
 * @throws SCRDescriptorFailureException
 */
public Result execute() throws SCRDescriptorException, SCRDescriptorFailureException {
    this.logger.debug("Starting SCR Descriptor Generator....");
    if (this.project == null) {
        throw new SCRDescriptorFailureException("Project has not been set!");
    }
    if (this.options == null) {
        // use default options
        this.options = new Options();
    }
    if (this.options.getOutputDirectory() == null) {
        throw new SCRDescriptorFailureException("Output directory has not been set!");
    }
    this.logger.debug("..using output directory: " + this.options.getOutputDirectory());
    this.logger.debug("..strict mode: " + this.options.isStrictMode());
    this.logger.debug("..generating accessors: " + this.options.isGenerateAccessors());
    // check speck version configuration
    SpecVersion specVersion = options.getSpecVersion();
    if (specVersion == null) {
        this.logger.debug("..auto detecting spec version");
    } else {
        this.logger.debug("..using spec version " + specVersion.getName());
    }
    // create a log
    this.iLog = new IssueLog(this.options.isStrictMode());
    // create the annotation processor manager
    final AnnotationProcessor aProcessor = new AnnotationProcessorManager(this.logger, this.project.getClassLoader());
    // create the class scanner - and start scanning
    this.scanner = new ClassScanner(logger, iLog, project, aProcessor);
    final List<ClassDescription> scannedDescriptions = scanner.scanSources();
    // create the result to hold the list of processed source files
    final Result result = new Result();
    final List<ComponentContainer> processedContainers = new ArrayList<ComponentContainer>();
    for (final ClassDescription desc : scannedDescriptions) {
        this.logger.debug("Processing component class " + desc.getSource());
        result.addProcessedSourceFile(desc.getSource());
        // check if there is more than one component definition
        if (desc.getDescriptions(ComponentDescription.class).size() > 1) {
            iLog.addError("Class has more than one component definition." + " Check the annotations and merge the definitions to a single definition.", desc.getSource());
        } else {
            final ComponentContainer container = this.createComponent(desc, iLog);
            if (container.getComponentDescription().getSpecVersion() != null) {
                if (specVersion == null) {
                    specVersion = container.getComponentDescription().getSpecVersion();
                    logger.debug("Setting used spec version to " + specVersion);
                } else if (container.getComponentDescription().getSpecVersion().ordinal() > specVersion.ordinal()) {
                    if (this.options.getSpecVersion() != null) {
                        // if a spec version has been configured and a component requires a higher
                        // version, this is considered an error!
                        iLog.addError("Component " + container + " requires spec version " + container.getComponentDescription().getSpecVersion().name() + " but plugin is configured to use version " + this.options.getSpecVersion(), desc.getSource());
                    } else {
                        specVersion = container.getComponentDescription().getSpecVersion();
                        logger.debug("Setting used spec version to " + specVersion);
                    }
                }
            } else {
                if (this.options.getSpecVersion() != null) {
                    container.getComponentDescription().setSpecVersion(options.getSpecVersion());
                } else {
                    container.getComponentDescription().setSpecVersion(SpecVersion.VERSION_1_0);
                }
            }
            processedContainers.add(container);
        }
    }
    // if spec version is still not set, we're using lowest available
    if (specVersion == null) {
        specVersion = SpecVersion.VERSION_1_0;
        logger.debug("Using default spec version " + specVersion);
    }
    this.logger.debug("Generating descriptor for spec version: " + specVersion);
    options.setSpecVersion(specVersion);
    // in order to create them if possible
    if (this.options.isGenerateAccessors()) {
        for (final ComponentContainer container : processedContainers) {
            this.generateMethods(container);
        }
    }
    // now validate
    final DescriptionContainer module = new DescriptionContainer(this.options);
    for (final ComponentContainer container : processedContainers) {
        final int errorCount = iLog.getNumberOfErrors();
        final Validator validator = new Validator(container, project, options, iLog);
        validator.validate();
        // ignore component if it has errors
        if (iLog.getNumberOfErrors() == errorCount) {
            module.add(container);
        }
    }
    // log issues
    iLog.logMessages(logger);
    // after checking all classes, throw if there were any failures
    if (iLog.hasErrors()) {
        throw new SCRDescriptorFailureException("SCR Descriptor parsing had failures (see log)");
    }
    // and generate files
    result.setMetatypeFiles(MetaTypeIO.generateDescriptors(module, this.project, this.options, this.logger));
    result.setScrFiles(ComponentDescriptorIO.generateDescriptorFiles(module, this.options, logger));
    return result;
}
Also used : ArrayList(java.util.ArrayList) AnnotationProcessor(org.apache.felix.scrplugin.annotations.AnnotationProcessor) ClassDescription(org.apache.felix.scrplugin.description.ClassDescription) AnnotationProcessorManager(org.apache.felix.scrplugin.helper.AnnotationProcessorManager) IssueLog(org.apache.felix.scrplugin.helper.IssueLog) ClassScanner(org.apache.felix.scrplugin.helper.ClassScanner) DescriptionContainer(org.apache.felix.scrplugin.helper.DescriptionContainer) ComponentContainer(org.apache.felix.scrplugin.helper.ComponentContainer) Validator(org.apache.felix.scrplugin.helper.Validator)

Example 3 with ClassDescription

use of org.apache.felix.scrplugin.description.ClassDescription in project felix by apache.

the class ClassScanner method getDescription.

/**
 * Get a description for the class
 */
public ClassDescription getDescription(final Class<?> clazz) throws SCRDescriptorException, SCRDescriptorFailureException {
    final String name = clazz.getName();
    // we don't need to scan classes in the java. or javax. package namespace
    if (name.startsWith("java.") || name.startsWith("javax.")) {
        return null;
    }
    ClassDescription result = this.allDescriptions.get(name);
    if (result == null) {
        // use scanner first
        result = this.processClass(clazz, GENERATED);
        if (result == null) {
            // now check loaded dependencies
            result = this.getComponentDescriptors().get(name);
        }
        // not found, create dummy
        if (result == null) {
            result = new ClassDescription(clazz, GENERATED);
        }
        // and cache
        allDescriptions.put(name, result);
    }
    return result.clone();
}
Also used : ClassDescription(org.apache.felix.scrplugin.description.ClassDescription)

Example 4 with ClassDescription

use of org.apache.felix.scrplugin.description.ClassDescription 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 5 with ClassDescription

use of org.apache.felix.scrplugin.description.ClassDescription in project felix by apache.

the class ClassScanner method process.

/**
 * Process a class
 * @throws SCRDescriptorException
 * @throws SCRDescriptorFailureException
 */
private void process(final Class<?> annotatedClass, final Source src, final List<ClassDescription> result) throws SCRDescriptorFailureException, SCRDescriptorException {
    final ClassDescription desc = this.processClass(annotatedClass, src.getFile().toString());
    if (desc != null) {
        this.allDescriptions.put(annotatedClass.getName(), desc);
        if (desc.getDescriptions(ComponentDescription.class).size() > 0) {
            result.add(desc);
            log.debug("Found component description " + desc + " in " + annotatedClass.getName());
        } else {
            // check whether one of the other annotations is used and log a warning (FELIX-3636)
            if (desc.getDescription(PropertyDescription.class) != null || desc.getDescription(ReferenceDescription.class) != null || desc.getDescription(ServiceDescription.class) != null) {
                iLog.addWarning("Class '" + src.getClassName() + "' contains SCR annotations, but not a " + "@Component (or equivalent) annotation. Therefore no component descriptor is created for this " + "class. Please add a @Component annotation and consider making it abstract.", src.getFile().toString());
            }
        }
    } else {
        this.allDescriptions.put(annotatedClass.getName(), new ClassDescription(annotatedClass, GENERATED));
    }
    // process inner classes
    for (final Class<?> innerClass : annotatedClass.getDeclaredClasses()) {
        if (!innerClass.isAnnotation() && !innerClass.isInterface()) {
            process(innerClass, src, result);
        }
    }
}
Also used : PropertyDescription(org.apache.felix.scrplugin.description.PropertyDescription) ReferenceDescription(org.apache.felix.scrplugin.description.ReferenceDescription) ClassDescription(org.apache.felix.scrplugin.description.ClassDescription)

Aggregations

ClassDescription (org.apache.felix.scrplugin.description.ClassDescription)8 SCRDescriptorException (org.apache.felix.scrplugin.SCRDescriptorException)3 FileInputStream (java.io.FileInputStream)2 FilterInputStream (java.io.FilterInputStream)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 ArrayList (java.util.ArrayList)2 ComponentContainer (org.apache.felix.scrplugin.helper.ComponentContainer)2 Validator (org.apache.felix.scrplugin.helper.Validator)2 File (java.io.File)1 StringTokenizer (java.util.StringTokenizer)1 JarFile (java.util.jar.JarFile)1 Manifest (java.util.jar.Manifest)1 SCRDescriptorFailureException (org.apache.felix.scrplugin.SCRDescriptorFailureException)1 Source (org.apache.felix.scrplugin.Source)1 AnnotationProcessor (org.apache.felix.scrplugin.annotations.AnnotationProcessor)1 ScannedAnnotation (org.apache.felix.scrplugin.annotations.ScannedAnnotation)1 ScannedClass (org.apache.felix.scrplugin.annotations.ScannedClass)1 ComponentDescription (org.apache.felix.scrplugin.description.ComponentDescription)1 PropertyDescription (org.apache.felix.scrplugin.description.PropertyDescription)1