You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@aries.apache.org by cs...@apache.org on 2016/03/11 20:43:49 UTC
[50/50] [abbrv] aries-rsa git commit: Switching to aries package names
Switching to aries package names
Project: http://git-wip-us.apache.org/repos/asf/aries-rsa/repo
Commit: http://git-wip-us.apache.org/repos/asf/aries-rsa/commit/5f4c6604
Tree: http://git-wip-us.apache.org/repos/asf/aries-rsa/tree/5f4c6604
Diff: http://git-wip-us.apache.org/repos/asf/aries-rsa/diff/5f4c6604
Branch: refs/heads/master
Commit: 5f4c6604a7613528096fb6075fc1988b8fdf5861
Parents: d73a3a7
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Fri Mar 11 20:42:17 2016 +0100
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Fri Mar 11 20:42:17 2016 +0100
----------------------------------------------------------------------
discovery/local/bnd.bnd | 6 +-
discovery/local/pom.xml | 5 +
.../EndpointDescriptionBundleParser.java | 104 ++++
.../endpoint/EndpointDescriptionParser.java | 90 +++
.../discovery/endpoint/PropertiesMapper.java | 345 +++++++++++
.../aries/rsa/discovery/local/Activator.java | 41 ++
.../rsa/discovery/local/LocalDiscovery.java | 258 ++++++++
.../discovery/local/internal/Activator.java | 41 --
.../local/internal/LocalDiscovery.java | 242 --------
.../cxf/dosgi/discovery/local/util/Utils.java | 125 ----
.../EndpointDescriptionBundleParser.java | 104 ----
.../endpointdesc/EndpointDescriptionParser.java | 90 ---
.../dosgi/endpointdesc/PropertiesMapper.java | 345 -----------
.../EndpointDescriptionBundleParserTest.java | 171 ++++++
.../endpoint/EndpointDescriptionParserTest.java | 51 ++
.../endpoint/PropertiesMapperTest.java | 98 +++
.../rsa/discovery/local/ActivatorTest.java | 54 ++
.../rsa/discovery/local/LocalDiscoveryTest.java | 410 +++++++++++++
.../discovery/local/internal/ActivatorTest.java | 52 --
.../local/internal/LocalDiscoveryTest.java | 409 -------------
.../EndpointDescriptionBundleParserTest.java | 138 -----
.../EndpointDescriptionParserTest.java | 49 --
.../endpointdesc/PropertiesMapperTest.java | 97 ---
.../zookeeper/server/config/Activator.java | 2 +-
discovery/zookeeper/pom.xml | 5 +
.../publish/PublishingEndpointListener.java | 7 +-
.../PublishingEndpointListenerFactory.java | 2 +-
.../zookeeper/subscribe/InterfaceMonitor.java | 4 +-
.../subscribe/InterfaceMonitorManager.java | 22 +-
.../dosgi/discovery/zookeeper/util/Utils.java | 47 +-
.../PublishingEndpointListenerFactoryTest.java | 4 +-
.../publish/PublishingEndpointListenerTest.java | 12 +-
.../subscribe/InterfaceMonitorManagerTest.java | 4 +-
.../subscribe/InterfaceMonitorTest.java | 4 +-
.../discovery/zookeeper/util/UtilsTest.java | 67 +--
features/src/main/resources/features.xml | 1 +
parent/pom.xml | 19 +-
provider/tcp/pom.xml | 6 +-
.../aries/rsa/provider/tcp/Activator.java | 2 +-
.../aries/rsa/provider/tcp/TCPProvider.java | 6 +-
.../aries/rsa/provider/tcp/TcpEndpoint.java | 2 +-
.../aries/rsa/provider/tcp/TcpProviderTest.java | 4 +-
rsa/bnd.bnd | 8 +-
rsa/pom.xml | 2 +-
.../org/apache/aries/rsa/core/Activator.java | 37 ++
.../aries/rsa/core/ClientServiceFactory.java | 110 ++++
.../rsa/core/DistributionProviderTracker.java | 73 +++
.../apache/aries/rsa/core/EventAdminHelper.java | 151 +++++
.../apache/aries/rsa/core/EventProducer.java | 114 ++++
.../aries/rsa/core/ExportReferenceImpl.java | 77 +++
.../aries/rsa/core/ExportRegistrationImpl.java | 152 +++++
.../aries/rsa/core/ImportRegistrationImpl.java | 230 ++++++++
.../org/apache/aries/rsa/core/PackageUtil.java | 85 +++
.../aries/rsa/core/RemoteServiceAdminCore.java | 590 +++++++++++++++++++
.../rsa/core/RemoteServiceAdminInstance.java | 99 ++++
.../rsa/core/RemoteServiceadminFactory.java | 51 ++
.../apache/cxf/dosgi/dsw/service/Activator.java | 37 --
.../dosgi/dsw/service/ClientServiceFactory.java | 110 ----
.../service/DistributionProviderTracker.java | 73 ---
.../cxf/dosgi/dsw/service/EventAdminHelper.java | 151 -----
.../cxf/dosgi/dsw/service/EventProducer.java | 114 ----
.../dosgi/dsw/service/ExportReferenceImpl.java | 77 ---
.../dsw/service/ExportRegistrationImpl.java | 152 -----
.../dsw/service/ImportRegistrationImpl.java | 230 --------
.../cxf/dosgi/dsw/service/PackageUtil.java | 85 ---
.../dsw/service/RemoteServiceAdminCore.java | 587 ------------------
.../dsw/service/RemoteServiceAdminInstance.java | 99 ----
.../dsw/service/RemoteServiceadminFactory.java | 51 --
.../cxf/dosgi/dsw/service/StringPlus.java | 72 ---
.../rsa/core/ClientServiceFactoryTest.java | 92 +++
.../core/DistributionProviderTrackerTest.java | 82 +++
.../aries/rsa/core/EventProducerTest.java | 189 ++++++
.../rsa/core/ImportRegistrationImplTest.java | 178 ++++++
.../rsa/core/RemoteServiceAdminCoreTest.java | 517 ++++++++++++++++
.../dsw/service/ClientServiceFactoryTest.java | 92 ---
.../DistributionProviderTrackerTest.java | 82 ---
.../dosgi/dsw/service/EventProducerTest.java | 189 ------
.../dsw/service/ImportRegistrationImplTest.java | 178 ------
.../dsw/service/RemoteServiceAdminCoreTest.java | 517 ----------------
.../cxf/dosgi/dsw/service/StringPlusTest.java | 63 --
spi/bnd.bnd | 3 +
spi/pom.xml | 14 -
.../aries/rsa/spi/DistributionProvider.java | 56 ++
.../java/org/apache/aries/rsa/spi/Endpoint.java | 27 +
.../org/apache/aries/rsa/spi/ExportPolicy.java | 46 ++
.../rsa/spi/IntentUnsatisfiedException.java | 35 ++
.../java/org/apache/aries/rsa/spi/packageinfo | 19 +
.../apache/aries/rsa/util/EndpointHelper.java | 41 ++
.../org/apache/aries/rsa/util/StringPlus.java | 73 +++
.../cxf/dosgi/dsw/api/DistributionProvider.java | 56 --
.../org/apache/cxf/dosgi/dsw/api/Endpoint.java | 27 -
.../cxf/dosgi/dsw/api/EndpointHelper.java | 41 --
.../apache/cxf/dosgi/dsw/api/ExportPolicy.java | 46 --
.../dsw/api/IntentUnsatisfiedException.java | 35 --
.../apache/aries/rsa/util/StringPlusTest.java | 54 ++
topology-manager/bnd.bnd | 2 +-
topology-manager/pom.xml | 5 +
.../aries/rsa/topologymanager/Activator.java | 192 ++++++
.../exporter/DefaultExportPolicy.java | 37 ++
.../exporter/EndpointListenerNotifier.java | 135 +++++
.../exporter/EndpointRepository.java | 140 +++++
.../exporter/TopologyManagerExport.java | 195 ++++++
.../importer/EndpointListenerManager.java | 98 +++
.../topologymanager/importer/FilterHelper.java | 43 ++
.../importer/ListenerHookImpl.java | 119 ++++
.../topologymanager/importer/RSATracker.java | 26 +
.../importer/ReferenceCounter.java | 76 +++
.../importer/ServiceInterestListener.java | 26 +
.../importer/TopologyManagerImport.java | 345 +++++++++++
.../cxf/dosgi/topologymanager/Activator.java | 192 ------
.../exporter/DefaultExportPolicy.java | 37 --
.../exporter/EndpointListenerNotifier.java | 133 -----
.../exporter/EndpointRepository.java | 140 -----
.../topologymanager/exporter/StringPlus.java | 57 --
.../exporter/TopologyManagerExport.java | 195 ------
.../importer/EndpointListenerManager.java | 98 ---
.../topologymanager/importer/FilterHelper.java | 43 --
.../importer/ListenerHookImpl.java | 119 ----
.../topologymanager/importer/RSATracker.java | 26 -
.../importer/ReferenceCounter.java | 76 ---
.../importer/ServiceInterestListener.java | 26 -
.../importer/TopologyManagerImport.java | 345 -----------
.../rsa/topologymanager/ActivatorTest.java | 68 +++
.../exporter/EndpointListenerNotifierTest.java | 160 +++++
.../exporter/EndpointRepositoryTest.java | 82 +++
.../exporter/TopologyManagerExportTest.java | 153 +++++
.../importer/EndpointListenerImplTest.java | 113 ++++
.../importer/ListenerHookImplTest.java | 91 +++
.../importer/ReferenceCounterTest.java | 44 ++
.../importer/TopologyManagerImportTest.java | 88 +++
.../dosgi/topologymanager/ActivatorTest.java | 68 ---
.../exporter/EndpointListenerNotifierTest.java | 160 -----
.../exporter/EndpointRepositoryTest.java | 82 ---
.../exporter/TopologyManagerExportTest.java | 153 -----
.../importer/EndpointListenerImplTest.java | 111 ----
.../importer/ListenerHookImplTest.java | 89 ---
.../importer/ReferenceCounterTest.java | 42 --
.../importer/TopologyManagerImportTest.java | 87 ---
138 files changed, 7134 insertions(+), 7297 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/5f4c6604/discovery/local/bnd.bnd
----------------------------------------------------------------------
diff --git a/discovery/local/bnd.bnd b/discovery/local/bnd.bnd
index b1233ce..6709868 100644
--- a/discovery/local/bnd.bnd
+++ b/discovery/local/bnd.bnd
@@ -1 +1,5 @@
-Bundle-Activator: org.apache.cxf.dosgi.discovery.local.internal.Activator
+Bundle-Activator: org.apache.aries.rsa.discovery.local.Activator
+Private-Package: org.apache.aries.rsa.discovery.local
+Export-Package: \
+ org.apache.aries.rsa.discovery.endpoint,\
+ org.osgi.xmlns.rsa.v1_0
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/5f4c6604/discovery/local/pom.xml
----------------------------------------------------------------------
diff --git a/discovery/local/pom.xml b/discovery/local/pom.xml
index 8b7435a..a3a0805 100644
--- a/discovery/local/pom.xml
+++ b/discovery/local/pom.xml
@@ -39,6 +39,11 @@
<dependencies>
<dependency>
+ <groupId>org.apache.aries.rsa</groupId>
+ <artifactId>spi</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
<groupId>xmlunit</groupId>
<artifactId>xmlunit</artifactId>
<version>1.6</version>
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/5f4c6604/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/EndpointDescriptionBundleParser.java
----------------------------------------------------------------------
diff --git a/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/EndpointDescriptionBundleParser.java b/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/EndpointDescriptionBundleParser.java
new file mode 100644
index 0000000..a702e8e
--- /dev/null
+++ b/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/EndpointDescriptionBundleParser.java
@@ -0,0 +1,104 @@
+/**
+ * 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.aries.rsa.discovery.endpoint;
+
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Dictionary;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.Map;
+
+import org.osgi.framework.Bundle;
+import org.osgi.service.remoteserviceadmin.EndpointDescription;
+import org.osgi.xmlns.rsa.v1_0.EndpointDescriptionType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public final class EndpointDescriptionBundleParser {
+ private static final Logger LOG = LoggerFactory.getLogger(EndpointDescriptionBundleParser.class);
+
+ private static final String REMOTE_SERVICES_HEADER_NAME = "Remote-Service";
+ private static final String REMOTE_SERVICES_DIRECTORY = "OSGI-INF/remote-service/";
+
+ private EndpointDescriptionParser parser;
+
+ public EndpointDescriptionBundleParser() {
+ parser = new EndpointDescriptionParser();
+ }
+
+ public List<EndpointDescription> getAllEndpointDescriptions(Bundle b) {
+ List<EndpointDescriptionType> elements = getAllDescriptionElements(b);
+
+ List<EndpointDescription> endpoints = new ArrayList<EndpointDescription>(elements.size());
+ for (EndpointDescriptionType epd : elements) {
+ Map<String, Object> props = new PropertiesMapper().toProps(epd.getProperty());
+ endpoints.add(new EndpointDescription(props));
+ }
+ return endpoints;
+ }
+
+ List<EndpointDescriptionType> getAllDescriptionElements(Bundle b) {
+ Enumeration<URL> urls = getEndpointDescriptionURLs(b);
+ List<EndpointDescriptionType> elements = new ArrayList<EndpointDescriptionType>();
+ while (urls.hasMoreElements()) {
+ URL resourceURL = (URL) urls.nextElement();
+ try {
+ elements.addAll(parser.getEndpointDescriptions(resourceURL.openStream()));
+ } catch (Exception ex) {
+ LOG.warn("Problem parsing: " + resourceURL, ex);
+ }
+ }
+ return elements;
+ }
+
+ Enumeration<URL> getEndpointDescriptionURLs(Bundle b) {
+ String origDir = getRemoteServicesDir(b);
+
+ // Split origDir into dir and file pattern
+ String filePattern = "*.xml";
+ String dir;
+ if (origDir.endsWith("/")) {
+ dir = origDir.substring(0, origDir.length() - 1);
+ } else {
+ int idx = origDir.lastIndexOf('/');
+ if (idx >= 0 & origDir.length() > idx) {
+ filePattern = origDir.substring(idx + 1);
+ dir = origDir.substring(0, idx);
+ } else {
+ filePattern = origDir;
+ dir = "";
+ }
+ }
+
+ Enumeration<URL> urls = b.findEntries(dir, filePattern, false);
+ return (urls == null) ? Collections.enumeration(new ArrayList<URL>()) : urls;
+ }
+
+ private static String getRemoteServicesDir(Bundle b) {
+ Dictionary<?, ?> headers = b.getHeaders();
+ Object header = null;
+ if (headers != null) {
+ header = headers.get(REMOTE_SERVICES_HEADER_NAME);
+ }
+ return (header == null) ? REMOTE_SERVICES_DIRECTORY : header.toString();
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/5f4c6604/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/EndpointDescriptionParser.java
----------------------------------------------------------------------
diff --git a/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/EndpointDescriptionParser.java b/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/EndpointDescriptionParser.java
new file mode 100644
index 0000000..291dc35
--- /dev/null
+++ b/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/EndpointDescriptionParser.java
@@ -0,0 +1,90 @@
+/**
+ * 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.aries.rsa.discovery.endpoint;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.List;
+
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBElement;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Marshaller;
+import javax.xml.bind.Unmarshaller;
+import javax.xml.namespace.QName;
+import javax.xml.transform.Source;
+import javax.xml.transform.stream.StreamSource;
+
+import org.osgi.xmlns.rsa.v1_0.EndpointDescriptionType;
+import org.osgi.xmlns.rsa.v1_0.EndpointDescriptionsType;
+
+public class EndpointDescriptionParser {
+ private JAXBContext jaxbContext;
+
+ public EndpointDescriptionParser() {
+ try {
+ jaxbContext = JAXBContext.newInstance(EndpointDescriptionsType.class.getPackage().getName(),
+ this.getClass().getClassLoader());
+ } catch (JAXBException e) {
+ throw new RuntimeException(e.getMessage(), e);
+ }
+ }
+
+ public List<EndpointDescriptionType> getEndpointDescriptions(InputStream is) {
+ try {
+ Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
+ Source source = new StreamSource(is);
+ JAXBElement<EndpointDescriptionsType> jaxb = unmarshaller.unmarshal(source, EndpointDescriptionsType.class);
+ EndpointDescriptionsType decorations = jaxb.getValue();
+ return decorations.getEndpointDescription();
+ } catch (Exception ex) {
+ throw new RuntimeException(ex.getMessage(), ex);
+ }
+ }
+
+ public void writeTo(EndpointDescriptionsType endpointDescriptions, OutputStream os) {
+ try {
+ Marshaller marshaller = jaxbContext.createMarshaller();
+ marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
+ QName name = new QName("http://www.osgi.org/xmlns/rsa/v1.0.0", "endpoint-descriptions");
+ JAXBElement<EndpointDescriptionsType> el =
+ new JAXBElement<EndpointDescriptionsType>(name, EndpointDescriptionsType.class,
+ endpointDescriptions);
+ marshaller.marshal(el, os);
+ } catch (Exception ex) {
+ throw new RuntimeException(ex.getMessage(), ex);
+ } finally {
+ try {
+ os.close();
+ } catch (IOException e) {
+ // Ignore
+ }
+ }
+ }
+
+ public byte[] getData(EndpointDescriptionType endpointDescription) {
+ EndpointDescriptionsType endpointDescriptions = new EndpointDescriptionsType();
+ endpointDescriptions.getEndpointDescription().add(endpointDescription);
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ writeTo(endpointDescriptions, bos);
+ return bos.toByteArray();
+ }
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/5f4c6604/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/PropertiesMapper.java
----------------------------------------------------------------------
diff --git a/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/PropertiesMapper.java b/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/PropertiesMapper.java
new file mode 100644
index 0000000..13c02bb
--- /dev/null
+++ b/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/PropertiesMapper.java
@@ -0,0 +1,345 @@
+/**
+ * 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.aries.rsa.discovery.endpoint;
+
+import java.io.Serializable;
+import java.io.StringWriter;
+import java.lang.reflect.Array;
+import java.lang.reflect.Constructor;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.xml.bind.JAXBElement;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+
+import org.w3c.dom.Node;
+import org.osgi.xmlns.rsa.v1_0.ArrayType;
+import org.osgi.xmlns.rsa.v1_0.ObjectFactory;
+import org.osgi.xmlns.rsa.v1_0.PropertyType;
+import org.osgi.xmlns.rsa.v1_0.ValueType;
+import org.osgi.xmlns.rsa.v1_0.XmlType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class PropertiesMapper {
+ private static final Logger LOG = LoggerFactory.getLogger(PropertiesMapper.class);
+
+ public Map<String, Object> toProps(List<PropertyType> properties) {
+ Map<String, Object> map = new HashMap<String, Object>();
+ for (PropertyType prop : properties) {
+ map.put(prop.getName(), getValue(prop));
+ }
+ return map;
+ }
+
+ private Object getValue(PropertyType prop) {
+ Object value = null;
+ String type = getTypeName(prop);
+ Object content = getFirstNonText(prop.getContent());
+ if (content instanceof JAXBElement<?>) {
+ JAXBElement<?> el = (JAXBElement<?>)content;
+ if (el.getDeclaredType() == ArrayType.class) {
+ String elName = el.getName().getLocalPart();
+ ArrayType inValue = (ArrayType)el.getValue();
+ if ("array".equals(elName)) {
+ value = getArray(inValue, type);
+ } else if ("set".equals(elName)) {
+ value = handleCollection(inValue, new HashSet<Object>(), type);
+ } else if ("list".equals(elName)) {
+ value = handleCollection(inValue, new ArrayList<Object>(), type);
+ }
+ } else if (el.getDeclaredType() == XmlType.class) {
+ value = readXML((XmlType)el.getValue(), type);
+ }
+ } else {
+ if (prop.getValue() != null) {
+ value = instantiate(type, prop.getValue());
+ } else {
+ if (prop.getContent().size() > 0) {
+ value = instantiate(type, prop.getContent().get(0).toString());
+ }
+ }
+ }
+ return value;
+ }
+
+ private Object getFirstNonText(List<Serializable> contentList) {
+ for (Object content : contentList) {
+ if (content instanceof JAXBElement<?>) {
+ return content;
+ }
+ }
+ return null;
+ }
+
+ private static String getTypeName(PropertyType prop) {
+ String type = prop.getValueType();
+ return type == null ? "String" : type;
+ }
+
+ private Object getArray(ArrayType arrayEl, String type) {
+ List<ValueType> values = arrayEl.getValue();
+ Class<?> cls = null;
+ if ("long".equals(type)) {
+ cls = long.class;
+ } else if ("double".equals(type)) {
+ cls = double.class;
+ } else if ("float".equals(type)) {
+ cls = float.class;
+ } else if ("int".equals(type)) {
+ cls = int.class;
+ } else if ("byte".equals(type)) {
+ cls = byte.class;
+ } else if ("boolean".equals(type)) {
+ cls = boolean.class;
+ } else if ("short".equals(type)) {
+ cls = short.class;
+ }
+
+ try {
+ if (cls == null) {
+ cls = ClassLoader.getSystemClassLoader().loadClass("java.lang." + type);
+ }
+ Object array = Array.newInstance(cls, values.size());
+
+ for (int i = 0; i < values.size(); i++) {
+ Object val = getValue(values.get(i), type);
+ Array.set(array, i, val);
+ }
+
+ return array;
+ } catch (Exception e) {
+ LOG.warn("Could not create array for Endpoint Description", e);
+ return null;
+ }
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ private Collection handleCollection(ArrayType el, Collection value, String type) {
+ List<ValueType> values = el.getValue();
+ for (ValueType val : values) {
+ Object obj = getValue(val, type);
+ value.add(obj);
+ }
+ return value;
+ }
+
+ private Object getValue(ValueType value, String type) {
+ if (value.getContent().size() == 1 && value.getContent().get(0) instanceof String) {
+ return handleValue((String)value.getContent().get(0), type);
+ }
+ JAXBElement<?> valueContent = (JAXBElement<?>)getFirstNonText(value.getContent());
+ if (valueContent.getDeclaredType() == XmlType.class) {
+ return readXML((XmlType)valueContent.getValue(), type);
+ }
+ return "";
+ }
+
+ private String readXML(XmlType el, String type) {
+ if (el == null) {
+ return null;
+ }
+ if (!"String".equals(type)) {
+ LOG.warn("Embedded XML must be of type String, found: " + type);
+ return null;
+ }
+ Node xmlContent = (Node)el.getAny();
+ xmlContent.normalize();
+ try {
+ TransformerFactory transFactory = TransformerFactory.newInstance();
+ Transformer transformer = transFactory.newTransformer();
+ StringWriter buffer = new StringWriter();
+ transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
+ transformer.transform(new DOMSource(xmlContent), new StreamResult(buffer));
+ return buffer.toString();
+ } catch (Exception e) {
+ return "";
+ }
+ }
+
+ private static Object handleValue(String val, String type) {
+ return instantiate(type, val);
+ }
+
+ private static Object instantiate(String type, String value) {
+ if ("String".equals(type)) {
+ return value;
+ }
+
+ value = value.trim();
+ String boxedType = null;
+ if ("long".equals(type)) {
+ boxedType = "Long";
+ } else if ("double".equals(type)) {
+ boxedType = "Double";
+ } else if ("float".equals(type)) {
+ boxedType = "Float";
+ } else if ("int".equals(type)) {
+ boxedType = "Integer";
+ } else if ("byte".equals(type)) {
+ boxedType = "Byte";
+ } else if ("char".equals(type)) {
+ boxedType = "Character";
+ } else if ("boolean".equals(type)) {
+ boxedType = "Boolean";
+ } else if ("short".equals(type)) {
+ boxedType = "Short";
+ }
+
+ if (boxedType == null) {
+ boxedType = type;
+ }
+ String javaType = "java.lang." + boxedType;
+
+ try {
+ if ("Character".equals(boxedType)) {
+ return new Character(value.charAt(0));
+ } else {
+ Class<?> cls = ClassLoader.getSystemClassLoader().loadClass(javaType);
+ Constructor<?> ctor = cls.getConstructor(String.class);
+ return ctor.newInstance(value);
+ }
+ } catch (Exception e) {
+ LOG.warn("Could not create Endpoint Property of type " + type + " and value " + value);
+ return null;
+ }
+ }
+
+ public List<PropertyType> fromProps(Map<String, Object> m) {
+ List<PropertyType> props = new ArrayList<PropertyType>();
+ for (Map.Entry<String, Object> entry : m.entrySet()) {
+ String key = entry.getKey();
+ Object val = entry.getValue();
+
+ PropertyType propEl = new PropertyType();
+ propEl.setName(key);
+ ObjectFactory factory = new ObjectFactory();
+ if (val.getClass().isArray()) {
+ ArrayType arrayEl = new ArrayType();
+ propEl.getContent().add(factory.createArray(arrayEl));
+ for (Object o : normalizeArray(val)) {
+ setValueType(propEl, o);
+ ValueType valueType = new ValueType();
+ valueType.getContent().add(o.toString());
+ arrayEl.getValue().add(valueType);
+ }
+ } else if (val instanceof List) {
+ ArrayType listEl = new ArrayType();
+ propEl.getContent().add(factory.createList(listEl));
+ handleCollectionValue((Collection<?>) val, propEl, listEl);
+ } else if (val instanceof Set) {
+ ArrayType setEl = new ArrayType();
+ propEl.getContent().add(factory.createSet(setEl));
+ handleCollectionValue((Collection<?>) val, propEl, setEl);
+ } else if (val instanceof String
+ || val instanceof Character
+ || val instanceof Boolean
+ || val instanceof Byte) {
+ setValueType(propEl, val);
+ propEl.setValue(val.toString());
+ } else if (val instanceof Long
+ || val instanceof Double
+ || val instanceof Float
+ || val instanceof Integer
+ || val instanceof Short) {
+ // various numbers.. maybe "val instanceof Number"?
+ setValueType(propEl, val);
+ propEl.setValue(val.toString());
+ } else {
+ // Don't add this property as the value type is not supported
+ continue;
+ }
+ props.add(propEl);
+ }
+ return props;
+ }
+
+ private static Object[] normalizeArray(Object val) {
+ List<Object> l = new ArrayList<Object>();
+ if (val instanceof int[]) {
+ int[] ia = (int[]) val;
+ for (int i : ia) {
+ l.add(i);
+ }
+ } else if (val instanceof long[]) {
+ long[] la = (long[]) val;
+ for (long i : la) {
+ l.add(i);
+ }
+ } else if (val instanceof float[]) {
+ float[] fa = (float[]) val;
+ for (float f : fa) {
+ l.add(f);
+ }
+ } else if (val instanceof byte[]) {
+ byte[] ba = (byte[]) val;
+ for (byte b : ba) {
+ l.add(b);
+ }
+ } else if (val instanceof boolean[]) {
+ boolean[] ba = (boolean[]) val;
+ for (boolean b : ba) {
+ l.add(b);
+ }
+ } else if (val instanceof short[]) {
+ short[] sa = (short[]) val;
+ for (short s : sa) {
+ l.add(s);
+ }
+ } else if (val instanceof char[]) {
+ char[] ca = (char[]) val;
+ for (char c : ca) {
+ l.add(c);
+ }
+ } else {
+ return (Object[]) val;
+ }
+ return l.toArray();
+ }
+
+ private static void handleCollectionValue(Collection<?> val, PropertyType propEl, ArrayType listEl) {
+ for (Object o : val) {
+ setValueType(propEl, o);
+ ValueType valueType = new ValueType();
+ valueType.getContent().add(o.toString());
+ listEl.getValue().add(valueType);
+ }
+ }
+
+ private static void setValueType(PropertyType propEl, Object val) {
+ if (val instanceof String) {
+ return;
+ }
+
+ String dataType = val.getClass().getName();
+ if (dataType.startsWith("java.lang.")) {
+ dataType = dataType.substring("java.lang.".length());
+ }
+ propEl.setValueType(dataType);
+ }
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/5f4c6604/discovery/local/src/main/java/org/apache/aries/rsa/discovery/local/Activator.java
----------------------------------------------------------------------
diff --git a/discovery/local/src/main/java/org/apache/aries/rsa/discovery/local/Activator.java b/discovery/local/src/main/java/org/apache/aries/rsa/discovery/local/Activator.java
new file mode 100644
index 0000000..7ac9ee0
--- /dev/null
+++ b/discovery/local/src/main/java/org/apache/aries/rsa/discovery/local/Activator.java
@@ -0,0 +1,41 @@
+/**
+ * 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.aries.rsa.discovery.local;
+
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class Activator implements BundleActivator {
+
+ private static final Logger LOG = LoggerFactory.getLogger(Activator.class);
+
+ LocalDiscovery localDiscovery;
+
+ public synchronized void start(BundleContext context) {
+ localDiscovery = new LocalDiscovery(context);
+ LOG.info("Local D-OSGi service discovery started");
+ }
+
+ public synchronized void stop(BundleContext context) {
+ localDiscovery.shutDown();
+ LOG.info("Local D-OSGi service discovery stopped");
+ }
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/5f4c6604/discovery/local/src/main/java/org/apache/aries/rsa/discovery/local/LocalDiscovery.java
----------------------------------------------------------------------
diff --git a/discovery/local/src/main/java/org/apache/aries/rsa/discovery/local/LocalDiscovery.java b/discovery/local/src/main/java/org/apache/aries/rsa/discovery/local/LocalDiscovery.java
new file mode 100644
index 0000000..31f49ca
--- /dev/null
+++ b/discovery/local/src/main/java/org/apache/aries/rsa/discovery/local/LocalDiscovery.java
@@ -0,0 +1,258 @@
+/**
+ * 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.aries.rsa.discovery.local;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Dictionary;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.aries.rsa.discovery.endpoint.EndpointDescriptionBundleParser;
+import org.apache.aries.rsa.util.StringPlus;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.BundleEvent;
+import org.osgi.framework.BundleListener;
+import org.osgi.framework.Filter;
+import org.osgi.framework.ServiceReference;
+import org.osgi.service.remoteserviceadmin.EndpointDescription;
+import org.osgi.service.remoteserviceadmin.EndpointListener;
+import org.osgi.util.tracker.ServiceTracker;
+
+public class LocalDiscovery implements BundleListener {
+
+ // this is effectively a set which allows for multiple service descriptions with the
+ // same interface name but different properties and takes care of itself with respect to concurrency
+ ConcurrentHashMap<EndpointDescription, Bundle> endpointDescriptions =
+ new ConcurrentHashMap<EndpointDescription, Bundle>();
+ Map<EndpointListener, Collection<String>> listenerToFilters =
+ new HashMap<EndpointListener, Collection<String>>();
+ Map<String, Collection<EndpointListener>> filterToListeners =
+ new HashMap<String, Collection<EndpointListener>>();
+ final BundleContext bundleContext;
+
+ EndpointDescriptionBundleParser bundleParser;
+ ServiceTracker<EndpointListener, EndpointListener> listenerTracker;
+
+ public LocalDiscovery(BundleContext bc) {
+ this.bundleParser = new EndpointDescriptionBundleParser();
+ bundleContext = bc;
+
+ listenerTracker = new ServiceTracker<EndpointListener, EndpointListener>(bundleContext,
+ EndpointListener.class, null) {
+
+ @Override
+ public EndpointListener addingService(ServiceReference<EndpointListener> reference) {
+ EndpointListener service = super.addingService(reference);
+ addListener(reference, service);
+ return service;
+ }
+
+ @Override
+ public void modifiedService(ServiceReference<EndpointListener> reference, EndpointListener service) {
+ super.modifiedService(reference, service);
+ removeListener(service);
+
+ // This may cause duplicate registrations of remote services,
+ // but that's fine and should be filtered out on another level.
+ // See Remote Service Admin spec section 122.6.3
+ addListener(reference, service);
+ }
+
+ @Override
+ public void removedService(ServiceReference<EndpointListener> reference, EndpointListener service) {
+ super.removedService(reference, service);
+ removeListener(service);
+ }
+ };
+ listenerTracker.open();
+
+ bundleContext.addBundleListener(this);
+ processExistingBundles();
+ }
+
+ private void processExistingBundles() {
+ Bundle[] bundles = bundleContext.getBundles();
+ if (bundles == null) {
+ return;
+ }
+
+ for (Bundle b : bundles) {
+ if (b.getState() == Bundle.ACTIVE) {
+ findDeclaredRemoteServices(b);
+ }
+ }
+ }
+
+ void addListener(ServiceReference<EndpointListener> endpointListenerRef, EndpointListener endpointListener) {
+ List<String> filters = StringPlus.normalize(endpointListenerRef.getProperty(EndpointListener.ENDPOINT_LISTENER_SCOPE));
+ if (filters.isEmpty()) {
+ return;
+ }
+
+ synchronized (listenerToFilters) {
+ listenerToFilters.put(endpointListener, filters);
+ for (String filter : filters) {
+ Collection<EndpointListener> listeners = filterToListeners.get(filter);
+ if (listeners == null) {
+ listeners = new ArrayList<EndpointListener>();
+ filterToListeners.put(filter, listeners);
+ }
+ listeners.add(endpointListener);
+ }
+ }
+
+ triggerCallbacks(filters, endpointListener);
+ }
+
+ /**
+ * If the tracker was removed or the scope was changed this doesn't require
+ * additional callbacks on the tracker. Its the responsibility of the tracker
+ * itself to clean up any orphans. See Remote Service Admin spec 122.6.3
+ * @param endpointListener
+ */
+ void removeListener(EndpointListener endpointListener) {
+ synchronized (listenerToFilters) {
+ Collection<String> filters = listenerToFilters.remove(endpointListener);
+ if (filters == null) {
+ return;
+ }
+
+ for (String filter : filters) {
+ Collection<EndpointListener> listeners = filterToListeners.get(filter);
+ if (listeners != null) {
+ listeners.remove(endpointListener);
+ if (listeners.isEmpty()) {
+ filterToListeners.remove(filter);
+ }
+ }
+ }
+ }
+ }
+
+ private Map<String, Collection<EndpointListener>> getMatchingListeners(EndpointDescription endpoint) {
+ // return a copy of matched filters/listeners so that caller doesn't need to hold locks while triggering events
+ Map<String, Collection<EndpointListener>> matched = new HashMap<String, Collection<EndpointListener>>();
+ synchronized (listenerToFilters) {
+ for (Entry<String, Collection<EndpointListener>> entry : filterToListeners.entrySet()) {
+ String filter = entry.getKey();
+ if (LocalDiscovery.matchFilter(bundleContext, filter, endpoint)) {
+ matched.put(filter, new ArrayList<EndpointListener>(entry.getValue()));
+ }
+ }
+ }
+ return matched;
+ }
+
+ public void shutDown() {
+ bundleContext.removeBundleListener(this);
+ listenerTracker.close();
+ }
+
+ // BundleListener method
+ public void bundleChanged(BundleEvent be) {
+ switch (be.getType()) {
+ case BundleEvent.STARTED:
+ findDeclaredRemoteServices(be.getBundle());
+ break;
+ case BundleEvent.STOPPED:
+ removeServicesDeclaredInBundle(be.getBundle());
+ break;
+ default:
+ }
+ }
+
+ private void findDeclaredRemoteServices(Bundle bundle) {
+ List<EndpointDescription> endpoints = bundleParser.getAllEndpointDescriptions(bundle);
+ for (EndpointDescription endpoint : endpoints) {
+ endpointDescriptions.put(endpoint, bundle);
+ addedEndpointDescription(endpoint);
+ }
+ }
+
+ private void removeServicesDeclaredInBundle(Bundle bundle) {
+ for (Iterator<Entry<EndpointDescription, Bundle>> i = endpointDescriptions.entrySet().iterator();
+ i.hasNext();) {
+ Entry<EndpointDescription, Bundle> entry = i.next();
+ if (bundle.equals(entry.getValue())) {
+ removedEndpointDescription(entry.getKey());
+ i.remove();
+ }
+ }
+ }
+
+ private void addedEndpointDescription(EndpointDescription endpoint) {
+ triggerCallbacks(endpoint, true);
+ }
+
+ private void removedEndpointDescription(EndpointDescription endpoint) {
+ triggerCallbacks(endpoint, false);
+ }
+
+ private void triggerCallbacks(EndpointDescription endpoint, boolean added) {
+ for (Map.Entry<String, Collection<EndpointListener>> entry : getMatchingListeners(endpoint).entrySet()) {
+ String filter = entry.getKey();
+ for (EndpointListener listener : entry.getValue()) {
+ triggerCallbacks(listener, filter, endpoint, added);
+ }
+ }
+ }
+
+ private void triggerCallbacks(EndpointListener endpointListener, String filter,
+ EndpointDescription endpoint, boolean added) {
+ if (!LocalDiscovery.matchFilter(bundleContext, filter, endpoint)) {
+ return;
+ }
+
+ if (added) {
+ endpointListener.endpointAdded(endpoint, filter);
+ } else {
+ endpointListener.endpointRemoved(endpoint, filter);
+ }
+ }
+
+ private void triggerCallbacks(Collection<String> filters, EndpointListener endpointListener) {
+ for (String filter : filters) {
+ for (EndpointDescription endpoint : endpointDescriptions.keySet()) {
+ triggerCallbacks(endpointListener, filter, endpoint, true);
+ }
+ }
+ }
+
+ private static boolean matchFilter(BundleContext bctx, String filter, EndpointDescription endpoint) {
+ if (filter == null) {
+ return false;
+ }
+
+ try {
+ Filter f = bctx.createFilter(filter);
+ Dictionary<String, Object> dict = new Hashtable<String, Object>(endpoint.getProperties());
+ return f.match(dict);
+ } catch (Exception e) {
+ return false;
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/5f4c6604/discovery/local/src/main/java/org/apache/cxf/dosgi/discovery/local/internal/Activator.java
----------------------------------------------------------------------
diff --git a/discovery/local/src/main/java/org/apache/cxf/dosgi/discovery/local/internal/Activator.java b/discovery/local/src/main/java/org/apache/cxf/dosgi/discovery/local/internal/Activator.java
deleted file mode 100644
index 918f009..0000000
--- a/discovery/local/src/main/java/org/apache/cxf/dosgi/discovery/local/internal/Activator.java
+++ /dev/null
@@ -1,41 +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.cxf.dosgi.discovery.local.internal;
-
-import org.osgi.framework.BundleActivator;
-import org.osgi.framework.BundleContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class Activator implements BundleActivator {
-
- private static final Logger LOG = LoggerFactory.getLogger(Activator.class);
-
- LocalDiscovery localDiscovery;
-
- public synchronized void start(BundleContext context) {
- localDiscovery = new LocalDiscovery(context);
- LOG.info("Local D-OSGi service discovery started");
- }
-
- public synchronized void stop(BundleContext context) {
- localDiscovery.shutDown();
- LOG.info("Local D-OSGi service discovery stopped");
- }
-}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/5f4c6604/discovery/local/src/main/java/org/apache/cxf/dosgi/discovery/local/internal/LocalDiscovery.java
----------------------------------------------------------------------
diff --git a/discovery/local/src/main/java/org/apache/cxf/dosgi/discovery/local/internal/LocalDiscovery.java b/discovery/local/src/main/java/org/apache/cxf/dosgi/discovery/local/internal/LocalDiscovery.java
deleted file mode 100644
index 2761cf3..0000000
--- a/discovery/local/src/main/java/org/apache/cxf/dosgi/discovery/local/internal/LocalDiscovery.java
+++ /dev/null
@@ -1,242 +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.cxf.dosgi.discovery.local.internal;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.cxf.dosgi.discovery.local.util.Utils;
-import org.apache.cxf.dosgi.endpointdesc.EndpointDescriptionBundleParser;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.BundleEvent;
-import org.osgi.framework.BundleListener;
-import org.osgi.framework.ServiceReference;
-import org.osgi.service.remoteserviceadmin.EndpointDescription;
-import org.osgi.service.remoteserviceadmin.EndpointListener;
-import org.osgi.util.tracker.ServiceTracker;
-
-public class LocalDiscovery implements BundleListener {
-
- // this is effectively a set which allows for multiple service descriptions with the
- // same interface name but different properties and takes care of itself with respect to concurrency
- ConcurrentHashMap<EndpointDescription, Bundle> endpointDescriptions =
- new ConcurrentHashMap<EndpointDescription, Bundle>();
- Map<EndpointListener, Collection<String>> listenerToFilters =
- new HashMap<EndpointListener, Collection<String>>();
- Map<String, Collection<EndpointListener>> filterToListeners =
- new HashMap<String, Collection<EndpointListener>>();
- final BundleContext bundleContext;
-
- EndpointDescriptionBundleParser bundleParser;
- ServiceTracker<EndpointListener, EndpointListener> listenerTracker;
-
- public LocalDiscovery(BundleContext bc) {
- this.bundleParser = new EndpointDescriptionBundleParser();
- bundleContext = bc;
-
- listenerTracker = new ServiceTracker<EndpointListener, EndpointListener>(bundleContext,
- EndpointListener.class, null) {
-
- @Override
- public EndpointListener addingService(ServiceReference<EndpointListener> reference) {
- EndpointListener service = super.addingService(reference);
- addListener(reference, service);
- return service;
- }
-
- @Override
- public void modifiedService(ServiceReference<EndpointListener> reference, EndpointListener service) {
- super.modifiedService(reference, service);
- removeListener(service);
-
- // This may cause duplicate registrations of remote services,
- // but that's fine and should be filtered out on another level.
- // See Remote Service Admin spec section 122.6.3
- addListener(reference, service);
- }
-
- @Override
- public void removedService(ServiceReference<EndpointListener> reference, EndpointListener service) {
- super.removedService(reference, service);
- removeListener(service);
- }
- };
- listenerTracker.open();
-
- bundleContext.addBundleListener(this);
- processExistingBundles();
- }
-
- private void processExistingBundles() {
- Bundle[] bundles = bundleContext.getBundles();
- if (bundles == null) {
- return;
- }
-
- for (Bundle b : bundles) {
- if (b.getState() == Bundle.ACTIVE) {
- findDeclaredRemoteServices(b);
- }
- }
- }
-
- void addListener(ServiceReference<EndpointListener> endpointListenerRef, EndpointListener endpointListener) {
- List<String> filters = Utils.getStringPlusProperty(endpointListenerRef,
- EndpointListener.ENDPOINT_LISTENER_SCOPE);
- if (filters.isEmpty()) {
- return;
- }
-
- synchronized (listenerToFilters) {
- listenerToFilters.put(endpointListener, filters);
- for (String filter : filters) {
- Collection<EndpointListener> listeners = filterToListeners.get(filter);
- if (listeners == null) {
- listeners = new ArrayList<EndpointListener>();
- filterToListeners.put(filter, listeners);
- }
- listeners.add(endpointListener);
- }
- }
-
- triggerCallbacks(filters, endpointListener);
- }
-
- /**
- * If the tracker was removed or the scope was changed this doesn't require
- * additional callbacks on the tracker. Its the responsibility of the tracker
- * itself to clean up any orphans. See Remote Service Admin spec 122.6.3
- * @param endpointListener
- */
- void removeListener(EndpointListener endpointListener) {
- synchronized (listenerToFilters) {
- Collection<String> filters = listenerToFilters.remove(endpointListener);
- if (filters == null) {
- return;
- }
-
- for (String filter : filters) {
- Collection<EndpointListener> listeners = filterToListeners.get(filter);
- if (listeners != null) {
- listeners.remove(endpointListener);
- if (listeners.isEmpty()) {
- filterToListeners.remove(filter);
- }
- }
- }
- }
- }
-
- private Map<String, Collection<EndpointListener>> getMatchingListeners(EndpointDescription endpoint) {
- // return a copy of matched filters/listeners so that caller doesn't need to hold locks while triggering events
- Map<String, Collection<EndpointListener>> matched = new HashMap<String, Collection<EndpointListener>>();
- synchronized (listenerToFilters) {
- for (Entry<String, Collection<EndpointListener>> entry : filterToListeners.entrySet()) {
- String filter = entry.getKey();
- if (Utils.matchFilter(bundleContext, filter, endpoint)) {
- matched.put(filter, new ArrayList<EndpointListener>(entry.getValue()));
- }
- }
- }
- return matched;
- }
-
- public void shutDown() {
- bundleContext.removeBundleListener(this);
- listenerTracker.close();
- }
-
- // BundleListener method
- public void bundleChanged(BundleEvent be) {
- switch (be.getType()) {
- case BundleEvent.STARTED:
- findDeclaredRemoteServices(be.getBundle());
- break;
- case BundleEvent.STOPPED:
- removeServicesDeclaredInBundle(be.getBundle());
- break;
- default:
- }
- }
-
- private void findDeclaredRemoteServices(Bundle bundle) {
- List<EndpointDescription> endpoints = bundleParser.getAllEndpointDescriptions(bundle);
- for (EndpointDescription endpoint : endpoints) {
- endpointDescriptions.put(endpoint, bundle);
- addedEndpointDescription(endpoint);
- }
- }
-
- private void removeServicesDeclaredInBundle(Bundle bundle) {
- for (Iterator<Entry<EndpointDescription, Bundle>> i = endpointDescriptions.entrySet().iterator();
- i.hasNext();) {
- Entry<EndpointDescription, Bundle> entry = i.next();
- if (bundle.equals(entry.getValue())) {
- removedEndpointDescription(entry.getKey());
- i.remove();
- }
- }
- }
-
- private void addedEndpointDescription(EndpointDescription endpoint) {
- triggerCallbacks(endpoint, true);
- }
-
- private void removedEndpointDescription(EndpointDescription endpoint) {
- triggerCallbacks(endpoint, false);
- }
-
- private void triggerCallbacks(EndpointDescription endpoint, boolean added) {
- for (Map.Entry<String, Collection<EndpointListener>> entry : getMatchingListeners(endpoint).entrySet()) {
- String filter = entry.getKey();
- for (EndpointListener listener : entry.getValue()) {
- triggerCallbacks(listener, filter, endpoint, added);
- }
- }
- }
-
- private void triggerCallbacks(EndpointListener endpointListener, String filter,
- EndpointDescription endpoint, boolean added) {
- if (!Utils.matchFilter(bundleContext, filter, endpoint)) {
- return;
- }
-
- if (added) {
- endpointListener.endpointAdded(endpoint, filter);
- } else {
- endpointListener.endpointRemoved(endpoint, filter);
- }
- }
-
- private void triggerCallbacks(Collection<String> filters, EndpointListener endpointListener) {
- for (String filter : filters) {
- for (EndpointDescription endpoint : endpointDescriptions.keySet()) {
- triggerCallbacks(endpointListener, filter, endpoint, true);
- }
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/5f4c6604/discovery/local/src/main/java/org/apache/cxf/dosgi/discovery/local/util/Utils.java
----------------------------------------------------------------------
diff --git a/discovery/local/src/main/java/org/apache/cxf/dosgi/discovery/local/util/Utils.java b/discovery/local/src/main/java/org/apache/cxf/dosgi/discovery/local/util/Utils.java
deleted file mode 100644
index 990ae9f..0000000
--- a/discovery/local/src/main/java/org/apache/cxf/dosgi/discovery/local/util/Utils.java
+++ /dev/null
@@ -1,125 +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.cxf.dosgi.discovery.local.util;
-
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Dictionary;
-import java.util.Hashtable;
-import java.util.List;
-import java.util.regex.Pattern;
-
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.stream.StreamResult;
-import javax.xml.transform.stream.StreamSource;
-
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Filter;
-import org.osgi.framework.ServiceReference;
-import org.osgi.service.remoteserviceadmin.EndpointDescription;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public final class Utils {
-
- private static final Logger LOG = LoggerFactory.getLogger(Utils.class);
-
- private Utils() {
- // prevent instantiation
- }
-
- public static List<String> getStringPlusProperty(ServiceReference<?> sr, String key) {
- Object value = sr.getProperty(key);
- if (value == null) {
- return Collections.emptyList();
- }
-
- if (value instanceof String) {
- return Collections.singletonList((String) value);
- }
-
- if (value instanceof String[]) {
- String[] values = (String[]) value;
- List<String> result = new ArrayList<String>(values.length);
- for (String v : values) {
- if (v != null) {
- result.add(v);
- }
- }
- return Collections.unmodifiableList(result);
- }
-
- if (value instanceof Collection<?>) {
- Collection<?> values = (Collection<?>) value;
- List<String> result = new ArrayList<String>(values.size());
- for (Object v : values) {
- if (v instanceof String) {
- result.add((String) v);
- }
- }
- return Collections.unmodifiableList(result);
- }
-
- return Collections.emptyList();
- }
-
- public static boolean matchFilter(BundleContext bctx, String filter, EndpointDescription endpoint) {
- if (filter == null) {
- return false;
- }
-
- try {
- Filter f = bctx.createFilter(filter);
- Dictionary<String, Object> dict = new Hashtable<String, Object>(endpoint.getProperties());
- return f.match(dict);
- } catch (Exception e) {
- LOG.error("Problem creating a Filter from " + filter, e);
- return false;
- }
- }
-
- public static String normXML(String s) {
- String s2 = stripComment(s);
- String s3 = stripProlog(s2);
- try {
- TransformerFactory transFactory = TransformerFactory.newInstance();
- Transformer transformer = transFactory.newTransformer();
- StringWriter buffer = new StringWriter();
- transformer.setOutputProperty(OutputKeys.INDENT, "yes");
- transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
- transformer.transform(new StreamSource(new StringReader(s3)), new StreamResult(buffer));
- return buffer.toString();
- } catch (Exception e) {
- return "";
- }
- }
-
- private static String stripComment(String s) {
- return Pattern.compile("<!--(.*?)-->", Pattern.DOTALL).matcher(s).replaceAll("");
- }
-
- private static String stripProlog(String s) {
- return s.replaceAll("<\\?(.*?)\\?>", "");
- }
-}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/5f4c6604/discovery/local/src/main/java/org/apache/cxf/dosgi/endpointdesc/EndpointDescriptionBundleParser.java
----------------------------------------------------------------------
diff --git a/discovery/local/src/main/java/org/apache/cxf/dosgi/endpointdesc/EndpointDescriptionBundleParser.java b/discovery/local/src/main/java/org/apache/cxf/dosgi/endpointdesc/EndpointDescriptionBundleParser.java
deleted file mode 100644
index edeaeac..0000000
--- a/discovery/local/src/main/java/org/apache/cxf/dosgi/endpointdesc/EndpointDescriptionBundleParser.java
+++ /dev/null
@@ -1,104 +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.cxf.dosgi.endpointdesc;
-
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Dictionary;
-import java.util.Enumeration;
-import java.util.List;
-import java.util.Map;
-
-import org.osgi.framework.Bundle;
-import org.osgi.service.remoteserviceadmin.EndpointDescription;
-import org.osgi.xmlns.rsa.v1_0.EndpointDescriptionType;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public final class EndpointDescriptionBundleParser {
- private static final Logger LOG = LoggerFactory.getLogger(EndpointDescriptionBundleParser.class);
-
- private static final String REMOTE_SERVICES_HEADER_NAME = "Remote-Service";
- private static final String REMOTE_SERVICES_DIRECTORY = "OSGI-INF/remote-service/";
-
- private EndpointDescriptionParser parser;
-
- public EndpointDescriptionBundleParser() {
- parser = new EndpointDescriptionParser();
- }
-
- public List<EndpointDescription> getAllEndpointDescriptions(Bundle b) {
- List<EndpointDescriptionType> elements = getAllDescriptionElements(b);
-
- List<EndpointDescription> endpoints = new ArrayList<EndpointDescription>(elements.size());
- for (EndpointDescriptionType epd : elements) {
- Map<String, Object> props = new PropertiesMapper().toProps(epd.getProperty());
- endpoints.add(new EndpointDescription(props));
- }
- return endpoints;
- }
-
- List<EndpointDescriptionType> getAllDescriptionElements(Bundle b) {
- Enumeration<URL> urls = getEndpointDescriptionURLs(b);
- List<EndpointDescriptionType> elements = new ArrayList<EndpointDescriptionType>();
- while (urls.hasMoreElements()) {
- URL resourceURL = (URL) urls.nextElement();
- try {
- elements.addAll(parser.getEndpointDescriptions(resourceURL.openStream()));
- } catch (Exception ex) {
- LOG.warn("Problem parsing: " + resourceURL, ex);
- }
- }
- return elements;
- }
-
- Enumeration<URL> getEndpointDescriptionURLs(Bundle b) {
- String origDir = getRemoteServicesDir(b);
-
- // Split origDir into dir and file pattern
- String filePattern = "*.xml";
- String dir;
- if (origDir.endsWith("/")) {
- dir = origDir.substring(0, origDir.length() - 1);
- } else {
- int idx = origDir.lastIndexOf('/');
- if (idx >= 0 & origDir.length() > idx) {
- filePattern = origDir.substring(idx + 1);
- dir = origDir.substring(0, idx);
- } else {
- filePattern = origDir;
- dir = "";
- }
- }
-
- Enumeration<URL> urls = b.findEntries(dir, filePattern, false);
- return (urls == null) ? Collections.enumeration(new ArrayList<URL>()) : urls;
- }
-
- private static String getRemoteServicesDir(Bundle b) {
- Dictionary<?, ?> headers = b.getHeaders();
- Object header = null;
- if (headers != null) {
- header = headers.get(REMOTE_SERVICES_HEADER_NAME);
- }
- return (header == null) ? REMOTE_SERVICES_DIRECTORY : header.toString();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/5f4c6604/discovery/local/src/main/java/org/apache/cxf/dosgi/endpointdesc/EndpointDescriptionParser.java
----------------------------------------------------------------------
diff --git a/discovery/local/src/main/java/org/apache/cxf/dosgi/endpointdesc/EndpointDescriptionParser.java b/discovery/local/src/main/java/org/apache/cxf/dosgi/endpointdesc/EndpointDescriptionParser.java
deleted file mode 100644
index fb502c8..0000000
--- a/discovery/local/src/main/java/org/apache/cxf/dosgi/endpointdesc/EndpointDescriptionParser.java
+++ /dev/null
@@ -1,90 +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.cxf.dosgi.endpointdesc;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.List;
-
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBElement;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Marshaller;
-import javax.xml.bind.Unmarshaller;
-import javax.xml.namespace.QName;
-import javax.xml.transform.Source;
-import javax.xml.transform.stream.StreamSource;
-
-import org.osgi.xmlns.rsa.v1_0.EndpointDescriptionType;
-import org.osgi.xmlns.rsa.v1_0.EndpointDescriptionsType;
-
-public class EndpointDescriptionParser {
- private JAXBContext jaxbContext;
-
- public EndpointDescriptionParser() {
- try {
- jaxbContext = JAXBContext.newInstance(EndpointDescriptionsType.class.getPackage().getName(),
- this.getClass().getClassLoader());
- } catch (JAXBException e) {
- throw new RuntimeException(e.getMessage(), e);
- }
- }
-
- public List<EndpointDescriptionType> getEndpointDescriptions(InputStream is) {
- try {
- Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
- Source source = new StreamSource(is);
- JAXBElement<EndpointDescriptionsType> jaxb = unmarshaller.unmarshal(source, EndpointDescriptionsType.class);
- EndpointDescriptionsType decorations = jaxb.getValue();
- return decorations.getEndpointDescription();
- } catch (Exception ex) {
- throw new RuntimeException(ex.getMessage(), ex);
- }
- }
-
- public void writeTo(EndpointDescriptionsType endpointDescriptions, OutputStream os) {
- try {
- Marshaller marshaller = jaxbContext.createMarshaller();
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
- QName name = new QName("http://www.osgi.org/xmlns/rsa/v1.0.0", "endpoint-descriptions");
- JAXBElement<EndpointDescriptionsType> el =
- new JAXBElement<EndpointDescriptionsType>(name, EndpointDescriptionsType.class,
- endpointDescriptions);
- marshaller.marshal(el, os);
- } catch (Exception ex) {
- throw new RuntimeException(ex.getMessage(), ex);
- } finally {
- try {
- os.close();
- } catch (IOException e) {
- // Ignore
- }
- }
- }
-
- public byte[] getData(EndpointDescriptionType endpointDescription) {
- EndpointDescriptionsType endpointDescriptions = new EndpointDescriptionsType();
- endpointDescriptions.getEndpointDescription().add(endpointDescription);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- writeTo(endpointDescriptions, bos);
- return bos.toByteArray();
- }
-}
http://git-wip-us.apache.org/repos/asf/aries-rsa/blob/5f4c6604/discovery/local/src/main/java/org/apache/cxf/dosgi/endpointdesc/PropertiesMapper.java
----------------------------------------------------------------------
diff --git a/discovery/local/src/main/java/org/apache/cxf/dosgi/endpointdesc/PropertiesMapper.java b/discovery/local/src/main/java/org/apache/cxf/dosgi/endpointdesc/PropertiesMapper.java
deleted file mode 100644
index a7ed445..0000000
--- a/discovery/local/src/main/java/org/apache/cxf/dosgi/endpointdesc/PropertiesMapper.java
+++ /dev/null
@@ -1,345 +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.cxf.dosgi.endpointdesc;
-
-import java.io.Serializable;
-import java.io.StringWriter;
-import java.lang.reflect.Array;
-import java.lang.reflect.Constructor;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.xml.bind.JAXBElement;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-
-import org.w3c.dom.Node;
-import org.osgi.xmlns.rsa.v1_0.ArrayType;
-import org.osgi.xmlns.rsa.v1_0.ObjectFactory;
-import org.osgi.xmlns.rsa.v1_0.PropertyType;
-import org.osgi.xmlns.rsa.v1_0.ValueType;
-import org.osgi.xmlns.rsa.v1_0.XmlType;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class PropertiesMapper {
- private static final Logger LOG = LoggerFactory.getLogger(PropertiesMapper.class);
-
- public Map<String, Object> toProps(List<PropertyType> properties) {
- Map<String, Object> map = new HashMap<String, Object>();
- for (PropertyType prop : properties) {
- map.put(prop.getName(), getValue(prop));
- }
- return map;
- }
-
- private Object getValue(PropertyType prop) {
- Object value = null;
- String type = getTypeName(prop);
- Object content = getFirstNonText(prop.getContent());
- if (content instanceof JAXBElement<?>) {
- JAXBElement<?> el = (JAXBElement<?>)content;
- if (el.getDeclaredType() == ArrayType.class) {
- String elName = el.getName().getLocalPart();
- ArrayType inValue = (ArrayType)el.getValue();
- if ("array".equals(elName)) {
- value = getArray(inValue, type);
- } else if ("set".equals(elName)) {
- value = handleCollection(inValue, new HashSet<Object>(), type);
- } else if ("list".equals(elName)) {
- value = handleCollection(inValue, new ArrayList<Object>(), type);
- }
- } else if (el.getDeclaredType() == XmlType.class) {
- value = readXML((XmlType)el.getValue(), type);
- }
- } else {
- if (prop.getValue() != null) {
- value = instantiate(type, prop.getValue());
- } else {
- if (prop.getContent().size() > 0) {
- value = instantiate(type, prop.getContent().get(0).toString());
- }
- }
- }
- return value;
- }
-
- private Object getFirstNonText(List<Serializable> contentList) {
- for (Object content : contentList) {
- if (content instanceof JAXBElement<?>) {
- return content;
- }
- }
- return null;
- }
-
- private static String getTypeName(PropertyType prop) {
- String type = prop.getValueType();
- return type == null ? "String" : type;
- }
-
- private Object getArray(ArrayType arrayEl, String type) {
- List<ValueType> values = arrayEl.getValue();
- Class<?> cls = null;
- if ("long".equals(type)) {
- cls = long.class;
- } else if ("double".equals(type)) {
- cls = double.class;
- } else if ("float".equals(type)) {
- cls = float.class;
- } else if ("int".equals(type)) {
- cls = int.class;
- } else if ("byte".equals(type)) {
- cls = byte.class;
- } else if ("boolean".equals(type)) {
- cls = boolean.class;
- } else if ("short".equals(type)) {
- cls = short.class;
- }
-
- try {
- if (cls == null) {
- cls = ClassLoader.getSystemClassLoader().loadClass("java.lang." + type);
- }
- Object array = Array.newInstance(cls, values.size());
-
- for (int i = 0; i < values.size(); i++) {
- Object val = getValue(values.get(i), type);
- Array.set(array, i, val);
- }
-
- return array;
- } catch (Exception e) {
- LOG.warn("Could not create array for Endpoint Description", e);
- return null;
- }
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- private Collection handleCollection(ArrayType el, Collection value, String type) {
- List<ValueType> values = el.getValue();
- for (ValueType val : values) {
- Object obj = getValue(val, type);
- value.add(obj);
- }
- return value;
- }
-
- private Object getValue(ValueType value, String type) {
- if (value.getContent().size() == 1 && value.getContent().get(0) instanceof String) {
- return handleValue((String)value.getContent().get(0), type);
- }
- JAXBElement<?> valueContent = (JAXBElement<?>)getFirstNonText(value.getContent());
- if (valueContent.getDeclaredType() == XmlType.class) {
- return readXML((XmlType)valueContent.getValue(), type);
- }
- return "";
- }
-
- private String readXML(XmlType el, String type) {
- if (el == null) {
- return null;
- }
- if (!"String".equals(type)) {
- LOG.warn("Embedded XML must be of type String, found: " + type);
- return null;
- }
- Node xmlContent = (Node)el.getAny();
- xmlContent.normalize();
- try {
- TransformerFactory transFactory = TransformerFactory.newInstance();
- Transformer transformer = transFactory.newTransformer();
- StringWriter buffer = new StringWriter();
- transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
- transformer.transform(new DOMSource(xmlContent), new StreamResult(buffer));
- return buffer.toString();
- } catch (Exception e) {
- return "";
- }
- }
-
- private static Object handleValue(String val, String type) {
- return instantiate(type, val);
- }
-
- private static Object instantiate(String type, String value) {
- if ("String".equals(type)) {
- return value;
- }
-
- value = value.trim();
- String boxedType = null;
- if ("long".equals(type)) {
- boxedType = "Long";
- } else if ("double".equals(type)) {
- boxedType = "Double";
- } else if ("float".equals(type)) {
- boxedType = "Float";
- } else if ("int".equals(type)) {
- boxedType = "Integer";
- } else if ("byte".equals(type)) {
- boxedType = "Byte";
- } else if ("char".equals(type)) {
- boxedType = "Character";
- } else if ("boolean".equals(type)) {
- boxedType = "Boolean";
- } else if ("short".equals(type)) {
- boxedType = "Short";
- }
-
- if (boxedType == null) {
- boxedType = type;
- }
- String javaType = "java.lang." + boxedType;
-
- try {
- if ("Character".equals(boxedType)) {
- return new Character(value.charAt(0));
- } else {
- Class<?> cls = ClassLoader.getSystemClassLoader().loadClass(javaType);
- Constructor<?> ctor = cls.getConstructor(String.class);
- return ctor.newInstance(value);
- }
- } catch (Exception e) {
- LOG.warn("Could not create Endpoint Property of type " + type + " and value " + value);
- return null;
- }
- }
-
- public List<PropertyType> fromProps(Map<String, Object> m) {
- List<PropertyType> props = new ArrayList<PropertyType>();
- for (Map.Entry<String, Object> entry : m.entrySet()) {
- String key = entry.getKey();
- Object val = entry.getValue();
-
- PropertyType propEl = new PropertyType();
- propEl.setName(key);
- ObjectFactory factory = new ObjectFactory();
- if (val.getClass().isArray()) {
- ArrayType arrayEl = new ArrayType();
- propEl.getContent().add(factory.createArray(arrayEl));
- for (Object o : normalizeArray(val)) {
- setValueType(propEl, o);
- ValueType valueType = new ValueType();
- valueType.getContent().add(o.toString());
- arrayEl.getValue().add(valueType);
- }
- } else if (val instanceof List) {
- ArrayType listEl = new ArrayType();
- propEl.getContent().add(factory.createList(listEl));
- handleCollectionValue((Collection<?>) val, propEl, listEl);
- } else if (val instanceof Set) {
- ArrayType setEl = new ArrayType();
- propEl.getContent().add(factory.createSet(setEl));
- handleCollectionValue((Collection<?>) val, propEl, setEl);
- } else if (val instanceof String
- || val instanceof Character
- || val instanceof Boolean
- || val instanceof Byte) {
- setValueType(propEl, val);
- propEl.setValue(val.toString());
- } else if (val instanceof Long
- || val instanceof Double
- || val instanceof Float
- || val instanceof Integer
- || val instanceof Short) {
- // various numbers.. maybe "val instanceof Number"?
- setValueType(propEl, val);
- propEl.setValue(val.toString());
- } else {
- // Don't add this property as the value type is not supported
- continue;
- }
- props.add(propEl);
- }
- return props;
- }
-
- private static Object[] normalizeArray(Object val) {
- List<Object> l = new ArrayList<Object>();
- if (val instanceof int[]) {
- int[] ia = (int[]) val;
- for (int i : ia) {
- l.add(i);
- }
- } else if (val instanceof long[]) {
- long[] la = (long[]) val;
- for (long i : la) {
- l.add(i);
- }
- } else if (val instanceof float[]) {
- float[] fa = (float[]) val;
- for (float f : fa) {
- l.add(f);
- }
- } else if (val instanceof byte[]) {
- byte[] ba = (byte[]) val;
- for (byte b : ba) {
- l.add(b);
- }
- } else if (val instanceof boolean[]) {
- boolean[] ba = (boolean[]) val;
- for (boolean b : ba) {
- l.add(b);
- }
- } else if (val instanceof short[]) {
- short[] sa = (short[]) val;
- for (short s : sa) {
- l.add(s);
- }
- } else if (val instanceof char[]) {
- char[] ca = (char[]) val;
- for (char c : ca) {
- l.add(c);
- }
- } else {
- return (Object[]) val;
- }
- return l.toArray();
- }
-
- private static void handleCollectionValue(Collection<?> val, PropertyType propEl, ArrayType listEl) {
- for (Object o : val) {
- setValueType(propEl, o);
- ValueType valueType = new ValueType();
- valueType.getContent().add(o.toString());
- listEl.getValue().add(valueType);
- }
- }
-
- private static void setValueType(PropertyType propEl, Object val) {
- if (val instanceof String) {
- return;
- }
-
- String dataType = val.getClass().getName();
- if (dataType.startsWith("java.lang.")) {
- dataType = dataType.substring("java.lang.".length());
- }
- propEl.setValueType(dataType);
- }
-}