You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tuscany.apache.org by an...@apache.org on 2007/07/02 13:26:41 UTC

svn commit: r552470 [1/3] - in /incubator/tuscany/java/sca/modules/implementation-osgi/src: main/java/org/apache/tuscany/implementation/osgi/context/ main/java/org/apache/tuscany/implementation/osgi/invocation/ main/java/org/apache/tuscany/implementati...

Author: antelder
Date: Mon Jul  2 04:26:39 2007
New Revision: 552470

URL: http://svn.apache.org/viewvc?view=rev&rev=552470
Log:
TUSCANY-1382, patch from Rajini Sivaram updating implementation-osgi

Added:
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/OSGiImplementationInterface.java   (with props)
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/context/
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/context/OSGiPropertyValueObjectFactory.java   (with props)
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiImplementationProvider.java   (with props)
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiImplementationProviderFactory.java   (with props)
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiInstanceWrapper.java   (with props)
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiRemotableInvoker.java   (with props)
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiTargetInvoker.java   (with props)
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/module/
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/module/OSGiModuleActivator.java   (with props)
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/EquinoxRuntime.java   (with props)
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/FelixRuntime.java   (with props)
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/KnopflerfishRuntime.java   (with props)
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiRuntime.java   (with props)
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/xml/
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/xml/OSGiImplementation.java   (with props)
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/xml/OSGiImplementationProcessor.java   (with props)
    incubator/tuscany/java/sca/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/invocation/
    incubator/tuscany/java/sca/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiPropertyTestCase.java   (with props)
    incubator/tuscany/java/sca/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiTestCase.java   (with props)
    incubator/tuscany/java/sca/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/runtime/
    incubator/tuscany/java/sca/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiRuntimeTestCase.java   (with props)
    incubator/tuscany/java/sca/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/test/
    incubator/tuscany/java/sca/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/test/OSGiTestBundles.java   (with props)
    incubator/tuscany/java/sca/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/test/OSGiTestImpl.java   (with props)
    incubator/tuscany/java/sca/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/test/OSGiTestInterface.java   (with props)
    incubator/tuscany/java/sca/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/test/OSGiTestWithPropertyImpl.java   (with props)
    incubator/tuscany/java/sca/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/xml/
    incubator/tuscany/java/sca/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/xml/OSGiReadImplTestCase.java   (with props)
    incubator/tuscany/java/sca/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/xml/TestModelResolver.java   (with props)
Removed:
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/implementation/osgi/context/OSGiPropertyValueObjectFactory.java
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/implementation/osgi/invocation/OSGiImplementationProvider.java
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/implementation/osgi/invocation/OSGiImplementationProviderFactory.java
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/implementation/osgi/invocation/OSGiInstanceWrapper.java
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/implementation/osgi/invocation/OSGiPassByValueInvoker.java
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/implementation/osgi/invocation/OSGiTargetInvoker.java
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/implementation/osgi/module/OSGiModuleActivator.java
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/implementation/osgi/runtime/EquinoxRuntime.java
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/implementation/osgi/runtime/FelixRuntime.java
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/implementation/osgi/runtime/KnopflerfishRuntime.java
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/implementation/osgi/runtime/OSGiRuntime.java
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/implementation/osgi/xml/OSGiImplementation.java
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/implementation/osgi/xml/OSGiImplementationProcessor.java
    incubator/tuscany/java/sca/modules/implementation-osgi/src/test/java/org/apache/tuscany/implementation/osgi/invocation/OSGiTestCase.java
    incubator/tuscany/java/sca/modules/implementation-osgi/src/test/java/org/apache/tuscany/implementation/osgi/runtime/OSGiRuntimeTestCase.java
    incubator/tuscany/java/sca/modules/implementation-osgi/src/test/java/org/apache/tuscany/implementation/osgi/test/OSGiTestBundles.java
    incubator/tuscany/java/sca/modules/implementation-osgi/src/test/java/org/apache/tuscany/implementation/osgi/test/OSGiTestImpl.java
    incubator/tuscany/java/sca/modules/implementation-osgi/src/test/java/org/apache/tuscany/implementation/osgi/test/OSGiTestInterface.java
    incubator/tuscany/java/sca/modules/implementation-osgi/src/test/java/org/apache/tuscany/implementation/osgi/xml/OSGiReadImplTestCase.java
    incubator/tuscany/java/sca/modules/implementation-osgi/src/test/java/org/apache/tuscany/implementation/osgi/xml/TestModelResolver.java
Modified:
    incubator/tuscany/java/sca/modules/implementation-osgi/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator
    incubator/tuscany/java/sca/modules/implementation-osgi/src/test/resources/OSGiTestService.componentType
    incubator/tuscany/java/sca/modules/implementation-osgi/src/test/resources/osgitest.composite

Added: incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/OSGiImplementationInterface.java
URL: http://svn.apache.org/viewvc/incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/OSGiImplementationInterface.java?view=auto&rev=552470
==============================================================================
--- incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/OSGiImplementationInterface.java (added)
+++ incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/OSGiImplementationInterface.java Mon Jul  2 04:26:39 2007
@@ -0,0 +1,48 @@
+/*
+ * 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.tuscany.sca.implementation.osgi;
+
+import java.util.List;
+
+import org.apache.tuscany.sca.assembly.ComponentProperty;
+import org.apache.tuscany.sca.assembly.Implementation;
+import org.apache.tuscany.sca.scope.Scope;
+
+/**
+ * 
+ * The model representing an OSGi implementation in an SCA assembly model.
+ *
+ */
+public interface OSGiImplementationInterface extends Implementation {
+    
+    public String getBundleName();
+    
+    public String getBundleLocation();
+
+    
+    public String[] getImports();
+    
+    
+    public Scope getScope();
+    
+    public List<ComponentProperty> getReferenceProperties(String referenceName);
+    
+    public List<ComponentProperty> getServiceProperties(String serviceName);
+
+}

Propchange: incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/OSGiImplementationInterface.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/OSGiImplementationInterface.java
------------------------------------------------------------------------------
    svn:keywords = Rev Date

Added: incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/context/OSGiPropertyValueObjectFactory.java
URL: http://svn.apache.org/viewvc/incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/context/OSGiPropertyValueObjectFactory.java?view=auto&rev=552470
==============================================================================
--- incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/context/OSGiPropertyValueObjectFactory.java (added)
+++ incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/context/OSGiPropertyValueObjectFactory.java Mon Jul  2 04:26:39 2007
@@ -0,0 +1,225 @@
+/*
+ * 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.tuscany.sca.implementation.osgi.context;
+
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.StringTokenizer;
+
+import org.apache.tuscany.sca.assembly.Property;
+import org.apache.tuscany.sca.databinding.Mediator;
+import org.apache.tuscany.sca.databinding.SimpleTypeMapper;
+import org.apache.tuscany.sca.databinding.impl.SimpleTypeMapperImpl;
+import org.apache.tuscany.sca.databinding.xml.DOMDataBinding;
+import org.apache.tuscany.sca.interfacedef.DataType;
+import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl;
+import org.apache.tuscany.sca.interfacedef.util.TypeInfo;
+import org.apache.tuscany.sca.interfacedef.util.XMLType;
+import org.apache.tuscany.sca.factory.ObjectCreationException;
+import org.apache.tuscany.sca.factory.ObjectFactory;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+/**
+ * 
+ * Process properties and create property values.
+ * 
+ * This code has been copied from the Java implementation to avoid dependencies on the Java implementation.
+ *
+ */
+public class OSGiPropertyValueObjectFactory {
+    protected SimpleTypeMapper simpleTypeMapper = new SimpleTypeMapperImpl();
+    boolean isSimpleType;
+    
+    
+    public OSGiPropertyValueObjectFactory() {
+    }
+    
+    public OSGiPropertyValueObjectFactory(Mediator mediator) {
+    }
+    
+    public ObjectFactory createValueFactory(Property property, Object propertyValue) {
+        
+        Class javaType = SimpleTypeMapperImpl.getJavaType(property.getXSDType());
+        isSimpleType = isSimpleType(property);
+        Document doc = (Document)propertyValue;
+        Element rootElement = doc.getDocumentElement();
+        if (property.isMany()) {
+            if (isSimpleType) {
+                String value = "";
+                if (rootElement.getChildNodes().getLength() > 0) {
+                    value = rootElement.getChildNodes().item(0).getTextContent();
+                }
+                List<String> values = 
+                    getSimplePropertyValues(value, javaType);
+                return new ListObjectFactoryImpl(property, 
+                                                 values,
+                                                 isSimpleType,
+                                                 javaType);
+            } else {
+                return new ListObjectFactoryImpl(property,
+                                                 getComplexPropertyValues(doc),
+                                                 isSimpleType,
+                                                 javaType);
+            }
+        } else {
+            if (isSimpleType) {
+                String value = "";
+                if (rootElement.getChildNodes().getLength() > 0) {
+                    value = rootElement.getChildNodes().item(0).getTextContent();
+                }
+                return new ObjectFactoryImpl(property,
+                                             value,
+                                             isSimpleType,
+                                             javaType);
+            } else {
+                Object value = getComplexPropertyValues(doc).get(0);
+                return new ObjectFactoryImpl(property,
+                                             value,
+                                             isSimpleType,
+                                             javaType);
+            }
+            
+        }
+    }
+    
+    private boolean isSimpleType(Property property) {
+        if (property.getXSDType() != null) {
+            return SimpleTypeMapperImpl.isSimpleXSDType(property.getXSDType());
+        } else {
+            if (property instanceof Document) {
+                Document doc = (Document)property;
+                Element element = doc.getDocumentElement(); 
+                if (element.getChildNodes().getLength() == 1 && 
+                    element.getChildNodes().item(0).getNodeType() == Element.TEXT_NODE) {
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+    
+    private List<String> getSimplePropertyValues(String concatenatedValue, Class javaType) {
+        List<String> propValues = new ArrayList<String>();
+        StringTokenizer st = null;
+        if ( javaType.getName().equals("java.lang.String")) {
+            st = new StringTokenizer(concatenatedValue, "\"");
+        } else {
+            st = new StringTokenizer(concatenatedValue);
+        }
+        String aToken = null;
+        while (st.hasMoreTokens()) {
+            aToken = st.nextToken();
+            if (aToken.trim().length() > 0) {
+                propValues.add(aToken);
+            }
+        }
+        return propValues;
+    }
+    
+    private List<Node> getComplexPropertyValues(Document document) {
+        Element rootElement = document.getDocumentElement();
+        List<Node> propValues = new ArrayList<Node>();
+        for (int count = 0 ; count < rootElement.getChildNodes().getLength() ; ++count) {
+            if (rootElement.getChildNodes().item(count).getNodeType() == Document.ELEMENT_NODE) {
+                propValues.add(rootElement.getChildNodes().item(count));
+            }
+        }
+        return propValues;
+    }
+    
+    public abstract class ObjectFactoryImplBase  implements ObjectFactory {
+        protected SimpleTypeMapper simpleTypeMapper = new SimpleTypeMapperImpl();
+        protected Property property;
+        protected Object propertyValue;
+        protected Class javaType;
+        protected DataType<XMLType> sourceDataType;
+        protected DataType<?> targetDataType;
+        boolean isSimpleType;
+
+        public ObjectFactoryImplBase(Property property, Object propertyValue, boolean isSimpleType, Class javaType)  {
+            this.isSimpleType = isSimpleType;
+            this.property = property;
+            this.propertyValue = propertyValue;
+            this.javaType = javaType;
+            sourceDataType =
+                new DataTypeImpl<XMLType>(DOMDataBinding.NAME, Node.class, 
+                    new XMLType(null, this.property.getXSDType()));
+            TypeInfo typeInfo = null;
+            if (this.property.getXSDType() != null) {
+                if (SimpleTypeMapperImpl.isSimpleXSDType(this.property.getXSDType())) {
+                    typeInfo = new TypeInfo(property.getXSDType(), true, null);
+                } else {
+                    typeInfo = new TypeInfo(property.getXSDType(), false, null);
+                }
+            } else {
+                typeInfo = new TypeInfo(property.getXSDType(), false, null);
+            }
+
+            XMLType xmlType = new XMLType(typeInfo);
+            String dataBinding = null; //(String)property.getExtensions().get(DataBinding.class.getName());
+            if (dataBinding != null) {
+                targetDataType = new DataTypeImpl<XMLType>(dataBinding, javaType, xmlType);
+            } else {
+                targetDataType = new DataTypeImpl<XMLType>(dataBinding, javaType, xmlType);
+            }
+        }
+    }
+    
+    public class ObjectFactoryImpl extends ObjectFactoryImplBase {
+        public ObjectFactoryImpl(Property property, Object propertyValue, boolean isSimpleType, Class javaType) {
+            super(property, propertyValue, isSimpleType, javaType);
+        }
+
+        @SuppressWarnings("unchecked")
+        public Object getInstance() throws ObjectCreationException {
+            if (isSimpleType) {
+                return simpleTypeMapper.toJavaObject(property.getXSDType(), (String)propertyValue, null);
+            } else {
+                return null;
+            }
+        }
+    }
+
+    public class ListObjectFactoryImpl extends ObjectFactoryImplBase  {
+        public ListObjectFactoryImpl(Property property, List<?>propertyValues, boolean isSimpleType, Class javaType) {
+            super(property, propertyValues, isSimpleType, javaType);
+        }
+
+        @SuppressWarnings("unchecked")
+        public List<?> getInstance() throws ObjectCreationException {
+            if (isSimpleType) {
+                List<Object> values = new ArrayList<Object>();
+                for (String aValue : (List<String>)propertyValue) {
+                    values.add(simpleTypeMapper.toJavaObject(property.getXSDType(), aValue, null));
+                }
+                return values;
+            } else {
+                List instances = new ArrayList();
+                for (Node aValue : (List<Node>)propertyValue) {
+                    instances.add(aValue);
+                }
+                return instances;
+            }
+        }
+    }
+}
+      

Propchange: incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/context/OSGiPropertyValueObjectFactory.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/context/OSGiPropertyValueObjectFactory.java
------------------------------------------------------------------------------
    svn:keywords = Rev Date

Added: incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiImplementationProvider.java
URL: http://svn.apache.org/viewvc/incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiImplementationProvider.java?view=auto&rev=552470
==============================================================================
--- incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiImplementationProvider.java (added)
+++ incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiImplementationProvider.java Mon Jul  2 04:26:39 2007
@@ -0,0 +1,1145 @@
+/*
+ * 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.tuscany.sca.implementation.osgi.invocation;
+
+
+import java.beans.Introspector;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.Dictionary;
+import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.StringTokenizer;
+import java.util.jar.JarOutputStream;
+import java.util.jar.Manifest;
+import java.util.zip.ZipEntry;
+
+
+import org.apache.tuscany.sca.assembly.ComponentProperty;
+import org.apache.tuscany.sca.assembly.ComponentReference;
+import org.apache.tuscany.sca.assembly.ComponentService;
+import org.apache.tuscany.sca.assembly.Multiplicity;
+import org.apache.tuscany.sca.assembly.Property;
+import org.apache.tuscany.sca.assembly.Reference;
+import org.apache.tuscany.sca.assembly.Service;
+import org.apache.tuscany.sca.core.invocation.JDKProxyService;
+import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint;
+import org.apache.tuscany.sca.runtime.RuntimeComponent;
+import org.apache.tuscany.sca.runtime.RuntimeComponentReference;
+import org.apache.tuscany.sca.runtime.RuntimeComponentService;
+import org.apache.tuscany.sca.runtime.RuntimeWire;
+import org.apache.tuscany.sca.implementation.osgi.OSGiImplementationInterface;
+import org.apache.tuscany.sca.implementation.osgi.context.OSGiPropertyValueObjectFactory;
+import org.apache.tuscany.sca.implementation.osgi.runtime.OSGiRuntime;
+import org.apache.tuscany.sca.implementation.osgi.xml.OSGiImplementation;
+import org.apache.tuscany.sca.interfacedef.Interface;
+import org.apache.tuscany.sca.interfacedef.Operation;
+import org.apache.tuscany.sca.interfacedef.java.JavaInterface;
+import org.apache.tuscany.sca.invocation.Invoker;
+import org.apache.tuscany.sca.factory.ObjectCreationException;
+import org.apache.tuscany.sca.factory.ObjectFactory;
+import org.apache.tuscany.sca.scope.Scope;
+import org.apache.tuscany.sca.scope.InstanceWrapper;
+import org.apache.tuscany.sca.scope.ScopedImplementationProvider;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.BundleException;
+import org.osgi.framework.Constants;
+import org.osgi.framework.FrameworkEvent;
+import org.osgi.framework.FrameworkListener;
+import org.osgi.framework.InvalidSyntaxException;
+import org.osgi.framework.ServiceEvent;
+import org.osgi.framework.ServiceListener;
+import org.osgi.service.packageadmin.ExportedPackage;
+import org.osgi.service.packageadmin.PackageAdmin;
+
+/**
+ * The runtime instantiation of OSGi component implementations
+ * 
+ */
+public class OSGiImplementationProvider  implements ScopedImplementationProvider, FrameworkListener {
+    
+    private static final String COMPONENT_SERVICE_NAME = "component.service.name";
+  
+    private OSGiImplementation implementation;
+    private BundleContext bundleContext;
+    
+    private Hashtable<RuntimeWire, Reference> referenceWires = new Hashtable<RuntimeWire,Reference>();
+    private Hashtable<RuntimeWire, ComponentReference> componentReferenceWires 
+                       = new Hashtable<RuntimeWire,ComponentReference>();
+    private HashSet<RuntimeWire> resolvedWires = new HashSet<RuntimeWire>();   
+    private boolean wiresResolved;
+    private OSGiPropertyValueObjectFactory propertyValueFactory = new OSGiPropertyValueObjectFactory();
+    
+
+    private Hashtable<String, Object> componentProperties = new Hashtable<String, Object>();
+    private RuntimeComponent runtimeComponent;
+    
+    private Bundle osgiBundle;
+    private OSGiServiceListener osgiServiceListener;
+    private PackageAdmin packageAdmin;
+    
+    private OSGiRuntime osgiRuntime;
+    
+    
+    private DataBindingExtensionPoint dataBindingRegistry;
+    
+    private boolean packagesRefreshed;
+    
+
+    public OSGiImplementationProvider(RuntimeComponent definition,
+            OSGiImplementationInterface impl,
+            DataBindingExtensionPoint dataBindingRegistry) throws BundleException {
+        
+        
+        this.implementation = (OSGiImplementation)impl;
+        this.runtimeComponent = definition;
+        this.dataBindingRegistry = dataBindingRegistry;
+
+        bundleContext = getBundleContext();
+        osgiBundle = installBundle();
+        
+        // Install and start all dependent  bundles
+        String[] imports = implementation.getImports();
+        ArrayList<Bundle>bundles = new ArrayList<Bundle>();
+        for (int i = 0; i < imports.length; i++) {
+            String location = imports[i].trim();
+            if (location.length() > 0) {
+                Bundle bundle = bundleContext.installBundle(location);
+                bundles.add(bundle);
+            }                
+        }
+        for (int i = 0; i < bundles.size(); i++) {
+            Bundle bundle = bundles.get(i);
+            try {
+                bundle.start();
+            } catch (BundleException e) {
+                if (bundle.getHeaders().get("Fragment-Host") == null)
+                    throw e;
+            }
+        }
+        
+        // PackageAdmin is used to resolve bundles 
+        org.osgi.framework.ServiceReference packageAdminReference = 
+            bundleContext.getServiceReference("org.osgi.service.packageadmin.PackageAdmin");
+        if (packageAdminReference != null) {
+            packageAdmin = (PackageAdmin) bundleContext.getService(packageAdminReference);
+        }
+        
+        
+    }
+    
+    protected RuntimeComponent getRuntimeComponent() {
+        return runtimeComponent;
+    }
+    
+    protected OSGiImplementation getImplementation() {
+        return implementation;
+    }
+    
+    // Create a property table from the list of properties 
+    // The source properties are properties read from <property/> elements
+    // Create property values in the table of the appropriate class based 
+    // on the property type specified.
+    private void processProperties(List<?> props, Hashtable<String, Object> propsTable) {
+        
+        if (props != null) {
+            for (Object p : props) {
+             
+                Property prop = (Property)p;
+                ObjectFactory<?> objFactory = propertyValueFactory.createValueFactory(prop, prop.getValue());
+                Object value = objFactory.getInstance();           
+
+                propsTable.put(prop.getName(), value);
+            }
+        }
+    }
+
+   
+    private BundleContext getBundleContext() throws BundleException {
+
+        if (bundleContext == null) {
+            osgiRuntime = OSGiRuntime.getRuntime();
+            bundleContext = osgiRuntime .getBundleContext();       
+        }
+        
+        return bundleContext;
+    }
+    
+    private Bundle getBundle() throws Exception {
+        
+        Bundle[] bundles = bundleContext.getBundles();
+        for (Bundle b : bundles) {
+            if (b.getLocation().equals(implementation.getBundleName())) {
+                return b;
+            }
+        }
+        return null;
+    }
+
+    
+    // Install the bundle corresponding to this component.
+    private Bundle installBundle() throws ObjectCreationException {
+        try {
+            
+            Bundle bundle = null;
+            
+            if ((bundle = getBundle()) == null) {
+               
+                String bundleName = implementation.getBundleLocation();
+                                
+                bundle = bundleContext.installBundle(bundleName);
+                
+            }          
+
+            osgiServiceListener = new OSGiServiceListener(bundle);
+            
+            bundleContext.addServiceListener(osgiServiceListener);    
+
+            return bundle;
+            
+        } catch (Exception e) {
+            throw new ObjectCreationException(e);
+        }
+    }
+    
+    private String getOSGiFilter(ComponentService service) {
+        
+        String filter = "";
+        Hashtable<String, Object> props = new Hashtable<String, Object>();
+        processProperties(implementation.getServiceProperties(service.getName()), props);
+        
+        if (props != null && props.size() > 0) {
+            int propCount = 0;
+            for (String propName : props.keySet()) {
+                if (propName.equals("service.pid"))
+                    continue;
+                filter = filter + "(" + propName + "=" + props.get(propName)  + ")";
+                propCount++;
+            }
+    
+            if (propCount > 1) filter = "(&" + filter + ")";
+        }
+        else
+            filter = null;
+        return filter;
+    }
+    
+    /*
+     * Return a matching service registered by the specified bundle.
+     * If <implementation.osgi /> has the attribute filter defined, return a service
+     * reference that matches the filter. Otherwise, return a service which has a component
+     * name equal to this component's name. If not found, return a service which no
+     * component name set.
+     * 
+     * Even though services registered by this bundle can be filtered using the
+     * service listener, we use this method to filter all service references so that 
+     * the service matching functionality of OSGi can be directly used.
+     */
+    private org.osgi.framework.ServiceReference getOSGiServiceReference( 
+            String scaServiceName,
+            String osgiServiceName, String filter) 
+        throws InvalidSyntaxException {
+        
+        String compServiceName = runtimeComponent.getName() + "/" + scaServiceName;
+        if (filter != null && filter.length() > 0) {
+           org.osgi.framework.ServiceReference[] references = 
+                   bundleContext.getServiceReferences(osgiServiceName, filter);
+           
+
+           org.osgi.framework.ServiceReference reference = null;
+           if (references != null) {
+                for (org.osgi.framework.ServiceReference ref : references) {
+                    if (ref.getBundle() != osgiBundle)
+                        continue;
+                    Object compName = ref.getProperty(COMPONENT_SERVICE_NAME);
+                    if (compName == null && reference == null)
+                        reference = ref;
+                    if (compServiceName.equals(compName)) {
+                        reference = ref;
+                        break;
+                    }
+                }
+           }
+        
+           return reference;
+           
+        }
+        
+        filter = "(" + COMPONENT_SERVICE_NAME + "="+ compServiceName + ")";
+        
+        org.osgi.framework.ServiceReference[] references = 
+            bundleContext.getServiceReferences(osgiServiceName, filter);
+        
+        if (references != null) {            
+            for (org.osgi.framework.ServiceReference ref : references) {
+                if (ref.getBundle() == osgiBundle) {
+                    return ref;
+               }
+             }
+        }
+        
+        references = bundleContext.getServiceReferences(osgiServiceName, null);
+        
+        org.osgi.framework.ServiceReference reference = null;
+        
+        if (references != null) {
+            for (org.osgi.framework.ServiceReference ref : references) {
+                
+                if (ref.getBundle() != osgiBundle)
+                    continue;
+                Object compName = ref.getProperty(COMPONENT_SERVICE_NAME);
+                if (compName == null && reference == null)
+                    reference = ref;
+                if (compServiceName.equals(compName)) {
+                    reference = ref;
+                    break;
+                }
+            }
+        }
+        
+        return reference;
+    }
+    
+    protected Bundle startBundle() throws ObjectCreationException {
+
+        try {
+    
+            if (osgiBundle.getState() != Bundle.ACTIVE && osgiBundle.getState() != Bundle.STARTING) {
+        
+                configurePropertiesUsingConfigAdmin();
+        
+                resolveBundle();
+            
+                if (osgiBundle.getState() != Bundle.ACTIVE && osgiBundle.getState() != Bundle.STARTING) {
+
+                    int retry = 0;
+                
+                    while (retry++ < 10) {
+                        try {
+                            osgiBundle.start();
+                            break;
+                       } catch (BundleException e) {
+                            // It is possible that the thread "Refresh Packages" is in the process of
+                            // changing the state of this bundle. 
+                            Thread.yield();
+                        
+                            if (retry == 10)
+                            throw e;
+                        }
+                    }
+                }                   
+            }
+   
+        } catch (Exception e) {
+            throw new ObjectCreationException(e);
+        }
+        return osgiBundle;
+    }
+    
+    
+    
+    protected org.osgi.framework.ServiceReference getOSGiServiceReference( 
+            RuntimeComponentService service) 
+            throws ObjectCreationException {
+        
+        try {
+            
+            String filter = getOSGiFilter(service);
+            Interface serviceInterface = service.getInterfaceContract().getInterface();
+            String serviceInterfaceName = null;
+            String scaServiceName = service.getName();
+
+            org.osgi.framework.ServiceReference osgiServiceReference = null;
+            
+            if (serviceInterface instanceof JavaInterface) {
+                serviceInterfaceName = ((JavaInterface)serviceInterface).getJavaClass().getName();
+                                  
+                if ((osgiServiceReference = getOSGiServiceReference( 
+                        scaServiceName,
+                        serviceInterfaceName, filter)) == null) {
+                    
+                    // The service listener for our bundle will notify us when the service is registered.
+                    synchronized (implementation) {                            
+                                                
+                        // When declarative services are used, the component is started asynchronously
+                        // So this thread has to wait for the service to be registered by the component
+                        // activate method
+                        // For regular bundle activators, bundle.start activates the bundle synchronously
+                        // and hence the service would probably have been started by the bundle activator
+                        while ((osgiServiceReference = getOSGiServiceReference( 
+                                scaServiceName,
+                                serviceInterfaceName, filter)) == null) {
+                                            
+                            // Wait for the bundle to register the service
+                            implementation.wait(100);
+                        }
+                    }   
+                    
+                        
+                }
+            }
+                
+            
+            
+            
+            return osgiServiceReference;
+            
+        } catch (Exception e) {
+            throw new ObjectCreationException(e);
+        }
+    }
+    
+    
+    // Felix does not support bundle fragments. This is a temporary workaround.
+    protected Bundle installDummyBundleWithoutFragments(Class<?> interfaceClass)
+            throws Exception {
+
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+
+        String EOL = System.getProperty("line.separator");
+
+        String interfaceName = interfaceClass.getName();
+        String packageName = interfaceClass.getPackage().getName();
+        String bundleName = "dummy.sca." + packageName;
+
+        String manifestStr = "Manifest-Version: 1.0" + EOL
+                + "Bundle-ManifestVersion: 2" + EOL + "Bundle-Name: "
+                + bundleName + EOL + "Bundle-SymbolicName: " + bundleName + EOL
+                + "Bundle-Version: " + "1.0.0" + EOL
+                + "Bundle-Localization: plugin" + EOL;
+        
+        ArrayList<String> dummyClasses = new ArrayList<String>();
+
+        StringBuilder manifestBuf = new StringBuilder();
+        manifestBuf.append(manifestStr);
+        manifestBuf.append("Export-Package: " + packageName + EOL);
+        String exportedInterfaces = interfaceName;
+        Bundle existingBundle = getDummyHostBundle(packageName);
+        String existingClasses;
+        dummyClasses.add(interfaceClass.getName());
+        for (Class<?> clazz :  interfaceClass.getClasses()) {
+            dummyClasses.add(clazz.getName());
+        }
+        if (existingBundle != null && 
+                (existingClasses = (String)existingBundle.getHeaders().get("SCA-Dummy-Classes")) != null) {
+            exportedInterfaces = exportedInterfaces + " " +  existingClasses;
+            
+            StringTokenizer tokenizer = new StringTokenizer(existingClasses);
+            while (tokenizer.hasMoreTokens()) {
+                String className = tokenizer.nextToken();
+                if (!dummyClasses.contains(className))
+                    dummyClasses.add(className);
+            }
+        }
+
+        manifestBuf.append("SCA-Dummy-Classes: " + exportedInterfaces + EOL);
+
+        ByteArrayInputStream manifestStream = new ByteArrayInputStream(
+                manifestBuf.toString().getBytes());
+        Manifest manifest = new Manifest();
+        manifest.read(manifestStream);
+
+        JarOutputStream jarOut = new JarOutputStream(out, manifest);
+
+        for (int i = 0; i < dummyClasses.size(); i++) {
+
+            String className = dummyClasses.get(i);
+            
+            Class clazz = interfaceClass.getClassLoader().loadClass(className);
+            className = clazz.getName().replaceAll("\\.", "/") + ".class";
+            ZipEntry ze = new ZipEntry(className);
+            jarOut.putNextEntry(ze);
+            InputStream stream = clazz.getResourceAsStream(clazz.getSimpleName() + ".class");
+            
+            byte[] bytes = new byte[stream.available()];
+            stream.read(bytes);
+            jarOut.write(bytes);
+            stream.close();
+        }
+        
+        
+        jarOut.close();
+        out.close();
+        
+        if (existingBundle != null) {
+            existingBundle.stop();
+            existingBundle.uninstall();
+        }
+
+        ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
+
+        Bundle bundle = bundleContext.installBundle("file://" + bundleName
+                + ".jar", in);
+
+        bundle.start();
+        
+        if (existingBundle != null && packageAdmin != null) {
+            
+
+            bundleContext.addFrameworkListener(this);
+                      
+            packagesRefreshed = false;
+            packageAdmin.refreshPackages(null);
+                        
+            synchronized (this) {
+                if (!packagesRefreshed) {
+                    this.wait(2000);
+                }
+            }            
+            packagesRefreshed = false;
+            bundleContext.removeFrameworkListener(this);
+            
+        }
+
+        return bundle;
+
+    }
+    
+    private Bundle getDummyHostBundle(String packageName) {
+        
+        if (packageAdmin == null)
+            return null;
+        
+        ExportedPackage exp = packageAdmin.getExportedPackage(packageName);
+        if (exp == null)
+            return null;
+        else
+            return exp.getExportingBundle();
+    }
+    
+    
+    private Bundle installDummyBundle(Class<?> interfaceClass)
+            throws Exception {
+        
+
+        if (!osgiRuntime.supportsBundleFragments()) {
+            return installDummyBundleWithoutFragments(interfaceClass);
+        }
+        
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+                
+        String EOL = System.getProperty("line.separator");
+        ArrayList<Class<?>> dummyClasses = new ArrayList<Class<?>>();
+        
+        String interfaceName = interfaceClass.getName();
+        String packageName = interfaceClass.getPackage().getName();
+        String bundleName = "dummy.sca." + interfaceName;
+        
+        
+        String manifestStr = "Manifest-Version: 1.0" + EOL +
+                        "Bundle-ManifestVersion: 2" + EOL +
+                        "Bundle-Name: " + bundleName + EOL +
+                        "Bundle-SymbolicName: " + bundleName + EOL +
+                        "Bundle-Version: " + "1.0.0" + EOL +
+                        "Bundle-Localization: plugin" + EOL;
+        
+                        
+        StringBuilder manifestBuf = new StringBuilder();
+        manifestBuf.append(manifestStr);
+        manifestBuf.append("Export-Package: " + packageName + EOL);
+        Bundle dummyHost = getDummyHostBundle(packageName);
+        if (dummyHost != null)
+            manifestBuf.append("Fragment-Host: " + dummyHost.getSymbolicName() + EOL);
+       
+        ByteArrayInputStream manifestStream = new ByteArrayInputStream(manifestBuf.toString().getBytes());
+        Manifest manifest = new Manifest();
+        manifest.read(manifestStream);
+        
+        dummyClasses.add(interfaceClass);
+        for (Class<?> clazz :  interfaceClass.getClasses()) {
+            dummyClasses.add(clazz);
+        }
+        
+        JarOutputStream jarOut = new JarOutputStream(out, manifest);
+
+        for (int i = 0; i < dummyClasses.size(); i++) {
+            
+            Class<?> clazz = dummyClasses.get(i);
+            String className = clazz.getName();
+            className = clazz.getName().replaceAll("\\.", "/") + ".class";
+            ZipEntry ze = new ZipEntry(className);
+            jarOut.putNextEntry(ze);
+            InputStream stream = clazz.getResourceAsStream(clazz.getSimpleName() + ".class");
+            
+            byte[] bytes = new byte[stream.available()];
+            stream.read(bytes);
+            jarOut.write(bytes);
+            stream.close();
+        }
+        
+        jarOut.close();
+        out.close();
+        
+        
+        ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
+        
+        
+        Bundle bundle = bundleContext.installBundle(
+                "file://" + bundleName + ".jar",
+                in);
+        
+        if (dummyHost == null)
+            bundle.start();
+        
+        return bundle;
+        
+    }
+    
+    
+    
+    public InstanceWrapper<?> createInstanceWrapper() throws ObjectCreationException {
+        
+        return new OSGiInstanceWrapper<Object>(this, bundleContext);
+    }
+    
+   
+    
+    private  void resolveWireCreateDummyBundles(Class interfaceClass, RuntimeWire wire) throws Exception {
+        
+        
+        try {
+                 
+            osgiBundle.loadClass(interfaceClass.getName());
+                            
+        } catch (ClassNotFoundException e) {
+                        
+            // The interface used by the proxy is not in the source bundle
+            // A dummy bundle needs to be installed to create the proxy
+                     
+            Bundle dummyBundle = installDummyBundle(interfaceClass);
+                                
+            if (packageAdmin != null) {
+                                    
+                packageAdmin.resolveBundles(new Bundle[]{dummyBundle, osgiBundle});
+                              
+            } 
+
+        }
+    }
+    
+    /**
+     * For OSGi->Java wires, create a proxy corresponding to the Java interfaces
+     * and register the proxy with the OSGi registry, so that the source OSGi bundle can 
+     * locate the target Java instance from the registry like a regular OSGi service.
+     * 
+     * For OSGi->OSGi wires, start the target OSGi bundle, so that references of the
+     * target are resolved before the source OSGi bundle is started. If the reference
+     * has properties specified, create a Proxy and register a service with highest
+     * possible ranking. The Proxy should wire to the correct OSGi instance specified
+     * in the SCA composite.
+     * 
+     * The first phase determines whether a proxy should be installed. It also registers
+     * a dummy bundle if necessary to resolve the bundle. When phase1 is completed on all
+     * wires of the component, the bundle should be resolved. Phase2 registers the proxy service.
+     */
+    private boolean resolveWireResolveReferences(Bundle bundle, Class interfaceClass, RuntimeWire wire,
+            boolean isOSGiToOSGiWire) throws Exception {
+        
+        boolean createProxy = false;
+       
+        ComponentReference scaRef = componentReferenceWires.get(wire);
+        Hashtable<String, Object> targetProperties = new Hashtable<String, Object>();
+        processProperties(implementation.getReferenceProperties(scaRef.getName()), targetProperties);
+            
+
+        if (isOSGiToOSGiWire) {
+                    
+                OSGiImplementationProvider implProvider = (OSGiImplementationProvider)wire.getTarget().getComponent().getImplementationProvider();
+                    
+                // This is an OSGi->OSGi wire
+                isOSGiToOSGiWire = true;
+                    
+                // If the target component is stateless, use a proxy to create a new service each time 
+                if (!implProvider.getScope().equals(Scope.COMPOSITE)) createProxy = true;
+                
+                Interface interfaze = wire.getTarget().getInterfaceContract().getInterface();
+                
+                // If the target interface is remotable, create a proxy to support pass-by-value semantics
+                // AllowsPassByReference is not detected until the target instance is obtained.
+                if (interfaze.isRemotable())
+                    createProxy = true;
+                    
+                // If any of the operations in the target interface is non-blocking, create a proxy
+                List<Operation> ops = interfaze.getOperations();
+                for (Operation op : ops) {
+                    if (op.isNonBlocking())
+                        createProxy = true;
+                }
+                    
+                // If properties are specified for the reference, create a proxy since rewiring may be required
+                if (targetProperties.size() > 0) {
+                    createProxy = true;
+                }
+                
+                // If properties are specified for the component, create a proxy for configuring
+                // the component services.
+                if (componentProperties.size() > 0) {
+                    createProxy = true;
+                }
+                    
+                // Since this is an OSGi->OSGi wire, start the target bundle before starting the
+                // source bundle if there is no proxy. For direct wiring without a proxy, this ordering 
+                // is irrelevant in terms of class resolution, but the target needs to be started at some 
+                // point. But there is no opportunity later on to start the target OSGi bundle without a proxy.    
+                // When a Proxy is used, the target bundle needs to be resolved for the source bundle
+                // to be resolved so that the interface is visible to the source. In this case the bundle
+                // will be started when an instance is needed.                    
+                if (!createProxy) {    
+                    implProvider.startBundle();
+                }
+                else {
+                    implProvider.resolveBundle();
+                }
+        }
+        else {
+                createProxy = true;
+        }
+            
+        return createProxy;
+    }
+    
+    
+    // Register proxy service 
+    private void resolveWireRegisterProxyService(Bundle bundle, Class interfaceClass, RuntimeWire wire) throws Exception {
+          
+        ComponentReference scaRef = componentReferenceWires.get(wire);
+        Hashtable<String, Object> targetProperties = new Hashtable<String, Object>();
+        processProperties(implementation.getReferenceProperties(scaRef.getName()), targetProperties);
+        targetProperties.put(Constants.SERVICE_RANKING, Integer.MAX_VALUE);
+        
+        if (targetProperties.get(COMPONENT_SERVICE_NAME) == null && wire.getTarget().getComponent() != null) {
+            String compServiceName = wire.getTarget().getComponent().getName() + "/" + 
+                                     wire.getTarget().getContract().getName();
+            targetProperties.put(COMPONENT_SERVICE_NAME, compServiceName);
+        }
+        
+           
+        JDKProxyService proxyService = new JDKProxyService();
+              
+        Class<?> proxyInterface = bundle.loadClass(interfaceClass.getName());
+                
+
+        Object proxy = proxyService.createProxy(proxyInterface, wire);
+       
+            
+        bundleContext.registerService(proxyInterface.getName(), proxy, targetProperties);
+            
+        
+    }
+    
+    
+    private void resolveBundle() throws ObjectCreationException {
+        
+        
+        try {
+            
+            if (!wiresResolved) {
+                wiresResolved = true;
+                    
+                boolean[] createProxyService = new boolean[referenceWires.size()];
+                Class<?>[] interfaceClasses = new Class<?>[referenceWires.size()] ;
+                boolean[] isOSGiToOSGiWire = new boolean[referenceWires.size()];
+                boolean[] wireResolved = new boolean[referenceWires.size()];
+                int index = 0;
+                for (RuntimeWire wire : referenceWires.keySet()) {
+                
+                    Reference reference = referenceWires.get(wire);
+                    
+                    isOSGiToOSGiWire[index] = wire.getTarget().getComponent() != null &&
+                            wire.getTarget().getComponent().getImplementationProvider() 
+                            instanceof OSGiImplementationProvider;
+                            
+                    Interface refInterface = reference.getInterfaceContract().getInterface();
+                    if (refInterface instanceof JavaInterface) {
+                        interfaceClasses[index] = ((JavaInterface)refInterface).getJavaClass();
+                    
+                        if (!isOSGiToOSGiWire[index])
+                            resolveWireCreateDummyBundles(interfaceClasses[index], wire);
+
+                    }
+                    
+                    if (!resolvedWires.contains(wire)) {
+                        resolvedWires.add(wire);                       
+                    }
+                    else
+                        wireResolved[index] = true;
+                    
+                    index++;
+                }
+                
+                index = 0;
+                for (RuntimeWire wire : referenceWires.keySet()) {
+                    
+                    if (!wireResolved[index]) {
+                        createProxyService[index] = resolveWireResolveReferences(osgiBundle, 
+                            interfaceClasses[index], 
+                            wire,
+                            isOSGiToOSGiWire[index]);
+                    }
+                    index++;
+                }
+                
+                index = 0;
+                for (RuntimeWire wire : referenceWires.keySet()) {
+                    
+                    if (createProxyService[index] && !wireResolved[index])
+                        resolveWireRegisterProxyService(osgiBundle, interfaceClasses[index], wire);
+                    index++;
+                }
+            }
+            else if (osgiBundle.getState() == Bundle.INSTALLED && packageAdmin != null) {
+                packageAdmin.resolveBundles(new Bundle[] {osgiBundle});
+            }
+            
+        } catch (Exception e) {
+            e.printStackTrace();
+            throw new ObjectCreationException(e);
+        }         
+    }
+    
+   
+    
+    private void configurePropertiesUsingConfigAdmin() {
+               
+        try {
+
+            if (componentProperties.size() == 0)
+                return;
+            
+            org.osgi.framework.ServiceReference configAdminReference = 
+                bundleContext.getServiceReference("org.osgi.service.cm.ConfigurationAdmin");
+            if (configAdminReference != null) {
+                
+                Object cm = bundleContext.getService(configAdminReference);
+                Class cmClass = cm.getClass().getClassLoader().loadClass("org.osgi.service.cm.ConfigurationAdmin");
+                Method getConfigMethod = cmClass.getMethod("getConfiguration", String.class, String.class);
+                
+
+                Class configClass = cm.getClass().getClassLoader().loadClass("org.osgi.service.cm.Configuration");
+                
+                Method getMethod = configClass.getMethod("getProperties");
+                Method updateMethod = configClass.getMethod("update", Dictionary.class);
+                
+                List<Service> services = implementation.getServices();
+                HashSet<String> pidsProcessed = new HashSet<String>();
+                
+                for (Service service : services) {
+                    
+                    List<ComponentProperty> serviceProps = implementation.getServiceProperties(service.getName());
+                    String pid = null;
+                    
+                    if (serviceProps != null) {
+                        for (ComponentProperty prop : serviceProps) {
+                            if (prop.getName().equals("service.pid")) {
+                                ObjectFactory objFactory = propertyValueFactory.createValueFactory(prop, prop.getValue());
+                                pid = (String)objFactory.getInstance();
+                            }
+                        }
+                    }
+                    if (pid == null || pidsProcessed.contains(pid))
+                        continue;
+                    
+
+                   
+                    
+                    Object config = getConfigMethod.invoke(cm, pid, null);
+                    Dictionary props = (Dictionary) getMethod.invoke(config);
+                    if (props == null)
+                        props = new Hashtable<String, Object>();
+                    for (String propertyName : componentProperties.keySet()) {
+
+                        props.put(propertyName, componentProperties.get(propertyName));
+                    }
+                    
+                    updateMethod.invoke(config, props);
+                    
+                    
+                }                
+                
+            }
+            
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+    }
+    
+    protected void injectPropertiesUsingAnnotations(Object instance)  {
+        
+        if (!implementation.needsPropertyInjection())
+            return;
+        
+        Class implClass = instance.getClass();
+        List<ComponentProperty> compProps = runtimeComponent.getProperties();
+        
+        for (ComponentProperty prop : compProps) {
+            
+            boolean hasSetProp = false;
+            String propName = prop.getName();
+            ObjectFactory objFactory = propertyValueFactory.createValueFactory(prop, prop.getValue());
+            
+            try {
+                Field field = implClass.getDeclaredField(propName);
+                org.osoa.sca.annotations.Property propAnn;
+                
+                if ((propAnn = field.getAnnotation(org.osoa.sca.annotations.Property.class)) != null
+                        || Modifier.isPublic(field.getModifiers())) {
+                    
+                    try {
+                        if (!field.isAccessible())
+                            field.setAccessible(true);
+                            
+                        field.set(instance, objFactory.getInstance());
+                        hasSetProp = true;
+                    } catch (IllegalAccessException e) {
+                        if (propAnn.required())
+                            throw new RuntimeException(e);
+                    }
+                    
+                }
+            } catch (NoSuchFieldException e) {
+                // Ignore exception
+            }
+
+            if (!hasSetProp) {
+                Method[] methods = implClass.getDeclaredMethods();
+                org.osoa.sca.annotations.Property propAnn = null;
+
+                for (Method method : methods) {
+
+                    if (!method.getName().startsWith("set"))
+                        continue;
+                    if ((propAnn = method.getAnnotation(org.osoa.sca.annotations.Property.class)) != null
+                            || Modifier.isPublic(method.getModifiers())) {
+                        
+                        String methodPropName = Introspector.decapitalize(method.getName().substring(3));
+                        if (!propName.equals(methodPropName))
+                            continue;
+                    }
+                    try {
+                        if (!method.isAccessible())
+                            method.setAccessible(true);
+
+                        method.invoke(instance, objFactory.getInstance());
+                        hasSetProp = true;
+                    } catch (Exception e) {
+                        if (propAnn != null && propAnn.required())
+                            throw new RuntimeException(e);
+                    }
+                }
+            }
+
+        }
+        
+    }
+    
+    protected void injectProperties(Object instance)  {
+        
+        if (!implementation.needsPropertyInjection())
+            return;
+        
+        Class implClass = instance.getClass();
+        List<ComponentProperty> compProps = runtimeComponent.getProperties();
+        
+        for (ComponentProperty prop : compProps) {
+            
+            boolean hasSetProp = false;
+            String propName = prop.getName();
+            ObjectFactory objFactory = propertyValueFactory.createValueFactory(prop, prop.getValue());
+            
+            try {
+                Field field = implClass.getDeclaredField(propName);
+                
+                if (Modifier.isPublic(field.getModifiers())) {
+                   
+                    try {
+                        field.set(instance, objFactory.getInstance());
+                        hasSetProp = true;
+                    
+                    } catch (Exception e) {
+                        // Ignore
+                    }
+                }
+            } catch (NoSuchFieldException e) {
+                // Ignore exception
+            }
+
+            if (!hasSetProp) {
+                Method[] methods = implClass.getDeclaredMethods();
+                for (Method method : methods) {
+
+                    if (!method.getName().startsWith("set"))
+                        continue;
+                    if (Modifier.isPublic(method.getModifiers())) {
+                        
+                        String methodPropName = Introspector.decapitalize(method.getName().substring(3));
+                        if (!propName.equals(methodPropName))
+                            continue;
+                    }
+                    try {
+                        method.invoke(instance, objFactory.getInstance());
+                    } catch (Exception e) {
+                       // Ignore
+                    }
+                }
+            }
+
+        }
+        
+    }
+
+
+    
+    public boolean isOptimizable() {
+        return false;
+    }
+    
+    public Scope getScope() {
+        return implementation.getScope();
+    }
+
+    public boolean isEagerInit() {
+        return implementation.isEagerInit();
+    }
+
+    public long getMaxAge() {
+        return implementation.getMaxAge();
+    }
+
+    public long getMaxIdleTime() {
+        return implementation.getMaxIdleTime();
+    }
+    
+    
+    public Invoker createTargetInvoker(RuntimeComponentService service, Operation operation)  {
+       
+        
+        Interface serviceInterface = operation.getInterface();
+        boolean isRemotable = serviceInterface.isRemotable();
+
+
+        Invoker invoker = new OSGiTargetInvoker(operation, runtimeComponent, service);
+        if (isRemotable) {
+            return new OSGiRemotableInvoker(implementation, dataBindingRegistry, operation, runtimeComponent, service);
+        } else {
+            return invoker;
+        }
+        
+    }
+    
+    public Invoker createCallbackInvoker(Operation operation) {
+        return createTargetInvoker(null, operation);
+    }
+
+    public Invoker createInvoker(RuntimeComponentService service, Operation operation) {
+        return createTargetInvoker(service, operation);
+    }
+
+    public void start() {
+        
+        
+        for (Reference ref: implementation.getReferences()) {
+            List<RuntimeWire> wireList = null;
+            ComponentReference compRef = null;
+            for (ComponentReference cRef : runtimeComponent.getReferences()) {
+                if (cRef.getName().equals(ref.getName())) {
+                    wireList = ((RuntimeComponentReference)cRef).getRuntimeWires();
+                    compRef = cRef;
+                    break;
+                }
+            }
+                
+            if (ref.getMultiplicity() == Multiplicity.ONE_N || ref.getMultiplicity() == Multiplicity.ZERO_N) {
+                 for (RuntimeWire wire : wireList) {
+                    referenceWires.put(wire, ref);
+                    componentReferenceWires.put(wire, compRef);
+                }
+                
+            } else {
+                if (wireList == null && ref.getMultiplicity() == Multiplicity.ONE_ONE) {
+                    throw new IllegalStateException("Required reference is missing: " + ref.getName());
+                }
+                if (wireList != null && !wireList.isEmpty()) {
+                    RuntimeWire wire = wireList.get(0);
+                    referenceWires.put(wire, ref);
+                    componentReferenceWires.put(wire, compRef);
+                }
+                
+            }
+            
+        }
+        
+        processProperties(runtimeComponent.getProperties(), componentProperties);
+        
+    }
+    
+    
+    public void stop() {
+
+        bundleContext.removeServiceListener(osgiServiceListener);
+    }
+
+    
+    
+    public void frameworkEvent(FrameworkEvent event) {
+        if (event.getType() == FrameworkEvent.PACKAGES_REFRESHED) {
+            synchronized (this) {
+                packagesRefreshed = true;
+                this.notifyAll();
+            }            
+        }
+        
+    }
+
+
+
+    private class OSGiServiceListener implements ServiceListener {
+        
+        private Bundle bundle;
+        
+        OSGiServiceListener(Bundle bundle) {
+            this.bundle = bundle;
+        }
+        
+        public void serviceChanged(org.osgi.framework.ServiceEvent event) {
+            
+
+            org.osgi.framework.ServiceReference reference = event.getServiceReference();
+            
+            if (event.getType() == ServiceEvent.REGISTERED && reference.getBundle() == bundle) {
+                
+                synchronized (implementation) {
+                    
+                    implementation.notifyAll();
+                }
+            }
+            
+            if (event.getType() == ServiceEvent.UNREGISTERING && reference.getBundle() == bundle) {
+                // TODO: Process deregistering of OSGi services.
+            }
+        }
+    }
+}

Propchange: incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiImplementationProvider.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiImplementationProvider.java
------------------------------------------------------------------------------
    svn:keywords = Rev Date

Added: incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiImplementationProviderFactory.java
URL: http://svn.apache.org/viewvc/incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiImplementationProviderFactory.java?view=auto&rev=552470
==============================================================================
--- incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiImplementationProviderFactory.java (added)
+++ incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiImplementationProviderFactory.java Mon Jul  2 04:26:39 2007
@@ -0,0 +1,64 @@
+/*
+ * 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.tuscany.sca.implementation.osgi.invocation;
+
+
+import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint;
+import org.apache.tuscany.sca.implementation.osgi.OSGiImplementationInterface;
+import org.apache.tuscany.sca.implementation.osgi.context.OSGiPropertyValueObjectFactory;
+import org.apache.tuscany.sca.provider.ImplementationProvider;
+import org.apache.tuscany.sca.provider.ImplementationProviderFactory;
+import org.apache.tuscany.sca.runtime.RuntimeComponent;
+import org.osgi.framework.BundleException;
+
+
+/**
+ * Builds a OSGi-based implementation provider from a component definition
+ * 
+ */
+public class OSGiImplementationProviderFactory implements ImplementationProviderFactory<OSGiImplementationInterface> {
+    
+    
+    DataBindingExtensionPoint dataBindingRegistry;
+    
+    public OSGiImplementationProviderFactory(DataBindingExtensionPoint dataBindings,
+            OSGiPropertyValueObjectFactory factory) {
+        
+        dataBindingRegistry = dataBindings;
+        
+    }
+
+    public ImplementationProvider createImplementationProvider(RuntimeComponent component,
+        OSGiImplementationInterface implementation) {
+                
+        try {
+                
+            return new OSGiImplementationProvider(component, implementation, dataBindingRegistry);
+                
+        } catch (BundleException e) {
+            throw new RuntimeException(e);
+        }
+        
+    }
+
+    public Class<OSGiImplementationInterface> getModelType() {
+        return OSGiImplementationInterface.class;
+    }
+
+}

Propchange: incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiImplementationProviderFactory.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiImplementationProviderFactory.java
------------------------------------------------------------------------------
    svn:keywords = Rev Date

Added: incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiInstanceWrapper.java
URL: http://svn.apache.org/viewvc/incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiInstanceWrapper.java?view=auto&rev=552470
==============================================================================
--- incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiInstanceWrapper.java (added)
+++ incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiInstanceWrapper.java Mon Jul  2 04:26:39 2007
@@ -0,0 +1,153 @@
+/*
+ * 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.tuscany.sca.implementation.osgi.invocation;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.util.Random;
+import java.util.jar.JarOutputStream;
+import java.util.jar.Manifest;
+import org.apache.tuscany.sca.runtime.RuntimeComponentService;
+import org.apache.tuscany.sca.scope.InstanceWrapper;
+import org.apache.tuscany.sca.scope.Scope;
+import org.apache.tuscany.sca.scope.TargetDestructionException;
+import org.apache.tuscany.sca.scope.TargetInitializationException;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceReference;
+
+
+/**
+ * InstanceWrapper for creating instances for OSGi components. 
+ * This class needs to implement InstanceWrapper since the wrapper is stored in
+ * the scope container. But getInstance() is called on this wrapper only through the
+ * OSGi target invoker. OSGiTargetInvoker always invokes getInstance for a specific
+ * service since one OSGi SCA component can associate different objects with 
+ * different services (this is different from Java SCA components which always associate 
+ * a single component instance with multiple services).
+ * 
+ */
+public class OSGiInstanceWrapper<T> implements InstanceWrapper<T> {
+    
+    private OSGiImplementationProvider provider;
+    private BundleContext bundleContext;
+    private T osgiInstance;
+    private ServiceReference osgiServiceReference;
+    private Bundle dummyBundle;
+    private BundleContext refBundleContext;
+
+    public OSGiInstanceWrapper(OSGiImplementationProvider provider, 
+            BundleContext bundleContext) {
+        
+        this.provider = provider;
+        this.bundleContext = bundleContext;
+    }
+    
+    public T getInstance(RuntimeComponentService service) throws TargetInitializationException {
+
+        Bundle refBundle = provider.startBundle();
+        
+        if (provider.getImplementation().getScope() != Scope.COMPOSITE) {
+            refBundle = getDummyReferenceBundle();
+        }
+
+        osgiServiceReference = provider.getOSGiServiceReference(service);
+        
+        refBundleContext = refBundle.getBundleContext();
+        osgiInstance = (T)refBundleContext.getService(osgiServiceReference);
+        
+        provider.injectProperties(osgiInstance);
+        
+        return osgiInstance;
+    }
+    
+    // This method is provided purely to implement InstanceWrapper interface, and is never called.
+    public T getInstance() {
+
+        return null;
+    }
+    
+    public void start() throws TargetInitializationException {
+        
+    }
+
+    public void stop() throws TargetDestructionException {
+        if (osgiInstance != null && osgiServiceReference != null) {
+            
+            refBundleContext.ungetService(osgiServiceReference);
+            
+            osgiInstance = null;
+            osgiServiceReference = null;
+            
+            try {
+                if (dummyBundle != null) {
+                    dummyBundle.uninstall();
+                }
+            } catch (Exception e) {
+                throw new TargetDestructionException(e);
+            }            
+        }
+    }
+    
+    private Bundle getDummyReferenceBundle() throws TargetInitializationException {
+        
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        
+        String EOL = System.getProperty("line.separator");
+        String bundleName = "dummy.sca." + new Random().nextInt();
+        
+        
+        String manifestStr = "Manifest-Version: 1.0" + EOL +
+                        "Bundle-ManifestVersion: 2" + EOL +
+                        "Bundle-Name: " + bundleName + EOL +
+                        "Bundle-SymbolicName: " + bundleName + EOL +
+                        "Bundle-Version: " + "1.0.0" + EOL +
+                        "Bundle-Localization: plugin" + EOL;
+        
+                        
+        StringBuilder manifestBuf = new StringBuilder();
+        manifestBuf.append(manifestStr);
+       
+        try {
+            ByteArrayInputStream manifestStream = new ByteArrayInputStream(manifestBuf.toString().getBytes());
+            Manifest manifest = new Manifest();
+            manifest.read(manifestStream);
+            
+      
+            JarOutputStream jarOut = new JarOutputStream(out, manifest);
+
+            jarOut.close();
+            out.close();
+            
+            
+            ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
+                   
+            dummyBundle = bundleContext.installBundle("file://" + bundleName + ".jar", in);
+            
+            dummyBundle.start();
+            
+        } catch (Exception e) {
+            throw new TargetInitializationException(e);
+        }
+        
+        return dummyBundle;
+        
+    }
+    
+}

Propchange: incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiInstanceWrapper.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiInstanceWrapper.java
------------------------------------------------------------------------------
    svn:keywords = Rev Date

Added: incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiRemotableInvoker.java
URL: http://svn.apache.org/viewvc/incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiRemotableInvoker.java?view=auto&rev=552470
==============================================================================
--- incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiRemotableInvoker.java (added)
+++ incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiRemotableInvoker.java Mon Jul  2 04:26:39 2007
@@ -0,0 +1,132 @@
+/*
+ * 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.tuscany.sca.implementation.osgi.invocation;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.IdentityHashMap;
+import java.util.Map;
+
+import org.apache.tuscany.sca.databinding.DataBinding;
+import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint;
+import org.apache.tuscany.sca.implementation.osgi.xml.OSGiImplementation;
+import org.apache.tuscany.sca.interfacedef.DataType;
+import org.apache.tuscany.sca.interfacedef.Operation;
+import org.apache.tuscany.sca.invocation.Message;
+import org.apache.tuscany.sca.runtime.RuntimeComponent;
+import org.apache.tuscany.sca.runtime.RuntimeComponentService;
+
+/**
+ * An interceptor to enforce pass-by-value semantics for remotable interfaces
+ * 
+ */
+public class OSGiRemotableInvoker extends OSGiTargetInvoker {
+    
+    private DataBindingExtensionPoint registry;
+    private Operation operation;
+    private OSGiImplementation osgiImplementation;
+
+    /**
+     * @param registry
+     * @param operation
+     * @param method
+     * @param component
+     */
+    public OSGiRemotableInvoker(OSGiImplementation osgiImplementation,
+                              DataBindingExtensionPoint registry,
+                              Operation operation,
+                              RuntimeComponent component,
+                              RuntimeComponentService service) {
+        super(operation, component, service);
+        this.osgiImplementation = osgiImplementation;
+        this.registry = registry;
+        this.operation = operation;
+    }
+
+    @Override
+    public Object invokeMethod(Object targetObject, Method m, Message msg) 
+        throws InvocationTargetException {
+        
+        Object result;
+        if (osgiImplementation.isAllowsPassByReference(m)) {
+            result = super.invokeMethod(targetObject, m, msg);
+        }
+        else {
+            Object obj = msg.getBody();
+            msg.setBody(copy((Object[])obj));
+
+            result = super.invokeMethod(targetObject, m, msg);
+
+            if (operation.getOutputType() != null) {
+                String dataBindingId = operation.getOutputType().getDataBinding();
+                DataBinding dataBinding = registry.getDataBinding(dataBindingId);
+                result = copy(result, dataBinding);
+            }
+        }
+        return result;
+    }
+
+    public Object[] copy(Object[] args) {
+        if (args == null) {
+            return null;
+        }
+        Object[] copiedArgs = new Object[args.length];
+        Map<Object, Object> map = new IdentityHashMap<Object, Object>();
+        for (int i = 0; i < args.length; i++) {
+            if (args[i] == null) {
+                copiedArgs[i] = null;
+            } else {
+                Object copiedArg = map.get(args[i]);
+                if (copiedArg != null) {
+                    copiedArgs[i] = copiedArg;
+                } else {
+                    String dataBindingId = operation.getInputType().getLogical().get(i).getDataBinding();
+                    DataBinding dataBinding = registry.getDataBinding(dataBindingId);
+                    copiedArg = copy(args[i], dataBinding);
+                    map.put(args[i], copiedArg);
+                    copiedArgs[i] = copiedArg;
+                }
+            }
+        }
+        return copiedArgs;
+    }
+
+    public Object copy(Object arg, DataBinding argDataBinding) {
+        if (arg == null) {
+            return null;
+        }
+        Object copiedArg;
+        if (argDataBinding != null) {
+            copiedArg = argDataBinding.copy(arg);
+        } else {
+            copiedArg = arg;
+            DataType<?> dataType = registry.introspectType(arg);
+            if (dataType != null) {
+                DataBinding binding = registry.getDataBinding(dataType.getDataBinding());
+                if (binding != null) {
+                    copiedArg = binding.copy(arg);
+                }
+            }
+            // FIXME: What to do if it's not recognized?
+        }
+        return copiedArg;
+    }
+
+}

Propchange: incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiRemotableInvoker.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: incubator/tuscany/java/sca/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/invocation/OSGiRemotableInvoker.java
------------------------------------------------------------------------------
    svn:keywords = Rev Date



---------------------------------------------------------------------
To unsubscribe, e-mail: tuscany-commits-unsubscribe@ws.apache.org
For additional commands, e-mail: tuscany-commits-help@ws.apache.org