Commit the new iPOJO Version (Felix-311)
Change the global pom file : the iPOJO profile is no more useful thanks to the new maven plugin. However, manipulator and metadata move inside the plugins profile (required to compile the new maven plugin)
git-svn-id: https://svn.apache.org/repos/asf/felix/trunk@550265 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/ipojo/arch/pom.xml b/ipojo/arch/pom.xml
index 4f1e91b..a32aa47 100644
--- a/ipojo/arch/pom.xml
+++ b/ipojo/arch/pom.xml
@@ -5,46 +5,54 @@
<version>0.9.0-incubator-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
- <packaging>ipojo-bundle</packaging>
+ <packaging>bundle</packaging>
<name>Apache Felix iPOJO Arch Command</name>
- <version>0.7.1-incubator-SNAPSHOT</version>
+ <version>0.7.3-incubator-SNAPSHOT</version>
<artifactId>org.apache.felix.ipojo.arch</artifactId>
<dependencies>
<dependency>
<groupId>${pom.groupId}</groupId>
<artifactId>org.apache.felix.ipojo</artifactId>
<version>${pom.version}</version>
- <scope>provided</scope>
</dependency>
<dependency>
<groupId>${pom.groupId}</groupId>
<artifactId>org.apache.felix.ipojo.metadata</artifactId>
<version>${pom.version}</version>
- <scope>provided</scope>
</dependency>
<dependency>
<groupId>${pom.groupId}</groupId>
<artifactId>org.apache.felix.shell</artifactId>
<version>0.9.0-incubator-SNAPSHOT</version>
- <scope>provided</scope>
</dependency>
</dependencies>
<build>
- <plugins>
+ <plugins>
<plugin>
- <groupId>${pom.groupId}</groupId>
- <artifactId>org.apache.felix.ipojo.plugin</artifactId>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
- <osgiManifest>
- <bundleName>iPOJO Arch Command</bundleName>
- <bundleVersion>0.7.1.incubator-SNAPSHOT</bundleVersion>
- <bundleSymbolicName>${pom.artifactId}</bundleSymbolicName>
- <bundleDescription>Architecture Shell Command (arch)</bundleDescription>
- <iPOJOMetadata>metadata.xml</iPOJOMetadata>
- </osgiManifest>
+ <instructions>
+ <Bundle-SymbolicName>${pom.artifactId}</Bundle-SymbolicName>
+ <Private-Package>org.apache.felix.ipojo.arch</Private-Package>
+ </instructions>
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>org.apache.felix.ipojo.plugin</artifactId>
+ <executions>
+ <execution>
+ <goals>
+ <goal>ipojo-bundle</goal>
+ </goals>
+ <configuration>
+ <metadata>metadata.xml</metadata>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
</plugins>
- </build>
+ </build>
</project>
diff --git a/ipojo/arch/src/main/resources/metadata.xml b/ipojo/arch/src/main/resources/metadata.xml
index 60379c8..24b7954 100644
--- a/ipojo/arch/src/main/resources/metadata.xml
+++ b/ipojo/arch/src/main/resources/metadata.xml
@@ -2,7 +2,7 @@
<iPOJO>
<Component className="org.apache.felix.ipojo.arch.ArchCommandImpl">
<Provides interface="org.ungoverned.osgi.service.shell.Command"/>
- <Dependency field="archiService" optional="true"/>
+ <Requires field="archiService" optional="true"/>
</Component>
<instance component="org.apache.felix.ipojo.arch.ArchCommandImpl" name="ArchCommand"/>
</iPOJO>
\ No newline at end of file
diff --git a/ipojo/core/pom.xml b/ipojo/core/pom.xml
index 610e81b..624c4d6 100644
--- a/ipojo/core/pom.xml
+++ b/ipojo/core/pom.xml
@@ -8,19 +8,17 @@
<packaging>bundle</packaging>
<name>Apache Felix iPOJO</name>
<artifactId>org.apache.felix.ipojo</artifactId>
- <version>0.7.1-incubator-SNAPSHOT</version>
+ <version>0.7.3-incubator-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>${pom.groupId}</groupId>
<artifactId>org.osgi.core</artifactId>
<version>0.9.0-incubator-SNAPSHOT</version>
- <scope>provided</scope>
</dependency>
<dependency>
<groupId>${pom.groupId}</groupId>
<artifactId>org.osgi.compendium</artifactId>
<version>0.9.0-incubator-SNAPSHOT</version>
- <scope>provided</scope>
</dependency>
<dependency>
<groupId>asm</groupId>
@@ -30,7 +28,12 @@
<dependency>
<groupId>${pom.groupId}</groupId>
<artifactId>org.apache.felix.ipojo.metadata</artifactId>
- <version>0.7.1-incubator-SNAPSHOT</version>
+ <version>0.7.3-incubator-SNAPSHOT</version>
+ </dependency>
+ <dependency>
+ <groupId>${pom.groupId}</groupId>
+ <artifactId>org.apache.felix.ipojo.manipulator</artifactId>
+ <version>0.7.3-incubator-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
@@ -50,6 +53,7 @@
org.osgi.service.log
</Import-Package>
<Private-Package>
+ org.apache.felix.ipojo.manipulation,
org.apache.felix.ipojo.composite.architecture,
org.apache.felix.ipojo.composite.service*,
org.apache.felix.ipojo.composite.instance,
@@ -57,17 +61,18 @@
org.apache.felix.ipojo.handlers.configuration,
org.apache.felix.ipojo.handlers.dependency.nullable,
org.apache.felix.ipojo.handlers.lifecycle.callback,
- org.objectweb.asm*
+ org.objectweb.asm,
+ org.objectweb.asm.commons
</Private-Package>
<Export-Package>
- org.apache.felix.ipojo; version="0.7.1",
- org.apache.felix.ipojo.metadata; version="0.7.1",
- org.apache.felix.ipojo.architecture; version="0.7.1",
- org.apache.felix.ipojo.parser; version="0.7.1",
- org.apache.felix.ipojo.util; version="0.7.1",
- org.apache.felix.ipojo.handlers.dependency; version="0.7.1",
- org.apache.felix.ipojo.handlers.providedservice; version="0.7.1",
- org.apache.felix.ipojo.composite; version="0.7.1",
+ org.apache.felix.ipojo; version="0.7.3",
+ org.apache.felix.ipojo.metadata; version="0.7.3",
+ org.apache.felix.ipojo.architecture; version="0.7.3",
+ org.apache.felix.ipojo.parser; version="0.7.3",
+ org.apache.felix.ipojo.util; version="0.7.3",
+ org.apache.felix.ipojo.handlers.dependency; version="0.7.3",
+ org.apache.felix.ipojo.handlers.providedservice; version="0.7.3",
+ org.apache.felix.ipojo.composite; version="0.7.3",
org.osgi.service.cm,
org.osgi.service.log
</Export-Package>
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/Activator.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/Activator.java
index 03c5bf8..abc6a50 100644
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/Activator.java
+++ b/ipojo/core/src/main/java/org/apache/felix/ipojo/Activator.java
@@ -152,7 +152,8 @@
for (int j = 0; j < m_factories.length; j++) {
String componentClass = m_factories[j].getComponentClassName();
String factoryName = m_factories[j].getName();
- if (conf.get("component") != null && (conf.get("component").equals(componentClass) || conf.get("component").equals(factoryName))) {
+ String componentName = m_factories[j].getComponentTypeName();
+ if (conf.get("component") != null && (conf.get("component").equals(componentClass) || conf.get("component").equals(factoryName)) || conf.get("component").equals(componentName)) {
try {
m_factories[j].createComponentInstance(conf);
created = true;
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/ComponentFactory.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/ComponentFactory.java
index 71e11d6..fb8a514 100644
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/ComponentFactory.java
+++ b/ipojo/core/src/main/java/org/apache/felix/ipojo/ComponentFactory.java
@@ -21,11 +21,13 @@
import java.io.IOException;
import java.net.URL;
import java.security.ProtectionDomain;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
+import java.util.List;
import java.util.Properties;
import org.apache.felix.ipojo.architecture.ComponentDescription;
@@ -52,6 +54,11 @@
* name (i.e. pid) of the created instance
*/
private HashMap m_componentInstances = new HashMap();
+
+ /**
+ * List of the managed instance name. This list is shared by all factories.
+ */
+ private static List m_instancesName = new ArrayList();
/**
* Ture if the component is a composition.
@@ -76,7 +83,7 @@
/**
* Composition Name.
*/
- private String m_compositeName = null;
+ private String m_typeName = null;
/**
* Classloader to delegate loading.
@@ -188,6 +195,10 @@
protected BundleContext getBundleContext() {
return m_context;
}
+
+ protected String getComponentTypeName() {
+ return m_typeName;
+ }
/**
* Get the implementation class of the component type.
@@ -221,17 +232,11 @@
m_isComposite = true;
// Get the name
if (cm.containsAttribute("name")) {
- m_compositeName = cm.getAttribute("name");
+ m_typeName = cm.getAttribute("name");
} else {
System.err.println("A composite needs a name");
return;
}
- // Compute factory name
- if (m_componentMetadata.containsAttribute("factory") && !m_componentMetadata.getAttribute("factory").equalsIgnoreCase("no")) {
- m_factoryName = m_componentMetadata.getAttribute("factory");
- } else {
- m_factoryName = m_compositeName;
- }
} else {
if (cm.containsAttribute("className")) {
m_componentClassName = cm.getAttribute("className");
@@ -239,20 +244,56 @@
System.err.println("A component needs a class name");
return;
}
- if (m_componentMetadata.containsAttribute("factory") && !m_componentMetadata.getAttribute("factory").equalsIgnoreCase("no")) {
- m_factoryName = m_componentMetadata.getAttribute("factory");
- } else {
- m_factoryName = m_componentMetadata.getAttribute("className");
+ // Get the name
+ if (cm.containsAttribute("name")) {
+ m_typeName = cm.getAttribute("name");
}
}
- if (m_factoryName != null) {
- m_logger = new Logger(m_context, m_factoryName, Logger.WARNING);
+
+ if (m_typeName != null) {
+ m_logger = new Logger(m_context, m_typeName, Logger.WARNING);
} else {
- if (m_isComposite) {
- m_logger = new Logger(m_context, m_compositeName, Logger.WARNING);
- } else {
- m_logger = new Logger(m_context, m_componentClassName, Logger.WARNING);
+ m_logger = new Logger(m_context, m_componentClassName, Logger.WARNING);
+ }
+
+ computeFactoryName();
+
+ }
+
+ /**
+ * Compute the factory name.
+ */
+ private void computeFactoryName() {
+ if (m_componentMetadata.containsAttribute("factory")) {
+ // DEPRECATED BLOCK
+ if (m_componentMetadata.getAttribute("factory").equalsIgnoreCase("no")) {
+ m_logger.log(Logger.WARNING, "'factory=no' is deprecated, Please use 'factory=false' instead of 'factory='no'");
+ m_factoryName = null;
+ return;
}
+ // END OF DEPRECATED BLOCK
+ if (m_componentMetadata.getAttribute("factory").equalsIgnoreCase("false")) {
+ m_factoryName = null;
+ return;
+ }
+ if (m_componentMetadata.getAttribute("factory").equalsIgnoreCase("true")) {
+ if (m_typeName == null) { //m_typeName is necessary set for composite.
+ m_factoryName = m_componentMetadata.getAttribute("className");
+ } else {
+ m_factoryName = m_typeName;
+ }
+ return;
+ }
+ // factory is set with the factory name
+ m_factoryName = m_componentMetadata.getAttribute("factory");
+ return;
+ } else {
+ if (m_typeName == null) { //m_typeName is necessary set for composite.
+ m_factoryName = m_componentMetadata.getAttribute("className");
+ } else {
+ m_factoryName = m_typeName;
+ }
+ return;
}
}
@@ -269,15 +310,16 @@
m_clazz = clazz;
m_componentClassName = cm.getAttribute("className");
m_componentMetadata = cm;
-
- // Get factory PID :
- if (m_componentMetadata.containsAttribute("factory") && !m_componentMetadata.getAttribute("factory").equalsIgnoreCase("no")) {
- m_factoryName = m_componentMetadata.getAttribute("factory");
+
+ // Get the name
+ if (cm.containsAttribute("name")) {
+ m_typeName = cm.getAttribute("name");
+ m_logger = new Logger(m_context, m_typeName, Logger.WARNING);
} else {
- m_factoryName = m_componentMetadata.getAttribute("className");
+ m_logger = new Logger(m_context, m_componentClassName, Logger.WARNING);
}
- m_logger = new Logger(m_context, m_factoryName, Logger.WARNING);
+ computeFactoryName();
}
/**
@@ -295,6 +337,7 @@
((InstanceManager) ci).kill();
}
}
+ m_instancesName.remove(ci.getInstanceName());
}
m_logger.stop();
@@ -332,7 +375,7 @@
}
// Check if the factory should be exposed
- if (m_componentMetadata.containsAttribute("factory") && m_componentMetadata.getAttribute("factory").equalsIgnoreCase("no")) {
+ if (m_factoryName == null) {
return;
}
@@ -342,6 +385,9 @@
props.put("component.class", "no implementation class");
}
props.put("factory.name", m_factoryName);
+ if (m_typeName != null) {
+ props.put("component.type", m_typeName);
+ }
props.put("component.providedServiceSpecifications", m_componentDesc.getprovidedServiceSpecification());
props.put("component.properties", m_componentDesc.getProperties());
props.put("component.description", m_componentDesc);
@@ -360,6 +406,7 @@
* @param ci : the destroyed instance
*/
protected synchronized void disposed(ComponentInstance ci) {
+ m_instancesName.remove(ci.getInstanceName());
m_componentInstances.remove(ci.getInstanceName());
}
@@ -432,7 +479,7 @@
* not consistent with the component type of this factory.
* @see org.apache.felix.ipojo.Factory#createComponentInstance(java.util.Dictionary)
*/
- public ComponentInstance createComponentInstance(Dictionary configuration) throws UnacceptableConfiguration {
+ public synchronized ComponentInstance createComponentInstance(Dictionary configuration) throws UnacceptableConfiguration {
if (configuration == null) {
configuration = new Properties();
}
@@ -452,8 +499,10 @@
configuration.put("name", pid);
}
- if (m_componentInstances.containsKey(pid)) {
+ if (m_instancesName.contains(pid)) {
throw new UnacceptableConfiguration("Name already used : " + pid);
+ } else {
+ m_instancesName.add(pid);
}
IPojoContext context = new IPojoContext(m_context);
@@ -505,8 +554,10 @@
configuration.put("name", pid);
}
- if (m_componentInstances.containsKey(pid)) {
+ if (m_instancesName.contains(pid)) {
throw new UnacceptableConfiguration("Name already used : " + pid);
+ } else {
+ m_instancesName.add(pid);
}
IPojoContext context = new IPojoContext(m_context, serviceContext);
@@ -532,7 +583,8 @@
* @param pid : name of the instance to delete
* @see org.osgi.service.cm.ManagedServiceFactory#deleted(java.lang.String)
*/
- public void deleted(String pid) {
+ public synchronized void deleted(String pid) {
+ m_instancesName.remove(pid);
InstanceManager cm = (InstanceManager) m_componentInstances.remove(pid);
if (cm == null) {
return; // do nothing, the component does not exist !
@@ -548,7 +600,13 @@
* @see org.apache.felix.ipojo.Factory#getName()
*/
public String getName() {
- return m_factoryName;
+ if (m_factoryName != null) {
+ return m_factoryName;
+ } else if (m_typeName != null) {
+ return m_typeName;
+ } else {
+ return m_componentClassName;
+ }
}
/**
@@ -561,7 +619,7 @@
* @see org.osgi.service.cm.ManagedServiceFactory#updated(java.lang.String,
* java.util.Dictionary)
*/
- public void updated(String pid, Dictionary properties) throws ConfigurationException {
+ public synchronized void updated(String pid, Dictionary properties) throws ConfigurationException {
InstanceManager cm = (InstanceManager) m_componentInstances.get(pid);
if (cm == null) {
try {
@@ -574,8 +632,7 @@
} else {
try {
properties.put("name", pid); // Add the name in the configuration
- checkAcceptability(properties); // Test if the configuration is
- // acceptable
+ checkAcceptability(properties); // Test if the configuration is acceptable
} catch (UnacceptableConfiguration e) {
m_logger.log(Logger.ERROR, "The configuration is not acceptable : " + e.getMessage());
throw new ConfigurationException(properties.toString(), e.getMessage());
@@ -656,7 +713,7 @@
*/
private synchronized String generateName() {
String name = getName() + "-" + m_index;
- while (m_componentInstances.containsKey(name)) {
+ while (m_instancesName.contains(name)) {
m_index = m_index + 1;
name = getName() + "-" + m_index;
}
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/Handler.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/Handler.java
index 90f4384..89f196e 100644
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/Handler.java
+++ b/ipojo/core/src/main/java/org/apache/felix/ipojo/Handler.java
@@ -69,6 +69,25 @@
public Object getterCallback(String fieldName, Object value) {
return value;
}
+
+ /**
+ * This method is called when the execution enter in a method.
+ *
+ * @param methodId : the method identifier
+ */
+ public void entryCallback(String methodId) {
+ }
+
+ /**
+ * This method is called when the execution exit a method (before a return or a throw).
+ * If the given returned object is an instance of Exception, this means that the method throwed this exception.
+ * If the given returned object is null, either the method is void, either it returns null.
+ * You must not modified the returned object.
+ * @param methodId : the method identifier
+ * @param returnedObj : the returned object (boxed for primitive type)
+ */
+ public void exitCallback(String methodId, Object returnedObj) {
+ }
/**
* Is the actual state valid for this handler ?
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/InstanceCreator.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/InstanceCreator.java
index 2d68760..e7fd8a9 100644
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/InstanceCreator.java
+++ b/ipojo/core/src/main/java/org/apache/felix/ipojo/InstanceCreator.java
@@ -140,7 +140,7 @@
Factory fact = null;
try {
- String fil = "(|(" + org.osgi.framework.Constants.SERVICE_PID + "=" + componentType + ")(component.class=" + componentType + "))";
+ String fil = "(|(" + org.osgi.framework.Constants.SERVICE_PID + "=" + componentType + ")(component.class=" + componentType + ")(component.type=" + componentType + ")";
ServiceReference[] refs = context.getServiceReferences(org.apache.felix.ipojo.Factory.class.getName(), fil);
if (refs != null) {
fact = (Factory) m_context.getService(refs[0]);
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/InstanceManager.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/InstanceManager.java
index 9cbe337..7e9e0f1 100644
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/InstanceManager.java
+++ b/ipojo/core/src/main/java/org/apache/felix/ipojo/InstanceManager.java
@@ -22,10 +22,13 @@
import java.lang.reflect.InvocationTargetException;
import java.util.Dictionary;
import java.util.HashMap;
+import java.util.Set;
import org.apache.felix.ipojo.architecture.ComponentDescription;
import org.apache.felix.ipojo.architecture.InstanceDescription;
import org.apache.felix.ipojo.metadata.Element;
+import org.apache.felix.ipojo.parser.FieldMetadata;
+import org.apache.felix.ipojo.parser.MethodMetadata;
import org.apache.felix.ipojo.util.Logger;
import org.osgi.framework.BundleContext;
@@ -66,6 +69,11 @@
* Map [field, handler list] storing handlers interested by the field.
*/
private HashMap m_fieldRegistration = new HashMap();
+
+ /**
+ * Map [method identifier, handler list] storing handlers interested by the method.
+ */
+ private HashMap m_methodRegistration = new HashMap();
/**
* Component state (STOPPED at the beginning).
@@ -91,6 +99,7 @@
* Component type information.
*/
private ComponentDescription m_componentDesc;
+
// Constructor
/**
@@ -624,15 +633,16 @@
* given in the list.
*
* @param h : the handler to register
- * @param fields : the fields list
+ * @param fields : the field metadata list
+ * @param methods : the method metadata list
*/
- public void register(Handler h, String[] fields) {
+ public void register(Handler h, FieldMetadata[] fields, MethodMetadata[] methods) {
register(h);
- for (int i = 0; i < fields.length; i++) {
- if (m_fieldRegistration.get(fields[i]) == null) {
- m_fieldRegistration.put(fields[i], new Handler[] { h });
+ for (int i = 0; fields != null && i < fields.length; i++) {
+ if (m_fieldRegistration.get(fields[i].getFieldName()) == null) {
+ m_fieldRegistration.put(fields[i].getFieldName(), new Handler[] { h });
} else {
- Handler[] list = (Handler[]) m_fieldRegistration.get(fields[i]);
+ Handler[] list = (Handler[]) m_fieldRegistration.get(fields[i].getFieldName());
for (int j = 0; j < list.length; j++) {
if (list[j] == h) {
return;
@@ -641,24 +651,42 @@
Handler[] newList = new Handler[list.length + 1];
System.arraycopy(list, 0, newList, 0, list.length);
newList[list.length] = h;
- m_fieldRegistration.put(fields[i], newList);
+ m_fieldRegistration.put(fields[i].getFieldName(), newList);
}
}
+ for (int i = 0; methods != null && i < methods.length; i++) {
+ if (m_methodRegistration.get(methods[i].getMethodIdentifier()) == null) {
+ m_methodRegistration.put(methods[i].getMethodIdentifier(), new Handler[] { h });
+ } else {
+ Handler[] list = (Handler[]) m_methodRegistration.get(methods[i].getMethodIdentifier());
+ for (int j = 0; j < list.length; j++) {
+ if (list[j] == h) {
+ return;
+ }
+ }
+ Handler[] newList = new Handler[list.length + 1];
+ System.arraycopy(list, 0, newList, 0, list.length);
+ newList[list.length] = h;
+ m_methodRegistration.put(methods[i].getMethodIdentifier(), newList);
+ }
+ }
+
}
/**
* Unregister an handler for the field list. The handler will not be
- * notified of field access but is allways register on the instance manager.
+ * notified of field access but is always register on the instance manager.
*
* @param h : the handler to unregister.
- * @param fields : the fields list
+ * @param fields : the field metadata list
+ * @param methods : the method metadata list
*/
- public void unregister(Handler h, String[] fields) {
+ public void unregister(Handler h, FieldMetadata[] fields, MethodMetadata[] methods) {
for (int i = 0; i < fields.length; i++) {
- if (m_fieldRegistration.get(fields[i]) == null) {
+ if (m_fieldRegistration.get(fields[i].getFieldName()) == null) {
break;
} else {
- Handler[] list = (Handler[]) m_fieldRegistration.get(fields[i]);
+ Handler[] list = (Handler[]) m_fieldRegistration.get(fields[i].getFieldName());
int idx = -1;
for (int j = 0; j < list.length; j++) {
if (list[j] == h) {
@@ -678,7 +706,35 @@
}
list = newList;
}
- m_fieldRegistration.put(fields[i], list);
+ m_fieldRegistration.put(fields[i].getFieldName(), list);
+ }
+ }
+ }
+ for (int i = 0; i < methods.length; i++) {
+ if (m_methodRegistration.get(methods[i].getMethodIdentifier()) == null) {
+ break;
+ } else {
+ Handler[] list = (Handler[]) m_methodRegistration.get(methods[i].getMethodIdentifier());
+ int idx = -1;
+ for (int j = 0; j < list.length; j++) {
+ if (list[j] == h) {
+ idx = j;
+ break;
+ }
+ }
+
+ if (idx >= 0) {
+ if ((list.length - 1) == 0) {
+ list = new Handler[0];
+ } else {
+ Handler[] newList = new Handler[list.length - 1];
+ System.arraycopy(list, 0, newList, 0, idx);
+ if (idx < newList.length) {
+ System.arraycopy(list, idx + 1, newList, idx, newList.length - idx);
+ }
+ list = newList;
+ }
+ m_methodRegistration.put(methods[i].getMethodIdentifier(), list);
}
}
}
@@ -711,6 +767,14 @@
}
}
}
+
+ public Set getRegistredFields() {
+ return m_fieldRegistration.keySet();
+ }
+
+ public Set getRegistredMethods() {
+ return m_methodRegistration.keySet();
+ }
/**
* This method is called by the manipulated class each time that a GETFIELD
@@ -740,6 +804,31 @@
return initialValue;
}
}
+
+ /**
+ * Dispatch entry method event on registred handler.
+ * @param methodId : method id
+ */
+ public void entryCallback(String methodId) {
+ Handler[] list = (Handler[]) m_methodRegistration.get(methodId);
+ for (int i = 0; list != null && i < list.length; i++) {
+ list[i].entryCallback(methodId);
+ }
+ }
+
+ /**
+ * Dispatch exit method event on registred handler.
+ * The given returned object is an instance of Exception if the method has throwed an exception.
+ * If the given object is null, either the method returns void, either the method has returned null.
+ * @param methodId : method id
+ * @param e : returned object.
+ */
+ public void exitCallback(String methodId, Object e) {
+ Handler[] list = (Handler[]) m_methodRegistration.get(methodId);
+ for (int i = 0; list != null && i < list.length; i++) {
+ list[i].exitCallback(methodId, e);
+ }
+ }
/**
* This method is called by the manipulated class each time that a PUTFILED
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/importer/ImportExportDescription.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/importer/ImportExportDescription.java
index ac61683..77de77b 100644
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/importer/ImportExportDescription.java
+++ b/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/importer/ImportExportDescription.java
@@ -63,7 +63,7 @@
Element handler = super.getHandlerInfo();
for (int i = 0; i < m_imports.size(); i++) {
ServiceImporter imp = (ServiceImporter) m_imports.get(i);
- Element impo = new Element("Import", "");
+ Element impo = new Element("Requires", "");
impo.addAttribute(new Attribute("Specification", imp.getSpecification()));
if (imp.getFilter() != null) { impo.addAttribute(new Attribute("Filter", imp.getFilter())); }
if (imp.isSatisfied()) {
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/importer/ImportExportHandler.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/importer/ImportExportHandler.java
index 5ccb6d1..d356f4f 100644
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/importer/ImportExportHandler.java
+++ b/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/importer/ImportExportHandler.java
@@ -82,7 +82,17 @@
m_context = im.getContext();
m_scope = m_manager.getServiceContext();
- Element[] imp = metadata.getElements("import");
+ Element[] imp = metadata.getElements("requires");
+
+ //DEPRECATED BLOCK:
+ if (imp.length == 0) {
+ imp = metadata.getElements("import");
+ if (imp.length != 0) {
+ im.getFactory().getLogger().log(Logger.WARNING, "Import is deprecated, please use 'requires' instead of 'import'");
+ }
+ }
+ // END OF DEPRECATED BLOCK
+
Element[] exp = metadata.getElements("export");
for (int i = 0; i < imp.length; i++) {
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/CompositionMetadata.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/CompositionMetadata.java
index c870ff7..4b8b2e1 100644
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/CompositionMetadata.java
+++ b/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/CompositionMetadata.java
@@ -28,8 +28,7 @@
import java.util.Set;
import org.apache.felix.ipojo.Factory;
-import org.apache.felix.ipojo.composite.service.provides.manipulation.Manipulator;
-import org.apache.felix.ipojo.composite.service.provides.manipulation.POJOWriter;
+import org.apache.felix.ipojo.manipulation.Manipulator;
import org.apache.felix.ipojo.metadata.Attribute;
import org.apache.felix.ipojo.metadata.Element;
import org.apache.felix.ipojo.util.Logger;
@@ -58,16 +57,11 @@
* Bundle Context.
*/
private BundleContext m_context;
-
+
/**
- * Manipulated field of the build Pojo.
+ * Manipulation Metadata.
*/
- private HashMap m_manipulatedFields = new HashMap();
-
- /**
- * Manipulated interface of the build Pojo.
- */
- private String[] m_manipulatedInterfaces = new String[0];
+ private Element m_manipulationMetadata;
/**
* Reference on the handler.
@@ -243,9 +237,8 @@
byte[] pojo = POJOWriter.dump(url, m_specification.getName(), m_name, getFieldList(), getMethodList());
Manipulator m = new Manipulator();
try {
- byte[] ff = m.process(pojo);
- m_manipulatedFields = m.getFields();
- m_manipulatedInterfaces = m.getInterfaces();
+ byte[] ff = m.manipulate(pojo);
+ m_manipulationMetadata = m.getManipulationMetadata();
return ff;
} catch (IOException e) {
e.printStackTrace();
@@ -261,7 +254,7 @@
protected Element buildMetadata(String in) {
Element elem = new Element("component", "");
Attribute className = new Attribute("className", m_name);
- Attribute factory = new Attribute("factory", "no");
+ Attribute factory = new Attribute("factory", "false");
elem.addAttribute(className);
elem.addAttribute(factory);
@@ -275,7 +268,7 @@
for (int i = 0; i < fields.size(); i++) {
FieldMetadata field = (FieldMetadata) fields.get(i);
if (field.isUseful() && field.getSpecification().isInterface()) {
- Element dep = new Element("Dependency", "");
+ Element dep = new Element("requires", "");
dep.addAttribute(new Attribute("field", field.getName()));
if (field.getSpecification().isOptional()) {
dep.addAttribute(new Attribute("optional", "true"));
@@ -299,28 +292,7 @@
}
// Insert information to metadata
- Element manip = new Element("Manipulation", "");
- for (int j = 0; j < m_manipulatedInterfaces.length; j++) {
- // Create an interface element for each implemented interface
- Element itf = new Element("Interface", "");
- Attribute att = new Attribute("name", m_manipulatedInterfaces[j]);
- itf.addAttribute(att);
- manip.addElement(itf);
- }
-
- Iterator it = m_manipulatedFields.keySet().iterator();
- while (it.hasNext()) {
- Element field = new Element("Field", "");
- String name = (String) it.next();
- String type = (String) m_manipulatedFields.get(name);
- Attribute attName = new Attribute("name", name);
- Attribute attType = new Attribute("type", type);
- field.addAttribute(attName);
- field.addAttribute(attType);
- manip.addElement(field);
- }
-
- elem.addElement(manip);
+ elem.addElement(m_manipulationMetadata);
return elem;
}
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/manipulation/POJOWriter.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/POJOWriter.java
similarity index 97%
rename from ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/manipulation/POJOWriter.java
rename to ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/POJOWriter.java
index 00f2903..d960bca 100644
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/manipulation/POJOWriter.java
+++ b/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/POJOWriter.java
@@ -1,409 +1,406 @@
-/*
- * 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.felix.ipojo.composite.service.provides.manipulation;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.List;
-
-import org.apache.felix.ipojo.composite.service.provides.FieldMetadata;
-import org.apache.felix.ipojo.composite.service.provides.MethodMetadata;
-import org.apache.felix.ipojo.composite.service.provides.SpecificationMetadata;
-import org.apache.felix.ipojo.handlers.dependency.nullable.MethodSignature;
-import org.apache.felix.ipojo.handlers.dependency.nullable.MethodSignatureVisitor;
-import org.objectweb.asm.ClassReader;
-import org.objectweb.asm.ClassWriter;
-import org.objectweb.asm.Label;
-import org.objectweb.asm.MethodVisitor;
-import org.objectweb.asm.Opcodes;
-import org.objectweb.asm.Type;
-
-/**
- * Create the proxy class.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class POJOWriter implements Opcodes {
-
- /**
- * Create a class.
- * @param cw : class writer
- * @param className : class name
- * @param spec : implemented specification
- */
- private static void createClass(ClassWriter cw, String className, String spec) {
- // Create the class
- cw.visit(V1_2, ACC_PUBLIC + ACC_SUPER, className, null, "java/lang/Object", new String[] { spec.replace('.', '/') });
- }
-
- /**
- * Inject field in the current class.
- * @param cw : class writer.
- * @param fields : list of field to inject.
- */
- private static void injectFields(ClassWriter cw, List fields) {
- // Inject fields
- for (int i = 0; i < fields.size(); i++) {
- FieldMetadata field = (FieldMetadata) fields.get(i);
- if (field.isUseful()) {
- SpecificationMetadata spec = field.getSpecification();
- String fieldName = field.getName();
- String desc = "";
- if (field.isAggregate()) {
- desc = "[L" + spec.getName().replace('.', '/') + ";";
- } else {
- desc = "L" + spec.getName().replace('.', '/') + ";";
- }
-
- cw.visitField(Opcodes.ACC_PRIVATE, fieldName, desc, null, null);
- }
- }
- }
-
- /**
- * Return the proxy classname for the contract contractname by delegating on available service.
- * @param url URL of the needed contract
- * @param contractName : The interface to implement
- * @param className : The class name to create
- * @param fields : the list of fields on which delegate
- * @param methods : the list of method on which delegate
- * @return byte[] : the build class
- */
- public static byte[] dump(URL url, String contractName, String className, List fields, List methods) {
-
- ClassReader cr = null;
- InputStream is = null;
- byte[] b = null;
- try {
- is = url.openStream();
- cr = new ClassReader(is);
- MethodSignatureVisitor msv = new MethodSignatureVisitor();
- cr.accept(msv, ClassReader.SKIP_FRAMES);
- is.close();
-
- MethodSignature[] methodsSign = msv.getMethods();
-
- ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
-
- // Create the class
- className = className.replace('.', '/');
- createClass(cw, className, contractName);
-
- // Inject fields inside the POJO
- injectFields(cw, fields);
-
- // Inject a constructor <INIT>()V
- MethodVisitor cst = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
- cst.visitVarInsn(ALOAD, 0);
- cst.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
- cst.visitInsn(RETURN);
- cst.visitMaxs(0, 0);
- cst.visitEnd();
-
- for (int i = 0; i < methodsSign.length; ++i) {
- MethodSignature method = methodsSign[i];
-
- // Get the field for this method
- // 1) find the MethodMetadata
- FieldMetadata delegator = null; // field to delegate
- MethodMetadata methodDelegator = null; // field to delegate
- for (int j = 0; j < methods.size(); j++) {
- MethodMetadata methodMeta = (MethodMetadata) methods.get(j);
- if (methodMeta.equals(method)) {
- delegator = methodMeta.getDelegation();
- methodDelegator = methodMeta;
- }
- }
-
- generateOneMethod(cw, className, methodDelegator, method, delegator);
-
- }
-
- // End process
- cw.visitEnd();
- b = cw.toByteArray();
-
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- // Write the class :
-// try {
-// FileOutputStream fos = new FileOutputStream(
-// "F:\\dev\\workspaces\\iPOJO_dev\\Test_Manipulator\\manipulated\\org\\apache\\felix\\ipojo\\test\\scenarios\\component\\"
-// + className.replace('/', '.') + ".class");
-//
-// fos.write(b);
-//
-// fos.close();
-// } catch (Exception e) {
-// System.err.println("Exception : " + e.getMessage());
-// }
-
- return b;
- }
-
- /**
- * Generate on method.
- * @param cw : class writer
- * @param className : the current class name
- * @param method : the method to generate
- * @param sign : method signature to generate
- * @param delegator : the field on which delegate
- */
- private static void generateOneMethod(ClassWriter cw, String className, MethodMetadata method, MethodSignature sign, FieldMetadata delegator) {
- String desc = sign.getDesc();
- String name = sign.getName();
- String signa = sign.getSignature();
- String[] exc = sign.getException();
-
- MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, name, desc, signa, exc);
-
- if (delegator.isOptional()) {
- if (!delegator.isAggregate()) {
- generateOptionalCase(mv, delegator, className);
- }
- if (delegator.isAggregate() /*&& method.getPolicy() == MethodMetadata.ONE_POLICY*/) {
- generateOptionalAggregateCase(mv, delegator, className);
- }
- }
-
- if (!delegator.isAggregate()) {
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, className, delegator.getName(), "L" + delegator.getSpecification().getName().replace('.', '/') + ";");
-
- // Loads args
- Type[] args = Type.getArgumentTypes(desc);
- for (int i = 0; i < args.length; i++) {
- writeLoad(args[i], i + 1, mv);
- }
-
- // Invoke
- if (delegator.getSpecification().isInterface()) {
- mv.visitMethodInsn(INVOKEINTERFACE, delegator.getSpecification().getName().replace('.', '/'), name, desc);
- } else {
- mv.visitMethodInsn(INVOKEVIRTUAL, delegator.getSpecification().getName().replace('.', '/'), name, desc);
- }
-
- // Return
- writeReturn(Type.getReturnType(desc), mv);
- } else {
- if (method.getPolicy() == MethodMetadata.ONE_POLICY) {
- // Aggregate and One Policy
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, className, delegator.getName(), "[L" + delegator.getSpecification().getName().replace('.', '/') + ";");
- mv.visitInsn(ICONST_0); // Take the first one
- mv.visitInsn(AALOAD);
-
- // Loads args
- Type[] args = Type.getArgumentTypes(desc);
- for (int i = 0; i < args.length; i++) {
- writeLoad(args[i], i + 1, mv);
- }
-
- // Invoke
- mv.visitMethodInsn(INVOKEINTERFACE, delegator.getSpecification().getName().replace('.', '/'), name, desc);
-
- // Return
- writeReturn(Type.getReturnType(desc), mv);
- } else { // All policy
- if (Type.getReturnType(desc).getSort() != Type.VOID) {
- System.err.println("All policy cannot be used on method which does not return void");
- }
-
- Type[] args = Type.getArgumentTypes(desc);
- int index = args.length + 1;
-
- // Init
- mv.visitInsn(ICONST_0);
- mv.visitVarInsn(ISTORE, index);
- Label l1b = new Label();
- mv.visitLabel(l1b);
- Label l2b = new Label();
- mv.visitJumpInsn(GOTO, l2b);
-
- // Loop
- Label l3b = new Label();
- mv.visitLabel(l3b);
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, className, delegator.getName(), "[L" + delegator.getSpecification().getName().replace('.', '/') + ";");
- mv.visitVarInsn(ILOAD, index);
- mv.visitInsn(AALOAD);
-
- // Loads args
- for (int i = 0; i < args.length; i++) {
- writeLoad(args[i], i + 1, mv);
- }
-
- mv.visitMethodInsn(INVOKEINTERFACE, delegator.getSpecification().getName().replace('.', '/'), name, desc);
-
- Label l4b = new Label();
- mv.visitLabel(l4b);
- mv.visitIincInsn(index, 1); // i++;
-
- // Condition
- mv.visitLabel(l2b);
- mv.visitVarInsn(ILOAD, index);
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, className, delegator.getName(), "[L" + delegator.getSpecification().getName().replace('.', '/') + ";");
- mv.visitInsn(ARRAYLENGTH);
- mv.visitJumpInsn(IF_ICMPLT, l3b);
-
- Label l5b = new Label();
- mv.visitLabel(l5b);
- mv.visitInsn(RETURN);
- }
- }
-
- mv.visitMaxs(0, 0);
- mv.visitEnd();
- }
-
- /**
- * Generate Optional Case for aggregate field.
- * @param mv : method visitor
- * @param delegator : Field on which delegate
- * @param className : current class name
- */
- private static void generateOptionalAggregateCase(MethodVisitor mv, FieldMetadata delegator, String className) {
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, className, delegator.getName(), "[L" + delegator.getSpecification().getName().replace('.', '/') + ";");
- mv.visitInsn(ARRAYLENGTH);
- Label l1a = new Label();
- mv.visitJumpInsn(IFNE, l1a);
- Label l2a = new Label();
- mv.visitLabel(l2a);
- mv.visitTypeInsn(NEW, "java/lang/UnsupportedOperationException");
- mv.visitInsn(DUP);
- mv.visitLdcInsn("Operation not supported");
- mv.visitMethodInsn(INVOKESPECIAL, "java/lang/UnsupportedOperationException", "<init>", "(Ljava/lang/String;)V");
- mv.visitInsn(ATHROW);
- mv.visitLabel(l1a);
- }
-
- /**
- * Generate Optional case for non aggregate fields.
- *
- * @param mv : the method visitor
- * @param delegator : the field on which delegate.
- * @param className : the name of the current class.
- */
- private static void generateOptionalCase(MethodVisitor mv, FieldMetadata delegator, String className) {
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, className, delegator.getName(), "L" + delegator.getSpecification().getName().replace('.', '/') + ";");
- mv.visitTypeInsn(INSTANCEOF, "org/apache/felix/ipojo/Nullable");
- Label end = new Label();
- mv.visitJumpInsn(IFEQ, end);
- Label begin = new Label();
- mv.visitLabel(begin);
- mv.visitTypeInsn(NEW, "java/lang/UnsupportedOperationException");
- mv.visitInsn(DUP);
- mv.visitLdcInsn("Operation not supported");
- mv.visitMethodInsn(INVOKESPECIAL, "java/lang/UnsupportedOperationException", "<init>", "(Ljava/lang/String;)V");
- mv.visitInsn(ATHROW);
- mv.visitLabel(end);
- }
-
- /**
- * Write a return instruction according to the given type.
- * @param t : the type
- * @param mv : the method visitor
- */
- private static void writeReturn(Type t, MethodVisitor mv) {
- switch (t.getSort()) {
- case Type.BOOLEAN:
- case Type.INT:
- case Type.BYTE:
- case Type.CHAR:
- case Type.SHORT:
- // Integer or Boolean : return 0 ( false)
- mv.visitInsn(IRETURN);
- break;
- case Type.LONG:
- // mv.visitInsn(LCONST_0);
- mv.visitInsn(LRETURN);
- break;
- case Type.DOUBLE:
- // Double : return 0.0
- // mv.visitInsn(DCONST_0);
- mv.visitInsn(DRETURN);
- break;
- case Type.FLOAT:
- // Double : return 0.0
- // mv.visitInsn(DCONST_0);
- mv.visitInsn(FRETURN);
- break;
- case Type.ARRAY:
- case Type.OBJECT:
- // Return always null for array and object
- // mv.visitInsn(ACONST_NULL);
- mv.visitInsn(ARETURN);
- break;
- case Type.VOID:
- mv.visitInsn(RETURN);
- break;
- default:
- System.err.println("Type not yet managed : " + t);
- break;
- }
- }
-
- /**
- * Write a load instruction according to the given type.
- * @param t : the type
- * @param mv : the method visitor
- * @param index : variable name (index)
- */
- private static void writeLoad(Type t, int index, MethodVisitor mv) {
- switch (t.getSort()) {
- case Type.BOOLEAN:
- case Type.INT:
- case Type.BYTE:
- case Type.CHAR:
- case Type.SHORT:
- // Integer or Boolean : return 0 ( false)
- mv.visitVarInsn(ILOAD, index);
- break;
- case Type.LONG:
- // mv.visitInsn(LCONST_0);
- mv.visitVarInsn(LLOAD, index);
- break;
- case Type.FLOAT:
- // mv.visitInsn(LCONST_0);
- mv.visitVarInsn(FLOAD, index);
- break;
- case Type.DOUBLE:
- // Double : return 0.0
- // mv.visitInsn(DCONST_0);
- mv.visitVarInsn(DLOAD, index);
- break;
- case Type.ARRAY:
- case Type.OBJECT:
- // Return always null for array and object
- // mv.visitInsn(ACONST_NULL);
- mv.visitVarInsn(ALOAD, index);
- break;
- default:
- System.err.println("Type not yet managed : " + t);
- break;
- }
- }
-
-}
+/*
+ * 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.felix.ipojo.composite.service.provides;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.List;
+
+import org.apache.felix.ipojo.handlers.dependency.nullable.MethodSignature;
+import org.apache.felix.ipojo.handlers.dependency.nullable.MethodSignatureVisitor;
+import org.objectweb.asm.ClassReader;
+import org.objectweb.asm.ClassWriter;
+import org.objectweb.asm.Label;
+import org.objectweb.asm.MethodVisitor;
+import org.objectweb.asm.Opcodes;
+import org.objectweb.asm.Type;
+
+/**
+ * Create the proxy class.
+ *
+ * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
+ */
+public class POJOWriter implements Opcodes {
+
+ /**
+ * Create a class.
+ * @param cw : class writer
+ * @param className : class name
+ * @param spec : implemented specification
+ */
+ private static void createClass(ClassWriter cw, String className, String spec) {
+ // Create the class
+ cw.visit(V1_2, ACC_PUBLIC + ACC_SUPER, className, null, "java/lang/Object", new String[] { spec.replace('.', '/') });
+ }
+
+ /**
+ * Inject field in the current class.
+ * @param cw : class writer.
+ * @param fields : list of field to inject.
+ */
+ private static void injectFields(ClassWriter cw, List fields) {
+ // Inject fields
+ for (int i = 0; i < fields.size(); i++) {
+ FieldMetadata field = (FieldMetadata) fields.get(i);
+ if (field.isUseful()) {
+ SpecificationMetadata spec = field.getSpecification();
+ String fieldName = field.getName();
+ String desc = "";
+ if (field.isAggregate()) {
+ desc = "[L" + spec.getName().replace('.', '/') + ";";
+ } else {
+ desc = "L" + spec.getName().replace('.', '/') + ";";
+ }
+
+ cw.visitField(Opcodes.ACC_PRIVATE, fieldName, desc, null, null);
+ }
+ }
+ }
+
+ /**
+ * Return the proxy classname for the contract contractname by delegating on available service.
+ * @param url URL of the needed contract
+ * @param contractName : The interface to implement
+ * @param className : The class name to create
+ * @param fields : the list of fields on which delegate
+ * @param methods : the list of method on which delegate
+ * @return byte[] : the build class
+ */
+ public static byte[] dump(URL url, String contractName, String className, List fields, List methods) {
+
+ ClassReader cr = null;
+ InputStream is = null;
+ byte[] b = null;
+ try {
+ is = url.openStream();
+ cr = new ClassReader(is);
+ MethodSignatureVisitor msv = new MethodSignatureVisitor();
+ cr.accept(msv, ClassReader.SKIP_FRAMES);
+ is.close();
+
+ MethodSignature[] methodsSign = msv.getMethods();
+
+ ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
+
+ // Create the class
+ className = className.replace('.', '/');
+ createClass(cw, className, contractName);
+
+ // Inject fields inside the POJO
+ injectFields(cw, fields);
+
+ // Inject a constructor <INIT>()V
+ MethodVisitor cst = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
+ cst.visitVarInsn(ALOAD, 0);
+ cst.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
+ cst.visitInsn(RETURN);
+ cst.visitMaxs(0, 0);
+ cst.visitEnd();
+
+ for (int i = 0; i < methodsSign.length; ++i) {
+ MethodSignature method = methodsSign[i];
+
+ // Get the field for this method
+ // 1) find the MethodMetadata
+ FieldMetadata delegator = null; // field to delegate
+ MethodMetadata methodDelegator = null; // field to delegate
+ for (int j = 0; j < methods.size(); j++) {
+ MethodMetadata methodMeta = (MethodMetadata) methods.get(j);
+ if (methodMeta.equals(method)) {
+ delegator = methodMeta.getDelegation();
+ methodDelegator = methodMeta;
+ }
+ }
+
+ generateOneMethod(cw, className, methodDelegator, method, delegator);
+
+ }
+
+ // End process
+ cw.visitEnd();
+ b = cw.toByteArray();
+
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ // Write the class :
+// try {
+// FileOutputStream fos = new FileOutputStream(
+// "F:\\dev\\workspaces\\iPOJO_dev\\Test_Manipulator\\manipulated\\org\\apache\\felix\\ipojo\\test\\scenarios\\component\\"
+// + className.replace('/', '.') + ".class");
+//
+// fos.write(b);
+//
+// fos.close();
+// } catch (Exception e) {
+// System.err.println("Exception : " + e.getMessage());
+// }
+
+ return b;
+ }
+
+ /**
+ * Generate on method.
+ * @param cw : class writer
+ * @param className : the current class name
+ * @param method : the method to generate
+ * @param sign : method signature to generate
+ * @param delegator : the field on which delegate
+ */
+ private static void generateOneMethod(ClassWriter cw, String className, MethodMetadata method, MethodSignature sign, FieldMetadata delegator) {
+ String desc = sign.getDesc();
+ String name = sign.getName();
+ String signa = sign.getSignature();
+ String[] exc = sign.getException();
+
+ MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, name, desc, signa, exc);
+
+ if (delegator.isOptional()) {
+ if (!delegator.isAggregate()) {
+ generateOptionalCase(mv, delegator, className);
+ }
+ if (delegator.isAggregate() /*&& method.getPolicy() == MethodMetadata.ONE_POLICY*/) {
+ generateOptionalAggregateCase(mv, delegator, className);
+ }
+ }
+
+ if (!delegator.isAggregate()) {
+ mv.visitVarInsn(ALOAD, 0);
+ mv.visitFieldInsn(GETFIELD, className, delegator.getName(), "L" + delegator.getSpecification().getName().replace('.', '/') + ";");
+
+ // Loads args
+ Type[] args = Type.getArgumentTypes(desc);
+ for (int i = 0; i < args.length; i++) {
+ writeLoad(args[i], i + 1, mv);
+ }
+
+ // Invoke
+ if (delegator.getSpecification().isInterface()) {
+ mv.visitMethodInsn(INVOKEINTERFACE, delegator.getSpecification().getName().replace('.', '/'), name, desc);
+ } else {
+ mv.visitMethodInsn(INVOKEVIRTUAL, delegator.getSpecification().getName().replace('.', '/'), name, desc);
+ }
+
+ // Return
+ writeReturn(Type.getReturnType(desc), mv);
+ } else {
+ if (method.getPolicy() == MethodMetadata.ONE_POLICY) {
+ // Aggregate and One Policy
+ mv.visitVarInsn(ALOAD, 0);
+ mv.visitFieldInsn(GETFIELD, className, delegator.getName(), "[L" + delegator.getSpecification().getName().replace('.', '/') + ";");
+ mv.visitInsn(ICONST_0); // Take the first one
+ mv.visitInsn(AALOAD);
+
+ // Loads args
+ Type[] args = Type.getArgumentTypes(desc);
+ for (int i = 0; i < args.length; i++) {
+ writeLoad(args[i], i + 1, mv);
+ }
+
+ // Invoke
+ mv.visitMethodInsn(INVOKEINTERFACE, delegator.getSpecification().getName().replace('.', '/'), name, desc);
+
+ // Return
+ writeReturn(Type.getReturnType(desc), mv);
+ } else { // All policy
+ if (Type.getReturnType(desc).getSort() != Type.VOID) {
+ System.err.println("All policy cannot be used on method which does not return void");
+ }
+
+ Type[] args = Type.getArgumentTypes(desc);
+ int index = args.length + 1;
+
+ // Init
+ mv.visitInsn(ICONST_0);
+ mv.visitVarInsn(ISTORE, index);
+ Label l1b = new Label();
+ mv.visitLabel(l1b);
+ Label l2b = new Label();
+ mv.visitJumpInsn(GOTO, l2b);
+
+ // Loop
+ Label l3b = new Label();
+ mv.visitLabel(l3b);
+ mv.visitVarInsn(ALOAD, 0);
+ mv.visitFieldInsn(GETFIELD, className, delegator.getName(), "[L" + delegator.getSpecification().getName().replace('.', '/') + ";");
+ mv.visitVarInsn(ILOAD, index);
+ mv.visitInsn(AALOAD);
+
+ // Loads args
+ for (int i = 0; i < args.length; i++) {
+ writeLoad(args[i], i + 1, mv);
+ }
+
+ mv.visitMethodInsn(INVOKEINTERFACE, delegator.getSpecification().getName().replace('.', '/'), name, desc);
+
+ Label l4b = new Label();
+ mv.visitLabel(l4b);
+ mv.visitIincInsn(index, 1); // i++;
+
+ // Condition
+ mv.visitLabel(l2b);
+ mv.visitVarInsn(ILOAD, index);
+ mv.visitVarInsn(ALOAD, 0);
+ mv.visitFieldInsn(GETFIELD, className, delegator.getName(), "[L" + delegator.getSpecification().getName().replace('.', '/') + ";");
+ mv.visitInsn(ARRAYLENGTH);
+ mv.visitJumpInsn(IF_ICMPLT, l3b);
+
+ Label l5b = new Label();
+ mv.visitLabel(l5b);
+ mv.visitInsn(RETURN);
+ }
+ }
+
+ mv.visitMaxs(0, 0);
+ mv.visitEnd();
+ }
+
+ /**
+ * Generate Optional Case for aggregate field.
+ * @param mv : method visitor
+ * @param delegator : Field on which delegate
+ * @param className : current class name
+ */
+ private static void generateOptionalAggregateCase(MethodVisitor mv, FieldMetadata delegator, String className) {
+ mv.visitVarInsn(ALOAD, 0);
+ mv.visitFieldInsn(GETFIELD, className, delegator.getName(), "[L" + delegator.getSpecification().getName().replace('.', '/') + ";");
+ mv.visitInsn(ARRAYLENGTH);
+ Label l1a = new Label();
+ mv.visitJumpInsn(IFNE, l1a);
+ Label l2a = new Label();
+ mv.visitLabel(l2a);
+ mv.visitTypeInsn(NEW, "java/lang/UnsupportedOperationException");
+ mv.visitInsn(DUP);
+ mv.visitLdcInsn("Operation not supported");
+ mv.visitMethodInsn(INVOKESPECIAL, "java/lang/UnsupportedOperationException", "<init>", "(Ljava/lang/String;)V");
+ mv.visitInsn(ATHROW);
+ mv.visitLabel(l1a);
+ }
+
+ /**
+ * Generate Optional case for non aggregate fields.
+ *
+ * @param mv : the method visitor
+ * @param delegator : the field on which delegate.
+ * @param className : the name of the current class.
+ */
+ private static void generateOptionalCase(MethodVisitor mv, FieldMetadata delegator, String className) {
+ mv.visitVarInsn(ALOAD, 0);
+ mv.visitFieldInsn(GETFIELD, className, delegator.getName(), "L" + delegator.getSpecification().getName().replace('.', '/') + ";");
+ mv.visitTypeInsn(INSTANCEOF, "org/apache/felix/ipojo/Nullable");
+ Label end = new Label();
+ mv.visitJumpInsn(IFEQ, end);
+ Label begin = new Label();
+ mv.visitLabel(begin);
+ mv.visitTypeInsn(NEW, "java/lang/UnsupportedOperationException");
+ mv.visitInsn(DUP);
+ mv.visitLdcInsn("Operation not supported");
+ mv.visitMethodInsn(INVOKESPECIAL, "java/lang/UnsupportedOperationException", "<init>", "(Ljava/lang/String;)V");
+ mv.visitInsn(ATHROW);
+ mv.visitLabel(end);
+ }
+
+ /**
+ * Write a return instruction according to the given type.
+ * @param t : the type
+ * @param mv : the method visitor
+ */
+ private static void writeReturn(Type t, MethodVisitor mv) {
+ switch (t.getSort()) {
+ case Type.BOOLEAN:
+ case Type.INT:
+ case Type.BYTE:
+ case Type.CHAR:
+ case Type.SHORT:
+ // Integer or Boolean : return 0 ( false)
+ mv.visitInsn(IRETURN);
+ break;
+ case Type.LONG:
+ // mv.visitInsn(LCONST_0);
+ mv.visitInsn(LRETURN);
+ break;
+ case Type.DOUBLE:
+ // Double : return 0.0
+ // mv.visitInsn(DCONST_0);
+ mv.visitInsn(DRETURN);
+ break;
+ case Type.FLOAT:
+ // Double : return 0.0
+ // mv.visitInsn(DCONST_0);
+ mv.visitInsn(FRETURN);
+ break;
+ case Type.ARRAY:
+ case Type.OBJECT:
+ // Return always null for array and object
+ // mv.visitInsn(ACONST_NULL);
+ mv.visitInsn(ARETURN);
+ break;
+ case Type.VOID:
+ mv.visitInsn(RETURN);
+ break;
+ default:
+ System.err.println("Type not yet managed : " + t);
+ break;
+ }
+ }
+
+ /**
+ * Write a load instruction according to the given type.
+ * @param t : the type
+ * @param mv : the method visitor
+ * @param index : variable name (index)
+ */
+ private static void writeLoad(Type t, int index, MethodVisitor mv) {
+ switch (t.getSort()) {
+ case Type.BOOLEAN:
+ case Type.INT:
+ case Type.BYTE:
+ case Type.CHAR:
+ case Type.SHORT:
+ // Integer or Boolean : return 0 ( false)
+ mv.visitVarInsn(ILOAD, index);
+ break;
+ case Type.LONG:
+ // mv.visitInsn(LCONST_0);
+ mv.visitVarInsn(LLOAD, index);
+ break;
+ case Type.FLOAT:
+ // mv.visitInsn(LCONST_0);
+ mv.visitVarInsn(FLOAD, index);
+ break;
+ case Type.DOUBLE:
+ // Double : return 0.0
+ // mv.visitInsn(DCONST_0);
+ mv.visitVarInsn(DLOAD, index);
+ break;
+ case Type.ARRAY:
+ case Type.OBJECT:
+ // Return always null for array and object
+ // mv.visitInsn(ACONST_NULL);
+ mv.visitVarInsn(ALOAD, index);
+ break;
+ default:
+ System.err.println("Type not yet managed : " + t);
+ break;
+ }
+ }
+
+}
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/ProvidedServiceHandler.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/ProvidedServiceHandler.java
index 322cc6d..164c5bc 100644
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/ProvidedServiceHandler.java
+++ b/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/ProvidedServiceHandler.java
@@ -196,7 +196,17 @@
m_services.add(sm);
}
- Element[] imports = metadata.getElements("import", "");
+ Element[] imports = metadata.getElements("requires", "");
+
+ // DEPRECATED BLOCK:
+ if (imports.length == 0) {
+ imports = metadata.getElements("import");
+ if (imports.length != 0) {
+ m_manager.getFactory().getLogger().log(Logger.WARNING, "Import is deprecated, please use 'requires' instead of 'import'");
+ }
+ }
+ // END OF DEPRECATED BLOCK
+
for (int i = 0; i < imports.length; i++) {
String itf = imports[i].getAttribute("specification");
boolean agg = false;
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/manipulation/ClassChecker.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/manipulation/ClassChecker.java
deleted file mode 100644
index 6983939..0000000
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/manipulation/ClassChecker.java
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- * 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.felix.ipojo.composite.service.provides.manipulation;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-import org.objectweb.asm.AnnotationVisitor;
-import org.objectweb.asm.Attribute;
-import org.objectweb.asm.ClassVisitor;
-import org.objectweb.asm.FieldVisitor;
-import org.objectweb.asm.MethodVisitor;
-import org.objectweb.asm.Opcodes;
-import org.objectweb.asm.Type;
-
-/**
- * Check if the class is already manipulated.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class ClassChecker implements ClassVisitor, Opcodes {
-
- /**
- * True if the class is already manipulated.
- */
- private boolean m_isAlreadyManipulated = false;
-
- /**
- * Interfaces implemented by the component.
- */
- private String[] m_itfs = new String[0];
-
- /**
- * Field hashmap [field name, type] discovered in the component class.
- */
- private HashMap m_fields = new HashMap();
-
- /**
- * Method List of method descriptor discovered in the component class.
- */
- private List m_methods = new ArrayList()/* <MethodDesciptor> */;
-
- /**
- * Check if the _cm field already exists.
- * @param access : Field visibility
- * @param name : Field name
- * @param desc : Field description
- * @param signature : Field signature
- * @param value : field default value (static only)
- * @return The field visitor for this field
- * @see org.objectweb.asm.ClassVisitor#visitField(int, java.lang.String,
- * java.lang.String, java.lang.String, java.lang.Object)
- */
- public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
-
- if (access == ACC_PRIVATE && name.equals("_cm") && desc.equals("Lorg/apache/felix/ipojo/InstanceManager;")) {
- m_isAlreadyManipulated = true;
- }
-
- Type type = Type.getType(desc);
- if (type.getSort() == Type.ARRAY) {
- if (type.getInternalName().startsWith("L")) {
- String internalType = type.getInternalName().substring(1);
- String nameType = internalType.replace('/', '.');
- m_fields.put(name, nameType + "[]");
- } else {
- String nameType = type.getClassName().substring(0, type.getClassName().length() - 2);
- m_fields.put(name, nameType + "[]");
- }
- } else {
- m_fields.put(name, type.getClassName());
- }
-
- return null;
- }
-
- /**
- * Check if the class is already manipulated.
- * @return true if the class is already manipulated.
- */
- public boolean isalreadyManipulated() {
- return m_isAlreadyManipulated;
- }
-
- /**
- * Visit a class.
- * @param version : Bytecode version
- * @param access : Class visibility
- * @param name : Class name
- * @param signature : Class signature
- * @param superName : Super Class
- * @param interfaces : Interfaces imlemented by the class
- * @see org.objectweb.asm.ClassVisitor#visit(int, int, java.lang.String,
- * java.lang.String, java.lang.String, java.lang.String[])
- */
- public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
- // Store the interfaces :
- m_itfs = interfaces;
- }
-
- /**
- * Visit source.
- * @param arg0 :
- * @param arg1 :
- * @see org.objectweb.asm.ClassVisitor#visitSource(java.lang.String, java.lang.String)
- */
- public void visitSource(String arg0, String arg1) {
- }
-
- /**
- * Visit a outer class.
- * @param arg0 :
- * @param arg1 :
- * @param arg2 :
- * @see org.objectweb.asm.ClassVisitor#visitOuterClass(java.lang.String, java.lang.String, java.lang.String)
- */
- public void visitOuterClass(String arg0, String arg1, String arg2) {
- }
-
- /**
- * Visit an annotation.
- * @param arg0 :
- * @param arg1 :
- * @return The annotation visitor (null)
- * @see org.objectweb.asm.ClassVisitor#visitAnnotation(java.lang.String, boolean)
- */
- public AnnotationVisitor visitAnnotation(String arg0, boolean arg1) {
- return null;
- }
-
- /**
- * Visit an Attribute.
- * @param arg0 :
- * @see org.objectweb.asm.ClassVisitor#visitAttribute(org.objectweb.asm.Attribute)
- */
- public void visitAttribute(Attribute arg0) {
- }
-
- /**
- * Visit an inner class.
- * @param arg0 :
- * @param arg1 :
- * @param arg2 :
- * @param arg3 :
- * @see org.objectweb.asm.ClassVisitor#visitInnerClass(java.lang.String, java.lang.String, java.lang.String, int)
- */
- public void visitInnerClass(String arg0, String arg1, String arg2, int arg3) {
- }
-
- /**
- * Visit a method.
- * @param access : Method visibility
- * @param name : Method name
- * @param desc : Method description
- * @param signature : Method signature
- * @param exceptions : Method exceptions list
- * @return The method visitor for this method
- * @see org.objectweb.asm.ClassVisitor#visitMethod(int, java.lang.String,
- * java.lang.String, java.lang.String, java.lang.String[])
- */
- public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
- return null;
- }
-
- /**
- * End of the visit.
- * @see org.objectweb.asm.ClassVisitor#visitEnd()
- */
- public void visitEnd() {
- }
-
- /**
- * Get the interfaces implemented by the visited class.
- * @return the interfaces implemented by the component class.
- */
- public String[] getInterfaces() {
- return m_itfs;
- }
-
- /**
- * Get the field contained in the visited class.
- * @return the field hashmap [field_name, type].
- */
- public HashMap getFields() {
- return m_fields;
- }
-
- /**
- * Get the list of the method contained in the visited class.
- * @return the method list of [method, signature].
- */
- public List getMethods() {
- return m_methods;
- }
-
-}
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/manipulation/ConstructorCodeAdapter.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/manipulation/ConstructorCodeAdapter.java
deleted file mode 100644
index 566d6ae..0000000
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/manipulation/ConstructorCodeAdapter.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * 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.felix.ipojo.composite.service.provides.manipulation;
-
-import org.objectweb.asm.Label;
-import org.objectweb.asm.MethodAdapter;
-import org.objectweb.asm.MethodVisitor;
-import org.objectweb.asm.Opcodes;
-
-/**
- * Constructor Adapter : add a component manager argument inside a constructor.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class ConstructorCodeAdapter extends MethodAdapter implements Opcodes {
-
- /**
- * The owner class of the field. m_owner : String
- */
- private String m_owner;
-
- /**
- * Is super constructor already invoked?
- */
- private boolean m_superDetected;
-
- /**
- * PropertyCodeAdapter constructor. A new FiledCodeAdapter should be create
- * for each method visit.
- *
- * @param mv MethodVisitor
- * @param owner Name of the class
- */
- public ConstructorCodeAdapter(final MethodVisitor mv, final String owner) {
- super(mv);
- m_owner = owner;
- m_superDetected = false;
- }
-
- /**
- * Visit Method for Field instance (GETFIELD).
- *
- * @see org.objectweb.asm.MethodVisitor#visitFieldInsn(int, String, String,
- * String)
- * @param opcode : visited operation code
- * @param owner : owner of the field
- * @param name : name of the field
- * @param desc : decriptor of the field
- */
- public void visitFieldInsn(final int opcode, final String owner, final String name, final String desc) {
- if (owner.equals(m_owner)) {
- if (opcode == GETFIELD) {
- String gDesc = "()" + desc;
- visitMethodInsn(INVOKEVIRTUAL, owner, "_get" + name, gDesc);
- return;
- } else if (opcode == PUTFIELD) {
- // replaces PUTFIELD f by INVOKESPECIAL _setf
- String sDesc = "(" + desc + ")V";
- visitMethodInsn(INVOKESPECIAL, owner, "_set" + name, sDesc);
- return;
- }
- }
- super.visitFieldInsn(opcode, owner, name, desc);
- }
-
- /**
- * Visit a method instruction.
- * Insert an invoke on _setComponentManager.
- * @param opcode : instructino code
- * @param owner : owning class
- * @param name : name of the method
- * @param desc : method description
- * @see org.objectweb.asm.MethodAdapter#visitMethodInsn(int, java.lang.String, java.lang.String, java.lang.String)
- */
- public void visitMethodInsn(int opcode, String owner, String name, String desc) {
- // A method call is detected, check if it is the super call :
- if (!m_superDetected) {
- m_superDetected = true;
- // The first invocation is the super call
- // 1) Visit the super constructor :
- mv.visitVarInsn(ALOAD, 0);
- mv.visitMethodInsn(opcode, owner, name, desc); // Super constructor
- // invocation
-
- // 2) Load the object and the component manager argument
- mv.visitVarInsn(ALOAD, 0);
- // mv.visitVarInsn(ALOAD,
- // Type.getArgumentTypes(m_constructorDesc).length);
- mv.visitVarInsn(ALOAD, 1); // CM is always the first argument
- // 3) Initialize the field
- mv.visitMethodInsn(INVOKESPECIAL, m_owner, "_setComponentManager", "(Lorg/apache/felix/ipojo/InstanceManager;)V");
- // insertion finished
- } else {
- mv.visitMethodInsn(opcode, owner, name, desc);
- }
- }
-
- /**
- * Visit a variable.
- * @param opcode : instruction code
- * @param var : visited variable
- * @see org.objectweb.asm.MethodAdapter#visitVarInsn(int, int)
- */
- public void visitVarInsn(int opcode, int var) {
- if (!m_superDetected) {
- return; // Do nothing the ALOAD 0 will be injected by
- // visitMethodInsn
- } else {
- if (var == 0) {
- mv.visitVarInsn(opcode, var);
- } else { // ALOAD 0 (THIS)
- mv.visitVarInsn(opcode, var + 1);
- } // All other variable count
- }
- }
-
- /**
- * Visit a variable to increment it.
- * @param var : incrementied variable
- * @param increment : increment
- * @see org.objectweb.asm.MethodAdapter#visitIincInsn(int, int)
- */
- public void visitIincInsn(int var, int increment) {
- if (var != 0) {
- mv.visitIincInsn(var + 1, increment);
- } else {
- mv.visitIincInsn(var, increment);
- } // Increment the current object ???
- }
-
- /**
- * Visit a local variable.
- * Add a visit on m_manager.
- * @param name : variable name
- * @param desc : variable description
- * @param signature : variable signature
- * @param start : start label of the variable definition
- * @param end : end label of the variable definition
- * @param index : vairable nuber.
- * @see org.objectweb.asm.MethodAdapter#visitLocalVariable(java.lang.String, java.lang.String, java.lang.String, org.objectweb.asm.Label, org.objectweb.asm.Label, int)
- */
- public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) {
- if (index == 0) {
- mv.visitLocalVariable(name, desc, signature, start, end, index);
- mv.visitLocalVariable("_manager", "Lorg/apache/felix/ipojo/InstanceManager;", null, start, end, 1);
- }
- mv.visitLocalVariable(name, desc, signature, start, end, index + 1);
- }
-
- /**
- * Computer visit max.
- * Add a local variable.
- * @param maxStack : stack max size.
- * @param maxLocals : maximum of visited local variable.
- * @see org.objectweb.asm.MethodAdapter#visitMaxs(int, int)
- */
- public void visitMaxs(int maxStack, int maxLocals) {
- mv.visitMaxs(maxStack, maxLocals + 1);
- }
-}
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/manipulation/ManipulationProperty.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/manipulation/ManipulationProperty.java
deleted file mode 100644
index 285600e..0000000
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/manipulation/ManipulationProperty.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * 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.felix.ipojo.composite.service.provides.manipulation;
-
-/**
- * Store properties for the manipulation process.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- *
- */
-public class ManipulationProperty {
-
- /**
- * iPOJO Package name.
- */
- protected static final String IPOJO_PACKAGE_NAME = "org.apache.felix.ipojo";
-
- /**
- * Activator internal package name.
- */
- protected static final String IPOJO_INTERNAL_PACKAGE_NAME = "org/apache/felix/ipojo/";
-
- /**
- * Ipojo internal package name for internal descriptor.
- */
- protected static final String IPOJO_INTERNAL_DESCRIPTOR = "L" + IPOJO_INTERNAL_PACKAGE_NAME;
-
- /**
- * Helper array for bytecode manipulation of primitive type.
- */
- protected static final String[][] PRIMITIVE_BOXING_INFORMATION = new String[][] {
- { "V", "ILLEGAL", "ILLEGAL" }, // void type [0]
- { "Z", "java/lang/Boolean", "booleanValue" }, // boolean [1]
- { "C", "java/lang/Character", "charValue" }, // char [2]
- { "B", "java/lang/Byte", "byteValue" }, // byte [3]
- { "S", "java/lang/Short", "shortValue" }, // short [4]
- { "I", "java/lang/Integer", "intValue" }, // int [5]
- { "F", "java/lang/Float", "floatValue" }, // float [6]
- { "J", "java/lang/Long", "longValue" }, // long [7]
- { "D", "java/lang/Double", "doubleValue" } // double [8]
- };
-
-}
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/manipulation/Manipulator.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/manipulation/Manipulator.java
deleted file mode 100644
index 63a22cc..0000000
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/manipulation/Manipulator.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * 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.felix.ipojo.composite.service.provides.manipulation;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import org.objectweb.asm.ClassReader;
-import org.objectweb.asm.ClassWriter;
-
-/**
- * iPOJO Bytecode Manipulator.
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- *
- */
-public class Manipulator {
- /**
- * Store the visited fields : [name fo the field, type of the field].
- */
- private HashMap m_fields = new HashMap();
-
- /**
- * Store the interface implemented by the class.
- */
- private String[] m_interfaces = new String[0];
-
- /**
- * Return the hashmap [name of the field, type of the field]. This
- * information is found when the class is manipulated It is a clone of the
- * original hashmap to avoid modification by handlers
- *
- * @return the hashmap [name of the field, type of the field].
- */
- public HashMap getFields() {
- return m_fields;
- }
-
- /**
- * Return the hashmap [name of the field, type of the field]. This
- * information is found when the class is manipulated It is a clone of the
- * original hashmap to avoid modification by handlers
- *
- * @return the hashmap [name of the field, type of the field].
- */
- public String[] getInterfaces() {
- return m_interfaces;
- }
-
- /**
- * Manipulate the given byte array.
- *
- * @param origin : original class.
- * @return the manipulated class.
- * @throws IOException : if an error occurs during the manipulation.
- */
- public byte[] process(byte[] origin) throws IOException {
- InputStream is1 = new ByteArrayInputStream(origin);
-
- // First check if the class is already manipulated :
- ClassReader ckReader = new ClassReader(is1);
- ClassChecker ck = new ClassChecker();
- ckReader.accept(ck, ClassReader.SKIP_FRAMES);
- is1.close();
-
- m_fields = ck.getFields();
-
- // Get interface and remove POJO interface is presents
- String[] its = ck.getInterfaces();
- ArrayList l = new ArrayList();
- for (int i = 0; i < its.length; i++) {
- l.add(its[i]);
- }
- l.remove("org/apache/felix/ipojo/Pojo");
-
- m_interfaces = new String[l.size()];
- for (int i = 0; i < m_interfaces.length; i++) {
- m_interfaces[i] = ((String) l.get(i)).replace('/', '.');
- }
-
- ClassWriter finalWriter = null;
- if (!ck.isalreadyManipulated()) {
- // Manipulation ->
- // Add the _setComponentManager method
- // Instrument all fields
- InputStream is2 = new ByteArrayInputStream(origin);
- ClassReader cr0 = new ClassReader(is2);
- ClassWriter cw0 = new ClassWriter(ClassWriter.COMPUTE_MAXS);
- PreprocessClassAdapter preprocess = new PreprocessClassAdapter(cw0);
- cr0.accept(preprocess, ClassReader.SKIP_FRAMES);
- is2.close();
- finalWriter = cw0;
- }
- // The file is in the bundle
- return finalWriter.toByteArray();
- }
-
-}
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/manipulation/PreprocessClassAdapter.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/manipulation/PreprocessClassAdapter.java
deleted file mode 100644
index 81f6856..0000000
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/manipulation/PreprocessClassAdapter.java
+++ /dev/null
@@ -1,661 +0,0 @@
-/*
- * 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.felix.ipojo.composite.service.provides.manipulation;
-
-import org.objectweb.asm.ClassAdapter;
-import org.objectweb.asm.ClassVisitor;
-import org.objectweb.asm.FieldVisitor;
-import org.objectweb.asm.Label;
-import org.objectweb.asm.MethodVisitor;
-import org.objectweb.asm.Opcodes;
-import org.objectweb.asm.Type;
-
-/**
- * Manipulate the class. - Add a component manager field (_cm) - Create getter
- * and setter for each fields - Store information about field - Store
- * information about implemented interfaces - Change GETFIELD and PUTFIELD to
- * called the getter and setter method
- *
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- *
- */
-public class PreprocessClassAdapter extends ClassAdapter implements Opcodes {
-
- /**
- * Constant : POJO interface.
- */
- private static final String POJO_INTERFACE = "org/apache/felix/ipojo/Pojo";
-
- /**
- * The owner. m_owner : String
- */
- private String m_owner;
-
- /**
- * Constructor.
- *
- * @param cv : Class visitor
- */
- public PreprocessClassAdapter(final ClassVisitor cv) {
- super(cv);
- }
-
- /**
- * The visit method. - Insert the _cm field - Create the _initialize method -
- * Create the _cm setter method
- *
- * @see org.objectweb.asm.ClassVisitor#visit(int, int, String, String,
- * String, String[])
- * @param version : Version
- * @param access : Access modifier
- * @param name : name of the visited element
- * @param signature : singature of the visited element
- * @param superName : superclasses (extend clause)
- * @param interfaces : implement clause
- */
- public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) {
-
- m_owner = name;
-
- // Insert _cm field
- FieldVisitor fv = super.visitField(ACC_PRIVATE, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;", null, null);
- fv.visitEnd();
-
- // Create the _cmSetter(ComponentManager cm) method
- createComponentManagerSetter();
-
- // Add the getComponentInstance
- createGetComponentInstanceMethod();
-
- // Add the POJO interface to the interface list
- // Check that the POJO interface isnot already in the list
- boolean found = false;
- for (int i = 0; i < interfaces.length; i++) {
- if (interfaces[i].equals(POJO_INTERFACE)) {
- found = true;
- }
- }
- String[] itfs;
- if (!found) {
- itfs = new String[interfaces.length + 1];
- for (int i = 0; i < interfaces.length; i++) {
- itfs[i] = interfaces[i];
- }
- itfs[interfaces.length] = POJO_INTERFACE;
- } else {
- itfs = interfaces;
- }
-
- String str = "";
- for (int i = 0; i < itfs.length; i++) {
- str += itfs[i] + " ";
- }
-
- super.visit(version, access, name, signature, superName, itfs);
- }
-
- /**
- * visit method method :-).
- *
- * @see org.objectweb.asm.ClassVisitor#visitMethod(int, java.lang.String,
- * java.lang.String, java.lang.String, java.lang.String[])
- * @param access : access modifier
- * @param name : name of the method
- * @param desc : descriptor of the method
- * @param signature : signature of the method
- * @param exceptions : exception launched by the method
- * @return MethodVisitor
- */
- public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) {
- // The method is a constructor, adapt the constructor to add a
- // ComponentManager argument
- if (name.equals("<init>")) {
- // 1) change the constructor descriptor (add a component manager arg
- // as first argument)
- String newDesc = desc.substring(1);
- newDesc = "(Lorg/apache/felix/ipojo/InstanceManager;" + newDesc;
-
- // Insert the new constructor
- MethodVisitor mv = super.visitMethod(ACC_PUBLIC, "<init>", newDesc, null, null);
-
- if (mv == null) {
- return null;
- } else {
- return new ConstructorCodeAdapter(mv, m_owner);
- }
-
- } else {
- MethodVisitor mv = cv.visitMethod(access, name, desc, signature, exceptions);
- if (mv == null) {
- return null;
- } else {
- return new PreprocessCodeAdapter(mv, m_owner);
- }
- }
-
- }
-
- /**
- * Create the setter method for the _cm field.
- */
- private void createComponentManagerSetter() {
- MethodVisitor mv = cv.visitMethod(ACC_PRIVATE, "_setComponentManager", "(Lorg/apache/felix/ipojo/InstanceManager;)V", null, null);
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitVarInsn(ALOAD, 1);
- mv.visitFieldInsn(PUTFIELD, m_owner, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;");
-
- mv.visitInsn(RETURN);
-
- mv.visitMaxs(0, 0);
- mv.visitEnd();
- }
-
- /**
- * Create the getComponentInstance method.
- */
- private void createGetComponentInstanceMethod() {
- MethodVisitor mv = cv.visitMethod(ACC_PUBLIC, "getComponentInstance", "()Lorg/apache/felix/ipojo/ComponentInstance;", null, null);
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;");
- mv.visitInsn(ARETURN);
-
- mv.visitMaxs(0, 0);
- mv.visitEnd();
- }
-
- /**
- * visit Field method.
- *
- * @see org.objectweb.asm.ClassVisitor#visitField(int, java.lang.String,
- * java.lang.String, java.lang.String, java.lang.Object)
- * @param access : acces modifier
- * @param name : name of the field
- * @param desc : description of the field
- * @param signature : signature of the field
- * @param value : value of the field
- * @return FieldVisitor
- */
- public FieldVisitor visitField(final int access, final String name, final String desc, final String signature, final Object value) {
- if ((access & ACC_STATIC) == 0) {
- Type type = Type.getType(desc);
-
- // Keep the field in the code
- FieldVisitor fv = cv.visitField(access, name, desc, signature, value);
-
- if (type.getSort() == Type.ARRAY) {
-
- String gDesc = "()" + desc;
- createArrayGetter(name, gDesc);
-
- // Generates setter method
- String sDesc = "(" + desc + ")V";
- createArraySetter(name, sDesc);
-
- } else {
-
- // Generate the getter method
- String gDesc = "()" + desc;
- createSimpleGetter(name, gDesc, type);
-
- // Generates setter method
- String sDesc = "(" + desc + ")V";
- createSimpleSetter(name, sDesc, type);
- }
-
- return fv;
-
- }
- return super.visitField(access, name, desc, signature, value);
- }
-
- /**
- * Generate a setter method for an array field.
- * @param name : name of the field.
- * @param desc : description of the method
- */
- private void createArraySetter(String name, String desc) {
- MethodVisitor mv = cv.visitMethod(ACC_PRIVATE, "_set" + name, desc, null, null);
-
- String internalType = desc.substring(1);
- internalType = internalType.substring(0, internalType.length() - 2);
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitVarInsn(ALOAD, 1);
- mv.visitFieldInsn(PUTFIELD, m_owner, name, internalType);
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;");
- mv.visitLdcInsn(name);
- mv.visitVarInsn(ALOAD, 1);
- mv.visitMethodInsn(INVOKEVIRTUAL, "org/apache/felix/ipojo/InstanceManager", "setterCallback", "(Ljava/lang/String;Ljava/lang/Object;)V");
-
- mv.visitInsn(RETURN);
-
- // End
- mv.visitMaxs(0, 0);
- mv.visitEnd();
- }
-
- /**
- * Generate a getter method for an array field.
- * @param name : name of the field.
- * @param desc : description of the method
- */
- private void createArrayGetter(String name, String desc) {
-
- String methodName = "_get" + name;
- MethodVisitor mv = cv.visitMethod(ACC_PRIVATE, methodName, desc, null, null);
-
- String internalType = desc.substring(2);
-
- mv.visitVarInsn(ALOAD, 0);
- // mv.visitFieldInsn(GETFIELD, m_owner, name,
- // "["+type.getInternalName()+";");
- mv.visitFieldInsn(GETFIELD, m_owner, name, internalType);
- mv.visitVarInsn(ASTORE, 1);
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;");
- mv.visitLdcInsn(name);
- mv.visitVarInsn(ALOAD, 1);
- mv.visitMethodInsn(INVOKEVIRTUAL, "org/apache/felix/ipojo/InstanceManager", "getterCallback",
- "(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;");
- mv.visitVarInsn(ASTORE, 2);
-
- mv.visitVarInsn(ALOAD, 2);
- mv.visitTypeInsn(CHECKCAST, internalType);
- mv.visitVarInsn(ASTORE, 3);
-
- Label l3a = new Label();
- mv.visitLabel(l3a);
-
- mv.visitVarInsn(ALOAD, 1);
- Label l4a = new Label();
- mv.visitJumpInsn(IFNULL, l4a);
- mv.visitVarInsn(ALOAD, 1);
- mv.visitVarInsn(ALOAD, 3);
- mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "equals", "(Ljava/lang/Object;)Z");
-
- Label l5a = new Label();
- mv.visitJumpInsn(IFNE, l5a);
- mv.visitLabel(l4a);
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitVarInsn(ALOAD, 3);
- mv.visitMethodInsn(INVOKEVIRTUAL, m_owner, "_set" + name, "(" + internalType + ")V");
- mv.visitLabel(l5a);
-
- mv.visitVarInsn(ALOAD, 3);
- mv.visitInsn(ARETURN);
-
- // End
- mv.visitMaxs(0, 0);
- mv.visitEnd();
- }
-
- /**
- * Create the getter for service dependency.
- *
- * @param name : field of the dependency
- * @param desc : description of the getter method
- * @param type : type to return
- */
- private void createSimpleGetter(String name, String desc, Type type) {
-
- String methodName = "_get" + name;
- MethodVisitor mv = cv.visitMethod(ACC_PRIVATE, methodName, desc, null, null);
-
- switch (type.getSort()) {
- // Generate the getter method for boolean, char, byte shot as for int.
- case Type.BOOLEAN:
- case Type.CHAR:
- case Type.BYTE:
- case Type.SHORT:
- case Type.INT:
- String internalName = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][0];
- String boxingType = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][1];
- String unboxingMethod = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][2];
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, name, internalName);
- mv.visitVarInsn(type.getOpcode(ISTORE), 1);
- mv.visitTypeInsn(NEW, boxingType);
- mv.visitInsn(DUP);
- mv.visitVarInsn(type.getOpcode(ILOAD), 1);
- mv.visitMethodInsn(INVOKESPECIAL, boxingType, "<init>", "(" + internalName + ")V");
- mv.visitVarInsn(ASTORE, 2);
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;");
- mv.visitLdcInsn(name);
- mv.visitVarInsn(ALOAD, 2);
- mv.visitMethodInsn(INVOKEVIRTUAL, "org/apache/felix/ipojo/InstanceManager", "getterCallback",
- "(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;");
- mv.visitVarInsn(ASTORE, 3);
- mv.visitVarInsn(ALOAD, 3);
- mv.visitTypeInsn(CHECKCAST, boxingType);
- mv.visitVarInsn(ASTORE, 4);
- mv.visitVarInsn(ALOAD, 4);
- mv.visitMethodInsn(INVOKEVIRTUAL, boxingType, unboxingMethod, "()" + internalName);
- mv.visitVarInsn(type.getOpcode(ISTORE), 5);
- Label l5 = new Label();
- mv.visitLabel(l5);
- mv.visitVarInsn(type.getOpcode(ILOAD), 1);
- mv.visitVarInsn(type.getOpcode(ILOAD), 5);
- Label l6 = new Label();
- mv.visitJumpInsn(type.getOpcode(IF_ICMPEQ), l6);
- Label l7 = new Label();
- mv.visitLabel(l7);
- mv.visitVarInsn(ALOAD, 0);
- mv.visitVarInsn(type.getOpcode(ILOAD), 5);
- mv.visitMethodInsn(INVOKEVIRTUAL, m_owner, "_set" + name, "(" + internalName + ")V");
- mv.visitLabel(l6);
- mv.visitVarInsn(type.getOpcode(ILOAD), 5);
- mv.visitInsn(type.getOpcode(IRETURN));
- break;
-
- // Generate the getter for long
- case Type.LONG:
- internalName = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][0];
- boxingType = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][1];
- unboxingMethod = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][2];
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, name, internalName);
- mv.visitVarInsn(LSTORE, 1);
- mv.visitTypeInsn(NEW, boxingType);
- mv.visitInsn(DUP);
- mv.visitVarInsn(LLOAD, 1);
- mv.visitMethodInsn(INVOKESPECIAL, boxingType, "<init>", "(" + internalName + ")V");
- mv.visitVarInsn(ASTORE, 3); // Double Space
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;");
- mv.visitLdcInsn(name);
- mv.visitVarInsn(ALOAD, 3);
- mv.visitMethodInsn(INVOKEVIRTUAL, "org/apache/felix/ipojo/InstanceManager", "getterCallback",
- "(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;");
- mv.visitVarInsn(ASTORE, 4);
- mv.visitVarInsn(ALOAD, 4);
- mv.visitTypeInsn(CHECKCAST, boxingType);
- mv.visitVarInsn(ASTORE, 5);
- mv.visitVarInsn(ALOAD, 5);
- mv.visitMethodInsn(INVOKEVIRTUAL, boxingType, unboxingMethod, "()" + internalName);
- mv.visitVarInsn(LSTORE, 6);
- l5 = new Label();
- mv.visitLabel(l5);
- mv.visitVarInsn(LLOAD, 1);
- mv.visitVarInsn(LLOAD, 6);
- mv.visitInsn(LCMP);
- l6 = new Label();
- mv.visitJumpInsn(IFEQ, l6);
- l7 = new Label();
- mv.visitLabel(l7);
- mv.visitVarInsn(ALOAD, 0);
- mv.visitVarInsn(LLOAD, 6);
- mv.visitMethodInsn(INVOKEVIRTUAL, m_owner, "_set" + name, "(" + internalName + ")V");
- mv.visitLabel(l6);
- mv.visitVarInsn(LLOAD, 6);
- mv.visitInsn(LRETURN);
- break;
-
- // Generate the getter for double
- case Type.DOUBLE:
- internalName = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][0];
- boxingType = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][1];
- unboxingMethod = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][2];
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, name, internalName);
- mv.visitVarInsn(DSTORE, 1);
- mv.visitTypeInsn(NEW, boxingType);
- mv.visitInsn(DUP);
- mv.visitVarInsn(DLOAD, 1);
- mv.visitMethodInsn(INVOKESPECIAL, boxingType, "<init>", "(" + internalName + ")V");
- mv.visitVarInsn(ASTORE, 3); // Double Space
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;");
- mv.visitLdcInsn(name);
- mv.visitVarInsn(ALOAD, 3);
- mv.visitMethodInsn(INVOKEVIRTUAL, "org/apache/felix/ipojo/InstanceManager", "getterCallback",
- "(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;");
- mv.visitVarInsn(ASTORE, 4);
- mv.visitVarInsn(ALOAD, 4);
- mv.visitTypeInsn(CHECKCAST, boxingType);
- mv.visitVarInsn(ASTORE, 5);
- mv.visitVarInsn(ALOAD, 5);
- mv.visitMethodInsn(INVOKEVIRTUAL, boxingType, unboxingMethod, "()" + internalName);
- mv.visitVarInsn(DSTORE, 6);
- l5 = new Label();
- mv.visitLabel(l5);
- mv.visitVarInsn(DLOAD, 1);
- mv.visitVarInsn(DLOAD, 6);
- mv.visitInsn(DCMPL);
- l6 = new Label();
- mv.visitJumpInsn(IFEQ, l6);
- l7 = new Label();
- mv.visitLabel(l7);
- mv.visitVarInsn(ALOAD, 0);
- mv.visitVarInsn(DLOAD, 6);
- mv.visitMethodInsn(INVOKEVIRTUAL, m_owner, "_set" + name, "(" + internalName + ")V");
- mv.visitLabel(l6);
- mv.visitVarInsn(DLOAD, 6);
- mv.visitInsn(DRETURN);
- break;
-
- // Generate for float.
- case Type.FLOAT:
- internalName = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][0];
- boxingType = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][1];
- unboxingMethod = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][2];
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, name, internalName);
- mv.visitVarInsn(FSTORE, 1);
-
- mv.visitTypeInsn(NEW, boxingType);
- mv.visitInsn(DUP);
- mv.visitVarInsn(FLOAD, 1);
- mv.visitMethodInsn(INVOKESPECIAL, boxingType, "<init>", "(" + internalName + ")V");
- mv.visitVarInsn(ASTORE, 2); // One Space
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;");
- mv.visitLdcInsn(name);
- mv.visitVarInsn(ALOAD, 2);
- mv.visitMethodInsn(INVOKEVIRTUAL, "org/apache/felix/ipojo/InstanceManager", "getterCallback",
- "(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;");
- mv.visitVarInsn(ASTORE, 3);
-
- mv.visitVarInsn(ALOAD, 3);
- mv.visitTypeInsn(CHECKCAST, boxingType);
- mv.visitVarInsn(ASTORE, 4);
-
- mv.visitVarInsn(ALOAD, 4);
- mv.visitMethodInsn(INVOKEVIRTUAL, boxingType, unboxingMethod, "()" + internalName);
- mv.visitVarInsn(FSTORE, 5);
-
- l5 = new Label();
- mv.visitLabel(l5);
-
- mv.visitVarInsn(FLOAD, 1);
- mv.visitVarInsn(FLOAD, 5);
- mv.visitInsn(FCMPL);
- l6 = new Label();
- mv.visitJumpInsn(IFEQ, l6);
-
- l7 = new Label();
- mv.visitLabel(l7);
- mv.visitVarInsn(ALOAD, 0);
- mv.visitVarInsn(FLOAD, 5);
- mv.visitMethodInsn(INVOKEVIRTUAL, m_owner, "_set" + name, "(" + internalName + ")V");
- mv.visitLabel(l6);
-
- mv.visitVarInsn(FLOAD, 5);
- mv.visitInsn(FRETURN);
-
- break;
-
- //Generate for array.
- case Type.OBJECT:
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, name, "L" + type.getInternalName() + ";");
- mv.visitVarInsn(ASTORE, 1);
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;");
- mv.visitLdcInsn(name);
- mv.visitVarInsn(ALOAD, 1);
- mv.visitMethodInsn(INVOKEVIRTUAL, "org/apache/felix/ipojo/InstanceManager", "getterCallback",
- "(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;");
- mv.visitVarInsn(ASTORE, 2);
-
- mv.visitVarInsn(ALOAD, 2);
- mv.visitTypeInsn(CHECKCAST, type.getInternalName());
- mv.visitVarInsn(ASTORE, 3);
-
- Label l3b = new Label();
- mv.visitLabel(l3b);
-
- mv.visitVarInsn(ALOAD, 1);
- Label l4b = new Label();
- mv.visitJumpInsn(IFNULL, l4b);
- mv.visitVarInsn(ALOAD, 1);
- mv.visitVarInsn(ALOAD, 3);
- mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "equals", "(Ljava/lang/Object;)Z");
-
- Label l5b = new Label();
- mv.visitJumpInsn(IFNE, l5b);
- mv.visitLabel(l4b);
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitVarInsn(ALOAD, 3);
- mv.visitMethodInsn(INVOKEVIRTUAL, m_owner, "_set" + name, "(L" + type.getInternalName() + ";)V");
- mv.visitLabel(l5b);
-
- mv.visitVarInsn(ALOAD, 3);
- mv.visitInsn(ARETURN);
-
- break;
-
- default:
- break;
- }
-
- mv.visitMaxs(0, 0);
- mv.visitEnd();
- }
-
- /**
- * Create the setter method for one property. The name of the method is
- * _set+name of the field
- *
- * @param name : name of the field representing a property
- * @param desc : description of the setter method
- * @param type : type of the property
- */
- private void createSimpleSetter(String name, String desc, Type type) {
- MethodVisitor mv = cv.visitMethod(ACC_PRIVATE, "_set" + name, desc, null, null);
-
- switch (type.getSort()) {
- case Type.BOOLEAN:
- case Type.CHAR:
- case Type.BYTE:
- case Type.SHORT:
- case Type.INT:
- case Type.FLOAT:
- String internalName = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][0];
- String boxingType = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][1];
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitVarInsn(type.getOpcode(ILOAD), 1);
- mv.visitFieldInsn(PUTFIELD, m_owner, name, internalName);
- Label l1 = new Label();
- mv.visitLabel(l1);
-
- mv.visitTypeInsn(NEW, boxingType);
- mv.visitInsn(DUP);
- mv.visitVarInsn(type.getOpcode(ILOAD), 1);
- mv.visitMethodInsn(INVOKESPECIAL, boxingType, "<init>", "(" + internalName + ")V");
- mv.visitVarInsn(ASTORE, 2);
-
- Label l2 = new Label();
- mv.visitLabel(l2);
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;");
- mv.visitLdcInsn(name);
- mv.visitVarInsn(ALOAD, 2);
- mv.visitMethodInsn(INVOKEVIRTUAL, "org/apache/felix/ipojo/InstanceManager", "setterCallback", "(Ljava/lang/String;Ljava/lang/Object;)V");
-
- Label l3 = new Label();
- mv.visitLabel(l3);
- mv.visitInsn(RETURN);
- break;
-
- case Type.LONG:
- case Type.DOUBLE:
- internalName = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][0];
- boxingType = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][1];
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitVarInsn(type.getOpcode(ILOAD), 1);
- mv.visitFieldInsn(PUTFIELD, m_owner, name, internalName);
- l1 = new Label();
- mv.visitLabel(l1);
-
- mv.visitTypeInsn(NEW, boxingType);
- mv.visitInsn(DUP);
- mv.visitVarInsn(type.getOpcode(ILOAD), 1);
- mv.visitMethodInsn(INVOKESPECIAL, boxingType, "<init>", "(" + internalName + ")V");
- mv.visitVarInsn(ASTORE, 3); // Double space
-
- l2 = new Label();
- mv.visitLabel(l2);
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;");
- mv.visitLdcInsn(name);
- mv.visitVarInsn(ALOAD, 3);
- mv.visitMethodInsn(INVOKEVIRTUAL, "org/apache/felix/ipojo/InstanceManager", "setterCallback", "(Ljava/lang/String;Ljava/lang/Object;)V");
-
- l3 = new Label();
- mv.visitLabel(l3);
- mv.visitInsn(RETURN);
- break;
-
- case Type.OBJECT:
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitVarInsn(ALOAD, 1);
- mv.visitFieldInsn(PUTFIELD, m_owner, name, "L" + type.getInternalName() + ";");
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;");
- mv.visitLdcInsn(name);
- mv.visitVarInsn(ALOAD, 1);
- mv.visitMethodInsn(INVOKEVIRTUAL, "org/apache/felix/ipojo/InstanceManager", "setterCallback", "(Ljava/lang/String;Ljava/lang/Object;)V");
-
- mv.visitInsn(RETURN);
- break;
- default:
- break;
- }
-
- mv.visitMaxs(0, 0);
- mv.visitEnd();
- }
-}
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/manipulation/PreprocessCodeAdapter.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/manipulation/PreprocessCodeAdapter.java
deleted file mode 100644
index ac6406e..0000000
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/composite/service/provides/manipulation/PreprocessCodeAdapter.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * 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.felix.ipojo.composite.service.provides.manipulation;
-
-import org.objectweb.asm.MethodAdapter;
-import org.objectweb.asm.MethodVisitor;
-import org.objectweb.asm.Opcodes;
-
-/**
- * Manipulate a method to change all getter and setter on field by invocations on getter and setter callbacks.
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class PreprocessCodeAdapter extends MethodAdapter implements Opcodes {
-
- /**
- * The owner class of the field. m_owner : String
- */
- private String m_owner;
-
- /**
- * PropertyCodeAdapter constructor. A new FieldCodeAdapter should be create
- * for each method visit.
- *
- * @param mv MethodVisitor
- * @param owner Name of the class
- */
- public PreprocessCodeAdapter(final MethodVisitor mv, final String owner) {
- super(mv);
- m_owner = owner;
- }
-
- /**
- * Visit Method for Filed instance (GETFIELD).
- *
- * @see org.objectweb.asm.MethodVisitor#visitFieldInsn(int, String, String,
- * String)
- * @param opcode : visited operation code
- * @param owner : owner of the field
- * @param name : name of the field
- * @param desc : decriptor of the field
- */
- public void visitFieldInsn(final int opcode, final String owner, final String name, final String desc) {
- if (owner.equals(m_owner)) {
- if (opcode == GETFIELD) {
- String gDesc = "()" + desc;
- visitMethodInsn(INVOKEVIRTUAL, owner, "_get" + name, gDesc);
- return;
- } else if (opcode == PUTFIELD) {
- String sDesc = "(" + desc + ")V";
- visitMethodInsn(INVOKESPECIAL, owner, "_set" + name, sDesc);
- return;
- }
- }
- super.visitFieldInsn(opcode, owner, name, desc);
- }
-
-}
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/configuration/ConfigurationHandler.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/configuration/ConfigurationHandler.java
index fb83c16..a16ee6a 100644
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/configuration/ConfigurationHandler.java
+++ b/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/configuration/ConfigurationHandler.java
@@ -29,7 +29,9 @@
import org.apache.felix.ipojo.architecture.PropertyDescription;
import org.apache.felix.ipojo.handlers.providedservice.ProvidedServiceHandler;
import org.apache.felix.ipojo.metadata.Element;
-import org.apache.felix.ipojo.parser.ParseUtils;
+import org.apache.felix.ipojo.parser.FieldMetadata;
+import org.apache.felix.ipojo.parser.ManipulationMetadata;
+import org.apache.felix.ipojo.parser.MethodMetadata;
import org.apache.felix.ipojo.util.Logger;
import org.osgi.framework.ServiceRegistration;
@@ -107,13 +109,22 @@
// Check if the component is dynamically configurable
m_isConfigurable = false;
+ // DEPRECATED BLOCK
if (confs[0].containsAttribute("configurable") && confs[0].getAttribute("configurable").equalsIgnoreCase("true")) {
+ m_manager.getFactory().getLogger().log(Logger.WARNING, "The configurable attribute is deprecated, please use the propagation attribute");
+ m_isConfigurable = true;
+ m_toPropagate = configuration;
+ }
+ // END
+ if (confs[0].containsAttribute("propagation") && confs[0].getAttribute("propagation").equalsIgnoreCase("true")) {
m_isConfigurable = true;
m_toPropagate = configuration;
}
Element[] configurables = confs[0].getElements("Property");
+ ArrayList ff = new ArrayList();
+
for (int i = 0; i < configurables.length; i++) {
String fieldName = null;
String methodName = null;
@@ -150,36 +161,35 @@
}
// Detect the type of the property
- Element manipulation = metadata.getElements("Manipulation")[0];
+ ManipulationMetadata manipulation = new ManipulationMetadata(metadata);
String type = null;
if (fieldName != null) {
- for (int kk = 0; kk < manipulation.getElements("Field").length; kk++) {
- if (fieldName.equals(manipulation.getElements("Field")[kk].getAttribute("name"))) {
- type = manipulation.getElements("Field")[kk].getAttribute("type");
- }
- }
- if (type == null) {
+ FieldMetadata fm = manipulation.getField(fieldName);
+ if (fm == null) {
m_manager.getFactory().getLogger().log(Logger.ERROR,
"[" + m_manager.getClassName() + "] The field " + fieldName + " does not exist in the implementation");
return;
}
+ type = fm.getFieldType();
+ ff.add(fm);
} else {
- for (int kk = 0; kk < manipulation.getElements("Method").length; kk++) {
- if (methodName.equals(manipulation.getElements("Method")[kk].getAttribute("name"))) {
- if (manipulation.getElements("Method")[kk].containsAttribute("arguments")) {
- String[] arg = ParseUtils.parseArrays(manipulation.getElements("Method")[kk].getAttribute("arguments"));
- if (arg.length != 1) {
- m_manager.getFactory().getLogger().log(Logger.ERROR, "A configurable property need to have a method with only one argument");
- return;
- }
- type = arg[0];
- }
- }
- }
- if (type == null) {
+ MethodMetadata[] mm = manipulation.getMethods(methodName);
+ if (mm.length == 0) {
m_manager.getFactory().getLogger().log(Logger.ERROR,
- "The method " + methodName + " does not exist in the implementation, or does not have one argument");
+ "[" + m_manager.getClassName() + "] The method " + methodName + " does not exist in the implementation");
return;
+ } else {
+ if (mm[0].getMethodArguments().length != 1) {
+ m_manager.getFactory().getLogger().log(Logger.ERROR,
+ "[" + m_manager.getClassName() + "] The method " + methodName + " does not have one argument");
+ return;
+ }
+ if (type != null && !type.equals(mm[0].getMethodArguments()[0])) {
+ m_manager.getFactory().getLogger().log(Logger.ERROR,
+ "[" + m_manager.getClassName() + "] The field type (" + type + ") and the method type (" + mm[0].getMethodArguments()[0] + ") are not the same.");
+ return;
+ }
+ type = mm[0].getMethodArguments()[0];
}
}
@@ -195,12 +205,7 @@
}
if (configurables.length > 0) {
- ArrayList ff = new ArrayList();
for (int k = 0; k < m_configurableProperties.length; k++) {
- if (m_configurableProperties[k].getField() != null) {
- ff.add(m_configurableProperties[k].getField());
- }
-
// Check if the instance configuration contains value for the
// current property :
String name = m_configurableProperties[k].getName();
@@ -213,7 +218,7 @@
}
}
}
- m_manager.register(this, (String[]) ff.toArray(new String[0]));
+ m_manager.register(this, (FieldMetadata[]) ff.toArray(new FieldMetadata[0]), null);
}
}
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/dependency/DependencyHandler.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/dependency/DependencyHandler.java
index ba8ea7e..c613466 100644
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/dependency/DependencyHandler.java
+++ b/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/dependency/DependencyHandler.java
@@ -19,14 +19,18 @@
package org.apache.felix.ipojo.handlers.dependency;
import java.net.URL;
+import java.util.ArrayList;
import java.util.Dictionary;
+import java.util.List;
import org.apache.felix.ipojo.Handler;
import org.apache.felix.ipojo.InstanceManager;
import org.apache.felix.ipojo.architecture.HandlerDescription;
import org.apache.felix.ipojo.handlers.dependency.nullable.NullableObjectWriter;
import org.apache.felix.ipojo.metadata.Element;
-import org.apache.felix.ipojo.parser.ParseUtils;
+import org.apache.felix.ipojo.parser.FieldMetadata;
+import org.apache.felix.ipojo.parser.ManipulationMetadata;
+import org.apache.felix.ipojo.parser.MethodMetadata;
import org.apache.felix.ipojo.util.Logger;
import org.osgi.framework.ServiceReference;
@@ -157,72 +161,57 @@
* @param manipulation : the component-type manipulation metadata
* @return true if the dependency is valid
*/
- private boolean checkDependency(Dependency dep, Element manipulation) {
+ private boolean checkDependency(Dependency dep, ManipulationMetadata manipulation) {
// Check the internal type of dependency
String field = dep.getField();
DependencyCallback[] callbacks = dep.getCallbacks();
for (int i = 0; i < callbacks.length; i++) {
- for (int j = 0; j < manipulation.getElements("Method").length; j++) {
- if (manipulation.getElements("Method")[j].getAttribute("name").equals(callbacks[i].getMethodName())) {
- if (manipulation.getElements("Method")[j].containsAttribute("Arguments")) {
- String[] args = ParseUtils.parseArrays(manipulation.getElements("Method")[j].getAttribute("Arguments"));
- if (args.length != 1) {
- getInstanceManager().getFactory().getLogger().log(Logger.ERROR, "A dependency callback " + callbacks[i].getMethodName() + " must have 0 or 1 argument");
- return false;
- } else {
- callbacks[i].setArgument(args[0]);
- if (!args[0].equals(ServiceReference.class.getName())) {
- if (dep.getSpecification() == null) {
- dep.setSpecification(args[0]);
- }
- if (!dep.getSpecification().equals(args[0])) {
- m_manager.getFactory().getLogger().log(Logger.WARNING, "[DependencyHandler on " + m_manager.getClassName() + "] The field type [" + args[0] + "] and the needed service interface ["
- + dep.getSpecification() + "] are not the same");
- dep.setSpecification(args[0]);
- }
- }
- }
- } else {
- callbacks[i].setArgument("EMPTY");
+ MethodMetadata[] mets = manipulation.getMethods(callbacks[i].getMethodName());
+ if (mets.length == 0) {
+ getInstanceManager().getFactory().getLogger().log(Logger.ERROR, "A dependency callback " + callbacks[i].getMethodName() + " does not exist in the implementation");
+ return false;
+ }
+ if (mets[0].getMethodArguments().length > 1) {
+ getInstanceManager().getFactory().getLogger().log(Logger.ERROR, "A dependency callback " + callbacks[i].getMethodName() + " must have 0 or 1 argument");
+ return false;
+ }
+ if (mets[0].getMethodArguments().length == 0) {
+ callbacks[i].setArgument("EMPTY");
+ } else {
+ callbacks[i].setArgument(mets[0].getMethodArguments()[0]);
+ if (!mets[0].getMethodArguments()[0].equals(ServiceReference.class.getName())) {
+ if (dep.getSpecification() == null) {
+ dep.setSpecification(mets[0].getMethodArguments()[0]);
+ }
+ if (!dep.getSpecification().equals(mets[0].getMethodArguments()[0])) {
+ m_manager.getFactory().getLogger().log(Logger.WARNING, "[DependencyHandler on " + m_manager.getClassName() + "] The field type [" + mets[0].getMethodArguments()[0] + "] and the needed service interface ["
+ + dep.getSpecification() + "] are not the same");
+ dep.setSpecification(mets[0].getMethodArguments()[0]);
}
}
- }
+ }
}
if (field != null) {
- String type = null;
- for (int i = 0; i < manipulation.getElements("Field").length; i++) {
- if (field.equals(manipulation.getElements("Field")[i].getAttribute("name"))) {
- type = manipulation.getElements("Field")[i].getAttribute("type");
- break;
- }
- }
-
- if (type == null) {
- m_manager.getFactory().getLogger().log(Logger.ERROR,
- "[DependencyHandler on " + m_manager.getClassName() + "] A declared dependency was not found in the class : " + dep.getField());
+ FieldMetadata fm = manipulation.getField(field);
+ if (field == null) {
+ getInstanceManager().getFactory().getLogger().log(Logger.ERROR, "A dependency field " + field + " does not exist in the implementation class");
return false;
}
+ String type = fm.getFieldType();
+ if (type.endsWith("[]")) {
+ // Set the dependency to multiple
+ dep.setAggregate();
+ type = type.substring(0, type.length() - 2);
+ }
- if (type != null) {
- if (type.endsWith("[]")) {
- // Set the dependency to multiple
- dep.setAggregate();
- type = type.substring(0, type.length() - 2);
- }
+ if (dep.getSpecification() == null) { dep.setSpecification(type); }
- if (dep.getSpecification() == null) {
- dep.setSpecification(type);
- }
-
- if (!dep.getSpecification().equals(type)) {
- m_manager.getFactory().getLogger().log(Logger.WARNING, "[DependencyHandler on " + m_manager.getClassName() + "] The field type [" + type + "] and the needed service interface ["
+ if (!dep.getSpecification().equals(type)) {
+ m_manager.getFactory().getLogger().log(Logger.WARNING, "[DependencyHandler on " + m_manager.getClassName() + "] The field type [" + type + "] and the needed service interface ["
+ dep.getSpecification() + "] are not the same");
- dep.setSpecification(type);
- }
- } else {
- m_manager.getFactory().getLogger().log(Logger.WARNING, "[DependencyHandler on " + m_manager.getClassName() + "] The declared dependency " + dep.getField() + " does not exist in the code");
+ dep.setSpecification(type);
}
}
@@ -241,9 +230,23 @@
m_manager = im;
m_dependencies = new Dependency[0];
m_nullableClasses = new Class[0];
+
+ ManipulationMetadata manipulation = new ManipulationMetadata(componentMetadata);
+ List fl = new ArrayList();
// Create the dependency according to the component metadata
- Element[] deps = componentMetadata.getElements("Dependency");
+ Element[] deps = componentMetadata.getElements("Requires");
+
+ // DEPRECATED BLOCK :
+ if (deps.length == 0) {
+ deps = componentMetadata.getElements("Dependency");
+ if (deps.length != 0) {
+ im.getFactory().getLogger().log(Logger.WARNING, "Dependency is deprecated, please use 'requires' instead of 'dependency'");
+ }
+ }
+ // END OF DEPRECATED BLOCK
+
+
for (int i = 0; i < deps.length; i++) {
// Create the dependency metadata
String field = null;
@@ -285,9 +288,11 @@
}
// Check the dependency :
- Element manipulation = componentMetadata.getElements("Manipulation")[0];
if (checkDependency(dep, manipulation)) {
addDependency(dep);
+ if (dep.getField() != null) {
+ fl.add(manipulation.getField(dep.getField()));
+ }
} else {
m_manager.getFactory().getLogger().log(Logger.ERROR,
"[DependencyHandler on " + m_manager.getClassName() + "] The dependency on " + dep.getField() + " is not valid");
@@ -296,11 +301,7 @@
}
if (deps.length > 0) {
- String[] fields = new String[m_dependencies.length];
- for (int k = 0; k < m_dependencies.length; k++) {
- fields[k] = m_dependencies[k].getField();
- }
- m_manager.register(this, fields);
+ m_manager.register(this, (FieldMetadata[]) fl.toArray(new FieldMetadata[0]), null);
}
}
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/dependency/DependencyHandlerDescription.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/dependency/DependencyHandlerDescription.java
index ec867de..6d01ff8 100644
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/dependency/DependencyHandlerDescription.java
+++ b/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/dependency/DependencyHandlerDescription.java
@@ -85,7 +85,7 @@
if (m_dependencies[i].getState() == 2) {
state = "unresolved";
}
- Element dep = new Element("Dependency", "");
+ Element dep = new Element("Requires", "");
dep.addAttribute(new Attribute("Specification", m_dependencies[i].getInterface()));
dep.addAttribute(new Attribute("Filter", m_dependencies[i].getFilter()));
dep.addAttribute(new Attribute("State", state));
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/lifecycle/callback/LifecycleCallback.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/lifecycle/callback/LifecycleCallback.java
index a9f4fe1..2d76148 100644
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/lifecycle/callback/LifecycleCallback.java
+++ b/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/lifecycle/callback/LifecycleCallback.java
@@ -20,7 +20,7 @@
import java.lang.reflect.InvocationTargetException;
-import org.apache.felix.ipojo.InstanceManager;
+import org.apache.felix.ipojo.parser.MethodMetadata;
import org.apache.felix.ipojo.util.Callback;
/**
@@ -29,16 +29,21 @@
* @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
*/
public class LifecycleCallback {
-
+
/**
- * Initial state of the transition.
+ * Invalid to Valid transition.
*/
- private int m_initialState;
-
+ protected static final int VALIDATE = 1;
+
/**
- * Final state of the transition.
+ * Valid to Invalid transition.
*/
- private int m_finalState;
+ protected static final int INVALIDATE = 0;
+
+ /**
+ * Transition on hwich calling the callback.
+ */
+ private int m_transition;
/**
* Callback object.
@@ -46,35 +51,15 @@
private Callback m_callback;
/**
- * Method called by the callback.
- */
- private String m_method;
-
- /**
* LifecycleCallback constructor.
*
* @param hh : the callback handler calling the callback
- * @param initialState : initial state of the callback
- * @param finalState : finali state of the callback
- * @param method : method to invoke
- * @param isStatic : is the method static ?
+ * @param transition : transition on which calling the callback
+ * @param mm : method metadata to invoke
*/
- public LifecycleCallback(LifecycleCallbackHandler hh, String initialState, String finalState, String method, boolean isStatic) {
- if (initialState.equals("VALID")) {
- m_initialState = InstanceManager.VALID;
- }
- if (initialState.equals("INVALID")) {
- m_initialState = InstanceManager.INVALID;
- }
- if (finalState.equals("VALID")) {
- m_finalState = InstanceManager.VALID;
- }
- if (finalState.equals("INVALID")) {
- m_finalState = InstanceManager.INVALID;
- }
-
- m_method = method;
- m_callback = new Callback(method, new String[0], isStatic, hh.getInstanceManager());
+ public LifecycleCallback(LifecycleCallbackHandler hh, int transition, MethodMetadata mm) {
+ m_transition = transition;
+ m_callback = new Callback(mm, hh.getInstanceManager());
}
/**
@@ -88,17 +73,17 @@
protected void call() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
m_callback.call();
}
-
- public int getFinalState() {
- return m_finalState;
+
+ protected int getTransition() {
+ return m_transition;
}
-
- public int getInitialState() {
- return m_initialState;
- }
-
- public String getMethod() {
- return m_method;
+
+ /**
+ * Get the method name of the callback.
+ * @return the method name
+ */
+ protected String getMethod() {
+ return m_callback.getMethod();
}
}
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/lifecycle/callback/LifecycleCallbackHandler.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/lifecycle/callback/LifecycleCallbackHandler.java
index c90529f..f602769 100644
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/lifecycle/callback/LifecycleCallbackHandler.java
+++ b/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/lifecycle/callback/LifecycleCallbackHandler.java
@@ -25,6 +25,8 @@
import org.apache.felix.ipojo.Handler;
import org.apache.felix.ipojo.InstanceManager;
import org.apache.felix.ipojo.metadata.Element;
+import org.apache.felix.ipojo.parser.ManipulationMetadata;
+import org.apache.felix.ipojo.parser.MethodMetadata;
import org.apache.felix.ipojo.util.Logger;
/**
@@ -91,19 +93,48 @@
if (metadata.containsAttribute("immediate") && metadata.getAttribute("immediate").equalsIgnoreCase("true")) {
m_immediate = true;
}
+
+ ManipulationMetadata mm = new ManipulationMetadata(metadata);
Element[] hooksMetadata = metadata.getElements("callback");
for (int i = 0; i < hooksMetadata.length; i++) {
- // Create an HookMetadata object
- String initialState = hooksMetadata[i].getAttribute("initial");
- String finalState = hooksMetadata[i].getAttribute("final");
- String method = hooksMetadata[i].getAttribute("method");
- boolean isStatic = false;
- if (hooksMetadata[i].containsAttribute("isStatic") && hooksMetadata[i].getAttribute("isStatic").equals("true")) {
- isStatic = true;
+ String methodName = hooksMetadata[i].getAttribute("method");
+
+ MethodMetadata met = mm.getMethod(methodName, new String[0]);
+ if (met == null) {
+ cm.getFactory().getLogger().log(Logger.ERROR, "The method " + methodName + " is not implemented in the " + cm.getInstanceName());
+ return;
}
-
- LifecycleCallback hk = new LifecycleCallback(this, initialState, finalState, method, isStatic);
+
+ int transition = -1;
+ if (hooksMetadata[i].containsAttribute("transition")) {
+ if (hooksMetadata[i].getAttribute("transition").equalsIgnoreCase("validate")) {
+ transition = LifecycleCallback.VALIDATE;
+ }
+ if (hooksMetadata[i].getAttribute("transition").equalsIgnoreCase("invalidate")) {
+ transition = LifecycleCallback.INVALIDATE;
+ }
+ }
+
+ //DEPRECATED BLOCK
+ if (hooksMetadata[i].containsAttribute("initial")) {
+ cm.getFactory().getLogger().log(Logger.WARNING, "initial & final are deprecated, please use 'transition=validate|invalidate' instead.");
+ if (hooksMetadata[i].containsAttribute("final")) {
+ if (hooksMetadata[i].getAttribute("initial").equalsIgnoreCase("valid") && hooksMetadata[i].getAttribute("final").equalsIgnoreCase("invalid")) {
+ transition = LifecycleCallback.INVALIDATE;
+ } else {
+ transition = LifecycleCallback.VALIDATE;
+ }
+ }
+ }
+ //END OF DEPRECATED BLOCK
+
+ if (transition == -1) {
+ cm.getFactory().getLogger().log(Logger.ERROR, "Unknown or malformed transition");
+ return;
+ }
+
+ LifecycleCallback hk = new LifecycleCallback(this, transition, met);
addCallback(hk);
}
if (m_callbacks.length > 0 || m_immediate) {
@@ -137,17 +168,25 @@
/**
* When the state change call the associated callback.
*
- * @param state : the new isntance state.
+ * @param state : the new instance state.
* @see org.apache.felix.ipojo.Handler#stateChanged(int)
*/
public void stateChanged(int state) {
+ int transition = -1;
+ if (m_state == ComponentInstance.INVALID && state == ComponentInstance.VALID) {
+ transition = LifecycleCallback.VALIDATE;
+ }
+ if (m_state == ComponentInstance.VALID && state == ComponentInstance.INVALID) {
+ transition = LifecycleCallback.INVALIDATE;
+ }
+
// Manage immediate component
- if (m_state == ComponentInstance.INVALID && state == ComponentInstance.VALID && m_manager.getPojoObjects().length == 0) {
+ if (m_immediate && transition == LifecycleCallback.VALIDATE && m_manager.getPojoObjects().length == 0) {
m_manager.createPojoObject();
}
for (int i = 0; i < m_callbacks.length; i++) {
- if (m_callbacks[i].getInitialState() == m_state && m_callbacks[i].getFinalState() == state) {
+ if (m_callbacks[i].getTransition() == transition) {
try {
m_callbacks[i].call();
} catch (NoSuchMethodException e) {
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/providedservice/Property.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/providedservice/Property.java
index feed1ab..b916171 100644
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/providedservice/Property.java
+++ b/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/providedservice/Property.java
@@ -22,7 +22,8 @@
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
-import org.apache.felix.ipojo.metadata.Element;
+import org.apache.felix.ipojo.parser.FieldMetadata;
+import org.apache.felix.ipojo.parser.ManipulationMetadata;
import org.apache.felix.ipojo.parser.ParseUtils;
import org.apache.felix.ipojo.util.Logger;
@@ -76,7 +77,7 @@
* @param value : initial value of the property
* @param manipulation : manipulation metadata
*/
- public Property(ProvidedService ps, String name, String field, String type, String value, Element manipulation) {
+ public Property(ProvidedService ps, String name, String field, String type, String value, ManipulationMetadata manipulation) {
m_providedService = ps;
m_name = name;
m_field = field;
@@ -96,16 +97,13 @@
ps.getInstanceManager().getFactory().getLogger().log(Logger.ERROR, "The property " + m_name + " has neither type neither field.");
return;
}
- for (int j = 0; j < manipulation.getElements("Field").length; j++) {
- if (field.equals(manipulation.getElements("Field")[j].getAttribute("name"))) {
- m_type = manipulation.getElements("Field")[j].getAttribute("type");
- break;
- }
- }
- if (m_type == null) {
+ FieldMetadata fm = manipulation.getField(field);
+ if (fm == null) {
m_providedService.getInstanceManager().getFactory().getLogger().log(Logger.ERROR,
"[" + ps.getInstanceManager().getClassName() + "] A declared property was not found in the class : " + m_field);
+ return;
}
+ m_type = fm.getFieldType();
}
if (m_initialValue != null) {
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/providedservice/ProvidedService.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/providedservice/ProvidedService.java
index 2d814cf..172811c 100644
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/providedservice/ProvidedService.java
+++ b/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/providedservice/ProvidedService.java
@@ -96,7 +96,7 @@
m_factoryPolicy = factoryPolicy;
// Add service pid and factory pid
- addProperty(new Property(this, org.osgi.framework.Constants.SERVICE_PID, handler.getInstanceManager().getInstanceName()));
+ addProperty(new Property(this, org.osgi.framework.Constants.SERVICE_PID, handler.getInstanceManager().getInstanceName()));
addProperty(new Property(this, "factory.pid", handler.getInstanceManager().getFactory().getName()));
}
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/providedservice/ProvidedServiceHandler.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/providedservice/ProvidedServiceHandler.java
index aa1cb4c..da2dda9 100644
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/providedservice/ProvidedServiceHandler.java
+++ b/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/providedservice/ProvidedServiceHandler.java
@@ -27,6 +27,8 @@
import org.apache.felix.ipojo.architecture.HandlerDescription;
import org.apache.felix.ipojo.architecture.PropertyDescription;
import org.apache.felix.ipojo.metadata.Element;
+import org.apache.felix.ipojo.parser.FieldMetadata;
+import org.apache.felix.ipojo.parser.ManipulationMetadata;
import org.apache.felix.ipojo.parser.ParseUtils;
import org.apache.felix.ipojo.util.Logger;
import org.osgi.framework.Constants;
@@ -97,13 +99,14 @@
public void configure(InstanceManager im, Element componentMetadata, Dictionary configuration) {
// Fix the instance manager & clean the provided service list
m_manager = im;
+
+ ManipulationMetadata manipulation = new ManipulationMetadata(componentMetadata);
ComponentDescription cd = im.getComponentDescription();
m_providedServices = new ProvidedService[0];
// Create the dependency according to the component metadata
Element[] providedServices = componentMetadata.getElements("Provides");
- Element manipulation = componentMetadata.getElements("Manipulation")[0];
for (int i = 0; i < providedServices.length; i++) {
// Create a ProvidedServiceMetadata object
@@ -111,13 +114,9 @@
String[] serviceSpecification = new String[0];
if (providedServices[i].containsAttribute("interface")) {
String serviceSpecificationStr = providedServices[i].getAttribute("interface");
- // Get serviceSpecification if exist in the metadata
serviceSpecification = ParseUtils.parseArrays(serviceSpecificationStr);
} else {
- serviceSpecification = new String[manipulation.getElements("Interface").length];
- for (int j = 0; j < manipulation.getElements("Interface").length; j++) {
- serviceSpecification[j] = manipulation.getElements("Interface")[j].getAttribute("name");
- }
+ serviceSpecification = manipulation.getInterfaces();
}
if (serviceSpecification.length == 0) {
m_manager.getFactory().getLogger().log(Logger.ERROR,
@@ -194,7 +193,7 @@
}
if (providedServices.length > 0) {
- String[] fields = new String[0];
+ FieldMetadata[] fields = new FieldMetadata[0];
for (int i = 0; i < m_providedServices.length; i++) {
ProvidedService ps = m_providedServices[i];
for (int j = 0; j < ps.getProperties().length; j++) {
@@ -210,15 +209,15 @@
}
}
if (prop.getField() != null) {
- String[] newFields = new String[fields.length + 1];
+ FieldMetadata[] newFields = new FieldMetadata[fields.length + 1];
System.arraycopy(fields, 0, newFields, 0, fields.length);
- newFields[fields.length] = prop.getField();
+ newFields[fields.length] = manipulation.getField(prop.getField());
fields = newFields;
}
}
}
- m_manager.register(this, fields);
+ m_manager.register(this, fields, null);
}
}
@@ -230,48 +229,39 @@
* @param manipulation : componenet-type manipulation metadata.
* @return true if the provided service is correct
*/
- private boolean checkProvidedService(ProvidedService ps, Element manipulation) {
+ private boolean checkProvidedService(ProvidedService ps, ManipulationMetadata manipulation) {
for (int i = 0; i < ps.getServiceSpecification().length; i++) {
- boolean b = false;
- for (int ii = 0; ii < manipulation.getElements("Interface").length; ii++) {
- if (manipulation.getElements("Interface")[ii].getAttribute("name").equals(ps.getServiceSpecification()[i])) {
- b = true;
- }
- }
- if (!b) {
- m_manager.getFactory().getLogger().log(
- Logger.ERROR,
- "[" + m_manager.getClassName() + "] The service specification " + ps.getServiceSpecification()[i]
+ if (! manipulation.isInterfaceImplemented(ps.getServiceSpecification()[i])) {
+ m_manager.getFactory().getLogger().log(Logger.ERROR, "[" + m_manager.getClassName() + "] The service specification " + ps.getServiceSpecification()[i]
+ " is not implemented by the component class");
return false;
}
-
}
- // Fix internal property type
- for (int i = 0; i < ps.getProperties().length; i++) {
- Property prop = ps.getProperties()[i];
- String field = prop.getField();
-
- if (field == null) {
- return true; // Static dependency -> Nothing to check
- } else {
- String type = null;
- for (int j = 0; j < manipulation.getElements("Field").length; j++) {
- if (field.equals(manipulation.getElements("Field")[j].getAttribute("name"))) {
- type = manipulation.getElements("Field")[j].getAttribute("type");
- break;
- }
- }
- if (type == null) {
- m_manager.getFactory().getLogger().log(Logger.ERROR,
- "[" + m_manager.getClassName() + "] A declared property was not found in the class : " + prop.getField());
- return false;
- }
- prop.setType(type); // Set the type
- }
- }
+// // Fix internal property type
+// for (int i = 0; i < ps.getProperties().length; i++) {
+// Property prop = ps.getProperties()[i];
+// String field = prop.getField();
+//
+// if (field == null) {
+// return true; // Static property -> Nothing to check
+// } else {
+// String type = null;
+// for (int j = 0; j < manipulation.getElements("Field").length; j++) {
+// if (field.equals(manipulation.getElements("Field")[j].getAttribute("name"))) {
+// type = manipulation.getElements("Field")[j].getAttribute("type");
+// break;
+// }
+// }
+// if (type == null) {
+// m_manager.getFactory().getLogger().log(Logger.ERROR,
+// "[" + m_manager.getClassName() + "] A declared property was not found in the class : " + prop.getField());
+// return false;
+// }
+// prop.setType(type); // Set the type
+// }
+// }
return true;
}
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/parser/MethodMetadata.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/parser/MethodMetadata.java
index 655bbd6..3a5162f 100644
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/parser/MethodMetadata.java
+++ b/ipojo/core/src/main/java/org/apache/felix/ipojo/parser/MethodMetadata.java
@@ -62,5 +62,22 @@
public String[] getMethodArguments() { return m_arguments; }
public String getMethodReturn() { return m_return; }
+
+ /**
+ * Get the method unique identifier. For internal usage only.
+ * @return the method identifier.
+ */
+ public String getMethodIdentifier() {
+ String id = m_name;
+ for (int i = 0; i < m_arguments.length; i++) {
+ String cn = m_arguments[i];
+ if (cn.endsWith("[]")) {
+ cn = cn.replace("[]", "$");
+ }
+ cn = cn.replace(".", "_");
+ id += cn;
+ }
+ return id;
+ }
}
diff --git a/ipojo/core/src/main/java/org/apache/felix/ipojo/util/Callback.java b/ipojo/core/src/main/java/org/apache/felix/ipojo/util/Callback.java
index f4caf06..b3f59f5 100644
--- a/ipojo/core/src/main/java/org/apache/felix/ipojo/util/Callback.java
+++ b/ipojo/core/src/main/java/org/apache/felix/ipojo/util/Callback.java
@@ -316,4 +316,8 @@
return m_methodObj.invoke(instance, arg);
}
+
+ public String getMethod() {
+ return m_method;
+ }
}
diff --git a/ipojo/plugin/pom.xml b/ipojo/plugin/pom.xml
index 463a3eb..116d580 100644
--- a/ipojo/plugin/pom.xml
+++ b/ipojo/plugin/pom.xml
@@ -6,7 +6,7 @@
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.apache.felix.ipojo.plugin</artifactId>
- <version>0.7.1-incubator-SNAPSHOT</version>
+ <version>0.7.3-incubator-SNAPSHOT</version>
<name>Apache Felix iPOJO Maven Plugin</name>
<packaging>maven-plugin</packaging>
<dependencies>
@@ -45,5 +45,10 @@
<artifactId>org.apache.felix.ipojo.metadata</artifactId>
<version>${pom.version}</version>
</dependency>
+ <dependency>
+ <groupId>${pom.groupId}</groupId>
+ <artifactId>org.apache.felix.ipojo.manipulator</artifactId>
+ <version>0.7.3-incubator-SNAPSHOT</version>
+ </dependency>
</dependencies>
</project>
diff --git a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/manipulation/ClassChecker.java b/ipojo/plugin/src/main/java/org/apache/felix/ipojo/manipulation/ClassChecker.java
deleted file mode 100644
index 289ccb9..0000000
--- a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/manipulation/ClassChecker.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * 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.felix.ipojo.manipulation;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-import org.objectweb.asm.AnnotationVisitor;
-import org.objectweb.asm.Attribute;
-import org.objectweb.asm.ClassVisitor;
-import org.objectweb.asm.FieldVisitor;
-import org.objectweb.asm.MethodVisitor;
-import org.objectweb.asm.Opcodes;
-import org.objectweb.asm.Type;
-
-public class ClassChecker implements ClassVisitor, Opcodes {
-
- /**
- * True if the class is already manipulated.
- */
- private boolean isAlreadyManipulated = false;
-
- /**
- * Interfaces implemented by the component.
- */
- private String[] m_itfs = new String[0];
-
- /**
- * Field hashmap [field name, type] discovered in the component class.
- */
- private HashMap m_fields = new HashMap();
-
- /**
- * Method List of method descriptor discovered in the component class.
- */
- private List m_methods = new ArrayList()/*<MethodDesciptor>*/;
-
- /** Check if the _cm field already exists.
- * @see org.objectweb.asm.ClassVisitor#visitField(int, java.lang.String, java.lang.String, java.lang.String, java.lang.Object)
- */
- public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
-
- if (access == ACC_PRIVATE && name.equals("_cm") && desc.equals("Lorg/apache/felix/ipojo/InstanceManager;")) {
- isAlreadyManipulated = true;
- }
-
- Type type = Type.getType(desc);
- if (type.getSort() == Type.ARRAY) {
- if (type.getInternalName().startsWith("L")) {
- String internalType = type.getInternalName().substring(1);
- String nameType = internalType.replace('/', '.');
- m_fields.put(name, nameType + "[]");
- }
- else {
- String nameType = type.getClassName().substring(0, type.getClassName().length() - 2);
- m_fields.put(name, nameType + "[]");
- }
- } else { m_fields.put(name, type.getClassName()); }
-
- return null;
- }
-
- public boolean isalreadyManipulated() { return isAlreadyManipulated; }
-
- /**
- * @see org.objectweb.asm.ClassVisitor#visit(int, int, java.lang.String, java.lang.String, java.lang.String, java.lang.String[])
- */
- public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
- //Store the interfaces :
- m_itfs = interfaces;
- }
-
- /**
- * @see org.objectweb.asm.ClassVisitor#visitSource(java.lang.String, java.lang.String)
- */
- public void visitSource(String arg0, String arg1) { }
-
- /**
- * @see org.objectweb.asm.ClassVisitor#visitOuterClass(java.lang.String, java.lang.String, java.lang.String)
- */
- public void visitOuterClass(String arg0, String arg1, String arg2) { }
-
- /**
- * @see org.objectweb.asm.ClassVisitor#visitAnnotation(java.lang.String, boolean)
- */
- public AnnotationVisitor visitAnnotation(String arg0, boolean arg1) { return null; }
-
- /**
- * @see org.objectweb.asm.ClassVisitor#visitAttribute(org.objectweb.asm.Attribute)
- */
- public void visitAttribute(Attribute arg0) { }
-
- /**
- * @see org.objectweb.asm.ClassVisitor#visitInnerClass(java.lang.String, java.lang.String, java.lang.String, int)
- */
- public void visitInnerClass(String arg0, String arg1, String arg2, int arg3) { }
-
- /**
- * @see org.objectweb.asm.ClassVisitor#visitMethod(int, java.lang.String, java.lang.String, java.lang.String, java.lang.String[])
- */
- public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
- if(!name.equals("<init>")) { m_methods.add(new MethodDescriptor(name, desc)); }
- return null;
- }
-
- /**
- * @see org.objectweb.asm.ClassVisitor#visitEnd()
- */
- public void visitEnd() { }
-
- /**
- * @return the interfaces implemented by the component class.
- */
- public String[] getInterfaces() {
- return m_itfs;
- }
-
- /**
- * @return the field hashmap [field_name, type].
- */
- public HashMap getFields() {
- return m_fields;
- }
-
-
- /**
- * @return the method list of [method, signature].
- */
- public List getMethods() {
- return m_methods;
- }
-
-}
diff --git a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/manipulation/ConstructorCodeAdapter.java b/ipojo/plugin/src/main/java/org/apache/felix/ipojo/manipulation/ConstructorCodeAdapter.java
deleted file mode 100644
index 47710b5..0000000
--- a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/manipulation/ConstructorCodeAdapter.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * 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.felix.ipojo.manipulation;
-
-import java.util.logging.Level;
-
-import org.apache.felix.ipojo.plugin.IPojoPluginConfiguration;
-import org.objectweb.asm.Label;
-import org.objectweb.asm.MethodAdapter;
-import org.objectweb.asm.MethodVisitor;
-import org.objectweb.asm.Opcodes;
-
-
-/**
- * Constructor Adapter : add a component manager argument inside a constructor.
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class ConstructorCodeAdapter extends MethodAdapter implements Opcodes {
-
- /** The owner class of the field.
- * m_owner : String
- */
- private String m_owner;
-
- private boolean m_superDetected;
-
- /** PropertyCodeAdapter constructor.
- * A new FiledCodeAdapter should be create for each method visit.
- * @param mv MethodVisitor
- * @param owner Name of the class
- */
- public ConstructorCodeAdapter(final MethodVisitor mv, final String owner) {
- super(mv);
- m_owner = owner;
- m_superDetected = false;
- }
-
-
- /** Visit Method for Field instance (GETFIELD).
- * @see org.objectweb.asm.MethodVisitor#visitFieldInsn(int, String, String, String)
- * @param opcode : visited operation code
- * @param owner : owner of the field
- * @param name : name of the field
- * @param desc : decriptor of the field
- */
- public void visitFieldInsn(
- final int opcode,
- final String owner,
- final String name,
- final String desc) {
- if (owner.equals(m_owner)) {
- if (opcode == GETFIELD) {
- IPojoPluginConfiguration.getLogger().log(Level.INFO, "Manipulate a GETFIELD on : " + name);
- String gDesc = "()" + desc;
- visitMethodInsn(INVOKEVIRTUAL, owner, "_get" + name, gDesc);
- return;
- } else
- if (opcode == PUTFIELD) {
- // replaces PUTFIELD f by INVOKESPECIAL _setf
- IPojoPluginConfiguration.getLogger().log(Level.INFO, "Manipulate a PUTFIELD on : " + name);
- String sDesc = "(" + desc + ")V";
- visitMethodInsn(INVOKESPECIAL, owner, "_set" + name, sDesc);
- return;
- }
- }
- super.visitFieldInsn(opcode, owner, name, desc);
- }
-
- public void visitMethodInsn(int opcode, String owner, String name, String desc) {
- // A method call is detected, check if it is the super call :
- if(!m_superDetected) {
- m_superDetected = true;
- // The first invocation is the super call
- // 1) Visit the super constructor :
- mv.visitVarInsn(ALOAD, 0);
- mv.visitMethodInsn(opcode, owner, name, desc); // Super constructor invocation
-
- // 2) Load the object and the component manager argument
- mv.visitVarInsn(ALOAD, 0);
- //mv.visitVarInsn(ALOAD, Type.getArgumentTypes(m_constructorDesc).length);
- mv.visitVarInsn(ALOAD, 1); // CM is always the first argument
- // 3) Initialize the field
- mv.visitMethodInsn(INVOKESPECIAL, m_owner, "_setComponentManager", "(Lorg/apache/felix/ipojo/InstanceManager;)V");
- // insertion finished
- }
- else { mv.visitMethodInsn(opcode, owner, name, desc); }
- }
-
- public void visitVarInsn(int opcode, int var) {
- if(!m_superDetected) { return; } // Do nothing the ALOAD 0 will be injected by visitMethodInsn
- else {
- if (var == 0) { mv.visitVarInsn(opcode, var); } // ALOAD 0 (THIS)
- else { mv.visitVarInsn(opcode, var+1); } // All other variable count
- }
- }
-
- public void visitIincInsn(int var, int increment) {
- if(var != 0) { mv.visitIincInsn(var+1, increment); }
- else { mv.visitIincInsn(var, increment); } // Increment the current object ???
- }
-
- public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) {
- if(index == 0) {
- mv.visitLocalVariable(name, desc, signature, start, end, index);
- mv.visitLocalVariable("_manager", "Lorg/apache/felix/ipojo/InstanceManager;", null, start, end, 1);
- IPojoPluginConfiguration.getLogger().log(Level.INFO, "Local Variable : " + name + " index = " + index + " desc = " + desc);
- IPojoPluginConfiguration.getLogger().log(Level.INFO, "Local Variable : " + "_manager" + " index = " + 1 + " desc = " + "Lorg/apache/felix/ipojo/InstanceManager;");
- }
- mv.visitLocalVariable(name, desc, signature, start, end, index+1);
- IPojoPluginConfiguration.getLogger().log(Level.INFO, "Local Variable : " + name + " index = " + index + " desc = " + desc);
- }
-
- public void visitMaxs(int maxStack, int maxLocals) {
- mv.visitMaxs(maxStack, maxLocals+1);
- }
-}
-
-
-
diff --git a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/manipulation/ManipulationProperty.java b/ipojo/plugin/src/main/java/org/apache/felix/ipojo/manipulation/ManipulationProperty.java
deleted file mode 100644
index d178231..0000000
--- a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/manipulation/ManipulationProperty.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * 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.felix.ipojo.manipulation;
-
-/**
- * Store properties for the manipulation process.
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- *
- */
-public class ManipulationProperty {
-
- /**
- * iPOJO Package name.
- */
- protected static final String IPOJO_PACKAGE_NAME = "org.apache.felix.ipojo";
-
- /**
- * Activator internal package name.
- */
- protected static final String IPOJO_INTERNAL_PACKAGE_NAME = "org/apache/felix/ipojo/";
-
- /**
- * Ipojo internal package name for internal descriptor.
- */
- protected static final String IPOJO_INTERNAL_DESCRIPTOR = "L" + IPOJO_INTERNAL_PACKAGE_NAME;
-
- /**
- * Helper array for bytecode manipulation of primitive type.
- */
- protected static final String[][] PRIMITIVE_BOXING_INFORMATION =
- new String[][] {
- {"V", "ILLEGAL", "ILLEGAL"}, // Void type [0]
- {"Z", "java/lang/Boolean", "booleanValue"}, // boolean [1]
- {"C", "java/lang/Character", "charValue"}, // char [2]
- {"B", "java/lang/Byte", "byteValue"}, // byte [3]
- {"S", "java/lang/Short", "shortValue"}, // short [4]
- {"I", "java/lang/Integer", "intValue"}, // int [5]
- {"F", "java/lang/Float", "floatValue"}, // float [6]
- {"J", "java/lang/Long", "longValue"}, // long [7]
- {"D", "java/lang/Double", "doubleValue"} // double [8]
- };
-
-}
diff --git a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/manipulation/Manipulator.java b/ipojo/plugin/src/main/java/org/apache/felix/ipojo/manipulation/Manipulator.java
deleted file mode 100644
index c0d59b3..0000000
--- a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/manipulation/Manipulator.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * 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.felix.ipojo.manipulation;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.logging.Level;
-
-import org.apache.felix.ipojo.plugin.IPojoPluginConfiguration;
-import org.objectweb.asm.ClassReader;
-import org.objectweb.asm.ClassWriter;
-
-/**
- * iPOJO Bytecode Manipulator.
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- *
- */
-public class Manipulator {
- /**
- * Store the visited fields : [name fo the field, type of the field].
- */
- private HashMap m_fields = new HashMap();
-
- /**
- * Store the interface implemented by the class.
- */
- private String[] m_interfaces = new String[0];
-
- /**
- * Store the methods list.
- */
- private List m_methods = new ArrayList();
-
- /**
- * Return the hashmap [name of the field, type of the field].
- * This information is found when the class is manipulated
- * It is a clone of the original hashmap to avoid modification by handlers
- * @return the hashmap [name of the field, type of the field].
- */
- public HashMap getFields() {
- return (HashMap)m_fields.clone();
- }
-
- /**
- * Return the hashmap [name of the field, type of the field].
- * This information is found when the class is manipulated
- * It is a clone of the original hashmap to avoid modification by handlers
- * @return the hashmap [name of the field, type of the field].
- */
- public String[] getInterfaces() { return (String[])m_interfaces.clone(); }
-
- /**
- * @return the method list.
- */
- public List getMethods() {
- return m_methods;
- }
-
- /**
- * Manipulate the class.
- * @param name The name of the class
- * @param cm The component manager attached to this manipulation
- * @throws Exception : throwed if the manipulation failed.
- */
- public boolean preProcess(String name, File outputDirectory) throws Exception {
-
- // Init field, itfs and methods
- m_fields = new HashMap();
- m_interfaces = new String[0];
- m_methods = new ArrayList();
-
- // gets an input stream to read the bytecode of the class
- String path = outputDirectory+"/"+name.replace('.', '/') + ".class";
- File clazz = new File(path);
-
- if(!clazz.exists()) { return false; }
-
- URL url = clazz.toURI().toURL();
-
- //if (url == null) { throw new ClassNotFoundException(name); }
- IPojoPluginConfiguration.getLogger().log(Level.INFO, "Manipulate the class file : " + clazz.getAbsolutePath());
-
- InputStream is1 = url.openStream();
-
- // First check if the class is already manipulated :
- ClassReader ckReader = new ClassReader(is1);
- ClassChecker ck = new ClassChecker();
- ckReader.accept(ck, ckReader.SKIP_FRAMES);
- is1.close();
-
- m_fields = ck.getFields();
-
- // Get interface and remove POJO interface is presents
- String[] its = ck.getInterfaces();
- ArrayList l = new ArrayList();
- for(int i = 0; i < its.length; i++) {
- l.add(its[i]);
- }
- l.remove("org/apache/felix/ipojo/Pojo");
-
- m_interfaces = new String[l.size()];
- for (int i = 0; i < m_interfaces.length; i++) {
- m_interfaces[i] = ((String) l.get(i)).replace('/', '.');
- }
-
-
- // Get the method list
- // Remove iPOJO methods
- for(int i = 0; i < ck.getMethods().size(); i++) {
- MethodDescriptor method = (MethodDescriptor) ck.getMethods().get(i);
- if(!(method.getName().startsWith("_get") || //Avoid getter method
- method.getName().startsWith("_set") || // Avoid setter method
- method.getName().equals("_setComponentManager") || // Avoid the set method
- method.getName().equals("getComponentInstance"))){ // Avoid the getComponentInstance method
- m_methods.add(method);
- }
- }
-
- if(!ck.isalreadyManipulated()) {
-
- //Manipulation ->
- // Add the _setComponentManager method
- // Instrument all fields
- InputStream is2 = url.openStream();
- ClassReader cr0 = new ClassReader(is2);
- ClassWriter cw0 = new ClassWriter(ClassWriter.COMPUTE_MAXS);
- PreprocessClassAdapter preprocess = new PreprocessClassAdapter(cw0);
- cr0.accept(preprocess, ClassReader.SKIP_FRAMES);
- is2.close();
-
- try {
- FileOutputStream fos = new FileOutputStream(clazz);
-
- fos.write(cw0.toByteArray());
-
- fos.close();
- IPojoPluginConfiguration.getLogger().log(Level.INFO, "Put the file " + clazz.getAbsolutePath() + " in the jar file");
- } catch (Exception e) { System.err.println("Problem to write the adapted class on the file system " + " [ "+ clazz.getAbsolutePath() +" ] " + e.getMessage()); }
- }
- // The file is in the bundle
- return true;
- }
-
-
-}
diff --git a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/manipulation/MethodDescriptor.java b/ipojo/plugin/src/main/java/org/apache/felix/ipojo/manipulation/MethodDescriptor.java
deleted file mode 100644
index cd1d457..0000000
--- a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/manipulation/MethodDescriptor.java
+++ /dev/null
@@ -1,82 +0,0 @@
-package org.apache.felix.ipojo.manipulation;
-
-import org.apache.felix.ipojo.metadata.Attribute;
-import org.apache.felix.ipojo.metadata.Element;
-import org.objectweb.asm.Type;
-
-public class MethodDescriptor {
-
- private String m_name;
- private String m_returnType;
- private String[] m_arguments;
-
- public MethodDescriptor(String name, String desc) {
- m_name = name;
- Type ret = Type.getReturnType(desc);
- Type[] args = Type.getArgumentTypes(desc);
-
- m_returnType = getType(ret);
- m_arguments = new String[args.length];
- for(int i = 0; i < args.length; i++) {
- m_arguments[i] = getType(args[i]);
- }
- }
-
- public Element getElement() {
- Element method = new Element("method", "");
- method.addAttribute(new Attribute("name", m_name));
-
- // Add return
- if(!m_returnType.equals("void")) {
- method.addAttribute(new Attribute("return", m_returnType));
- }
-
- // Add arguments
- if(m_arguments.length > 0) {
- String args = "{";
- args += m_arguments[0];
- for(int i = 1; i < m_arguments.length; i++) {
- args += "," + m_arguments[i];
- }
- args += "}";
- method.addAttribute(new Attribute("arguments", args));
- }
-
-
- return method;
- }
-
-
- private String getType(Type type) {
- switch(type.getSort()) {
- case Type.ARRAY :
- Type elemType = type.getElementType();
- return getType(elemType)+"[]";
- case Type.BOOLEAN :
- return "boolean";
- case Type.BYTE :
- return "byte";
- case Type.CHAR :
- return "char";
- case Type.DOUBLE :
- return "double";
- case Type.FLOAT :
- return "float";
- case Type.INT :
- return "int";
- case Type.LONG :
- return "long";
- case Type.OBJECT :
- return type.getClassName();
- case Type.SHORT :
- return "short";
- case Type.VOID :
- return "void";
- default :
- return "unknown";
- }
- }
-
- public String getName() { return m_name; }
-
-}
diff --git a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/manipulation/PreprocessClassAdapter.java b/ipojo/plugin/src/main/java/org/apache/felix/ipojo/manipulation/PreprocessClassAdapter.java
deleted file mode 100644
index e9658c1..0000000
--- a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/manipulation/PreprocessClassAdapter.java
+++ /dev/null
@@ -1,685 +0,0 @@
-/*
- * 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.felix.ipojo.manipulation;
-
-import java.util.logging.Level;
-
-import org.apache.felix.ipojo.plugin.IPojoPluginConfiguration;
-import org.objectweb.asm.ClassAdapter;
-import org.objectweb.asm.ClassVisitor;
-import org.objectweb.asm.FieldVisitor;
-import org.objectweb.asm.Label;
-import org.objectweb.asm.MethodVisitor;
-import org.objectweb.asm.Opcodes;
-import org.objectweb.asm.Type;
-
-
-/**
- * Manipulate the class.
- * - Add a component manager field (_cm)
- * - Create getter and setter for each fields
- * - Store information about field
- * - Store information about implemented interfaces
- * - Change GETFIELD and PUTFIELD to called the getter and setter method
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- *
- */
-public class PreprocessClassAdapter extends ClassAdapter implements Opcodes {
-
-
- private final String POJO_INTERFACE = "org/apache/felix/ipojo/Pojo";
-
- /**
- * The owner.
- * m_owner : String
- */
- private String m_owner;
-
- /**
- * Constructor.
- * @param cv : Class visitor
- */
- public PreprocessClassAdapter(final ClassVisitor cv) {
- super(cv);
- }
-
- /** The visit method.
- * - Insert the _cm field
- * - Create the _initialize method
- * - Create the _cm setter method
- * @see org.objectweb.asm.ClassVisitor#visit(int, int, String, String, String, String[])
- * @param version : Version
- * @param access : Access modifier
- * @param name : name of the visited element
- * @param signature : singature of the visited element
- * @param superName : superclasses (extend clause)
- * @param interfaces : implement clause
- */
- public void visit(
- final int version,
- final int access,
- final String name,
- final String signature,
- final String superName,
- final String[] interfaces) {
-
- m_owner = name;
-
- // Insert _cm field
- FieldVisitor fv = super.visitField(ACC_PRIVATE, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;", null, null);
- fv.visitEnd();
-
- // Create the _cmSetter(ComponentManager cm) method
- createComponentManagerSetter();
-
- // Add the getComponentInstance
- createGetComponentInstanceMethod();
-
- // Add the POJO interface to the interface list
- // Check that the POJO interface isnot already in the list
- boolean found = false;
- for(int i = 0; i < interfaces.length; i++) {
- if(interfaces[i].equals(POJO_INTERFACE)) { found = true; }
- }
- String[] itfs;
- if(!found) {
- itfs = new String[interfaces.length + 1];
- for(int i = 0; i < interfaces.length; i++) {
- itfs[i] = interfaces[i];
- }
- itfs[interfaces.length] = POJO_INTERFACE;
- } else {
- itfs = interfaces;
- }
-
- String str = "";
- for(int i = 0; i < itfs.length; i++) {
- str += itfs[i] + " ";
- }
-
- super.visit(version, access, name, signature, superName, itfs);
- }
-
-
- /** visit method method :-).
- * @see org.objectweb.asm.ClassVisitor#visitMethod(int, java.lang.String, java.lang.String, java.lang.String, java.lang.String[])
- * @param access : access modifier
- * @param name : name of the method
- * @param desc : descriptor of the method
- * @param signature : signature of the method
- * @param exceptions : exception launched by the method
- * @return MethodVisitor
- */
- public MethodVisitor visitMethod(
- final int access,
- final String name,
- final String desc,
- final String signature,
- final String[] exceptions) {
- // The method is a constructor, adapt the constructor to add a ComponentManager argument
- if(name.equals("<init>")) {
- // 1) change the constructor descriptor (add a component manager arg as first argument)
- String new_desc = desc.substring(1);
- new_desc = "(Lorg/apache/felix/ipojo/InstanceManager;"+new_desc;
-
- // Insert the new constructor
- MethodVisitor mv = super.visitMethod(ACC_PUBLIC, "<init>", new_desc, null, null);
-
- if (mv == null) { return null; }
- else {return new ConstructorCodeAdapter(mv, m_owner); }
-
- }
- else {
- MethodVisitor mv = cv.visitMethod(access, name, desc, signature, exceptions);
- if (mv == null) { return null; }
- else {return new PreprocessCodeAdapter(mv, m_owner); }
- }
-
- }
-
- /**
- * Create the setter method for the _cm field.
- */
- private void createComponentManagerSetter() {
- MethodVisitor mv = cv.visitMethod(ACC_PRIVATE, "_setComponentManager", "(Lorg/apache/felix/ipojo/InstanceManager;)V", null, null);
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitVarInsn(ALOAD, 1);
- mv.visitFieldInsn(PUTFIELD, m_owner, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;");
-
- mv.visitInsn(RETURN);
-
- mv.visitMaxs(0, 0);
- mv.visitEnd();
- }
-
- /**
- * Create the getComponentInstance method.
- */
- private void createGetComponentInstanceMethod() {
- MethodVisitor mv = cv.visitMethod(ACC_PUBLIC, "getComponentInstance", "()Lorg/apache/felix/ipojo/ComponentInstance;", null, null);
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;");
- mv.visitInsn(ARETURN);
-
- mv.visitMaxs(0, 0);
- mv.visitEnd();
- }
-
- /** visit Field method.
- * @see org.objectweb.asm.ClassVisitor#visitField(int, java.lang.String, java.lang.String, java.lang.String, java.lang.Object)
- * @param access : acces modifier
- * @param name : name of the field
- * @param desc : description of the field
- * @param signature : signature of the field
- * @param value : value of the field
- * @return FieldVisitor
- */
- public FieldVisitor visitField(
- final int access,
- final String name,
- final String desc,
- final String signature,
- final Object value) {
- if ((access & ACC_STATIC) == 0) {
- IPojoPluginConfiguration.getLogger().log(Level.INFO, "Manipulate the field declaration of " + name);
- Type type = Type.getType(desc);
-
- // Keep the field in the code
- FieldVisitor fv = cv.visitField(access, name, desc, signature, value);
-
- if (type.getSort() == Type.ARRAY) {
-
- String gDesc = "()" + desc;
- createArrayGetter(name, gDesc, type);
-
- // Generates setter method
- String sDesc = "(" + desc + ")V";
- createArraySetter(name, sDesc, type);
-
- }
- else {
-
- // Generate the getter method
- String gDesc = "()" + desc;
- createSimpleGetter(name, gDesc, type);
-
- // Generates setter method
- String sDesc = "(" + desc + ")V";
- createSimpleSetter(name, sDesc, type);
- }
-
- return fv;
-
- }
- return super.visitField(access, name, desc, signature, value);
- }
-
- private void createArraySetter(String name, String desc, Type type) {
- MethodVisitor mv = cv.visitMethod(ACC_PRIVATE, "_set" + name, desc, null, null);
-
- String internalType = desc.substring(1);
- internalType = internalType.substring(0, internalType.length() - 2);
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitVarInsn(ALOAD, 1);
- mv.visitFieldInsn(PUTFIELD, m_owner, name, internalType);
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;");
- mv.visitLdcInsn(name);
- mv.visitVarInsn(ALOAD, 1);
- mv.visitMethodInsn(INVOKEVIRTUAL, "org/apache/felix/ipojo/InstanceManager", "setterCallback", "(Ljava/lang/String;Ljava/lang/Object;)V");
-
- mv.visitInsn(RETURN);
-
- // End
- mv.visitMaxs(0, 0);
- mv.visitEnd();
- }
-
- private void createArrayGetter(String name, String desc, Type type) {
-
-// try {
-// System.out.println("Field Name : " + name);
-// System.out.println("Desc : " + desc);
-// System.out.println("ClassName : " + type.getClassName());
-// System.out.println("Descriptor of the type : " + type.getDescriptor());
-// System.out.println("Internal Name : " + type.getInternalName());
-// } catch(Exception e) {}
-//
-
- String methodName = "_get" + name;
- MethodVisitor mv = cv.visitMethod(ACC_PRIVATE, methodName, desc, null, null);
-
- String internalType = desc.substring(2);
-
- mv.visitVarInsn(ALOAD, 0);
- //mv.visitFieldInsn(GETFIELD, m_owner, name, "["+type.getInternalName()+";");
- mv.visitFieldInsn(GETFIELD, m_owner, name, internalType);
- mv.visitVarInsn(ASTORE, 1);
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;");
- mv.visitLdcInsn(name);
- mv.visitVarInsn(ALOAD, 1);
- mv.visitMethodInsn(INVOKEVIRTUAL, "org/apache/felix/ipojo/InstanceManager", "getterCallback", "(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;");
- mv.visitVarInsn(ASTORE, 2);
-
- mv.visitVarInsn(ALOAD, 2);
- mv.visitTypeInsn(CHECKCAST, internalType);
- mv.visitVarInsn(ASTORE, 3);
-
- Label l3a = new Label();
- mv.visitLabel(l3a);
-
- mv.visitVarInsn(ALOAD, 1);
- Label l4a = new Label();
- mv.visitJumpInsn(IFNULL, l4a);
- mv.visitVarInsn(ALOAD, 1);
- mv.visitVarInsn(ALOAD, 3);
- mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "equals", "(Ljava/lang/Object;)Z");
-
- Label l5a = new Label();
- mv.visitJumpInsn(IFNE, l5a);
- mv.visitLabel(l4a);
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitVarInsn(ALOAD, 3);
- mv.visitMethodInsn(INVOKEVIRTUAL, m_owner, "_set" + name, "(" + internalType + ")V");
- mv.visitLabel(l5a);
-
- mv.visitVarInsn(ALOAD, 3);
- mv.visitInsn(ARETURN);
-
- //End
- mv.visitMaxs(0, 0);
- mv.visitEnd();
- }
-
-
- /**
- * Create the getter for service dependency.
- * @param name : field of the dependency
- * @param desc : description of the getter method
- * @param type : type to return
- */
- private void createSimpleGetter(String name, String desc, Type type) {
-
- String methodName = "_get" + name;
- MethodVisitor mv = cv.visitMethod(ACC_PRIVATE, methodName, desc, null, null);
-
- switch (type.getSort()) {
- case Type.BOOLEAN :
- case Type.CHAR :
- case Type.BYTE :
- case Type.SHORT :
- case Type.INT :
-
- String internalName = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][0];
- String boxingType = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][1];
- String unboxingMethod = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][2];
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, name, internalName);
- mv.visitVarInsn(type.getOpcode(ISTORE), 1);
-
- mv.visitTypeInsn(NEW, boxingType);
- mv.visitInsn(DUP);
- mv.visitVarInsn(type.getOpcode(ILOAD), 1);
- mv.visitMethodInsn(INVOKESPECIAL, boxingType, "<init>", "(" + internalName + ")V");
- mv.visitVarInsn(ASTORE, 2);
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;");
- mv.visitLdcInsn(name);
- mv.visitVarInsn(ALOAD, 2);
- mv.visitMethodInsn(INVOKEVIRTUAL, "org/apache/felix/ipojo/InstanceManager", "getterCallback", "(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;");
- mv.visitVarInsn(ASTORE, 3);
-
- mv.visitVarInsn(ALOAD, 3);
- mv.visitTypeInsn(CHECKCAST, boxingType);
- mv.visitVarInsn(ASTORE, 4);
-
- mv.visitVarInsn(ALOAD, 4);
- mv.visitMethodInsn(INVOKEVIRTUAL, boxingType, unboxingMethod, "()" + internalName);
- mv.visitVarInsn(type.getOpcode(ISTORE), 5);
-
- Label l5 = new Label();
- mv.visitLabel(l5);
-
- mv.visitVarInsn(type.getOpcode(ILOAD), 1);
- mv.visitVarInsn(type.getOpcode(ILOAD), 5);
- Label l6 = new Label();
- mv.visitJumpInsn(type.getOpcode(IF_ICMPEQ), l6);
-
- Label l7 = new Label();
- mv.visitLabel(l7);
- mv.visitVarInsn(ALOAD, 0);
- mv.visitVarInsn(type.getOpcode(ILOAD), 5);
- mv.visitMethodInsn(INVOKEVIRTUAL, m_owner, "_set" + name, "(" + internalName + ")V");
- mv.visitLabel(l6);
-
- mv.visitVarInsn(type.getOpcode(ILOAD), 5);
- mv.visitInsn(type.getOpcode(IRETURN));
- break;
-
- case Type.LONG :
- internalName = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][0];
- boxingType = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][1];
- unboxingMethod = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][2];
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, name, internalName);
- mv.visitVarInsn(LSTORE, 1);
-
- mv.visitTypeInsn(NEW, boxingType);
- mv.visitInsn(DUP);
- mv.visitVarInsn(LLOAD, 1);
- mv.visitMethodInsn(INVOKESPECIAL, boxingType, "<init>", "(" + internalName + ")V");
- mv.visitVarInsn(ASTORE, 3); // Double Space
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;");
- mv.visitLdcInsn(name);
- mv.visitVarInsn(ALOAD, 3);
- mv.visitMethodInsn(INVOKEVIRTUAL, "org/apache/felix/ipojo/InstanceManager", "getterCallback", "(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;");
- mv.visitVarInsn(ASTORE, 4);
-
- mv.visitVarInsn(ALOAD, 4);
- mv.visitTypeInsn(CHECKCAST, boxingType);
- mv.visitVarInsn(ASTORE, 5);
-
- mv.visitVarInsn(ALOAD, 5);
- mv.visitMethodInsn(INVOKEVIRTUAL, boxingType, unboxingMethod, "()" + internalName);
- mv.visitVarInsn(LSTORE, 6);
-
- l5 = new Label();
- mv.visitLabel(l5);
-
- mv.visitVarInsn(LLOAD, 1);
- mv.visitVarInsn(LLOAD, 6);
- mv.visitInsn(LCMP);
- l6 = new Label();
- mv.visitJumpInsn(IFEQ, l6);
-
- l7 = new Label();
- mv.visitLabel(l7);
- mv.visitVarInsn(ALOAD, 0);
- mv.visitVarInsn(LLOAD, 6);
- mv.visitMethodInsn(INVOKEVIRTUAL, m_owner, "_set" + name, "(" + internalName + ")V");
- mv.visitLabel(l6);
-
- mv.visitVarInsn(LLOAD, 6);
- mv.visitInsn(LRETURN);
-
- break;
-
- case Type.DOUBLE :
- internalName = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][0];
- boxingType = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][1];
- unboxingMethod = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][2];
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, name, internalName);
- mv.visitVarInsn(DSTORE, 1);
-
- mv.visitTypeInsn(NEW, boxingType);
- mv.visitInsn(DUP);
- mv.visitVarInsn(DLOAD, 1);
- mv.visitMethodInsn(INVOKESPECIAL, boxingType, "<init>", "(" + internalName + ")V");
- mv.visitVarInsn(ASTORE, 3); // Double Space
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;");
- mv.visitLdcInsn(name);
- mv.visitVarInsn(ALOAD, 3);
- mv.visitMethodInsn(INVOKEVIRTUAL, "org/apache/felix/ipojo/InstanceManager", "getterCallback", "(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;");
- mv.visitVarInsn(ASTORE, 4);
-
- mv.visitVarInsn(ALOAD, 4);
- mv.visitTypeInsn(CHECKCAST, boxingType);
- mv.visitVarInsn(ASTORE, 5);
-
- mv.visitVarInsn(ALOAD, 5);
- mv.visitMethodInsn(INVOKEVIRTUAL, boxingType, unboxingMethod, "()" + internalName);
- mv.visitVarInsn(DSTORE, 6);
-
- l5 = new Label();
- mv.visitLabel(l5);
-
- mv.visitVarInsn(DLOAD, 1);
- mv.visitVarInsn(DLOAD, 6);
- mv.visitInsn(DCMPL);
- l6 = new Label();
- mv.visitJumpInsn(IFEQ, l6);
-
- l7 = new Label();
- mv.visitLabel(l7);
- mv.visitVarInsn(ALOAD, 0);
- mv.visitVarInsn(DLOAD, 6);
- mv.visitMethodInsn(INVOKEVIRTUAL, m_owner, "_set" + name, "(" + internalName + ")V");
- mv.visitLabel(l6);
-
- mv.visitVarInsn(DLOAD, 6);
- mv.visitInsn(DRETURN);
-
- break;
-
- case Type.FLOAT :
- internalName = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][0];
- boxingType = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][1];
- unboxingMethod = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][2];
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, name, internalName);
- mv.visitVarInsn(FSTORE, 1);
-
- mv.visitTypeInsn(NEW, boxingType);
- mv.visitInsn(DUP);
- mv.visitVarInsn(FLOAD, 1);
- mv.visitMethodInsn(INVOKESPECIAL, boxingType, "<init>", "(" + internalName + ")V");
- mv.visitVarInsn(ASTORE, 2); // One Space
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;");
- mv.visitLdcInsn(name);
- mv.visitVarInsn(ALOAD, 2);
- mv.visitMethodInsn(INVOKEVIRTUAL, "org/apache/felix/ipojo/InstanceManager", "getterCallback", "(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;");
- mv.visitVarInsn(ASTORE, 3);
-
- mv.visitVarInsn(ALOAD, 3);
- mv.visitTypeInsn(CHECKCAST, boxingType);
- mv.visitVarInsn(ASTORE, 4);
-
- mv.visitVarInsn(ALOAD, 4);
- mv.visitMethodInsn(INVOKEVIRTUAL, boxingType, unboxingMethod, "()" + internalName);
- mv.visitVarInsn(FSTORE, 5);
-
- l5 = new Label();
- mv.visitLabel(l5);
-
- mv.visitVarInsn(FLOAD, 1);
- mv.visitVarInsn(FLOAD, 5);
- mv.visitInsn(FCMPL);
- l6 = new Label();
- mv.visitJumpInsn(IFEQ, l6);
-
- l7 = new Label();
- mv.visitLabel(l7);
- mv.visitVarInsn(ALOAD, 0);
- mv.visitVarInsn(FLOAD, 5);
- mv.visitMethodInsn(INVOKEVIRTUAL, m_owner, "_set" + name, "(" + internalName + ")V");
- mv.visitLabel(l6);
-
- mv.visitVarInsn(FLOAD, 5);
- mv.visitInsn(FRETURN);
-
- break;
-
- case Type.OBJECT :
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, name, "L" + type.getInternalName() + ";");
- mv.visitVarInsn(ASTORE, 1);
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;");
- mv.visitLdcInsn(name);
- mv.visitVarInsn(ALOAD, 1);
- mv.visitMethodInsn(INVOKEVIRTUAL, "org/apache/felix/ipojo/InstanceManager", "getterCallback", "(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;");
- mv.visitVarInsn(ASTORE, 2);
-
- mv.visitVarInsn(ALOAD, 2);
- mv.visitTypeInsn(CHECKCAST, type.getInternalName());
- mv.visitVarInsn(ASTORE, 3);
-
- Label l3b = new Label();
- mv.visitLabel(l3b);
-
- mv.visitVarInsn(ALOAD, 1);
- Label l4b = new Label();
- mv.visitJumpInsn(IFNULL, l4b);
- mv.visitVarInsn(ALOAD, 1);
- mv.visitVarInsn(ALOAD, 3);
- mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "equals", "(Ljava/lang/Object;)Z");
-
- Label l5b = new Label();
- mv.visitJumpInsn(IFNE, l5b);
- mv.visitLabel(l4b);
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitVarInsn(ALOAD, 3);
- mv.visitMethodInsn(INVOKEVIRTUAL, m_owner, "_set" + name, "(L" + type.getInternalName() + ";)V");
- mv.visitLabel(l5b);
-
- mv.visitVarInsn(ALOAD, 3);
- mv.visitInsn(ARETURN);
-
- break;
-
- default :
- IPojoPluginConfiguration.getLogger().log(Level.SEVERE, "Manipulation problem in " + m_owner + " : a type is not implemented : " + type);
- break;
- }
-
- mv.visitMaxs(0, 0);
- mv.visitEnd();
- }
-
- /**
- * Create the setter method for one property.
- * The name of the method is _set+name of the field
- * @param name : name of the field representing a property
- * @param desc : description of the setter method
- * @param type : type of the property
- */
- private void createSimpleSetter(String name, String desc, Type type) {
- MethodVisitor mv = cv.visitMethod(ACC_PRIVATE, "_set" + name, desc, null, null);
-
- switch(type.getSort()) {
- case Type.BOOLEAN :
- case Type.CHAR :
- case Type.BYTE :
- case Type.SHORT :
- case Type.INT :
- case Type.FLOAT :
- String internalName = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][0];
- String boxingType = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][1];
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitVarInsn(type.getOpcode(ILOAD), 1);
- mv.visitFieldInsn(PUTFIELD, m_owner, name, internalName);
- Label l1 = new Label();
- mv.visitLabel(l1);
-
- mv.visitTypeInsn(NEW, boxingType);
- mv.visitInsn(DUP);
- mv.visitVarInsn(type.getOpcode(ILOAD), 1);
- mv.visitMethodInsn(INVOKESPECIAL, boxingType, "<init>", "(" + internalName + ")V");
- mv.visitVarInsn(ASTORE, 2);
-
- Label l2 = new Label();
- mv.visitLabel(l2);
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;");
- mv.visitLdcInsn(name);
- mv.visitVarInsn(ALOAD, 2);
- mv.visitMethodInsn(INVOKEVIRTUAL, "org/apache/felix/ipojo/InstanceManager", "setterCallback", "(Ljava/lang/String;Ljava/lang/Object;)V");
-
- Label l3 = new Label();
- mv.visitLabel(l3);
- mv.visitInsn(RETURN);
- break;
-
- case Type.LONG :
- case Type.DOUBLE :
- internalName = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][0];
- boxingType = ManipulationProperty.PRIMITIVE_BOXING_INFORMATION[type.getSort()][1];
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitVarInsn(type.getOpcode(ILOAD), 1);
- mv.visitFieldInsn(PUTFIELD, m_owner, name, internalName);
- l1 = new Label();
- mv.visitLabel(l1);
-
- mv.visitTypeInsn(NEW, boxingType);
- mv.visitInsn(DUP);
- mv.visitVarInsn(type.getOpcode(ILOAD), 1);
- mv.visitMethodInsn(INVOKESPECIAL, boxingType, "<init>", "(" + internalName + ")V");
- mv.visitVarInsn(ASTORE, 3); // Double space
-
- l2 = new Label();
- mv.visitLabel(l2);
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;");
- mv.visitLdcInsn(name);
- mv.visitVarInsn(ALOAD, 3);
- mv.visitMethodInsn(INVOKEVIRTUAL, "org/apache/felix/ipojo/InstanceManager", "setterCallback", "(Ljava/lang/String;Ljava/lang/Object;)V");
-
- l3 = new Label();
- mv.visitLabel(l3);
- mv.visitInsn(RETURN);
- break;
-
- case (Type.OBJECT) :
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitVarInsn(ALOAD, 1);
- mv.visitFieldInsn(PUTFIELD, m_owner, name, "L" + type.getInternalName() + ";");
-
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, m_owner, "_cm", "Lorg/apache/felix/ipojo/InstanceManager;");
- mv.visitLdcInsn(name);
- mv.visitVarInsn(ALOAD, 1);
- mv.visitMethodInsn(INVOKEVIRTUAL, "org/apache/felix/ipojo/InstanceManager", "setterCallback", "(Ljava/lang/String;Ljava/lang/Object;)V");
-
- mv.visitInsn(RETURN);
- break;
- default :
- IPojoPluginConfiguration.getLogger().log(Level.SEVERE, "Manipulation Error : Cannot create the setter method for the field : " + name + " (" + type + ")");
- break;
- }
-
- mv.visitMaxs(0, 0);
- mv.visitEnd();
- }
-}
-
diff --git a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/manipulation/PreprocessCodeAdapter.java b/ipojo/plugin/src/main/java/org/apache/felix/ipojo/manipulation/PreprocessCodeAdapter.java
deleted file mode 100644
index 9f711b5..0000000
--- a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/manipulation/PreprocessCodeAdapter.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * 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.felix.ipojo.manipulation;
-
-import java.util.logging.Level;
-
-import org.apache.felix.ipojo.plugin.IPojoPluginConfiguration;
-import org.objectweb.asm.MethodAdapter;
-import org.objectweb.asm.MethodVisitor;
-import org.objectweb.asm.Opcodes;
-
-
-/**
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class PreprocessCodeAdapter extends MethodAdapter implements Opcodes {
-
- /** The owner class of the field.
- * m_owner : String
- */
- private String m_owner;
-
- /** PropertyCodeAdapter constructor.
- * A new FiledCodeAdapter should be create for each method visit.
- * @param mv MethodVisitor
- * @param owner Name of the class
- */
- public PreprocessCodeAdapter(final MethodVisitor mv, final String owner) {
- super(mv);
- m_owner = owner;
- }
-
-
- /** Visit Method for Filed instance (GETFIELD).
- * @see org.objectweb.asm.MethodVisitor#visitFieldInsn(int, String, String, String)
- * @param opcode : visited operation code
- * @param owner : owner of the field
- * @param name : name of the field
- * @param desc : decriptor of the field
- */
- public void visitFieldInsn(
- final int opcode,
- final String owner,
- final String name,
- final String desc) {
- if (owner.equals(m_owner)) {
- if (opcode == GETFIELD) {
- IPojoPluginConfiguration.getLogger().log(Level.INFO, "Manipulate a GETFIELD on : " + name);
- String gDesc = "()" + desc;
- visitMethodInsn(INVOKEVIRTUAL, owner, "_get" + name, gDesc);
- return;
- } else
- if (opcode == PUTFIELD) {
- IPojoPluginConfiguration.getLogger().log(Level.INFO, "Manipulate a PUTFIELD on : " + name);
- String sDesc = "(" + desc + ")V";
- visitMethodInsn(INVOKESPECIAL, owner, "_set" + name, sDesc);
- return;
- }
- }
- super.visitFieldInsn(opcode, owner, name, desc);
- }
-
-}
-
diff --git a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/parser/ManifestMetadataParser.java b/ipojo/plugin/src/main/java/org/apache/felix/ipojo/parser/ManifestMetadataParser.java
deleted file mode 100644
index 0690a44..0000000
--- a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/parser/ManifestMetadataParser.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * 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.felix.ipojo.parser;
-
-import java.util.Dictionary;
-import java.util.logging.Level;
-
-import org.apache.felix.ipojo.metadata.Attribute;
-import org.apache.felix.ipojo.metadata.Element;
-import org.apache.felix.ipojo.plugin.IPojoPluginConfiguration;
-
-/**
- * Manifest Metadata parser.
- * Read a manifest file and construct metadata
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class ManifestMetadataParser {
-
- /**
- * Manifest Headers.
- */
- private Dictionary m_headers;
-
- /**
- * Element list.
- */
- private Element[] m_elements = new Element[0];
-
- /**
- * @return the component metadata.
- * @throws ParseException when a parsing error occurs
- */
- public Element[] getComponentsMetadata() throws ParseException {
- return m_elements[0].getElements("Component");
- }
-
- private void addElement(Element elem) {
- for (int i = 0; (m_elements != null) && (i < m_elements.length); i++) {
- if (m_elements[i] == elem) { return; }
- }
-
- if (m_elements != null) {
- Element[] newElementsList = new Element[m_elements.length + 1];
- System.arraycopy(m_elements, 0, newElementsList, 0, m_elements.length);
- newElementsList[m_elements.length] = elem;
- m_elements = newElementsList;
- }
- else { m_elements = new Element[] {elem}; }
- }
-
- private Element removeLastElement() {
- int idx = -1;
- idx = m_elements.length - 1;
- Element last = m_elements[idx];
- if (idx >= 0) {
- if ((m_elements.length - 1) == 0) {
- // It is the last element of the list;
- m_elements = new Element[0];
- }
- else {
- // Remove the last element of the list :
- Element[] newElementsList = new Element[m_elements.length - 1];
- System.arraycopy(m_elements, 0, newElementsList, 0, idx);
- m_elements = newElementsList;
- }
- }
- return last;
- }
-
- /**
- * Parse the given dictionnary and create the components manager.
- * @param dict : the given headers of the manifest file
- * @throws ParseException : if any error occurs
- */
- public void parse(Dictionary dict) throws ParseException {
- m_headers = dict;
- String componentClassesStr = (String)m_headers.get("iPOJO-Components");
- parseElements(componentClassesStr.trim());
-
- }
-
- /**
- * PArse the metadata from the string given in argument.
- * @param metadata : the metadata
- * @throws ParseException when a parse error occurs
- */
- public void parse(String metadata) throws ParseException {
- parseElements(metadata);
- }
-
- private void parseElements(String s) {
- //Add the ipojo element inside the element list
- addElement(new Element("iPOJO", ""));
- char[] string = s.toCharArray();
-
- for (int i = 0; i < string.length; i++) {
- char c = string[i];
- switch(c) {
-
- case '$' :
- String attName = "";
- String attValue = "";
- String attNs = "";
- i++;
- c = string[i];
- while (c != '=') {
- if(c == ':') {
- attNs = attName;
- attName= "";
- } else { attName = attName + c; }
- i = i + 1;
- c = string[i];
- }
- i++; // skip =
- c = string[i];
- while (c != ' ') {
- attValue = attValue + c;
- i++;
- c = string[i];
- }
- Attribute att = new Attribute(attName, attNs ,attValue);
- IPojoPluginConfiguration.getLogger().log(Level.INFO, "Detect a new attribute : '" + "[" + attNs + "]" + attName + "' = '" + attValue + "'");
- m_elements[m_elements.length - 1].addAttribute(att);
- break;
-
- case '}' :
- Element lastElement = removeLastElement();
- IPojoPluginConfiguration.getLogger().log(Level.INFO, "End of the element : " + lastElement.getName());
- if (m_elements.length != 0) {
- Element newQueue = m_elements[m_elements.length - 1];
- newQueue.addElement(lastElement);
- }
- else {
- addElement(lastElement);
- }
- break;
- case ' ' : break; // do nothing;
- default :
- String name = "";
- String ns = "";
- c = string[i];
- while (c != ' ') {
- if(c == ':') {
- ns = name;
- name = "";
- i++;
- }
- else {
- name = name + c;
- i++;
- c = string[i];
- }
- }
- // Skip spaces
- while (string[i] == ' ') { i = i + 1; }
- i = i + 1; // skip {
- Element elem = new Element(name, ns);
- addElement(elem);
- IPojoPluginConfiguration.getLogger().log(Level.INFO, "Start an new element : " + name);
- break;
- }
- }
- }
-
-}
diff --git a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/parser/ParseException.java b/ipojo/plugin/src/main/java/org/apache/felix/ipojo/parser/ParseException.java
deleted file mode 100644
index e28c559..0000000
--- a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/parser/ParseException.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * 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.felix.ipojo.parser;
-
-/**
- * Exceptions thrown by parsers.
- * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
- */
-public class ParseException extends Exception {
-
- /**
- * serialVersionUID.
- */
- private static final long serialVersionUID = 1L;
-
- /**
- * Parsing error.
- * @param msg : the error emssage.
- */
- public ParseException(String msg) {
- super(msg);
- }
-
-}
diff --git a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/parser/XMLMetadataParser.java b/ipojo/plugin/src/main/java/org/apache/felix/ipojo/parser/XMLMetadataParser.java
deleted file mode 100644
index 030eee5..0000000
--- a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/parser/XMLMetadataParser.java
+++ /dev/null
@@ -1,239 +0,0 @@
-/*
- * 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.felix.ipojo.parser;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.logging.Level;
-
-import org.apache.felix.ipojo.metadata.Attribute;
-import org.apache.felix.ipojo.metadata.Element;
-import org.apache.felix.ipojo.plugin.IPojoPluginConfiguration;
-import org.xml.sax.Attributes;
-import org.xml.sax.ContentHandler;
-import org.xml.sax.Locator;
-import org.xml.sax.SAXException;
-
-public class XMLMetadataParser implements ContentHandler {
-
-
- /**
- * Element of the metadata.
- */
- private Element[] m_elements = new Element[0];
-
- /**
- * @return a components metadata
- * @throws ParseException when an error occurs in the xml parsing
- */
- public Element[] getComponentsMetadata() throws ParseException {
- Element[] comp = m_elements[0].getElements("Component");
- Element[] compo = m_elements[0].getElements("Composite");
- Element[] metadata = new Element[comp.length + compo.length];
- int l = 0;
- for(int i = 0; i < comp.length; i++) { metadata[l] = comp[i]; l++;}
- for(int i = 0; i < compo.length; i++) { metadata[l] = compo[i]; l++;}
- return metadata;
- }
-
- public List getReferredPackages() {
- List referred = new ArrayList();
- Element[] compo = m_elements[0].getElements("Composite");
- for(int i= 0; i < compo.length; i++) {
- for(int j = 0; j < compo[i].getElements().length; j++) {
- if(compo[i].getElements()[j].containsAttribute("specification")) {
- String p = compo[i].getElements()[j].getAttribute("specification");
- int last = p.lastIndexOf('.');
- if(last != -1) { referred.add(p.substring(0, last)); }
- }
- }
- }
- return referred;
- }
-
- public Element[] getMetadata() throws ParseException {
- Element[] comp = m_elements[0].getElements("Component");
- Element[] compo = m_elements[0].getElements("Composite");
- Element[] conf = m_elements[0].getElements("Instance");
- Element[] metadata = new Element[comp.length + conf.length + compo.length];
- int l = 0;
- for(int i = 0; i < comp.length; i++) { metadata[l] = comp[i]; l++;}
- for(int i = 0; i < compo.length; i++) { metadata[l] = compo[i]; l++;}
- for(int i = 0; i < conf.length; i++) { metadata[l] = conf[i]; l++;}
- return metadata;
- }
-
-
-
- /* (non-Javadoc)
- * @see org.xml.sax.ContentHandler#characters(char[], int, int)
- */
- public void characters(char[] ch, int start, int length)
- throws SAXException {
- // NOTHING TO DO
-
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.ContentHandler#endDocument()
- */
- public void endDocument() throws SAXException {
- IPojoPluginConfiguration.getLogger().log(Level.INFO, "End of the XML parsing, " + m_elements.length + " primary elements found");
-
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
- */
- public void endElement(String namespaceURI, String localName, String qName)
- throws SAXException {
- // Get the last element of the list
- Element lastElement = removeLastElement();
-
- // Check if the name is consitent with the name of this end tag
- if (!lastElement.getName().equalsIgnoreCase(qName) && !lastElement.getNameSpace().equals(namespaceURI)) {
- IPojoPluginConfiguration.getLogger().log(Level.SEVERE, "Parse error when ending an element : " + qName + " [" + namespaceURI + "]");
- throw new SAXException("Parse error when ending an element : " + qName + " [" + namespaceURI + "]");
- }
-
- // The name is consitent
- // Add this element last element with if it is not the root
- if (m_elements.length != 0) {
- Element newQueue = m_elements[m_elements.length - 1];
- newQueue.addElement(lastElement);
- }
- else {
- // It is the last element
- addElement(lastElement);
- }
-
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String)
- */
- public void endPrefixMapping(String prefix) throws SAXException {
- //NOTHING TO DO
-
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int)
- */
- public void ignorableWhitespace(char[] ch, int start, int length)
- throws SAXException {
- // NOTHING TO DO
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, java.lang.String)
- */
- public void processingInstruction(String target, String data)
- throws SAXException {
- // DO NOTHING
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.ContentHandler#setDocumentLocator(org.xml.sax.Locator)
- */
- public void setDocumentLocator(Locator locator) {
- // NOTHING TO DO
-
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String)
- */
- public void skippedEntity(String name) throws SAXException {
- // NOTHING TO DO
-
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.ContentHandler#startDocument()
- */
- public void startDocument() throws SAXException {
- IPojoPluginConfiguration.getLogger().log(Level.INFO, "Start of the XML parsing");
-
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
- */
- public void startElement(String namespaceURI, String localName,
- String qName, Attributes atts) throws SAXException {
- IPojoPluginConfiguration.getLogger().log(Level.INFO, "An XML tag was openend : " + localName + " [" + namespaceURI + "]");
-
- Element elem = new Element(localName, namespaceURI);
-
- for (int i = 0; i < atts.getLength(); i++) {
- String name = (String)atts.getLocalName(i);
- String ns = (String) atts.getURI(i);
- String value = (String)atts.getValue(i);
- Attribute att = new Attribute(name, ns, value);
- elem.addAttribute(att);
- }
-
- addElement(elem);
-
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String, java.lang.String)
- */
- public void startPrefixMapping(String prefix, String uri)
- throws SAXException {
- // NOTHING TO DO
-
- }
-
- private void addElement(Element elem) {
- for (int i = 0; (m_elements != null) && (i < m_elements.length); i++) {
- if (m_elements[i] == elem) { return; }
- }
-
- if (m_elements != null) {
- Element[] newElementsList = new Element[m_elements.length + 1];
- System.arraycopy(m_elements, 0, newElementsList, 0, m_elements.length);
- newElementsList[m_elements.length] = elem;
- m_elements = newElementsList;
- }
- else { m_elements = new Element[] {elem}; }
- }
-
- private Element removeLastElement() {
- int idx = -1;
- idx = m_elements.length - 1;
- Element last = m_elements[idx];
- if (idx >= 0) {
- if ((m_elements.length - 1) == 0) {
- // It is the last element of the list;
- m_elements = new Element[0];
- }
- else {
- // Remove the last element of the list :
- Element[] newElementsList = new Element[m_elements.length - 1];
- System.arraycopy(m_elements, 0, newElementsList, 0, idx);
- m_elements = newElementsList;
- }
- }
- return last;
- }
-
-}
diff --git a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/plugin/Clazz.java b/ipojo/plugin/src/main/java/org/apache/felix/ipojo/plugin/Clazz.java
deleted file mode 100644
index a034ed1..0000000
--- a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/plugin/Clazz.java
+++ /dev/null
@@ -1,208 +0,0 @@
-/*
- * 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.felix.ipojo.plugin;
-
-import java.io.*;
-import java.util.*;
-
-public class Clazz {
- static byte SkipTable[] = {0, // 0 non existent
- -1, // 1 CONSTANT_utf8 UTF 8, handled in
- // method
- -1, // 2
- 4, // 3 CONSTANT_Integer
- 4, // 4 CONSTANT_Float
- 8, // 5 CONSTANT_Long (index +=2!)
- 8, // 6 CONSTANT_Double (index +=2!)
- -1, // 7 CONSTANT_Class
- 2, // 8 CONSTANT_String
- 4, // 9 CONSTANT_FieldRef
- 4, // 10 CONSTANT_MethodRef
- 4, // 11 CONSTANT_InterfaceMethodRef
- 4, // 12 CONSTANT_NameAndType
- };
-
- Set imports = new HashSet();
- String path;
- Jar jar;
-
- public Clazz(Jar jar, String path, InputStream in) throws IOException {
- this.path = path;
- this.jar = jar;
- DataInputStream din = new DataInputStream(in);
- parseClassFile(din);
- }
-
-
- void parseClassFile(DataInputStream in)
- throws IOException {
- Set classes = new HashSet();
- Set descriptors = new HashSet();
- Hashtable pool = new Hashtable();
- try {
- int magic = in.readInt();
- if (magic != 0xCAFEBABE)
- throw new IOException(
- "Not a valid class file (no CAFEBABE header)");
- in.readShort(); // minor version
- in.readShort(); // major version
- int count = in.readUnsignedShort();
- process: for (int i = 1; i < count; i++) {
- byte tag = in.readByte();
- switch (tag) {
- case 0 :
- break process;
- case 1 :
- // CONSTANT_Utf8
- String name = in.readUTF();
- pool.put(new Integer(i), name);
- break;
- // A Class constant is just a short reference in
- // the constant pool
- case 7 :
- // CONSTANT_Class
- Integer index = new Integer(in.readShort());
- classes.add(index);
- break;
- // For some insane optimization reason are
- // the long and the double two entries in the
- // constant pool. See 4.4.5
- case 5 :
- // CONSTANT_Long
- case 6 :
- // CONSTANT_Double
- in.skipBytes(8);
- i++;
- break;
-
- // Interface Method Ref
- case 12 :
- in.readShort(); // Name index
- int descriptorIndex = in.readShort();
- descriptors.add(new Integer(descriptorIndex));
- break;
-
- // We get the skip count for each record type
- // from the SkipTable. This will also automatically
- // abort when
- default :
- if (tag == 2)
- throw new IOException("Invalid tag " + tag);
- in.skipBytes(SkipTable[tag]);
- break;
- }
- }
- }
- catch (Exception e) {
- e.printStackTrace();
- return;
- }
- //
- // Now iterate over all classes we found and
- // parse those as well. We skip duplicates
- //
-
- for (Iterator e = classes.iterator(); e.hasNext();) {
- Integer n = (Integer) e.next();
- String next = (String) pool.get(n);
- if (next != null) {
- String normalized = normalize(next);
- if (normalized != null) {
- // For purposes of trying to guess the activator class, we assume
- // that any class that references the BundleActivator interface
- // must be a BundleActivator implementation.
- if ( normalized.startsWith("org/osgi/framework/BundleActivator")) {
- String cname = path.replace('/', '.');
- cname = cname.substring(0,cname.length()-".class" .length());
- jar.addActivator(cname);
- }
- String pack = getPackage(normalized);
- if (!pack.startsWith("java."))
- imports.add(pack);
- }
- }
- else
- throw new IllegalArgumentException("Invalid class, parent=");
- }
- for (Iterator e = descriptors.iterator(); e.hasNext();) {
- Integer n = (Integer) e.next();
- String prototype = (String) pool.get(n);
- if (prototype != null)
- parseDescriptor(prototype);
- }
- }
-
- void parseDescriptor(String prototype) {
- addReference(prototype);
- StringTokenizer st = new StringTokenizer(prototype, "(;)", true);
- while (st.hasMoreTokens()) {
- if (st.nextToken().equals("(")) {
- String token = st.nextToken();
- while (!token.equals(")")) {
- addReference(token);
- token = st.nextToken();
- }
- token = st.nextToken();
- addReference(token);
- }
- }
- }
-
- private void addReference(String token) {
- if (token.startsWith("L")) {
- String clazz = normalize(token.substring(1));
- if (clazz.startsWith("java/"))
- return;
- String pack = getPackage(clazz);
- imports.add(pack);
- }
- }
-
- static String normalize(String s) {
- if (s.startsWith("[L"))
- return normalize(s.substring(2));
- if (s.startsWith("["))
- if (s.length() == 2)
- return null;
- else
- return normalize(s.substring(1));
- if (s.endsWith(";"))
- return normalize(s.substring(0, s.length() - 1));
- return s + ".class";
- }
-
- static String getPackage(String clazz) {
- int n = clazz.lastIndexOf('/');
- if (n < 0)
- return ".";
- return clazz.substring(0, n).replace('/', '.');
- }
-
-
- public Collection getReferred() {
- return imports;
- }
-
-
- public Object getPath() {
- return path;
- }
-
-
-}
diff --git a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/plugin/IPojoPluginConfiguration.java b/ipojo/plugin/src/main/java/org/apache/felix/ipojo/plugin/IPojoPluginConfiguration.java
deleted file mode 100644
index a936d1a..0000000
--- a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/plugin/IPojoPluginConfiguration.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * 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.felix.ipojo.plugin;
-
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-public class IPojoPluginConfiguration {
-
- private static Logger logger;
-
- public static Level logLevel = Level.WARNING;
-
- public static Logger getLogger() {
- if (logger == null) {
- String name = "org.apache.felix.ipojo.tools.plugin";
- logger = Logger.getLogger(name);
- logger.setLevel(logLevel);
- }
- return logger;
- }
-
- public static final String ipojo_version = "0.7.0";
-
- public static final String ipojo_package = "org.apache.felix.ipojo";
- public static final String ipojo_arch_package = "org.apache.felix.ipojo.architecture";
- public static final String config_admin_package = "org.osgi.service.cm";
-
-
-
-
-
-}
diff --git a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/plugin/Jar.java b/ipojo/plugin/src/main/java/org/apache/felix/ipojo/plugin/Jar.java
deleted file mode 100644
index 58b09c7..0000000
--- a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/plugin/Jar.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * 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.felix.ipojo.plugin;
-
-import java.io.*;
-import java.util.*;
-import java.util.jar.*;
-import java.util.zip.*;
-
-public class Jar {
- Map resources = new TreeMap();
- Map imports = new HashMap();
- Map exports = new HashMap();
- Manifest manifest;
- boolean manifestFirst;
- String name;
- Jar parent;
- List activators = new ArrayList();
-
- public Jar(Jar parent, String name, InputStream in) throws IOException {
- this.name = name;
- this.parent = parent;
- ZipInputStream jar = new ZipInputStream(in);
- ZipEntry entry = jar.getNextEntry();
- boolean first = true;
- while (entry != null) {
- String path = entry.getName();
-
- if (path.endsWith(".class")) {
- Clazz clazz = new Clazz(this, path, jar);
- resources.put(path, clazz);
- }
- else if (path.endsWith(".jar")) {
- Jar pool = new Jar(this, path, jar);
- resources.put(path, pool);
- }
- else if (path.endsWith("/packageinfo")
- && !path.startsWith("OSGI-OPT")) {
- String version = parsePackageInfo(jar, exports);
- resources.put(path, version);
- }
- else if (path.equals("META-INF/MANIFEST.MF")) {
- manifestFirst = first;
- manifest = new Manifest(jar);
- }
- else
- resources.put(path, null);
-
- entry = jar.getNextEntry();
- if (!path.endsWith("/"))
- first = false;
- }
- }
-
- public Jar(Jar parent, String name, File rootDir) throws IOException {
- this.name = name;
- this.parent = parent;
- traverse(rootDir.getAbsolutePath().length(), rootDir, rootDir.list());
- }
-
- void traverse(int root, File dir, String list[]) throws IOException {
- for (int i = 0; i < list.length; i++) {
- File sub = new File(dir, list[i]);
- if (sub.isDirectory())
- traverse(root, sub, sub.list());
- else {
- String path = sub.getAbsolutePath().substring(root + 1)
- .replace(File.separatorChar, '/');
- FileInputStream in = new FileInputStream(sub);
-
- if (path.endsWith(".class")) {
- Clazz clazz = new Clazz(this, path, in);
- resources.put(path, clazz);
- }
- else if (path.endsWith(".jar")) {
- Jar pool = new Jar(this, path, in);
- resources.put(path, pool);
- }
- else if (path.endsWith("/packageinfo")
- && !path.startsWith("OSGI-OPT")) {
- String version = parsePackageInfo(in, exports);
- resources.put(path, version);
- }
- else if (path.endsWith("META-INF/MANIFEST.MF")) {
- manifest = new Manifest(in);
- }
- else
- resources.put(path, null);
- }
- }
- }
-
- private static String parsePackageInfo(InputStream jar, Map exports)
- throws IOException {
- try {
- byte[] buf = collect(jar, 0);
- String line = new String(buf);
- StringTokenizer qt = new StringTokenizer(line, " \r\n\t");
- if (qt.hasMoreElements()) {
- qt.nextToken();
- if (qt.hasMoreElements()) {
- String version = qt.nextToken();
- return version;
- }
- }
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
-
- /**
- * Convenience method to turn an inputstream into a byte array. The method
- * uses a recursive algorithm to minimize memory usage.
- *
- * @param in stream with data
- * @param offset where we are in the stream
- * @returns byte array filled with data
- */
- private static byte[] collect(InputStream in, int offset)
- throws IOException {
- byte[] result;
- byte[] buffer = new byte[10000];
- int size = in.read(buffer);
- if (size <= 0)
- return new byte[offset];
- else
- result = collect(in, offset + size);
- System.arraycopy(buffer, 0, result, offset, size);
- return result;
- }
-
- public Manifest getManifest() {
- return manifest;
- }
-
- public Object getEntry(String resource) {
- return resources.get(resource);
- }
-
- public boolean exists(String jarOrDir) {
- return resources.keySet().contains(jarOrDir);
- }
-
- public Set getEntryPaths(String prefix) {
- Set result = new TreeSet();
- for (Iterator i = resources.keySet().iterator(); i.hasNext();) {
- String path = (String) i.next();
- if (path.startsWith(prefix))
- result.add(path);
- }
- return result;
- }
-
- String getName() {
- return name;
- }
-
- public String toString() {
- return getName();
- }
-
- public void addActivator(String path) {
- if (parent != null)
- parent.addActivator(path);
- else {
- activators.add(path);
- }
-
- }
-
- public boolean containsActivator(String path) {
- if (parent != null)
- return parent.containsActivator(path);
- return activators.contains(path);
- }
-}
diff --git a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/plugin/ManipulatorMojo.java b/ipojo/plugin/src/main/java/org/apache/felix/ipojo/plugin/ManipulatorMojo.java
new file mode 100644
index 0000000..c2393e9
--- /dev/null
+++ b/ipojo/plugin/src/main/java/org/apache/felix/ipojo/plugin/ManipulatorMojo.java
@@ -0,0 +1,82 @@
+package org.apache.felix.ipojo.plugin;
+
+import java.io.File;
+
+import org.apache.felix.ipojo.manipulator.Pojoization;
+import org.apache.maven.plugin.AbstractMojo;
+import org.apache.maven.plugin.MojoExecutionException;
+import org.apache.maven.plugin.MojoFailureException;
+
+/**
+ * Package an OSGi jar "bundle."
+ *
+ * @author <a href="mailto:felix-dev@incubator.apache.org">Apache Felix Project</a>
+ * @version $Rev$, $Date$
+ * @goal ipojo-bundle
+ * @phase package
+ * @requiresDependencyResolution runtime
+ * @description manipulate an OSGi bundle jar to build an iPOJO bundle
+ */
+public class ManipulatorMojo extends AbstractMojo {
+
+ /**
+ * The directory for the generated JAR.
+ *
+ * @parameter expression="${project.build.directory}"
+ * @required
+ */
+ private String buildDirectory;
+
+ /**
+ * The directory containing generated classes.
+ *
+ * @parameter expression="${project.build.outputDirectory}"
+ * @required
+ * @readonly
+ */
+ private File outputDirectory;
+
+ /**
+ * The name of the generated JAR file.
+ *
+ * @parameter alias="jarName" expression="${project.build.finalName}"
+ * @required
+ */
+ private String jarName;
+
+ /**
+ * @parameter expression="${metadata}" default-value="metadata.xml"
+ */
+ private String metadata;
+
+ public void execute() throws MojoExecutionException, MojoFailureException {
+ getLog().info("Start bundle manipulation");
+
+ // Get metadata file
+ File meta = new File(outputDirectory + "\\" + metadata);
+ getLog().info("Metadata File : " + meta.getAbsolutePath());
+ if(!meta.exists()) {
+ throw new MojoExecutionException("the specified metadata file does not exists");
+ }
+
+ // Get input bundle
+ File in = new File(buildDirectory + "\\" + jarName + ".jar" );
+ getLog().info("Input Bundle File : " + in.getAbsolutePath());
+ if(!in.exists()) {
+ throw new MojoExecutionException("the specified bundle file does not exists");
+ }
+
+ File out = new File(buildDirectory + "\\_out.jar");
+
+ Pojoization pojo = new Pojoization();
+ pojo.pojoization(in, out, meta);
+ for(int i = 0; i < pojo.getWarnings().size(); i++) {
+ getLog().warn((String) pojo.getWarnings().get(i));
+ }
+ if(pojo.getErrors().size() > 0 ) { throw new MojoExecutionException((String) pojo.getErrors().get(0)); }
+ in.delete();
+ out.renameTo(in);
+ getLog().info("Bundle manipulation - SUCCESS");
+ }
+
+}
diff --git a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/plugin/OsgiJarMojo.java b/ipojo/plugin/src/main/java/org/apache/felix/ipojo/plugin/OsgiJarMojo.java
deleted file mode 100644
index bd12261..0000000
--- a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/plugin/OsgiJarMojo.java
+++ /dev/null
@@ -1,1024 +0,0 @@
-/*
- * 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.felix.ipojo.plugin;
-
-import java.io.*;
-import java.util.*;
-import java.util.zip.ZipFile;
-import java.util.zip.ZipEntry;
-
-import org.apache.maven.archiver.*;
-import org.apache.maven.artifact.*;
-import org.apache.maven.plugin.*;
-import org.apache.maven.project.MavenProject;
-import org.codehaus.plexus.archiver.ArchiverException;
-import org.codehaus.plexus.archiver.jar.*;
-import org.codehaus.plexus.util.FileUtils;
-
-import java.net.MalformedURLException;
-import java.net.URL;
-
-import org.apache.felix.ipojo.manipulation.Manipulator;
-import org.apache.felix.ipojo.manipulation.MethodDescriptor;
-import org.apache.felix.ipojo.metadata.Attribute;
-import org.apache.felix.ipojo.metadata.Element;
-
-import org.apache.felix.ipojo.parser.ManifestMetadataParser;
-import org.apache.felix.ipojo.parser.ParseException;
-import org.apache.felix.ipojo.parser.XMLMetadataParser;
-
-import org.xml.sax.InputSource;
-import org.xml.sax.XMLReader;
-import org.xml.sax.helpers.XMLReaderFactory;
-
-/**
- * Package an OSGi jar "bundle."
- *
- * @author <a href="mailto:dev@felix.apache.org">Apache Felix Project</a>
- * @version $Rev$, $Date$
- * @goal ipojo-bundle
- * @phase package
- * @requiresDependencyResolution runtime
- * @description build an OSGi bundle jar
- */
-public class OsgiJarMojo extends AbstractMojo {
- public static final String OSGI_REFERENCES = "osgi.references";
- public static final String AUTO_DETECT = "auto-detect";
-
- private static final String[] EMPTY_STRING_ARRAY = {};
-
- int bundleManifestVersion = 1;
-
- /**
- * Jars to Inline
- *
- * @parameter
- */
- private List inlinedArtifacts = new ArrayList();
-
- /**
- * Packages to ignore when generating import-package header.
- *
- * @parameter
- */
- private String ignorePackage;
-
- /**
- * The Maven project.
- *
- * @parameter expression="${project}"
- * @required
- * @readonly
- */
- private MavenProject project;
-
- /**
- * The directory for the generated JAR.
- *
- * @parameter expression="${project.build.directory}"
- * @required
- */
- private String buildDirectory;
-
- /**
- * The directory containing generated classes.
- *
- * @parameter expression="${project.build.outputDirectory}"
- * @required
- * @readonly
- */
- private File outputDirectory;
-
- /**
- * The name of the generated JAR file.
- *
- * @parameter alias="jarName" expression="${project.build.finalName}"
- * @required
- */
- private String jarName;
-
- /**
- * The Jar archiver.
- *
- * @parameter expression="${component.org.codehaus.plexus.archiver.Archiver#jar}"
- * @required
- */
- private JarArchiver jarArchiver;
-
- /**
- * The maven archive configuration to use.
- */
- private MavenArchiveConfiguration archiveConfig = new MavenArchiveConfiguration();
-
- /**
- * The comma separated list of tokens to include in the JAR. Default is
- * '**'.
- *
- * @parameter alias="includes"
- */
- private String jarSourceIncludes = "**";
-
- /**
- * The comma separated list of tokens to exclude from the JAR.
- *
- * @parameter alias="excludes"
- */
- private String jarSourceExcludes;
-
- /**
- * @parameter
- */
- private String manifestFile;
-
- /**
- * @parameter expression="${org.apache.felix.ipojo.tools.maven.plugin.OsgiManifest}"
- */
- private OsgiManifest osgiManifest;
-
- private String[][] namespaces;
- private List referredPackages;
-
- /**
- * Execute this Mojo
- *
- * @throws MojoExecutionException
- */
- public void execute() throws MojoExecutionException {
- File jarFile = new File(buildDirectory, jarName + ".jar");
-
- try {
- performPackaging(jarFile);
- }
- catch (Exception e) {
- throw new MojoExecutionException("Error assembling JAR bundle", e);
- }
- }
-
- /**
- * Generates the JAR bundle file.
- *
- * @param jarFile the target JAR file
- * @throws IOException
- * @throws ArchiverException
- * @throws ManifestException
- * @throws DependencyResolutionRequiredException
- */
- private void performPackaging(File jarFile) throws IOException,
- ArchiverException, ManifestException,
- DependencyResolutionRequiredException, MojoExecutionException {
-
- outputDirectory.mkdirs();
-
- verifyDeclaredBundleManifestVersion();
-
- getLog().info("Generating JAR bundle " + jarFile.getAbsolutePath());
-
- MavenArchiver archiver = new MavenArchiver();
-
- archiver.setArchiver(jarArchiver);
- archiver.setOutputFile(jarFile);
-
- addManifestFile();
- addManifestEntries();
-
- // Inline the contents of the indicated jar artifacts
- inlineArtifacts();
-
- // Add the JARs that were specified in the POM
- // as "not" provided
- addEmbeddedJars();
- addBundleVersion();
-
- // Insert iPOJO Manipulation
- iPojoManipulation();
-
- jarArchiver.addDirectory(outputDirectory, getIncludes(), getExcludes());
-
- // Parse the output directory as if it was a JAR file.
- // This creates special entries for classes, packageinfo
- // and embedded JAR files (which are parsed as well).
- Jar mainJar = new Jar(null, jarName, outputDirectory);
-
- // Calculate the Bundle Classpath from the embedded
- // JAR files. We hardcode the bcp as ., <embedded jars>
- // TODO we add all the found JARs to the Bcp, maybe we
- // should look if they are needed by traversing the imports.
- List bundleClassPath = getBundleClassPath(mainJar);
- bundleClassPath.add(0, ".");
- createBundleClasspathHeader(bundleClassPath);
-
- // Calculate the exports (contained) and imports (referred)
- // The bundleClassPath contains the JARs in the right order
- Set contained = new HashSet(); // package name
- Set referred = new HashSet(); // package name
- Map uses = new HashMap(); // package name => Set of package name
-
- // Iterate over the bundle class path and calculate the contained
- // and referred packages as well as the uses.
- for (Iterator i = bundleClassPath.iterator(); i.hasNext();) {
- String path = (String) i.next();
- Jar jar = path.equals(".") ? mainJar : (Jar) mainJar.resources
- .get(path);
- analyzeJar(jar, contained, referred, uses);
- }
-
- referred.removeAll(contained);
-
- // Check if the osgi.references property is set and display result
- // if necessary.
- checkReferencesProperty(uses);
-
- // Dump referenced package information if debug logging is enabled.
- if (getLog().isDebugEnabled()) {
- printReferencedPackages(uses);
- }
-
- Map exports = parseHeader(osgiManifest.getExportPackage());
- Map imports = parseHeader(osgiManifest.getImportPackage());
- Map dynamicImports = parseHeader(osgiManifest.getDynamicImportPackage());
-
- if (dynamicImports != null) {
- // Remove any dynamic imports from the referred set.
- referred = new HashSet(referred);
- referred.removeAll(dynamicImports.keySet());
- }
-
- if (exports != null) {
- verifyDeclaredExports(exports, contained);
- createExportHeader(exports, uses);
- }
-
- // Remove any ignored packages from the referred set.
- Set ignorePackage = parseIgnorePackage();
- referred.removeAll(ignorePackage);
-
- // If the POM file contains an import declaration,
- // we verify its validity. Otherwise, we generate the
- // import package header from the referred. Exports
- // are added to automatically imports for R4 bundles.
- if (imports == null) {
- createImportHeader(referred, exports == null ? new HashSet()
- : exports.keySet());
- }
- else {
- verifyDeclaredImports(referred, imports);
- }
-
- //verifyBundleActivator(mainJar); // Replace it by setBundleActivator
-
- archiver.createArchive(project, archiveConfig);
- project.getArtifact().setFile(jarFile);
- }
-
-// private void verifyBundleActivator(Jar mainJar) {
-// String ba = osgiManifest.getBundleActivator();
-// if (ba == null || ba.trim().length() == 0) {
-// switch ( mainJar.activators.size() ) {
-// case 0: break;
-// case 1: archiveConfig.addManifestEntry("Bundle-Activator", mainJar.activators.get(0));
-// break;
-// default:
-// getLog().info("[OSGi] No Bundle-Activator specified and multiple found" );
-// break;
-// }
-// }
-// else {
-// if( ! mainJar.activators.contains(ba))
-// getLog().warn("[OSGi] UNABLE TO VERIFY BUNDLE ACTIVATOR: " + ba);
-// }
-// }
-
- private void createBundleClasspathHeader(List bundleClassPath) {
- StringBuffer sb = new StringBuffer();
- for (Iterator i = bundleClassPath.iterator(); i.hasNext(); ) {
- sb.append(i.next());
- if (i.hasNext()) {
- sb.append(",");
- }
- }
- if (sb.length() > 0)
- archiveConfig.addManifestEntry("Bundle-Classpath", sb.toString());
- }
-
- /**
- * Iterate over the declared exports from the POM, verify that they are
- * present, add the uses clause if necessary and finally add the manifest
- * entry.
- *
- * @param contained Set of contained packages
- * @param exports Map with the export clauses from the POM
- * @throws MojoExecutionException
- */
- void verifyDeclaredExports(Map exports, Set contained)
- throws MojoExecutionException {
- Set declaredExports = exports.keySet();
- for (Iterator i = declaredExports.iterator(); i.hasNext();) {
- String pack = (String) i.next();
- if (!contained.contains(pack)) {
- getLog()
- .error("[OSGi] EXPORTED PACKAGE NOT IN BUNDLE: " + pack);
- throw new MojoExecutionException(
- "Exported Package not found in bundle or JARs on bundle class path "
- + pack);
- }
-
- }
- }
-
- /**
- * Print out the export headers after adding the uses clause.
- *
- * @param exports
- * @param uses
- * @throws MojoExecutionException
- */
- void createExportHeader(Map exports, Map uses)
- throws MojoExecutionException {
- if (exports.size() > 0) {
- Set declaredExports = exports.keySet();
- for (Iterator i = declaredExports.iterator(); i.hasNext();) {
- String pack = (String) i.next();
- Map clause = (Map) exports.get(pack);
-
- if (bundleManifestVersion >= 2) {
- Set t = (Set) uses.get(pack);
- if (t != null && !t.isEmpty()) {
- StringBuffer sb = new StringBuffer();
- String del = "\"";
- for (Iterator u = t.iterator(); u.hasNext();) {
- String usedPackage = (String) u.next();
- if (!usedPackage.equals(pack)) {
- sb.append(del);
- sb.append(usedPackage);
- del = ",";
- }
- }
- sb.append("\"");
- clause.put("uses:", sb.toString());
- }
- }
- }
- archiveConfig.addManifestEntry(
- "Export-Package",
- printClauses(exports));
- }
- }
-
- /**
- * Verify that the declared imports match the referred packages.
- *
- * @param referred referred package
- * @param imports imported packages from POM
- * @throws MojoExecutionException
- */
- void verifyDeclaredImports(Set referred, Map imports)
- throws MojoExecutionException {
- Set declaredImports = imports.keySet();
- Set test = new HashSet(referred);
- test.removeAll(declaredImports);
- for (Iterator m = test.iterator(); m.hasNext();) {
- Object o = m.next();
- // For backwards compatibility with existing builds, only
- // issue a warning for missing imports. Other the other hand,
- // if packages are being ignored, then this is a new build
- // so be more strict and throw an error.
- if (osgiManifest.getIgnorePackage() == null) {
- getLog().warn("[OSGi] MISSING IMPORT: " + o);
- }
- else {
- getLog().error("[OSGi] MISSING IMPORT: " + o);
- throw new MojoExecutionException("Missing Import " + o);
- }
- }
-
- test = new HashSet(declaredImports);
- test.removeAll(referred);
- for (Iterator m = test.iterator(); m.hasNext();) {
- getLog().warn("[OSGi] SUPERFLUOUS IMPORT: " + m.next());
- getLog()
- .warn(
- "[OSGi] Removing the POM Import-Package element will automatically generate the import clauses");
- }
- }
-
- /**
- * Standard OSGi header parser. This parser can handle the format clauses
- * ::= clause ( ',' clause ) + clause ::= name ( ';' name ) (';' key '='
- * value )
- *
- * This is mapped to a Map { name => Map { attr|directive => value } }
- *
- * @param value
- * @return
- * @throws MojoExecutionException
- */
- static Map parseHeader(String value) throws MojoExecutionException {
- if (value == null || value.trim().length() == 0)
- return null;
-
- Map result = new HashMap();
- QuotedTokenizer qt = new QuotedTokenizer(value, ";=,");
- char del;
- do {
- boolean hadAttribute = false;
- Map clause = new HashMap();
- List aliases = new ArrayList();
- aliases.add(qt.nextToken());
- del = qt.getSeparator();
- while (del == ';') {
- String adname = qt.nextToken();
- if ((del = qt.getSeparator()) != '=') {
- if (hadAttribute)
- throw new MojoExecutionException(
- "Header contains name field after attribute or directive: "
- + adname + " from " + value);
- aliases.add(adname);
- }
- else {
- String advalue = qt.nextToken();
- clause.put(adname, advalue);
- del = qt.getSeparator();
- hadAttribute = true;
- }
- }
- for (Iterator i = aliases.iterator(); i.hasNext();) {
- result.put(i.next(), clause);
- }
- } while (del == ',');
- return result;
- }
-
- /**
- * Create the import header, taking into account R4 automatic import clauses
- * for the exports.
- *
- * @param referred
- * @param contained
- */
- void createImportHeader(Set referred, Set contained) {
- // Add handler import
- for(int j = 0; j < namespaces.length; j++) {
- for(int k = 0; k < namespaces[j].length; k++) {
- if(!namespaces[j][k].equals("")) {
- int lastIndex = namespaces[j][k].lastIndexOf('.');
- String ns = namespaces[j][k].substring(0, lastIndex);
- referred.add(ns);
- }
- }
- }
-
- // Add refered imports form the metadata
- for(int i = 0; i < referredPackages.size(); i++) {
- String pack = (String) referredPackages.get(i);
- referred.add(pack);
- }
-
- // Add org.apache.felix.ipojo, org.apache.felix.ipojo.architecture is not already in the set
- referred.add(IPojoPluginConfiguration.ipojo_package);
- referred.add(IPojoPluginConfiguration.ipojo_arch_package);
- referred.add(IPojoPluginConfiguration.config_admin_package);
-
- if (referred.isEmpty())
- return;
-
- referred = new TreeSet(referred);
-
- if (bundleManifestVersion > 1) {
- referred.addAll(contained);
- }
-
- StringBuffer sb = new StringBuffer();
- String del = "";
-
- for (Iterator i = referred.iterator(); i.hasNext();) {
- sb.append(del);
- sb.append(i.next());
- del = ", ";
- }
- archiveConfig.addManifestEntry("Import-Package", sb.toString());
- getLog().info("Set Imports to : " + sb.toString());
- }
-
- /**
- * Calculate the bundle class path based on the list of JARs in our bundle.
- * This list includes outselves. We also calculate the Bundle-Classpath
- * header (a bit clumsy) This is a bit cheap, so maybe this needs to be
- * changed
-
- *
- * @param mainJar
- * @return
- */
- List getBundleClassPath(Jar mainJar) {
- List result = new ArrayList();
- for (Iterator i = mainJar.resources.keySet().iterator(); i.hasNext();) {
- String path = (String) i.next();
- Object resource = mainJar.resources.get(path);
- if (resource instanceof Jar) {
- result.add(path);
- }
- }
- return result;
- }
-
- /**
- * We traverse through al the classes that we can find and calculate the
- * contained and referred set and uses.
- *
- * @param jar
- * @param contained
- * @param referred
- * @param uses
- */
- void analyzeJar(Jar jar, Set contained, Set referred, Map uses) {
- String prefix = "";
- Set set = jar.getEntryPaths(prefix);
- for (Iterator r = set.iterator(); r.hasNext();) {
- String path = (String) r.next();
- Object resource = jar.getEntry(path);
- if (resource instanceof Clazz) {
- Clazz clazz = (Clazz) resource;
- String pathOfClass = path.substring(prefix.length());
- String pack = Clazz.getPackage(pathOfClass);
- contained.add(pack);
- referred.addAll(clazz.getReferred());
-
- // Add all the used packages
- // to this package
- Set t = (Set) uses.get(pack);
- if (t == null)
- uses.put(pack, t = new HashSet());
- t.addAll(clazz.getReferred());
- t.remove(pack);
- }
- }
- }
-
- /**
- * Print a standard Map based OSGi header.
- *
- * @param exports map { name => Map { attribute|directive => value } }
- * @return the clauses
- */
- String printClauses(Map exports) {
- StringBuffer sb = new StringBuffer();
- String del = "";
- for (Iterator i = exports.keySet().iterator(); i.hasNext();) {
- String name = (String) i.next();
- Map map = (Map) exports.get(name);
- sb.append(del);
- sb.append(name);
-
- for (Iterator j = map.keySet().iterator(); j.hasNext();) {
- String key = (String) j.next();
- String value = (String) map.get(key);
- sb.append(";");
- sb.append(key);
- sb.append("=");
- sb.append(value);
- }
- del = ", ";
- }
- return sb.toString();
- }
-
- /**
- * Check if the BundleManifest version is set correctly, base the manifest
- * version on it.
- *
- * @throws MojoExecutionException
- */
- void verifyDeclaredBundleManifestVersion() throws MojoExecutionException {
- String mfv = osgiManifest.getBundleManifestVersion();
- if (mfv != null && mfv.trim().length() != 0) {
- try {
- bundleManifestVersion = Integer.parseInt(mfv);
- if (bundleManifestVersion != 2)
- throw new MojoExecutionException(
- "Bundle-ManifestVersion must be 2, it is " + mfv);
- }
- catch (Exception e) {
- throw new MojoExecutionException(
- "Bundle-ManifestVersion must be an integer: " + mfv);
- }
- }
- }
-
- /**
- * TODO: Decide if we accept merging of entire manifest.mf files Here's a
- * big question to make a final decision at some point: Do accept merging of
- * manifest entries located in some file somewhere in the project directory?
- * If so, do we allow both file and configuration based entries to be
- * specified simultaneously and how do we merge these?
- */
- private void addManifestFile() {
- if (manifestFile != null) {
- File file = new File(project.getBasedir().getAbsolutePath(),
- manifestFile);
- getLog().info(
- "Manifest file: " + file.getAbsolutePath()
- + " will be used");
- archiveConfig.setManifestFile(file);
- }
- else {
- getLog().info("No manifest file specified. Default will be used.");
- }
- }
-
- /**
- * Look for any OSGi specified manifest entries in the maven-osgi-plugin
- * configuration section of the POM. If we find some, then add them to the
- * target artifact's manifest.
- */
- private void addManifestEntries() {
- if (osgiManifest.getBundleVersion() == null) {
- addBundleVersion();
- }
- if (osgiManifest != null && osgiManifest.getEntries().size() > 0) {
- Map entries = osgiManifest.getEntries();
-
- getLog().debug(
- "Bundle manifest will be modified with the following entries: "
- + entries.toString());
- archiveConfig.addManifestEntries(entries);
- }
- else {
- getLog()
- .info(
- "No OSGi bundle manifest entries have been specified in the POM.");
- }
- }
-
- /**
- * We are going to iterate through the POM's specified JAR dependencies. If
- * a dependency has a scope of either RUNTIME or COMPILE, then we'll JAR
- * them up inside the OSGi bundle artifact. We will then add the
- * Bundle-Classpath manifest entry.
- *
- * Artifacts which are inlined will not be included.
- */
- private void addEmbeddedJars() throws MojoExecutionException {
- Set artifacts = project.getArtifacts();
-
- for (Iterator it = artifacts.iterator(); it.hasNext();) {
- Artifact artifact = (Artifact) it.next();
- if (!Artifact.SCOPE_PROVIDED.equals(artifact.getScope())
- && !Artifact.SCOPE_TEST.equals(artifact.getScope())) {
- String type = artifact.getType();
-
- if ("jar".equals(type)) {
- // Do not include artifacts which are inlined
- if (!(inlinedArtifacts.contains(artifact.getArtifactId()))) {
- File depFile = artifact.getFile();
-
- try {
- FileUtils.copyFileToDirectory(depFile, outputDirectory);
-
- }
- catch (Exception e) {
- String errmsg = "Error copying "
- + depFile.getAbsolutePath() + " to "
- + outputDirectory.getAbsolutePath();
- throw new MojoExecutionException(errmsg, e);
- }
- }
- }
- }
- }
- }
-
- /**
- * Auto-set the bundle version.
- */
- private void addBundleVersion() {
- // Maven uses a '-' to separate the version qualifier,
- // while OSGi uses a '.', so we need to convert to a '.'
- String version = project.getVersion().replace('-', '.');
- osgiManifest.setBundleVersion(version);
- }
-
- /**
- * Returns a string array of the includes to be used when assembling/copying
- * the war.
- *
- * @return an array of tokens to include
- */
- private String[] getIncludes() {
- return new String[] {jarSourceIncludes};
- }
-
- /**
- * Returns a string array of the excludes to be used when assembling/copying
- * the jar.
- *
- * @return an array of tokens to exclude
- */
- private String[] getExcludes() {
- List excludeList = new ArrayList(FileUtils.getDefaultExcludesAsList());
-
- if (jarSourceExcludes != null && !"".equals(jarSourceExcludes)) {
- excludeList.add(jarSourceExcludes);
- }
-
- return (String[]) excludeList.toArray(EMPTY_STRING_ARRAY);
- }
-
- private Set parseIgnorePackage() {
- HashSet result = new HashSet();
- if ((ignorePackage == null) && (osgiManifest.getIgnorePackage() != null)) {
- ignorePackage = osgiManifest.getIgnorePackage();
- getLog().warn("DEPRECATED METADATA! "
- + "The <ignorePackage> tag should be set inside the <configuration> "
- + "tag, not in the <osgiManifest> tag.");
- }
- if (ignorePackage != null) {
- StringTokenizer st = new StringTokenizer(ignorePackage, ",", false);
- while (st.hasMoreTokens()) {
- result.add(st.nextToken().trim());
- }
- }
- return result;
- }
-
- private void checkReferencesProperty(Map uses) {
- String interestedIn = System.getProperty(OSGI_REFERENCES);
- if (interestedIn == null) {
- return;
- }
- StringBuffer buf = new StringBuffer();
- Iterator it1 = uses.entrySet().iterator();
- while (it1.hasNext()) {
- Map.Entry entry = (Map.Entry) it1.next();
- String pack = (String) entry.getKey();
- Set references = (Set) entry.getValue();
- Iterator it2 = references.iterator();
- while (it2.hasNext()) {
- String packReferred = (String) it2.next();
- if (interestedIn.equals(packReferred)) {
- buf.append(" |-- ");
- buf.append(pack);
- buf.append('\n');
- break;
- }
- }
- }
- if (buf.length() == 0) {
- getLog().info("Noone uses " + interestedIn);
- }
- else {
- int changePos = buf.lastIndexOf("|");
- buf.setCharAt(changePos, '+');
- getLog().info(interestedIn + " used by;\n" + buf);
- }
- }
-
- private void printReferencedPackages(Map uses) {
- StringBuffer buf = new StringBuffer();
- Iterator it1 = uses.entrySet().iterator();
- while (it1.hasNext()) {
- Map.Entry entry = (Map.Entry) it1.next();
- String pack = (String) entry.getKey();
- buf.append(pack);
- buf.append('\n');
- Set references = (Set) entry.getValue();
- Iterator it2 = references.iterator();
- while (it2.hasNext()) {
- String packReferred = (String) it2.next();
- buf.append(" |-- ");
- buf.append(packReferred);
- buf.append('\n');
- }
- int changePos = buf.lastIndexOf("|");
- if (changePos >= 0) {
- buf.setCharAt(changePos, '+');
- }
- buf.append('\n');
- }
- getLog().debug("Referenced package list: \n" + buf.toString());
- }
-
- private void inlineArtifacts() throws MojoExecutionException {
- Set artifacts = project.getArtifacts();
-
- for (Iterator it = artifacts.iterator(); it.hasNext();) {
- Artifact artifact = (Artifact) it.next();
- if (!Artifact.SCOPE_PROVIDED.equals(artifact.getScope())
- && !Artifact.SCOPE_TEST.equals(artifact.getScope())) {
- String type = artifact.getType();
-
- if ("jar".equals(type)) {
- if ((inlinedArtifacts.contains(artifact.getArtifactId()))) {
- File depFile = artifact.getFile();
-
- try {
- ZipFile inlinedJar = new ZipFile(depFile);
- Enumeration entries = inlinedJar.entries();
- byte[] buffer = new byte[4096];
- while (entries.hasMoreElements()) {
- ZipEntry entry = (ZipEntry) entries.nextElement();
- if (entry.isDirectory()) {
- new File(outputDirectory, entry.getName()).mkdirs();
- } else {
- // Have to do this because some JARs ship without directories, i.e., just files.
- new File(outputDirectory, entry.getName()).getParentFile().mkdirs();
- FileOutputStream out = new FileOutputStream(new File(outputDirectory, entry.getName()));
- InputStream in = inlinedJar.getInputStream(entry);
- for (int read = in.read(buffer); read != -1; read = in.read(buffer)) {
- out.write(buffer, 0, read);
- }
- in.close();
- out.close();
- }
- }
- } catch (Exception e) {
- String errmsg = "Error inlining "
- + depFile.getAbsolutePath() + " to "
- + outputDirectory.getAbsolutePath();
- throw new MojoExecutionException(errmsg, e);
- }
- }
- }
- }
- }
- }
-
- // ===== iPOJO's methods =====
-
- private Element[] parseXMLMetadata(String path) throws MojoExecutionException {
- File metadata = new File(outputDirectory+path);
- URL url;
- Element[] meta = null;
- try {
- url = metadata.toURI().toURL();
- if (url == null) {
- getLog().error("No metadata at : " + outputDirectory+path);
- throw new MojoExecutionException("[iPOJO] No metadata at : " + outputDirectory+path);
- }
-
- InputStream stream = url.openStream();
- XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
- XMLMetadataParser handler = new XMLMetadataParser();
- parser.setContentHandler(handler);
- InputSource is = new InputSource(stream);
- parser.parse(is);
-
- meta = handler.getMetadata();
- referredPackages = handler.getReferredPackages();
-
- } catch (MalformedURLException e) {
- getLog().error("Malformed URL for " + outputDirectory+path+ "("+e.getMessage()+")");
- throw new MojoExecutionException("[iPOJO] Malformed URL for " + outputDirectory+path);
- } catch (IOException e) {
- getLog().error("Cannot open the file : " + outputDirectory+path + "("+e.getMessage()+")");
- throw new MojoExecutionException("[iPOJO] Cannot open the file : " + outputDirectory+path);
- } catch (Exception e) {
- getLog().error("Parsing Error when parsing the XML file " + outputDirectory+path+ "("+e.getMessage()+")");
- throw new MojoExecutionException("[iPOJO] Parsing Error when parsing the XML file " + outputDirectory+path);
- }
-
- if(meta == null || meta.length == 0) {
- getLog().error("No component in " + outputDirectory+path); //TODO : change the message
- throw new MojoExecutionException("[iPOJO] No component in " + outputDirectory+path);
- }
-
- return meta;
- }
-
- private Element[] parseManifestMetadata(String metadata) throws MojoExecutionException {
- Element[] components = null;
- ManifestMetadataParser parser = new ManifestMetadataParser();
- try {
- parser.parse(metadata);
- components = parser.getComponentsMetadata();
- } catch (ParseException e) {
- getLog().error("Parsing Error when parsing the Manifest metadata " + metadata + "("+e.getMessage()+")");
- throw new MojoExecutionException("[iPOJO] Parsing Error when parsing the Manifest metadata " + metadata);
-
- }
-
- if(components == null || components.length == 0) {
- getLog().error("No component in " + metadata);
- throw new MojoExecutionException("[iPOJO] No component in " + metadata);
- }
-
- return components;
- }
-
- private void iPojoManipulation() throws MojoExecutionException {
- //Try to read the content of a file of the ouptut directory
- getLog().info("iPOJO Manipulation ...");
-
- Element[] original_meta = null;
-
- // Get the metadata.xml location
- String path = (String) osgiManifest.getEntries().get("iPOJO-Metadata");
-
- if(path != null) {
- if(!path.startsWith("/")) { path = "/" + path; }
- original_meta = parseXMLMetadata(path);
- } else {
- String meta_ = (String) osgiManifest.getEntries().get("iPOJO-Components");
- if(meta_ != null) {
- original_meta = parseManifestMetadata(meta_);
- } else {
- getLog().error("Neither iPOJO-Metadata nor iPOJO-Components are in the manifest, please in the osgi-bundle packaging instead og ipojo-bundle");
- throw new MojoExecutionException("[iPOJO] Neither iPOJO-Metadata nor iPOJO-Components are in the manifest");
- }
- }
-
- Manipulator manipulator = new Manipulator();
- String[] metadata = new String[original_meta.length];
- String meta = "";
-
- if(namespaces == null) { namespaces = new String[original_meta.length][]; } //NO
- for(int i = 0; i < original_meta.length; i++) {
- if(original_meta[i].getName().equalsIgnoreCase("component")) {
- namespaces[i] = original_meta[i].getNamespaces();
- try {
- manipulator.preProcess(original_meta[i].getAttribute("className"), outputDirectory);
- } catch (Exception e) {
- getLog().error("Manipulation error in the class : " + original_meta[i].getAttribute("className") + "("+e.getMessage()+")");
- throw new MojoExecutionException("[iPOJO] Manipulation error in the class : " + original_meta[i].getAttribute("className"));
- }
-
- // Insert information to metadata
- Element elem = new Element("Manipulation", "");
- for(int j = 0; j < manipulator.getInterfaces().length; j++) {
- // Create an interface element for each implemented interface
- Element itf = new Element("Interface", "");
- Attribute att =new Attribute("name", manipulator.getInterfaces()[j]);
- itf.addAttribute(att);
- elem.addElement(itf);
- }
-
- for(Iterator it = manipulator.getFields().keySet().iterator(); it.hasNext(); ) {
- Element field = new Element("Field", "");
- String name = (String) it.next();
- String type = (String) manipulator.getFields().get(name);
- Attribute attName =new Attribute("name", name);
- Attribute attType =new Attribute("type", type);
- field.addAttribute(attName);
- field.addAttribute(attType);
- elem.addElement(field);
- }
-
- for(int j= 0; j < manipulator.getMethods().size(); j++) {
- MethodDescriptor method = (MethodDescriptor) manipulator.getMethods().get(j);
- elem.addElement(method.getElement());
- }
-
- original_meta[i].addElement(elem);
- } else { namespaces[i] = new String[0]; }
-
-
- // Transform the metadate to manifest metadata
- metadata[i] = buildManifestMetadata(original_meta[i], "");
- meta = meta + metadata[i];
- }
-
- archiveConfig.addManifestEntry("iPOJO-Components", meta);
-
- setBundleActivator();
-
- getLog().info("iPOJO Packaging ... SUCCESS");
- }
-
- private String buildManifestMetadata(Element element, String actual) {
- String result="";
- if(element.getNameSpace().equals("")) { result = actual + element.getName() + " { "; }
- else { result = actual + element.getNameSpace()+":"+element.getName() + " { "; }
-
- for(int i = 0; i < element.getAttributes().length; i++) {
- if(element.getAttributes()[i].getNameSpace().equals("")) {
- result = result + "$" + element.getAttributes()[i].getName() + "=\""+element.getAttributes()[i].getValue() + "\" ";
- }
- else {
- result = result + "$" + element.getAttributes()[i].getNameSpace()+ ":" + element.getAttributes()[i].getName() + "=\""+element.getAttributes()[i].getValue() + "\" ";
- }
- }
- for(int i = 0; i < element.getElements().length; i++) {
- result = buildManifestMetadata(element.getElements()[i], result);
- }
- return result +"}";
- }
-
- private void setBundleActivator() throws MojoExecutionException {
- archiveConfig.addManifestEntry("Bundle-Activator", "org.apache.felix.ipojo.Activator");
- }
-}
diff --git a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/plugin/OsgiManifest.java b/ipojo/plugin/src/main/java/org/apache/felix/ipojo/plugin/OsgiManifest.java
deleted file mode 100644
index e47aa19..0000000
--- a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/plugin/OsgiManifest.java
+++ /dev/null
@@ -1,490 +0,0 @@
-/*
- * 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.felix.ipojo.plugin;
-
-import java.util.Properties;
-
-/**
- * Hold values for an OSGi jar "bundle" manifest.
- *
- * @author <a href="mailto:dev@felix.apache.org">Apache Felix Project</a>
- * @version $Rev$, $Date$
- */
-public class OsgiManifest
-{
- /**
- * Bundle manifest header constants from the OSGi R4 framework constants.
- */
- private static final String BUNDLE_CATEGORY = "Bundle-Category";
- // private static final String BUNDLE_CLASSPATH = "Bundle-ClassPath";
- private static final String BUNDLE_COPYRIGHT = "Bundle-Copyright";
- private static final String BUNDLE_DESCRIPTION = "Bundle-Description";
- private static final String BUNDLE_NAME = "Bundle-Name";
- private static final String BUNDLE_NATIVECODE = "Bundle-NativeCode";
- private static final String EXPORT_PACKAGE = "Export-Package";
- private static final String EXPORT_SERVICE = "Export-Service";
- private static final String IMPORT_PACKAGE = "Import-Package";
- private static final String DYNAMICIMPORT_PACKAGE = "DynamicImport-Package";
- private static final String IMPORT_SERVICE = "Import-Service";
- private static final String BUNDLE_VENDOR = "Bundle-Vendor";
- private static final String BUNDLE_VERSION = "Bundle-Version";
- private static final String BUNDLE_DOCURL = "Bundle-DocURL";
- private static final String BUNDLE_CONTACTADDRESS = "Bundle-ContactAddress";
- private static final String BUNDLE_ACTIVATOR = "Bundle-Activator";
- private static final String BUNDLE_UPDATELOCATION = "Bundle-UpdateLocation";
- private static final String BUNDLE_REQUIREDEXECUTIONENVIRONMENT = "Bundle-RequiredExecutionEnvironment";
- private static final String BUNDLE_SYMBOLICNAME = "Bundle-SymbolicName";
- private static final String BUNDLE_LOCALIZATION = "Bundle-Localization";
- private static final String REQUIRE_BUNDLE = "Require-Bundle";
- private static final String FRAGMENT_HOST = "Fragment-Host";
- private static final String BUNDLE_MANIFESTVERSION = "Bundle-ManifestVersion";
- private static final String BUNDLE_URL = "Bundle-URL";
- private static final String BUNDLE_SOURCE = "Bundle-Source";
- private static final String BUNDLE_DATE = "Bundle-Date";
- private static final String METADATA_LOCATION = "Metadata-Location";
- private static final String SERVICE_COMPONENT = "Service-Component";
-
- // iPOJO Manifest Headers
- private static final String IPOJO_METADATA ="iPOJO-Metadata";
- private static final String IPOJO_COMPONENTS ="iPOJO-Components";
-
- /**
- * Instance variables corresponding to the R4 framework manifest headers
- */
- private String bundleCategory;
- // private String bundleClassPath;
- private String bundleCopyright;
- private String bundleDescription;
- private String bundleName;
- private String bundleNativeCode;
- private String exportPackage;
- private String exportService;
- private String importPackage;
- private String dynamicImportPackage;
- private String importService;
- private String bundleVendor;
- private String bundleVersion;
- private String bundleDocUrl;
- private String bundleContactAddress;
- private String bundleActivator;
- private String bundleUpdateLocation;
- private String bundleRequiredExecutionEnvironment;
- private String bundleSymbolicName;
- private String bundleLocalization;
- private String requireBundle;
- private String fragmentHost;
- private String bundleManifestVersion;
-
- /**
- * Instance variables supporting non-framework manifest headers
- */
- private String bundleUrl;
- private String bundleSource;
- private String bundleDate;
- private String metadataLocation;
- private String serviceComponent;
- private String ignorePackage;
-
- /**
- * iPOJO Headers
- */
- private String iPOJOMetadata;
- private String iPOJOComponents;
-
- private Properties entries = new Properties();
-
- public Properties getEntries()
- {
- /*
- * setEntryValue( BUNDLE_CLASSPATH, getBundleClassPath(), null);
- */
- setEntryValue(BUNDLE_CATEGORY, getBundleCategory(), null);
- setEntryValue(BUNDLE_COPYRIGHT, getBundleCopyright(), null);
- setEntryValue(BUNDLE_DESCRIPTION, getBundleDescription(), null);
- setEntryValue(BUNDLE_NAME, getBundleName(), null);
- setEntryValue(BUNDLE_NATIVECODE, getBundleNativeCode(), null);
- setEntryValue(EXPORT_PACKAGE, getExportPackage(), null);
- setEntryValue(EXPORT_SERVICE, getExportService(), null);
- setEntryValue(IMPORT_PACKAGE, getImportPackage(), null);
- setEntryValue(DYNAMICIMPORT_PACKAGE, getDynamicImportPackage(), null);
- setEntryValue(IMPORT_SERVICE, getImportService(), null);
- setEntryValue(BUNDLE_VENDOR, getBundleVendor(), null);
- setEntryValue(BUNDLE_VERSION, getBundleVersion(), null);
- setEntryValue(BUNDLE_DOCURL, getBundleDocUrl(), null);
- setEntryValue(BUNDLE_CONTACTADDRESS, getBundleContactAddress(), null);
- setEntryValue(BUNDLE_ACTIVATOR, getBundleActivator(), null);
- setEntryValue(BUNDLE_UPDATELOCATION, getBundleUpdateLocation(), null);
- setEntryValue(BUNDLE_REQUIREDEXECUTIONENVIRONMENT,
- getBundleRequiredExecutionEnvironment(), null);
- setEntryValue(BUNDLE_SYMBOLICNAME, getBundleSymbolicName(), null);
- setEntryValue(BUNDLE_LOCALIZATION, getBundleLocalization(), null);
- setEntryValue(REQUIRE_BUNDLE, getRequireBundle(), null);
- setEntryValue(FRAGMENT_HOST, getFragmentHost(), null);
- setEntryValue(BUNDLE_MANIFESTVERSION, getBundleManifestVersion(), null);
- setEntryValue(BUNDLE_URL, getBundleUrl(), null);
- setEntryValue(BUNDLE_SOURCE, getBundleSource(), null);
- setEntryValue(BUNDLE_DATE, getBundleDate(), null);
- setEntryValue(METADATA_LOCATION, getMetadataLocation(), null);
- setEntryValue(SERVICE_COMPONENT, getServiceComponent(), null);
-
- // iPOJO's metadata
- setEntryValue(IPOJO_METADATA, getiPOJOMetadata(), null);
- setEntryValue(IPOJO_COMPONENTS, getiPOJOComponents(), null);
- return entries;
- }
-
- public String getBundleCategory()
- {
- return bundleCategory;
- }
-
- public void setBundleCategory(String bundleCategory)
- {
- this.bundleCategory = bundleCategory;
- }
-
- /*
- * public String getBundleClasspath() { return bundleClasspath; }
- *
- * public void setBundleClasspath(String bundleClasspath) {
- * this.bundleClasspath = bundleClasspath; }
- */
-
- public String getBundleCopyright()
- {
- return bundleCopyright;
- }
-
- public void setBundleCopyright(String bundleCopyright)
- {
- this.bundleCopyright = bundleCopyright;
- }
-
- public String getBundleDescription()
- {
- return bundleDescription;
- }
-
- public void setBundleDescription(String bundleDescription)
- {
- this.bundleDescription = bundleDescription;
- }
-
- public String getBundleName()
- {
- return bundleName;
- }
-
- public void setBundleName(String bundleName)
- {
- this.bundleName = bundleName;
- }
-
- public String getBundleNativeCode()
- {
- return bundleNativeCode;
- }
-
- public void setBundleNativeCode(String bundleNativeCode)
- {
- this.bundleNativeCode = bundleNativeCode;
- }
-
- public String getExportPackage()
- {
- return exportPackage;
- }
-
- public void setExportPackage(String exportPackage)
- {
- this.exportPackage = trim(exportPackage);
- }
-
- public String getExportService()
- {
- return exportService;
- }
-
- public void setExportService(String exportService)
- {
- this.exportService = trim(exportService);
- }
-
- public String getImportPackage()
- {
- return importPackage;
- }
-
- public void setImportPackage(String importPackage)
- {
- this.importPackage = trim(importPackage);
- }
-
- public String getDynamicImportPackage()
- {
- return dynamicImportPackage;
- }
-
- public void setDynamicImportPackage(String dynamicImportPackage)
- {
- this.dynamicImportPackage = trim(dynamicImportPackage);
- }
-
- public String getImportService()
- {
- return importService;
- }
-
- public void setImportService(String importService)
- {
- this.importService = importService;
- }
-
- public String getBundleVendor()
- {
- return bundleVendor;
- }
-
- public void setBundleVendor(String bundleVendor)
- {
- this.bundleVendor = bundleVendor;
- }
-
- public String getBundleVersion()
- {
- return bundleVersion;
- }
-
- public void setBundleVersion(String bundleVersion)
- {
- this.bundleVersion = bundleVersion;
- }
-
- public String getBundleDocUrl()
- {
- return bundleDocUrl;
- }
-
- public void setBundleDocUrl(String bundleDocUrl)
- {
- this.bundleDocUrl = bundleDocUrl;
- }
-
- public String getBundleContactAddress()
- {
- return bundleContactAddress;
- }
-
- public void setBundleContactAddress(String bundleContactAddress)
- {
- this.bundleContactAddress = bundleContactAddress;
- }
-
- public String getBundleActivator()
- {
- return bundleActivator;
- }
-
- public void setBundleActivator(String bundleActivator)
- {
- this.bundleActivator = trim(bundleActivator);
- }
-
- public String getBundleUpdateLocation()
- {
- return bundleUpdateLocation;
- }
-
- public void setBundleUpdateLocation(String bundleUpdateLocation)
- {
- this.bundleUpdateLocation = bundleUpdateLocation;
- }
-
- public String getBundleRequiredExecutionEnvironment()
- {
- return bundleRequiredExecutionEnvironment;
- }
-
- public void setBundleRequiredExecutionEnvironment(
- String bundleRequiredExecutionEnvironment)
- {
- this.bundleRequiredExecutionEnvironment = bundleRequiredExecutionEnvironment;
- }
-
- public String getBundleSymbolicName()
- {
- return bundleSymbolicName;
- }
-
- public void setBundleSymbolicName(String bundleSymbolicName)
- {
- this.bundleSymbolicName = trim(bundleSymbolicName);
- }
-
- public String getBundleLocalization()
- {
- return bundleLocalization;
- }
-
- public void setBundleLocalization(String bundleLocalization)
- {
- this.bundleLocalization = bundleLocalization;
- }
-
- public String getRequireBundle()
- {
- return requireBundle;
- }
-
- public void setRequireBundle(String requireBundle)
- {
- this.requireBundle = trim(requireBundle);
- }
-
- public String getFragmentHost()
- {
- return fragmentHost;
- }
-
- public void setFragmentHost(String fragmentHost)
- {
- this.fragmentHost = trim(fragmentHost);
- }
-
- public String getBundleManifestVersion()
- {
- return bundleManifestVersion;
- }
-
- public void setBundleManifestVersion(String bundleManifestVersion)
- {
- this.bundleManifestVersion = bundleManifestVersion;
- }
-
- public String getBundleUrl()
- {
- return bundleUrl;
- }
-
- public void setBundleUrl(String bundleUrl)
- {
- this.bundleUrl = bundleUrl;
- }
-
- public String getBundleSource()
- {
- return bundleSource;
- }
-
- public void setBundleSource(String bundleSource)
- {
- this.bundleSource = bundleSource;
- }
-
- public String getBundleDate()
- {
- return bundleDate;
- }
-
- public void setBundleDate(String bundleDate)
- {
- this.bundleDate = bundleDate;
- }
-
- public String getMetadataLocation()
- {
- return metadataLocation;
- }
-
- public void setMetadataLocation(String metadataLocation)
- {
- this.metadataLocation = metadataLocation;
- }
-
- public String getServiceComponent()
- {
- return serviceComponent;
- }
-
- public void setServiceComponent(String serviceComponent)
- {
- this.serviceComponent = serviceComponent;
- }
-
- public String getIgnorePackage()
- {
- return ignorePackage;
- }
-
- public void setIgnorePackage(String ignorePackage)
- {
- this.ignorePackage = ignorePackage;
- }
-
- /**
- * Removes all whitespace in the entry.
- *
- * @param entry
- * The entry to be cleaned up.
- * @return A copy of the entry string without any whitespace.
- */
- private String trim(String entry)
- {
- StringBuffer buf = new StringBuffer(entry.length());
- for (int i = 0; i < entry.length(); i++)
- {
- char ch = entry.charAt(i);
- if (ch > 32)
- {
- buf.append(ch);
- }
- }
- return buf.toString();
- }
-
- private void setEntryValue(String key, String value, String defaultValue)
- {
- if (value != null)
- {
- entries.put(key, value);
- }
- else if (defaultValue != null)
- {
- entries.put(key, defaultValue);
- }
- }
-
-
- // iPOJO Headers
- public String getiPOJOMetadata() {
- return iPOJOMetadata;
- }
-
- public void setiPOJOMetadata( String metadata) {
- this.iPOJOMetadata = metadata;
- }
-
- public String getiPOJOComponents() {
- return iPOJOComponents;
- }
-
- public void setiPOJOComponents( String metadata) {
- this.iPOJOComponents = metadata;
- }
-}
diff --git a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/plugin/QuotedTokenizer.java b/ipojo/plugin/src/main/java/org/apache/felix/ipojo/plugin/QuotedTokenizer.java
deleted file mode 100644
index 5f2b12c..0000000
--- a/ipojo/plugin/src/main/java/org/apache/felix/ipojo/plugin/QuotedTokenizer.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * 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.felix.ipojo.plugin;
-
-import java.util.*;
-
-public class QuotedTokenizer {
- String string;
- int index = 0;
- String separators;
- boolean returnTokens;
- boolean ignoreWhiteSpace = true;
- String peek;
- char separator;
-
- public QuotedTokenizer(String string, String separators, boolean returnTokens ) {
- if ( string == null )
- throw new IllegalArgumentException("string argument must be not null");
- this.string = string;
- this.separators = separators;
- this.returnTokens = returnTokens;
- }
- public QuotedTokenizer(String string, String separators) {
- this(string,separators,false);
- }
-
- public String nextToken(String separators) {
- separator = 0;
- if ( peek != null ) {
- String tmp = peek;
- peek = null;
- return tmp;
- }
-
- if ( index == string.length())
- return null;
-
- StringBuffer sb = new StringBuffer();
-
- while (index < string.length()) {
- char c = string.charAt(index++);
-
- if ( Character.isWhitespace(c)) {
- if ( index == string.length())
- break;
- else
- continue;
- }
-
- if (separators.indexOf(c) >= 0) {
- if (returnTokens)
- peek = Character.toString(c);
- else
- separator = c;
- break;
- }
-
- switch (c) {
- case '"' :
- case '\'' :
- quotedString(sb, c);
- break;
-
- default :
- sb.append(c);
- }
- }
- String result = sb.toString().trim();
- if ( result.length()==0 && index==string.length())
- return null;
- return result;
- }
-
- public String nextToken() {
- return nextToken(separators);
- }
-
- private void quotedString(StringBuffer sb, char c) {
- char quote = c;
- while (index < string.length()) {
- c = string.charAt(index++);
- if (c == quote)
- break;
- if (c == '\\' && index < string.length()
- && string.charAt(index + 1) == quote)
- c = string.charAt(index++);
- sb.append(c);
- }
- }
-
- public String[] getTokens() {
- return getTokens(0);
- }
-
- private String [] getTokens(int cnt){
- String token = nextToken();
- if ( token == null )
- return new String[cnt];
-
- String result[] = getTokens(cnt+1);
- result[cnt]=token;
- return result;
- }
-
- public char getSeparator() { return separator; }
-
- public List getTokenSet() {
- List list = new ArrayList();
- String token = nextToken();
- while ( token != null ) {
- list.add(token);
- token = nextToken();
- }
- return list;
- }
-}
diff --git a/ipojo/plugin/src/main/resources/META-INF/plexus/components.xml b/ipojo/plugin/src/main/resources/META-INF/plexus/components.xml
deleted file mode 100644
index d6710f2..0000000
--- a/ipojo/plugin/src/main/resources/META-INF/plexus/components.xml
+++ /dev/null
@@ -1,40 +0,0 @@
-<component-set>
- <components>
- <component>
- <role>org.apache.maven.lifecycle.mapping.LifecycleMapping</role>
- <role-hint>ipojo-bundle</role-hint>
- <implementation>org.apache.maven.lifecycle.mapping.DefaultLifecycleMapping</implementation>
- <configuration>
- <lifecycles>
- <lifecycle>
- <id>default</id>
- <!-- START SNIPPET: ipojo-bundle-lifecycle -->
- <phases>
- <process-resources>org.apache.maven.plugins:maven-resources-plugin:resources</process-resources>
- <compile>org.apache.maven.plugins:maven-compiler-plugin:compile</compile>
- <process-test-resources>org.apache.maven.plugins:maven-resources-plugin:testResources</process-test-resources>
- <test-compile>org.apache.maven.plugins:maven-compiler-plugin:testCompile</test-compile>
- <test>org.apache.maven.plugins:maven-surefire-plugin:test</test>
- <package>org.apache.felix:org.apache.felix.ipojo.plugin:ipojo-bundle</package>
- <install>org.apache.maven.plugins:maven-install-plugin:install</install>
- <deploy>org.apache.maven.plugins:maven-deploy-plugin:deploy</deploy>
- </phases>
- <!-- END SNIPPET: ipojo-bundle-lifecycle -->
- </lifecycle>
- </lifecycles>
- </configuration>
- </component>
- <component>
- <role>org.apache.maven.artifact.handler.ArtifactHandler</role>
- <role-hint>ipojo-bundle</role-hint>;
- <implementation>org.apache.maven.artifact.handler.DefaultArtifactHandler</implementation>
- <configuration>
- <extension>jar</extension>
- <type>ipojo-bundle</type>
- <includesDependencies>true</includesDependencies>
- <language>java</language>
- <addedToClasspath>true</addedToClasspath>
- </configuration>
- </component>
- </components>
-</component-set>
diff --git a/ipojo/plugin/src/main/resources/archetype-resources/pom.xml b/ipojo/plugin/src/main/resources/archetype-resources/pom.xml
index 8da7b7b..faa7477 100644
--- a/ipojo/plugin/src/main/resources/archetype-resources/pom.xml
+++ b/ipojo/plugin/src/main/resources/archetype-resources/pom.xml
@@ -10,16 +10,28 @@
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
- <artifactId>org.apache.felix.ipojo.plugin</artifactId>
+ <artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
- <osgiManifest>
- <bundleName>${pom.name}</bundleName>
- <bundleDescription>$YOUR_BUNDLE_DESCRIPTION</bundleDescription>
- <iPOJOMetadata>metadata.xml</iPOJOMetadata>
- </osgiManifest>
+ <instructions>
+ <Bundle-SymbolicName>${pom.artifactId}</Bundle-SymbolicName>
+ <Private-Package>YOUR_PRIVATE_PACKAGES</Private-Package>
+ <Import-Package>*</Import-Package> <!-- YOUR_IMPORTED_PACKAGES -->
+ <Export-Package>*</Export-Package> <!-- YOUR_EXPORTED_PACKAGES -->
+ </instructions>
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>org.apache.felix.ipojo.plugin</artifactId>
+ <executions>
+ <execution>
+ <goals>
+ <goal>ipojo-bundle</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
</plugins>
</build>
</project>
diff --git a/ipojo/plugin/src/main/resources/archetype-resources/src/main/resources/metadata.xml b/ipojo/plugin/src/main/resources/archetype-resources/src/main/resources/metadata.xml
index 9b9615d..a3d0839 100644
--- a/ipojo/plugin/src/main/resources/archetype-resources/src/main/resources/metadata.xml
+++ b/ipojo/plugin/src/main/resources/archetype-resources/src/main/resources/metadata.xml
@@ -3,4 +3,5 @@
<component className="$YOUR_COMPONENT_CLASS">
</component>
+ <instance component="$YOUR_COMPONENT_CLASS"/>
</iPOJO>
\ No newline at end of file
diff --git a/pom.xml b/pom.xml
index 3b21267..02a33a5 100644
--- a/pom.xml
+++ b/pom.xml
@@ -97,6 +97,8 @@
<modules>
<module>bundleplugin</module>
<module>tools/maven2/maven-osgi-plugin</module>
+ <module>ipojo/metadata</module>
+ <module>ipojo/manipulator</module>
<module>ipojo/plugin</module>
</modules>
</profile>
@@ -110,7 +112,7 @@
</property>
</activation>
<modules>
- <module>ipojo/arch</module>
+ <!--<module>ipojo/arch</module>-->
</modules>
</profile>
@@ -145,7 +147,7 @@
<module>wireadmin</module>
<module>ipojo/core</module>
- <module>ipojo/metadata</module>
+ <module>ipojo/arch</module>
</modules>
</profile>