felix-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From gno...@apache.org
Subject svn commit: r925279 [2/3] - in /felix/trunk: bundleplugin/ bundleplugin/src/main/java/org/apache/felix/bundleplugin/ bundleplugin/src/main/java/org/apache/felix/obrplugin/ bundleplugin/src/main/java/org/osgi/impl/bundle/obr/resource/ bundleplugin/src/t...
Date Fri, 19 Mar 2010 15:32:19 GMT
Added: felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/DataModelHelperImpl.java
URL: http://svn.apache.org/viewvc/felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/DataModelHelperImpl.java?rev=925279&view=auto
==============================================================================
--- felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/DataModelHelperImpl.java (added)
+++ felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/DataModelHelperImpl.java Fri Mar 19 15:32:17 2010
@@ -0,0 +1,1042 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.felix.bundlerepository.impl;
+
+import java.io.*;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Dictionary;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.jar.Attributes;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+import java.util.jar.JarInputStream;
+import java.util.jar.Manifest;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+import org.apache.felix.bundlerepository.Capability;
+import org.apache.felix.bundlerepository.DataModelHelper;
+import org.apache.felix.bundlerepository.Property;
+import org.apache.felix.bundlerepository.Repository;
+import org.apache.felix.bundlerepository.Requirement;
+import org.apache.felix.bundlerepository.Resource;
+import org.apache.felix.utils.filter.FilterImpl;
+import org.apache.felix.utils.manifest.Attribute;
+import org.apache.felix.utils.manifest.Clause;
+import org.apache.felix.utils.manifest.Directive;
+import org.apache.felix.utils.manifest.Parser;
+import org.apache.felix.utils.version.VersionCleaner;
+import org.apache.felix.utils.version.VersionRange;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.Constants;
+import org.osgi.framework.Filter;
+import org.osgi.framework.InvalidSyntaxException;
+import org.osgi.framework.Version;
+
+public class DataModelHelperImpl implements DataModelHelper
+{
+
+    public static final String BUNDLE_LICENSE = "Bundle-License";
+    public static final String BUNDLE_SOURCE = "Bundle-Source";
+
+    public Requirement requirement(String name, String filter)
+    {
+        RequirementImpl req = new RequirementImpl();
+        req.setName(name);
+        if (filter != null)
+        {
+            req.setFilter(filter);
+        }
+        return req;
+    }
+
+    public Filter filter(String filter)
+    {
+        try
+        {
+            return FilterImpl.newInstance(filter);
+        }
+        catch (InvalidSyntaxException e)
+        {
+            IllegalArgumentException ex = new IllegalArgumentException();
+            ex.initCause(e);
+            throw ex;
+        }
+    }
+
+    public Repository repository(final URL url) throws Exception
+    {
+        InputStream is = null;
+        BufferedReader br = null;
+
+        try
+        {
+            // Do it the manual way to have a chance to
+            // set request properties as proxy auth (EW).
+            URLConnection conn = url.openConnection();
+
+            // Support for http proxy authentication
+            String auth = System.getProperty("http.proxyAuth");
+            if ((auth != null) && (auth.length() > 0))
+            {
+                if ("http".equals(url.getProtocol()) || "https".equals(url.getProtocol()))
+                {
+                    String base64 = Base64Encoder.base64Encode(auth);
+                    conn.setRequestProperty("Proxy-Authorization", "Basic " + base64);
+                }
+            }
+
+            if (url.getPath().endsWith(".zip"))
+            {
+                ZipInputStream zin = new ZipInputStream(conn.getInputStream());
+                ZipEntry entry = zin.getNextEntry();
+                while (entry != null)
+                {
+                    if (entry.getName().equals("repository.xml"))
+                    {
+                        is = zin;
+                        break;
+                    }
+                    entry = zin.getNextEntry();
+                }
+            }
+            else
+            {
+                is = conn.getInputStream();
+            }
+
+            if (is != null)
+            {
+                RepositoryImpl repository = repository(is);
+                repository.setURI(url.toExternalForm());
+                return repository;
+            }
+            else
+            {
+                // This should not happen.
+                throw new Exception("Unable to get input stream for repository.");
+            }
+        }
+        finally
+        {
+            try
+            {
+                if (is != null)
+                {
+                    is.close();
+                }
+            }
+            catch (IOException ex)
+            {
+                // Not much we can do.
+            }
+        }
+    }
+
+    public RepositoryImpl repository(InputStream is) throws Exception
+    {
+        RepositoryParser parser = RepositoryParser.getParser();
+        RepositoryImpl repository = parser.parseRepository(is);
+        return repository;
+    }
+
+    public Repository repository(Resource[] resources)
+    {
+        return new RepositoryImpl(resources);
+    }
+
+    public Capability capability(String name, Map properties)
+    {
+        CapabilityImpl cap = new CapabilityImpl(name);
+        for (Iterator it = properties.entrySet().iterator(); it.hasNext();)
+        {
+            Map.Entry e = (Map.Entry) it.next();
+            cap.addProperty((String) e.getKey(), (String) e.getValue());
+        }
+        return cap;
+    }
+
+    public String writeRepository(Repository repository)
+    {
+        try
+        {
+            StringWriter sw = new StringWriter();
+            writeRepository(repository, sw);
+            return sw.toString();
+        }
+        catch (IOException e)
+        {
+            IllegalStateException ex = new IllegalStateException(e);
+            ex.initCause(e);
+            throw ex;
+        }
+    }
+
+    public void writeRepository(Repository repository, Writer writer) throws IOException
+    {
+        XmlWriter w = new XmlWriter(writer);
+        toXml(w, repository);
+    }
+
+    public String writeResource(Resource resource)
+    {
+        try
+        {
+            StringWriter sw = new StringWriter();
+            writeResource(resource, sw);
+            return sw.toString();
+        }
+        catch (IOException e)
+        {
+            IllegalStateException ex = new IllegalStateException(e);
+            ex.initCause(e);
+            throw ex;
+        }
+    }
+
+    public void writeResource(Resource resource, Writer writer) throws IOException
+    {
+        XmlWriter w = new XmlWriter(writer);
+        toXml(w, resource);
+    }
+
+    public String writeCapability(Capability capability)
+    {
+        try
+        {
+            StringWriter sw = new StringWriter();
+            writeCapability(capability, sw);
+            return sw.toString();
+        }
+        catch (IOException e)
+        {
+            IllegalStateException ex = new IllegalStateException(e);
+            ex.initCause(e);
+            throw ex;
+        }
+    }
+
+    public void writeCapability(Capability capability, Writer writer) throws IOException
+    {
+        XmlWriter w = new XmlWriter(writer);
+        toXml(w, capability);
+    }
+
+    public String writeRequirement(Requirement requirement)
+    {
+        try
+        {
+            StringWriter sw = new StringWriter();
+            writeRequirement(requirement, sw);
+            return sw.toString();
+        }
+        catch (IOException e)
+        {
+            IllegalStateException ex = new IllegalStateException(e);
+            ex.initCause(e);
+            throw ex;
+        }
+    }
+
+    public void writeRequirement(Requirement requirement, Writer writer) throws IOException
+    {
+        XmlWriter w = new XmlWriter(writer);
+        toXml(w, requirement);
+    }
+
+    public String writeProperty(Property property)
+    {
+        try
+        {
+            StringWriter sw = new StringWriter();
+            writeProperty(property, sw);
+            return sw.toString();
+        }
+        catch (IOException e)
+        {
+            IllegalStateException ex = new IllegalStateException(e);
+            ex.initCause(e);
+            throw ex;
+        }
+    }
+
+    public void writeProperty(Property property, Writer writer) throws IOException
+    {
+        XmlWriter w = new XmlWriter(writer);
+        toXml(w, property);
+    }
+
+    private static void toXml(XmlWriter w, Repository repository) throws IOException
+    {
+        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss.SSS");
+        w.element(RepositoryParser.REPOSITORY)
+            .attribute(RepositoryParser.NAME, repository.getName())
+            .attribute(RepositoryParser.LASTMODIFIED, format.format(new Date(repository.getLastModified())));
+
+        if (repository instanceof RepositoryImpl)
+        {
+            Referral[] referrals = ((RepositoryImpl) repository).getReferrals();
+            for (int i = 0; referrals != null && i < referrals.length; i++)
+            {
+                w.element(RepositoryParser.REFERRAL)
+                    .attribute(RepositoryParser.DEPTH, new Integer(referrals[i].getDepth()))
+                    .attribute(RepositoryParser.URL, referrals[i].getUrl())
+                    .end();
+            }
+        }
+
+        Resource[] resources = repository.getResources();
+        for (int i = 0; resources != null && i < resources.length; i++)
+        {
+            toXml(w, resources[i]);
+        }
+
+        w.end();
+    }
+
+    private static void toXml(XmlWriter w, Resource resource) throws IOException
+    {
+        w.element(RepositoryParser.RESOURCE)
+            .attribute(Resource.ID, resource.getId())
+            .attribute(Resource.SYMBOLIC_NAME, resource.getSymbolicName())
+            .attribute(Resource.PRESENTATION_NAME, resource.getPresentationName())
+            .attribute(Resource.URI, resource.getURI())
+            .attribute(Resource.VERSION, resource.getVersion().toString());
+
+        w.textElement(Resource.DESCRIPTION, resource.getProperties().get(Resource.DESCRIPTION))
+            .textElement(Resource.SIZE, resource.getProperties().get(Resource.SIZE))
+            .textElement(Resource.DOCUMENTATION_URI, resource.getProperties().get(Resource.DOCUMENTATION_URI))
+            .textElement(Resource.SOURCE_URI, resource.getProperties().get(Resource.SOURCE_URI))
+            .textElement(Resource.JAVADOC_URI, resource.getProperties().get(Resource.JAVADOC_URI))
+            .textElement(Resource.LICENSE_URI, resource.getProperties().get(Resource.LICENSE_URI));
+
+        String[] categories = resource.getCategories();
+        for (int i = 0; categories != null && i < categories.length; i++)
+        {
+            w.element(RepositoryParser.CATEGORY)
+                .attribute(RepositoryParser.ID, categories[i])
+                .end();
+        }
+        Capability[] capabilities = resource.getCapabilities();
+        for (int i = 0; capabilities != null && i < capabilities.length; i++)
+        {
+            toXml(w, capabilities[i]);
+        }
+        Requirement[] requirements = resource.getRequirements();
+        for (int i = 0; requirements != null && i < requirements.length; i++)
+        {
+            toXml(w, requirements[i]);
+        }
+        w.end();
+    }
+
+    private static void toXml(XmlWriter w, Capability capability) throws IOException
+    {
+        w.element(RepositoryParser.CAPABILITY)
+            .attribute(RepositoryParser.NAME, capability.getName());
+        Property[] props = capability.getProperties();
+        for (int j = 0; props != null && j < props.length; j++)
+        {
+            toXml(w, props[j]);
+        }
+        w.end();
+    }
+
+    private static void toXml(XmlWriter w, Property property) throws IOException
+    {
+        w.element(RepositoryParser.P)
+            .attribute(RepositoryParser.N, property.getName())
+            .attribute(RepositoryParser.T, property.getType())
+            .attribute(RepositoryParser.V, property.getValue())
+            .end();
+    }
+
+    private static void toXml(XmlWriter w, Requirement requirement) throws IOException
+    {
+        w.element(RepositoryParser.REQUIRE)
+            .attribute(RepositoryParser.NAME, requirement.getName())
+            .attribute(RepositoryParser.FILTER, requirement.getFilter())
+            .attribute(RepositoryParser.EXTEND, Boolean.toString(requirement.isExtend()))
+            .attribute(RepositoryParser.MULTIPLE, Boolean.toString(requirement.isMultiple()))
+            .attribute(RepositoryParser.OPTIONAL, Boolean.toString(requirement.isOptional()))
+            .text(requirement.getComment().trim())
+            .end();
+    }
+
+    public Resource createResource(final Bundle bundle)
+    {
+        final Dictionary dict = bundle.getHeaders();
+        return createResource(new Headers()
+        {
+            public String getHeader(String name)
+            {
+                return (String) dict.get(name);
+            }
+        });
+    }
+
+    public Resource createResource(final URL bundleUrl) throws IOException
+    {
+        ResourceImpl resource = createResource(new Headers()
+        {
+            private final Manifest manifest;
+            private Properties localization;
+            {
+                // Do not use a JarInputStream so that we can read the manifest even if it's not
+                // the first entry in the JAR.  
+                byte[] man = loadEntry(JarFile.MANIFEST_NAME);
+                if (man == null)
+                {
+                    throw new IllegalArgumentException("The specified url is not a valid jar (can't read manifest): " + bundleUrl);
+                }
+                manifest = new Manifest(new ByteArrayInputStream(man));
+            }
+            public String getHeader(String name)
+            {
+                String value = manifest.getMainAttributes().getValue(name);
+                if (value != null && value.startsWith("%"))
+                {
+                    if (localization == null)
+                    {
+                        try
+                        {
+                            localization = new Properties();
+                            String path = manifest.getMainAttributes().getValue(Constants.BUNDLE_LOCALIZATION);
+                            if (path == null)
+                            {
+                                path = Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME;
+                            }
+                            path += ".properties";
+                            byte[] loc = loadEntry(path);
+                            if (loc != null)
+                            {
+                                localization.load(new ByteArrayInputStream(loc));
+                            }
+                        }
+                        catch (IOException e)
+                        {
+                            // TODO: ?
+                        }
+                    }
+                    value = value.substring(1);
+                    value = localization.getProperty(value, value);
+                }
+                return value;
+            }
+            private byte[] loadEntry(String name) throws IOException
+            {
+                InputStream is = bundleUrl.openStream();
+                try
+                {
+                    ZipInputStream jis = new ZipInputStream(is);
+                    for (ZipEntry e = jis.getNextEntry(); e != null; e = jis.getNextEntry())
+                    {
+                        if (name.equalsIgnoreCase(e.getName()))
+                        {
+                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
+                            byte[] buf = new byte[1024];
+                            int n;
+                            while ((n = jis.read(buf, 0, buf.length)) > 0)
+                            {
+                                baos.write(buf, 0, n);
+                            }
+                            return baos.toByteArray();
+                        }
+                    }
+                }
+                finally
+                {
+                    is.close();
+                }
+                return null;
+            }
+        });
+        if (resource != null)
+        {
+            if ("file".equals(bundleUrl.getProtocol()))
+            {
+                try {
+                    File f = new File(bundleUrl.toURI());
+                    resource.put(Resource.SIZE, Long.toString(f.length()), null);
+                } catch (URISyntaxException e) {
+                    throw new RuntimeException(e);
+                }
+            }
+            resource.put(Resource.URI, bundleUrl.toExternalForm(), null);
+        }
+        return resource;
+    }
+
+    public Resource createResource(final Attributes attributes)
+    {
+        return createResource(new Headers()
+        {
+            public String getHeader(String name)
+            {
+                return attributes.getValue(name);
+            }
+        });
+    }
+
+    public ResourceImpl createResource(Headers headers)
+    {
+        String bsn = headers.getHeader(Constants.BUNDLE_SYMBOLICNAME);
+        if (bsn == null)
+        {
+            return null;
+        }
+        ResourceImpl resource = new ResourceImpl();
+        populate(headers, resource);
+        return resource;
+    }
+
+    static void populate(Headers headers, ResourceImpl resource)
+    {
+        String bsn = getSymbolicName(headers);
+        String v = getVersion(headers);
+
+        resource.put(Resource.ID, bsn + "/" + v);
+        resource.put(Resource.SYMBOLIC_NAME, bsn);
+        resource.put(Resource.VERSION, v);
+        if (headers.getHeader(Constants.BUNDLE_NAME) != null)
+        {
+            resource.put(Resource.PRESENTATION_NAME, headers.getHeader(Constants.BUNDLE_NAME));
+        }
+        if (headers.getHeader(Constants.BUNDLE_DESCRIPTION) != null)
+        {
+            resource.put(Resource.DESCRIPTION, headers.getHeader(Constants.BUNDLE_DESCRIPTION));
+        }
+        if (headers.getHeader(BUNDLE_LICENSE) != null)
+        {
+            resource.put(Resource.LICENSE_URI, headers.getHeader(BUNDLE_LICENSE));
+        }
+        if (headers.getHeader(Constants.BUNDLE_COPYRIGHT) != null)
+        {
+            resource.put(Resource.COPYRIGHT, headers.getHeader(Constants.BUNDLE_COPYRIGHT));
+        }
+        if (headers.getHeader(Constants.BUNDLE_DOCURL) != null)
+        {
+            resource.put(Resource.DOCUMENTATION_URI, headers.getHeader(Constants.BUNDLE_DOCURL));
+        }
+        if (headers.getHeader(BUNDLE_SOURCE) != null)
+        {
+            resource.put(Resource.SOURCE_URI, headers.getHeader(BUNDLE_SOURCE));
+        }
+
+        doSize(resource, headers);
+        doCategories(resource, headers);
+        doBundle(resource, headers);
+        doImportExportServices(resource, headers);
+        doFragment(resource, headers);
+        doRequires(resource, headers);
+        doExports(resource, headers);
+        doImports(resource, headers);
+        doExecutionEnvironment(resource, headers);
+    }
+
+    private static void doSize(ResourceImpl resource, Headers headers)
+    {
+        //To change body of created methods use File | Settings | File Templates.
+    }
+
+    private static void doCategories(ResourceImpl resource, Headers headers)
+    {
+        Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.BUNDLE_CATEGORY));
+        for (int i = 0; clauses != null && i < clauses.length; i++)
+        {
+            resource.addCategory(clauses[i].getName());
+        }
+    }
+
+    private static void doImportExportServices(ResourceImpl resource, Headers headers)
+    {
+        Clause[] imports = Parser.parseHeader(headers.getHeader(Constants.IMPORT_SERVICE));
+        for (int i = 0; imports != null && i < imports.length; i++) {
+            RequirementImpl ri = new RequirementImpl(Capability.SERVICE);
+            ri.setFilter(createServiceFilter(imports[i]));
+            ri.addText("Import Service " + imports[i].getName());
+
+            String avail = imports[i].getDirective("availability");
+            ri.setOptional("optional".equalsIgnoreCase(avail));
+            ri.setMultiple(true);
+            resource.addRequire(ri);
+        }
+
+        Clause[] exports = Parser.parseHeader(headers.getHeader(Constants.EXPORT_SERVICE));
+        for (int i = 0; exports != null && i < exports.length; i++) {
+            CapabilityImpl cap = createServiceCapability(exports[i]);
+            resource.addCapability(cap);
+        }
+    }
+
+    private static String createServiceFilter(Clause clause) {
+        String f = clause.getAttribute("filter");
+		StringBuffer filter = new StringBuffer();
+        if (f != null) {
+            filter.append("(&");
+        }
+        filter.append("(");
+        filter.append(Capability.SERVICE);
+        filter.append("=");
+		filter.append(clause.getName());
+		filter.append(")");
+        if (f != null) {
+            if (!f.startsWith("("))
+            {
+                filter.append("(").append(f).append(")");
+            }
+            else
+            {
+                filter.append(f);
+            }
+            filter.append(")");
+        }
+		return filter.toString();
+    }
+
+    private static CapabilityImpl createServiceCapability(Clause clause) {
+        CapabilityImpl capability = new CapabilityImpl(Capability.SERVICE);
+        capability.addProperty(Capability.SERVICE, clause.getName());
+        Attribute[] attributes = clause.getAttributes();
+        for (int i = 0; attributes != null && i < attributes.length; i++)
+        {
+            capability.addProperty(attributes[i].getName(), attributes[i].getValue());
+        }
+        return capability;
+    }
+
+    private static void doFragment(ResourceImpl resource, Headers headers)
+    {
+        // Check if we are a fragment
+        Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.FRAGMENT_HOST));
+        if (clauses != null && clauses.length == 1)
+        {
+            // We are a fragment, create a requirement
+            // to our host.
+            RequirementImpl r = new RequirementImpl(Capability.BUNDLE);
+            StringBuffer sb = new StringBuffer();
+            sb.append("(&(symbolicname=");
+            sb.append(clauses[0].getName());
+            sb.append(")");
+            appendVersion(sb, VersionRange.parseVersionRange(clauses[0].getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE)));
+            sb.append(")");
+            r.setFilter(sb.toString());
+            r.addText("Required Host " + clauses[0].getName());
+            r.setExtend(true);
+            r.setOptional(false);
+            r.setMultiple(false);
+            resource.addRequire(r);
+
+            // And insert a capability that we are available
+            // as a fragment. ### Do we need that with extend?
+            CapabilityImpl capability = new CapabilityImpl(Capability.FRAGMENT);
+            capability.addProperty("host", clauses[0].getName());
+            capability.addProperty("version", Property.VERSION, getVersion(clauses[0]));
+            resource.addCapability(capability);
+        }
+    }
+
+    private static void doRequires(ResourceImpl resource, Headers headers)
+    {
+        Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.REQUIRE_BUNDLE));
+        for (int i = 0; clauses != null && i < clauses.length; i++) {
+            RequirementImpl r = new RequirementImpl(Capability.BUNDLE);
+
+            VersionRange v = VersionRange.parseVersionRange(clauses[i].getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE));
+
+            StringBuffer sb = new StringBuffer();
+            sb.append("(&(symbolicname=");
+            sb.append(clauses[i].getName());
+            sb.append(")");
+            appendVersion(sb, v);
+            sb.append(")");
+            r.setFilter(sb.toString());
+
+            r.addText("Require Bundle " + clauses[i].getName() + "; " + v);
+            r.setOptional(Constants.RESOLUTION_OPTIONAL.equalsIgnoreCase(clauses[i].getDirective(Constants.RESOLUTION_DIRECTIVE)));
+            resource.addRequire(r);
+        }
+    }
+
+    private static void doBundle(ResourceImpl resource, Headers headers) {
+        CapabilityImpl capability = new CapabilityImpl(Capability.BUNDLE);
+        capability.addProperty(Resource.SYMBOLIC_NAME, getSymbolicName(headers));
+        if (headers.getHeader(Constants.BUNDLE_NAME) != null)
+        {
+            capability.addProperty(Resource.PRESENTATION_NAME, headers.getHeader(Constants.BUNDLE_NAME));
+        }
+        capability.addProperty(Resource.VERSION, Property.VERSION, getVersion(headers));
+        capability.addProperty(Resource.MANIFEST_VERSION, getManifestVersion(headers));
+        resource.addCapability(capability);
+    }
+
+    private static void doExports(ResourceImpl resource, Headers headers)
+    {
+        Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.EXPORT_PACKAGE));
+        for (int i = 0; clauses != null && i < clauses.length; i++)
+        {
+            CapabilityImpl capability = createCapability(Capability.PACKAGE, clauses[i]);
+            resource.addCapability(capability);
+        }
+    }
+
+    private static CapabilityImpl createCapability(String name, Clause clause)
+    {
+        CapabilityImpl capability = new CapabilityImpl(name);
+        capability.addProperty(name, clause.getName());
+        capability.addProperty(Resource.VERSION, Property.VERSION, getVersion(clause));
+        Attribute[] attributes = clause.getAttributes();
+        for (int i = 0; attributes != null && i < attributes.length; i++)
+        {
+            String key = attributes[i].getName();
+            if (key.equalsIgnoreCase(Constants.PACKAGE_SPECIFICATION_VERSION) || key.equalsIgnoreCase(Constants.VERSION_ATTRIBUTE))
+            {
+                continue;
+            }
+            else
+            {
+                String value = attributes[i].getValue();
+                capability.addProperty(key, value);
+            }
+        }
+        Directive[] directives = clause.getDirectives();
+        for (int i = 0; directives != null && i < directives.length; i++)
+        {
+            String key = directives[i].getName();
+            String value = directives[i].getValue();
+            capability.addProperty(key + ":", value);
+        }
+        return capability;
+    }
+
+    private static void doImports(ResourceImpl resource, Headers headers)
+    {
+        Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.IMPORT_PACKAGE));
+        for (int i = 0; clauses != null && i < clauses.length; i++)
+        {
+            RequirementImpl requirement = new RequirementImpl(Capability.PACKAGE);
+
+            createImportFilter(requirement, Capability.PACKAGE, clauses[i]);
+            requirement.addText("Import package " + clauses[i]);
+            requirement.setOptional(Constants.RESOLUTION_OPTIONAL.equalsIgnoreCase(clauses[i].getDirective(Constants.RESOLUTION_DIRECTIVE)));
+            resource.addRequire(requirement);
+        }
+    }
+
+    private static void createImportFilter(RequirementImpl requirement, String name, Clause clause)
+    {
+        StringBuffer filter = new StringBuffer();
+        filter.append("(&(");
+        filter.append(name);
+        filter.append("=");
+        filter.append(clause.getName());
+        filter.append(")");
+        appendVersion(filter, getVersionRange(clause));
+        Attribute[] attributes = clause.getAttributes();
+        Set attrs = doImportPackageAttributes(requirement, filter, attributes);
+
+        // The next code is using the subset operator
+        // to check mandatory attributes, it seems to be
+        // impossible to rewrite. It must assert that whateber
+        // is in mandatory: must be in any of the attributes.
+        // This is a fundamental shortcoming of the filter language.
+        if (attrs.size() > 0)
+        {
+            String del = "";
+            filter.append("(mandatory:<*");
+            for (Iterator i = attrs.iterator(); i.hasNext();)
+            {
+                filter.append(del);
+                filter.append(i.next());
+                del = ", ";
+            }
+            filter.append(")");
+        }
+        filter.append(")");
+        requirement.setFilter(filter.toString());
+    }
+
+    private static Set doImportPackageAttributes(RequirementImpl requirement, StringBuffer filter, Attribute[] attributes)
+    {
+        HashSet set = new HashSet();
+        for (int i = 0; attributes != null && i < attributes.length; i++)
+        {
+            String name = attributes[i].getName();
+            String value = attributes[i].getValue();
+            if (name.equalsIgnoreCase(Constants.PACKAGE_SPECIFICATION_VERSION) || name.equalsIgnoreCase(Constants.VERSION_ATTRIBUTE))
+            {
+                continue;
+            }
+            else if (name.equalsIgnoreCase(Constants.RESOLUTION_DIRECTIVE + ":"))
+            {
+                requirement.setOptional(Constants.RESOLUTION_OPTIONAL.equalsIgnoreCase(value));
+            }
+            if (name.endsWith(":"))
+            {
+                // Ignore
+            }
+            else
+            {
+                filter.append("(");
+                filter.append(name);
+                filter.append("=");
+                filter.append(value);
+                filter.append(")");
+                set.add(name);
+            }
+        }
+        return set;
+    }
+
+    private static void doExecutionEnvironment(ResourceImpl resource, Headers headers)
+    {
+        Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT));
+        if (clauses != null && clauses.length > 0)
+        {
+            StringBuffer sb = new StringBuffer();
+            sb.append("(|");
+            for (int i = 0; i < clauses.length; i++)
+            {
+                sb.append("(");
+                sb.append(Capability.EXECUTIONENVIRONMENT);
+                sb.append("=");
+                sb.append(clauses[i].getName());
+                sb.append(")");
+            }
+            sb.append(")");
+            RequirementImpl req = new RequirementImpl(Capability.EXECUTIONENVIRONMENT);
+            req.setFilter(sb.toString());
+            req.addText("Execution Environment " + sb.toString());
+            resource.addRequire(req);
+        }
+    }
+
+    private static String getVersion(Clause clause)
+    {
+        String v = clause.getAttribute(Constants.VERSION_ATTRIBUTE);
+        if (v == null)
+        {
+            v = clause.getAttribute(Constants.PACKAGE_SPECIFICATION_VERSION);
+        }
+        if (v == null)
+        {
+            v = clause.getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE);
+        }
+        return VersionCleaner.clean(v);
+    }
+
+    private static VersionRange getVersionRange(Clause clause)
+    {
+        String v = clause.getAttribute(Constants.VERSION_ATTRIBUTE);
+        if (v == null)
+        {
+            v = clause.getAttribute(Constants.PACKAGE_SPECIFICATION_VERSION);
+        }
+        if (v == null)
+        {
+            v = clause.getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE);
+        }
+        return VersionRange.parseVersionRange(v);
+    }
+
+    private static String getSymbolicName(Headers headers)
+    {
+        String bsn = headers.getHeader(Constants.BUNDLE_SYMBOLICNAME);
+        if (bsn == null)
+        {
+            bsn = headers.getHeader(Constants.BUNDLE_NAME);
+            if (bsn == null)
+            {
+                bsn = "Untitled-" + headers.hashCode();
+            }
+        }
+        Clause[] clauses = Parser.parseHeader(bsn);
+        return clauses[0].getName();
+    }
+
+    private static String getVersion(Headers headers)
+    {
+        String v = headers.getHeader(Constants.BUNDLE_VERSION);
+        return VersionCleaner.clean(v);
+    }
+
+    private static String getManifestVersion(Headers headers)
+    {
+        String v = headers.getHeader(Constants.BUNDLE_MANIFESTVERSION);
+        if (v == null)
+        {
+            v = "1";
+        }
+        return v;
+    }
+
+    private static void appendVersion(StringBuffer filter, VersionRange version)
+    {
+        if (version != null)
+        {
+            if ( !version.isOpenFloor() )
+            {
+                if ( !Version.emptyVersion.equals(version.getFloor()) )
+                {
+                    filter.append("(");
+                    filter.append(Constants.VERSION_ATTRIBUTE);
+                    filter.append(">=");
+                    filter.append(version.getFloor());
+                    filter.append(")");
+                }
+            }
+            else
+            {
+                filter.append("(!(");
+                filter.append(Constants.VERSION_ATTRIBUTE);
+                filter.append("<=");
+                filter.append(version.getFloor());
+                filter.append("))");
+            }
+
+            if (!VersionRange.INFINITE_VERSION.equals(version.getCeiling()))
+            {
+                if ( !version.isOpenCeiling() )
+                {
+                    filter.append("(");
+                    filter.append(Constants.VERSION_ATTRIBUTE);
+                    filter.append("<=");
+                    filter.append(version.getCeiling());
+                    filter.append(")");
+                }
+                else
+                {
+                    filter.append("(!(");
+                    filter.append(Constants.VERSION_ATTRIBUTE);
+                    filter.append(">=");
+                    filter.append(version.getCeiling());
+                    filter.append("))");
+                }
+            }
+        }
+    }
+
+    interface Headers
+    {
+        String getHeader(String name);
+    }
+
+    public Repository readRepository(String xml) throws Exception
+    {
+        try
+        {
+            return readRepository(new StringReader(xml));
+        }
+        catch (IOException e)
+        {
+            IllegalStateException ex = new IllegalStateException(e);
+            ex.initCause(e);
+            throw ex;
+        }
+    }
+
+    public Repository readRepository(Reader reader) throws Exception
+    {
+        return RepositoryParser.getParser().parseRepository(reader);
+    }
+
+    public Resource readResource(String xml) throws Exception
+    {
+        try
+        {
+            return readResource(new StringReader(xml));
+        }
+        catch (IOException e)
+        {
+            IllegalStateException ex = new IllegalStateException(e);
+            ex.initCause(e);
+            throw ex;
+        }
+    }
+
+    public Resource readResource(Reader reader) throws Exception
+    {
+        return RepositoryParser.getParser().parseResource(reader);
+    }
+
+    public Capability readCapability(String xml) throws Exception
+    {
+        try
+        {
+            return readCapability(new StringReader(xml));
+        }
+        catch (IOException e)
+        {
+            IllegalStateException ex = new IllegalStateException(e);
+            ex.initCause(e);
+            throw ex;
+        }
+    }
+
+    public Capability readCapability(Reader reader) throws Exception
+    {
+        return RepositoryParser.getParser().parseCapability(reader);
+    }
+
+    public Requirement readRequirement(String xml) throws Exception
+    {
+        try
+        {
+            return readRequirement(new StringReader(xml));
+        }
+        catch (IOException e)
+        {
+            IllegalStateException ex = new IllegalStateException(e);
+            ex.initCause(e);
+            throw ex;
+        }
+    }
+
+    public Requirement readRequirement(Reader reader) throws Exception
+    {
+        return RepositoryParser.getParser().parseRequirement(reader);
+    }
+
+    public Property readProperty(String xml) throws Exception
+    {
+        try
+        {
+            return readProperty(new StringReader(xml));
+        }
+        catch (IOException e)
+        {
+            IllegalStateException ex = new IllegalStateException(e);
+            ex.initCause(e);
+            throw ex;
+        }
+    }
+
+    public Property readProperty(Reader reader) throws Exception
+    {
+        return RepositoryParser.getParser().parseProperty(reader);
+    }
+}

Modified: felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/LocalRepositoryImpl.java
URL: http://svn.apache.org/viewvc/felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/LocalRepositoryImpl.java?rev=925279&r1=925278&r2=925279&view=diff
==============================================================================
--- felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/LocalRepositoryImpl.java (original)
+++ felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/LocalRepositoryImpl.java Fri Mar 19 15:32:17 2010
@@ -21,6 +21,7 @@ package org.apache.felix.bundlerepositor
 import java.util.HashMap;
 import java.util.Map;
 
+import org.apache.felix.utils.log.Logger;
 import org.osgi.framework.AllServiceListener;
 import org.osgi.framework.Bundle;
 import org.osgi.framework.BundleContext;

Modified: felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/LocalResourceImpl.java
URL: http://svn.apache.org/viewvc/felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/LocalResourceImpl.java?rev=925279&r1=925278&r2=925279&view=diff
==============================================================================
--- felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/LocalResourceImpl.java (original)
+++ felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/LocalResourceImpl.java Fri Mar 19 15:32:17 2010
@@ -18,15 +18,11 @@
  */
 package org.apache.felix.bundlerepository.impl;
 
-import java.util.ArrayList;
 import java.util.Dictionary;
-import java.util.Enumeration;
 import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
 import java.util.Set;
-import java.util.StringTokenizer;
 
+import org.apache.felix.bundlerepository.Capability;
 import org.osgi.framework.Bundle;
 import org.osgi.framework.Constants;
 import org.osgi.framework.InvalidSyntaxException;
@@ -38,13 +34,6 @@ public class LocalResourceImpl extends R
 
     LocalResourceImpl(Bundle bundle) throws InvalidSyntaxException
     {
-        this(null, bundle);
-    }
-
-    LocalResourceImpl(ResourceImpl resource, Bundle bundle)
-        throws InvalidSyntaxException
-    {
-        super(resource);
         m_bundle = bundle;
         initialize();
     }
@@ -61,22 +50,16 @@ public class LocalResourceImpl extends R
 
     private void initialize() throws InvalidSyntaxException
     {
-        Dictionary dict = m_bundle.getHeaders();
-
-        // Convert bundle manifest header attributes to resource properties.
-        convertAttributesToProperties(dict);
-
-        // Convert properties to bundle capability
-        convertAttributesToBundleCapability();
-
-        // Convert import package declarations into requirements.
-        convertImportPackageToRequirement(dict);
+        final Dictionary dict = m_bundle.getHeaders();
 
-        // Convert import service declarations into requirements.
-        convertImportServiceToRequirement(dict);
-
-        // Convert export package declarations into capabilities.
-        convertExportPackageToCapability(dict);
+        DataModelHelperImpl.populate(new DataModelHelperImpl.Headers()
+        {
+            public String getHeader(String name)
+            {
+                return (String) dict.get(name);
+            }
+            public void close() { }
+        }, this);
 
         // Convert export service declarations and services into capabilities.
         convertExportServiceToCapability(dict, m_bundle);
@@ -85,23 +68,12 @@ public class LocalResourceImpl extends R
         if (m_bundle.getBundleId() == 0)
         {
             // set the execution environment(s) as Capability ee of the
-            // system bundle to resolve bundles with specifc requirements
+            // system bundle to resolve bundles with specific requirements
             String ee = m_bundle.getBundleContext().getProperty(Constants.FRAMEWORK_EXECUTIONENVIRONMENT);
             if (ee != null)
             {
-                StringTokenizer tokener = new StringTokenizer(ee, ",");
-                List eeList = new ArrayList();
-                while (tokener.hasMoreTokens())
-                {
-                    String eeName = tokener.nextToken().trim();
-                    if (eeName.length() > 0)
-                    {
-                        eeList.add(eeName);
-                    }
-                }
-                CapabilityImpl cap = new CapabilityImpl();
-                cap.setName("ee");
-                cap.addP("ee", eeList);
+                CapabilityImpl cap = new CapabilityImpl(Capability.EXECUTIONENVIRONMENT);
+                cap.addProperty(Capability.EXECUTIONENVIRONMENT, ee);
                 addCapability(cap);
             }
 
@@ -151,181 +123,10 @@ public class LocalResourceImpl extends R
         }
     }
 
-    private void convertAttributesToProperties(Dictionary dict)
-    {
-        for (Enumeration keys = dict.keys(); keys.hasMoreElements(); )
-        {
-            String key = (String) keys.nextElement();
-            if (key.equalsIgnoreCase(Constants.BUNDLE_SYMBOLICNAME))
-            {
-                String sn = (String) dict.get(key);
-                sn = sn.trim();
-                int index = sn.indexOf(";singleton:=true");
-                if (index != -1) {
-                    sn = sn.substring(0, index);
-                }
-                put(SYMBOLIC_NAME, sn);
-            }
-            else if (key.equalsIgnoreCase(Constants.BUNDLE_NAME))
-            {
-                put(PRESENTATION_NAME, (String) dict.get(key));
-            }
-            else if (key.equalsIgnoreCase(Constants.BUNDLE_VERSION))
-            {
-                put(VERSION, (String) dict.get(key));
-            }
-            else if (key.equalsIgnoreCase("Bundle-Source"))
-            {
-                put(SOURCE_URI, (String) dict.get(key));
-            }
-            else if (key.equalsIgnoreCase(Constants.BUNDLE_DESCRIPTION))
-            {
-                put(DESCRIPTION, (String) dict.get(key));
-            }
-            else if (key.equalsIgnoreCase(Constants.BUNDLE_DOCURL))
-            {
-                put(DOCUMENTATION_URI, (String) dict.get(key));
-            }
-            else if (key.equalsIgnoreCase(Constants.BUNDLE_COPYRIGHT))
-            {
-                put(COPYRIGHT, (String) dict.get(key));
-            }
-            else if (key.equalsIgnoreCase("Bundle-License"))
-            {
-                put(LICENSE_URI, (String) dict.get(key));
-            }
-        }
-    }
-
-    private void convertAttributesToBundleCapability()
-    {
-        CapabilityImpl cap = new CapabilityImpl();
-        cap.setName("bundle");
-        if (getPresentationName() != null) {
-            cap.addP(PRESENTATION_NAME, getPresentationName());
-        }
-        cap.addP(SYMBOLIC_NAME, getSymbolicName());
-        cap.addP(VERSION, getVersion());
-        addCapability(cap);
-    }
-
-    private void convertImportPackageToRequirement(Dictionary dict)
-        throws InvalidSyntaxException
-    {
-        String target = (String) dict.get(Constants.IMPORT_PACKAGE);
-        if (target != null)
-        {
-            R4Package[] pkgs = R4Package.parseImportOrExportHeader(target);
-            R4Import[] imports = new R4Import[pkgs.length];
-            for (int i = 0; i < pkgs.length; i++)
-            {
-                imports[i] = new R4Import(pkgs[i]);
-            }
-
-            for (int impIdx = 0; impIdx < imports.length; impIdx++)
-            {
-                RequirementImpl req = new RequirementImpl();
-                req.setMultiple("false");
-                req.setOptional(Boolean.toString(imports[impIdx].isOptional()));
-                req.setName("package");
-                req.addText("Import package " + imports[impIdx].toString());
-
-                String low = imports[impIdx].isLowInclusive()
-                            ? "(version>=" + imports[impIdx].getVersion() + ")"
-                            : "(!(version<=" + imports[impIdx].getVersion() + "))";
-
-                if (imports[impIdx].getVersionHigh() != null)
-                {
-                    String high = imports[impIdx].isHighInclusive()
-                        ? "(version<=" + imports[impIdx].getVersionHigh() + ")"
-                        : "(!(version>=" + imports[impIdx].getVersionHigh() + "))";
-                    req.setFilter("(&(package="
-                        + imports[impIdx].getName() + ")"
-                        + low + high + ")");
-                }
-                else
-                {
-                    req.setFilter(
-                        "(&(package="
-                        + imports[impIdx].getName() + ")"
-                        + low + ")");
-                }
-
-                addRequire(req);
-            }
-        }
-    }
-
-    private void convertImportServiceToRequirement(Dictionary dict)
-        throws InvalidSyntaxException
-    {
-        String target = (String) dict.get(Constants.IMPORT_SERVICE);
-        if (target != null)
-        {
-            R4Package[] pkgs = R4Package.parseImportOrExportHeader(target);
-            for (int pkgIdx = 0; (pkgs != null) && (pkgIdx < pkgs.length); pkgIdx++)
-            {
-                RequirementImpl req = new RequirementImpl();
-                req.setMultiple("false");
-                req.setName("service");
-                req.addText("Import service " + pkgs[pkgIdx].toString());
-                req.setFilter("(service="
-                    + pkgs[pkgIdx].getName() + ")");
-                addRequire(req);
-            }
-        }
-    }
-
-    private void convertExportPackageToCapability(Dictionary dict)
-    {
-        String target = (String) dict.get(Constants.EXPORT_PACKAGE);
-        if (target != null)
-        {
-            R4Package[] pkgs = R4Package.parseImportOrExportHeader(target);
-            for (int pkgIdx = 0; (pkgs != null) && (pkgIdx < pkgs.length); pkgIdx++)
-            {
-                CapabilityImpl cap = new CapabilityImpl();
-                cap.setName("package");
-                cap.addP(new PropertyImpl("package", null, pkgs[pkgIdx].getName()));
-                cap.addP(new PropertyImpl("version", "version", pkgs[pkgIdx].getVersion().toString()));
-                for (int i = 0; i < pkgs[pkgIdx].getAttributes().length; i++)
-                {
-                    R4Attribute attribute = pkgs[pkgIdx].getAttributes()[i];
-                    String key = attribute.getName();
-                    if (!key.equalsIgnoreCase("specification-version")
-                        && !key.equalsIgnoreCase("version"))
-                    {
-                        Object value = attribute.getValue();
-                        cap.addP(key, value);
-                    }
-                }
-                for (int i = 0; i < pkgs[pkgIdx].getDirectives().length; i++)
-                {
-                    R4Directive directive = pkgs[pkgIdx].getDirectives()[i];
-                    String key = directive.getName() + ":";
-                    Object value = directive.getValue();
-                    cap.addP(key, value);
-                }
-                addCapability(cap);
-            }
-        }
-    }
-
     private void convertExportServiceToCapability(Dictionary dict, Bundle bundle)
     {
         Set services = new HashSet();
 
-        // collect Export-Service
-        String target = (String) dict.get(Constants.EXPORT_SERVICE);
-        if (target != null)
-        {
-            R4Package[] pkgs = R4Package.parseImportOrExportHeader(target);
-            for (int pkgIdx = 0; (pkgs != null) && (pkgIdx < pkgs.length); pkgIdx++)
-            {
-                services.add(pkgs[pkgIdx].getName());
-            }
-        }
-
         // add actual registered services
         ServiceReference[] refs = bundle.getRegisteredServices();
         for (int i = 0; refs != null && i < refs.length; i++)
@@ -333,18 +134,14 @@ public class LocalResourceImpl extends R
             String[] cls = (String[]) refs[i].getProperty(Constants.OBJECTCLASS);
             for (int j = 0; cls != null && j < cls.length; j++)
             {
-                services.add(cls[j]);
+                CapabilityImpl cap = new CapabilityImpl();
+                cap.setName(Capability.SERVICE);
+                cap.addProperty(new PropertyImpl(Capability.SERVICE, null, cls[j]));
+                // TODO: add service properties
+                addCapability(cap);
             }
         }
-
-        // register capabilities for combined set
-        for (Iterator si = services.iterator(); si.hasNext();)
-        {
-            CapabilityImpl cap = new CapabilityImpl();
-            cap.setName("service");
-            cap.addP(new PropertyImpl("service", null, (String) si.next()));
-            addCapability(cap);
-        }
+        // TODO: check duplicates with service-export properties
     }
 
     public String toString()

Modified: felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/ObrCommandImpl.java
URL: http://svn.apache.org/viewvc/felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/ObrCommandImpl.java?rev=925279&r1=925278&r2=925279&view=diff
==============================================================================
--- felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/ObrCommandImpl.java (original)
+++ felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/ObrCommandImpl.java Fri Mar 19 15:32:17 2010
@@ -28,6 +28,7 @@ import org.apache.felix.bundlerepository
 import org.apache.felix.bundlerepository.Requirement;
 import org.apache.felix.bundlerepository.Resolver;
 import org.apache.felix.bundlerepository.Resource;
+import org.apache.felix.bundlerepository.impl.FileUtil;
 import org.apache.felix.shell.Command;
 import org.osgi.framework.*;
 
@@ -577,7 +578,7 @@ public class ObrCommandImpl implements C
             out.println("Capabilities:");
             for (int i = 0; i < caps.length; i++)
             {
-                out.println("   " + caps[i].getProperties());
+                out.println("   " + caps[i].getPropertiesAsMap());
             }
         }
     }

Modified: felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/ObrURLStreamHandlerService.java
URL: http://svn.apache.org/viewvc/felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/ObrURLStreamHandlerService.java?rev=925279&r1=925278&r2=925279&view=diff
==============================================================================
--- felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/ObrURLStreamHandlerService.java (original)
+++ felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/ObrURLStreamHandlerService.java Fri Mar 19 15:32:17 2010
@@ -26,6 +26,7 @@ import java.net.URLStreamHandler;
 import java.util.SortedMap;
 import java.util.TreeMap;
 
+import org.apache.felix.utils.log.Logger;
 import org.osgi.framework.Bundle;
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.Constants;

Modified: felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/PropertyImpl.java
URL: http://svn.apache.org/viewvc/felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/PropertyImpl.java?rev=925279&r1=925278&r2=925279&view=diff
==============================================================================
--- felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/PropertyImpl.java (original)
+++ felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/PropertyImpl.java Fri Mar 19 15:32:17 2010
@@ -18,83 +18,93 @@
  */
 package org.apache.felix.bundlerepository.impl;
 
-import java.net.MalformedURLException;
+import java.net.URI;
 import java.net.URL;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.StringTokenizer;
 
-import org.osgi.framework.Version;
-import org.osgi.service.obr.Resource;
+import org.apache.felix.bundlerepository.Property;
+import org.apache.felix.utils.version.VersionTable;
 
-public class PropertyImpl
+public class PropertyImpl implements Property
 {
-    private String m_name = null;
-    private String m_type = null;
-    private Object m_value = null;
-
-    public PropertyImpl()
-    {
-    }
+    private final String name;
+    private final String type;
+    private final String value;
 
     public PropertyImpl(String name, String type, String value)
     {
-        setN(name);
-        setT(type);
-        setV(value);
-    }
-
-    public void setN(String name)
-    {
-        m_name = name;
+        this.name = name;
+        this.type = type;
+        this.value = value;
     }
 
-    public String getN()
+    public String getName()
     {
-        return m_name;
-    }
-
-    public void setT(String type)
-    {
-        m_type = type;
-
-        // If there is an existing value, then convert
-        // it based on the new type.
-        if (m_value != null)
-        {
-            m_value = convertType(m_value.toString());
-        }
+        return name;
     }
 
-    public String getT()
+    public String getType()
     {
-        return m_type;
+        return type;
     }
 
-    public void setV(String value)
+    public String getValue()
     {
-        m_value = convertType(value);
+        return value;
     }
 
-    public Object getV()
+    public Object getConvertedValue()
     {
-        return m_value;
+        return convert(value, type);
     }
 
-    private Object convertType(String value)
+    private static Object convert(String value, String type)
     {
-        if ((m_type != null) && m_type.equalsIgnoreCase(Resource.VERSION))
-        {
-            return new Version(value);
-        }
-        else if ((m_type != null) && (m_type.equalsIgnoreCase(Resource.URL)))
+        try
         {
-            try
+            if (value != null && type != null)
             {
-                return new URL(value);
-            }
-            catch (MalformedURLException ex)
-            {
-                ex.printStackTrace();
+                if (VERSION.equalsIgnoreCase(type))
+                {
+                    return VersionTable.getVersion(value);
+                }
+                else if (URI.equalsIgnoreCase(type))
+                {
+                    return new URI(value);
+                }
+                else if (URL.equalsIgnoreCase(type))
+                {
+                    return new URL(value);
+                }
+                else if (LONG.equalsIgnoreCase(type))
+                {
+                    return new Long(value);
+                }
+                else if (DOUBLE.equalsIgnoreCase(type))
+                {
+                    return new Double(value);
+                }
+                else if (SET.equalsIgnoreCase(type))
+                {
+                    StringTokenizer st = new StringTokenizer(value, ",");
+                    Set s = new HashSet();
+                    while (st.hasMoreTokens())
+                    {
+                        s.add(st.nextToken().trim());
+                    }
+                    return s;
+                }
             }
+            return value;
+        }
+        catch (Exception e)
+        {
+            IllegalArgumentException ex = new IllegalArgumentException();
+            ex.initCause(e);
+            throw ex;
         }
-        return value;
     }
 }
\ No newline at end of file

Modified: felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/PullParser.java
URL: http://svn.apache.org/viewvc/felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/PullParser.java?rev=925279&r1=925278&r2=925279&view=diff
==============================================================================
--- felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/PullParser.java (original)
+++ felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/PullParser.java Fri Mar 19 15:32:17 2010
@@ -18,34 +18,99 @@
  */
 package org.apache.felix.bundlerepository.impl;
 
-import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStream;
-import java.io.InputStreamReader;
+import java.io.Reader;
 
 import org.kxml2.io.KXmlParser;
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
 
 /**
- * Repository XML parser based on StaX
+ * Repository XML xml based on StaX
  */
-public class PullParser implements RepositoryImpl.RepositoryParser
+public class PullParser extends RepositoryParser
 {
 
     public PullParser()
     {
     }
 
-    public void parse(RepositoryImpl repository, InputStream is) throws Exception
+    public RepositoryImpl parseRepository(InputStream is) throws Exception
     {
-        KXmlParser reader = new KXmlParser();
-        reader.setInput(new BufferedReader(new InputStreamReader(is)));
+        XmlPullParser reader = new KXmlParser();
+        reader.setInput(is, null);
         int event = reader.nextTag();
         if (event != XmlPullParser.START_TAG || !REPOSITORY.equals(reader.getName()))
         {
             throw new Exception("Expected element 'repository' at the root of the document");
         }
+        return parse(reader);
+    }
+
+    public RepositoryImpl parseRepository(Reader r) throws Exception
+    {
+        XmlPullParser reader = new KXmlParser();
+        reader.setInput(r);
+        int event = reader.nextTag();
+        if (event != XmlPullParser.START_TAG || !REPOSITORY.equals(reader.getName()))
+        {
+            throw new Exception("Expected element 'repository' at the root of the document");
+        }
+        return parse(reader);
+    }
+
+    public ResourceImpl parseResource(Reader r) throws Exception
+    {
+        XmlPullParser reader = new KXmlParser();
+        reader.setInput(r);
+        int event = reader.nextTag();
+        if (event != XmlPullParser.START_TAG || !RESOURCE.equals(reader.getName()))
+        {
+            throw new Exception("Expected element 'resource'");
+        }
+        return parseResource(reader);
+    }
+
+    public CapabilityImpl parseCapability(Reader r) throws Exception
+    {
+        XmlPullParser reader = new KXmlParser();
+        reader.setInput(r);
+        int event = reader.nextTag();
+        if (event != XmlPullParser.START_TAG || !CAPABILITY.equals(reader.getName()))
+        {
+            throw new Exception("Expected element 'capability'");
+        }
+        return parseCapability(reader);
+    }
+
+    public PropertyImpl parseProperty(Reader r) throws Exception
+    {
+        XmlPullParser reader = new KXmlParser();
+        reader.setInput(r);
+        int event = reader.nextTag();
+        if (event != XmlPullParser.START_TAG || !P.equals(reader.getName()))
+        {
+            throw new Exception("Expected element 'p'");
+        }
+        return parseProperty(reader);
+    }
+
+    public RequirementImpl parseRequirement(Reader r) throws Exception
+    {
+        XmlPullParser reader = new KXmlParser();
+        reader.setInput(r);
+        int event = reader.nextTag();
+        if (event != XmlPullParser.START_TAG || !REQUIRE.equals(reader.getName()))
+        {
+            throw new Exception("Expected element 'require'");
+        }
+        return parseRequire(reader);
+    }
+
+    public RepositoryImpl parse(XmlPullParser reader) throws Exception
+    {
+        RepositoryImpl repository = new RepositoryImpl();
         for (int i = 0, nb = reader.getAttributeCount(); i < nb; i++)
         {
             String name = reader.getAttributeName(i);
@@ -56,9 +121,10 @@ public class PullParser implements Repos
             }
             else if (LASTMODIFIED.equals(name))
             {
-                repository.setLastmodified(value);
+                repository.setLastModified(value);
             }
         }
+        int event;
         while ((event = reader.nextTag()) == XmlPullParser.START_TAG)
         {
             String element = reader.getName();
@@ -79,9 +145,10 @@ public class PullParser implements Repos
         }
         // Sanity check
         sanityCheckEndElement(reader, event, REPOSITORY);
+        return repository;
     }
 
-    private void sanityCheckEndElement(KXmlParser reader, int event, String element)
+    private void sanityCheckEndElement(XmlPullParser reader, int event, String element)
     {
         if (event != XmlPullParser.END_TAG || !element.equals(reader.getName()))
         {
@@ -89,7 +156,7 @@ public class PullParser implements Repos
         }
     }
 
-    private Referral parseReferral(KXmlParser reader) throws Exception
+    public Referral parseReferral(XmlPullParser reader) throws Exception
     {
         Referral referral = new Referral();
         for (int i = 0, nb = reader.getAttributeCount(); i < nb; i++)
@@ -109,7 +176,7 @@ public class PullParser implements Repos
         return referral;
     }
 
-    private ResourceImpl parseResource(KXmlParser reader) throws Exception
+    public ResourceImpl parseResource(XmlPullParser reader) throws Exception
     {
         ResourceImpl resource = new ResourceImpl();
         try
@@ -124,7 +191,7 @@ public class PullParser implements Repos
                 String element = reader.getName();
                 if (CATEGORY.equals(element))
                 {
-                    CategoryImpl category = parseCategory(reader);
+                    String category = parseCategory(reader);
                     resource.addCategory(category);
                 }
                 else if (CAPABILITY.equals(element))
@@ -175,21 +242,21 @@ public class PullParser implements Repos
         }
     }
 
-    private CategoryImpl parseCategory(KXmlParser reader) throws IOException, XmlPullParserException
+    public String parseCategory(XmlPullParser reader) throws IOException, XmlPullParserException
     {
-        CategoryImpl category = new CategoryImpl();
+        String id = null;
         for (int i = 0, nb = reader.getAttributeCount(); i < nb; i++)
         {
             if (ID.equals(reader.getAttributeName(i)))
             {
-                category.setId(reader.getAttributeValue(i));
+                id = reader.getAttributeValue(i);
             }
         }
         sanityCheckEndElement(reader, reader.nextTag(), CATEGORY);
-        return category;
+        return id;
     }
 
-    private CapabilityImpl parseCapability(KXmlParser reader) throws Exception
+    public CapabilityImpl parseCapability(XmlPullParser reader) throws Exception
     {
         CapabilityImpl capability = new CapabilityImpl();
         for (int i = 0, nb = reader.getAttributeCount(); i < nb; i++)
@@ -208,7 +275,7 @@ public class PullParser implements Repos
             if (P.equals(element))
             {
                 PropertyImpl prop = parseProperty(reader);
-                capability.addP(prop);
+                capability.addProperty(prop);
             }
             else
             {
@@ -220,7 +287,7 @@ public class PullParser implements Repos
         return capability;
     }
 
-    private PropertyImpl parseProperty(KXmlParser reader) throws Exception
+    public PropertyImpl parseProperty(XmlPullParser reader) throws Exception
     {
         String n = null, t = null, v = null;
         for (int i = 0, nb = reader.getAttributeCount(); i < nb; i++)
@@ -246,7 +313,7 @@ public class PullParser implements Repos
         return prop;
     }
 
-    private RequirementImpl parseRequire(KXmlParser reader) throws Exception
+    public RequirementImpl parseRequire(XmlPullParser reader) throws Exception
     {
         RequirementImpl requirement = new RequirementImpl();
         for (int i = 0, nb = reader.getAttributeCount(); i < nb; i++)
@@ -263,15 +330,15 @@ public class PullParser implements Repos
             }
             else if (EXTEND.equals(name))
             {
-                requirement.setExtend(value);
+                requirement.setExtend(Boolean.parseBoolean(value));
             }
             else if (MULTIPLE.equals(name))
             {
-                requirement.setMultiple(value);
+                requirement.setMultiple(Boolean.parseBoolean(value));
             }
             else if (OPTIONAL.equals(name))
             {
-                requirement.setOptional(value);
+                requirement.setOptional(Boolean.parseBoolean(value));
             }
         }
         int event;
@@ -300,17 +367,16 @@ public class PullParser implements Repos
         return requirement;
     }
 
-    private void ignoreTag(KXmlParser reader) throws IOException, XmlPullParserException {
+    public void ignoreTag(XmlPullParser reader) throws IOException, XmlPullParserException {
         int level = 1;
-        int event = 0;
         while (level > 0)
         {
-            event = reader.next();
-            if (event == XmlPullParser.START_TAG)
+            int eventType = reader.next();
+            if (eventType == XmlPullParser.START_TAG)
             {
                 level++;
             }
-            else if (event == XmlPullParser.END_TAG)
+            else if (eventType == XmlPullParser.END_TAG)
             {
                 level--;
             }

Modified: felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/RepositoryAdminImpl.java
URL: http://svn.apache.org/viewvc/felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/RepositoryAdminImpl.java?rev=925279&r1=925278&r2=925279&view=diff
==============================================================================
--- felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/RepositoryAdminImpl.java (original)
+++ felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/RepositoryAdminImpl.java Fri Mar 19 15:32:17 2010
@@ -19,19 +19,25 @@
 package org.apache.felix.bundlerepository.impl;
 
 import java.net.URL;
+import java.security.AccessController;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Comparator;
 import java.util.HashMap;
-import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.StringTokenizer;
 
 import org.apache.felix.bundlerepository.Capability;
+import org.apache.felix.bundlerepository.DataModelHelper;
 import org.apache.felix.bundlerepository.Requirement;
+import org.apache.felix.bundlerepository.Repository;
 import org.apache.felix.bundlerepository.Resolver;
 import org.apache.felix.bundlerepository.Resource;
+import org.apache.felix.utils.collections.MapToDictionary;
+import org.apache.felix.utils.log.Logger;
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.Filter;
 import org.osgi.framework.InvalidSyntaxException;
@@ -40,10 +46,11 @@ import org.apache.felix.bundlerepository
 
 public class RepositoryAdminImpl implements RepositoryAdmin
 {
-    static BundleContext m_context = null;
+    private final BundleContext m_context;
     private final Logger m_logger;
     private final SystemRepositoryImpl m_system;
     private final LocalRepositoryImpl m_local;
+    private final DataModelHelper m_helper = new DataModelHelperImpl();
     private Map m_repoMap = new HashMap();
     private boolean m_initialized = false;
 
@@ -61,12 +68,17 @@ public class RepositoryAdminImpl impleme
         m_local = new LocalRepositoryImpl(context, logger);
     }
 
-    public org.apache.felix.bundlerepository.Repository getLocalRepository()
+    public DataModelHelper getHelper()
+    {
+        return m_helper;
+    }
+
+    public Repository getLocalRepository()
     {
         return m_local;
     }
 
-    public org.apache.felix.bundlerepository.Repository getSystemRepository()
+    public Repository getSystemRepository()
     {
         return m_system;
     }
@@ -86,16 +98,46 @@ public class RepositoryAdminImpl impleme
         return addRepository(url, Integer.MAX_VALUE);
     }
 
-    public synchronized RepositoryImpl addRepository(URL url, int hopCount) throws Exception
+    public synchronized RepositoryImpl addRepository(final URL url, int hopCount) throws Exception
     {
         initialize();
 
         // If the repository URL is a duplicate, then we will just
         // replace the existing repository object with a new one,
         // which is effectively the same as refreshing the repository.
-        RepositoryImpl repo = new RepositoryImpl(this, url, hopCount, m_logger);
-        m_repoMap.put(url.toExternalForm(), repo);
-        return repo;
+        try
+        {
+            RepositoryImpl repository = (RepositoryImpl) AccessController.doPrivileged(new PrivilegedExceptionAction()
+            {
+                public Object run() throws Exception
+                {
+                    return m_helper.repository(url);
+                }
+            });
+            m_repoMap.put(url.toExternalForm(), repository);
+
+            // resolve referrals
+            hopCount--;
+            if (hopCount > 0 && repository.getReferrals() != null)
+            {
+                for (int i = 0; i < repository.getReferrals().length; i++)
+                {
+                    Referral referral = repository.getReferrals()[i];
+
+                    URL referralUrl = new URL(url, referral.getUrl());
+                    hopCount = (referral.getDepth() > hopCount) ? hopCount : referral.getDepth();
+
+                    addRepository(referralUrl, hopCount);
+                }
+            }
+
+            return repository;
+        }
+        catch (PrivilegedActionException ex)
+        {
+            throw (Exception) ex.getCause();
+        }
+
     }
 
     public synchronized boolean removeRepository(String uri)
@@ -138,7 +180,7 @@ public class RepositoryAdminImpl impleme
     {
         initialize();
 
-        Filter filter = filterExpr != null ? filter(filterExpr) : null;
+        Filter filter = filterExpr != null ? m_helper.filter(filterExpr) : null;
         Resource[] resources;
         MapToDictionary dict = new MapToDictionary(null);
         Repository[] repos = listRepositories();
@@ -208,44 +250,6 @@ public class RepositoryAdminImpl impleme
         return resources;
     }
 
-    public Requirement requirement(String name, String filter) throws InvalidSyntaxException
-    {
-        RequirementImpl req = new RequirementImpl();
-        req.setName(name);
-        if (filter != null)
-        {
-            req.setFilter(filter);
-        }
-        return req;
-    }
-
-    public Filter filter(String filter) throws InvalidSyntaxException
-    {
-        return FilterImpl.newInstance(filter);
-    }
-
-    public Repository repository(URL url) throws Exception
-    {
-        return new RepositoryImpl(null, url, 0, m_logger);
-    }
-
-    public Repository repository(Resource[] resources) 
-    {
-        return new RepositoryImpl(resources);
-    }
-
-    public Capability capability(String name, Map properties)
-    {
-        CapabilityImpl cap = new CapabilityImpl();
-        cap.setName(name);
-        for (Iterator it = properties.entrySet().iterator(); it.hasNext();)
-        {
-            Map.Entry e = (Map.Entry) it.next();
-            cap.addP((String) e.getKey(), e.getValue());
-        }
-        return cap;
-    }
-
     private void initialize()
     {
         if (m_initialized)
@@ -280,4 +284,5 @@ public class RepositoryAdminImpl impleme
         }
 
     }
-}
\ No newline at end of file
+
+}

Modified: felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/RepositoryImpl.java
URL: http://svn.apache.org/viewvc/felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/RepositoryImpl.java?rev=925279&r1=925278&r2=925279&view=diff
==============================================================================
--- felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/RepositoryImpl.java (original)
+++ felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/RepositoryImpl.java Fri Mar 19 15:32:17 2010
@@ -18,83 +18,32 @@
  */
 package org.apache.felix.bundlerepository.impl;
 
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.lang.reflect.Method;
-import java.net.URL;
-import java.net.URLConnection;
-import java.security.AccessController;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
 import java.text.ParseException;
 import java.text.SimpleDateFormat;
-import java.util.ArrayList;
 import java.util.Collections;
-import java.util.List;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipInputStream;
+import java.util.Set;
+import java.util.TreeSet;
 
-import org.apache.felix.bundlerepository.Capability;
-import org.apache.felix.bundlerepository.Requirement;
 import org.apache.felix.bundlerepository.Resource;
 import org.apache.felix.bundlerepository.Repository;
+import org.apache.felix.bundlerepository.impl.ResourceImpl;
 
 public class RepositoryImpl implements Repository
 {
-    public static final String OBR_PARSER_CLASS = "obr.parser.class";
-    public static final String OBR_PARSER_CLASS_DEFAULT = "org.apache.felix.bundlerepository.impl.StaxParser";
-
     private String m_name = null;
-    private long m_lastmodified = 0;
+    private long m_lastmodified = System.currentTimeMillis();
     private String m_uri = null;
-    private final Logger m_logger;
     private Resource[] m_resources = null;
     private Referral[] m_referrals = null;
-    private RepositoryAdminImpl m_repoAdmin = null;
-    private List m_resourceList;
-
-    // Reusable comparator for sorting resources by name.
-    private ResourceComparator m_nameComparator = new ResourceComparator();
+    private Set m_resourceSet = new TreeSet(new ResourceComparator());
 
-    public RepositoryImpl(Resource[] resources)
+    public RepositoryImpl()
     {
-        m_repoAdmin = null;
-        m_uri = null;
-        m_logger = null;
-        m_resources = resources;
-        m_lastmodified = System.currentTimeMillis();
     }
 
-    public RepositoryImpl(RepositoryAdminImpl repoAdmin, URL url, Logger logger)
-        throws Exception
-    {
-        this(repoAdmin, url, Integer.MAX_VALUE, logger);
-    }
-
-    public RepositoryImpl(RepositoryAdminImpl repoAdmin, URL url, final int hopCount, Logger logger)
-        throws Exception
+    public RepositoryImpl(Resource[] resources)
     {
-        m_repoAdmin = repoAdmin;
-        m_uri = url.toExternalForm();
-        m_logger = logger;
-        m_resourceList = new ArrayList();
-        try
-        {
-            AccessController.doPrivileged(new PrivilegedExceptionAction()
-            {
-                public Object run() throws Exception
-                {
-                    parseRepositoryFile(hopCount);
-                    return null;
-                }
-            });
-        }
-        catch (PrivilegedActionException ex)
-        {
-            throw (Exception) ex.getCause();
-        }
+        m_resources = resources;
     }
 
     public String getURI()
@@ -109,9 +58,9 @@ public class RepositoryImpl implements R
 
     public Resource[] getResources()
     {
-        if (m_resources == null) {
-            Collections.sort(m_resourceList, m_nameComparator);
-            m_resources = (Resource[]) m_resourceList.toArray(new Resource[m_resourceList.size()]);
+        if (m_resources == null)
+        {
+            m_resources = (Resource[]) m_resourceSet.toArray(new Resource[m_resourceSet.size()]);
         }
         return m_resources;
     }
@@ -119,10 +68,14 @@ public class RepositoryImpl implements R
     public void addResource(Resource resource)
     {
         // Set resource's repository.
-        ((ResourceImpl) resource).setRepository(this);
+        if (resource instanceof ResourceImpl)
+        {
+            ((ResourceImpl) resource).setRepository(this);
+        }
 
         // Add to resource array.
-        m_resourceList.add(resource);
+        m_resourceSet.remove(resource);
+        m_resourceSet.add(resource);
         m_resources = null;
     }
 
@@ -162,7 +115,12 @@ public class RepositoryImpl implements R
         return m_lastmodified;
     }
 
-    public void setLastmodified(String s)
+    public void setLastModified(long lastModified)
+    {
+        m_lastmodified = lastModified;
+    }
+
+    public void setLastModified(String s)
     {
         SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss.SSS");
         try
@@ -184,136 +142,4 @@ public class RepositoryImpl implements R
         return null;
     }
 
-    protected void parseRepositoryFile(int hopCount) throws Exception
-    {
-        InputStream is = null;
-        BufferedReader br = null;
-
-        try
-        {
-            URL url = new URL(m_uri);
-            // Do it the manual way to have a chance to
-            // set request properties as proxy auth (EW).
-            URLConnection conn = url.openConnection();
-
-            // Support for http proxy authentication
-            String auth = System.getProperty("http.proxyAuth");
-            if ((auth != null) && (auth.length() > 0))
-            {
-                if ("http".equals(url.getProtocol()) || "https".equals(url.getProtocol()))
-                {
-                    String base64 = Util.base64Encode(auth);
-                    conn.setRequestProperty("Proxy-Authorization", "Basic " + base64);
-                }
-            }
-
-            if (url.getPath().endsWith(".zip"))
-            {
-                ZipInputStream zin = new ZipInputStream(conn.getInputStream());
-                ZipEntry entry = zin.getNextEntry();
-                while (entry != null)
-                {
-                    if (entry.getName().equals("repository.xml"))
-                    {
-                        is = zin;
-                        break;
-                    }
-                    entry = zin.getNextEntry();
-                }
-            }
-            else
-            {
-                is = conn.getInputStream();
-            }
-
-            if (is != null)
-            {
-                parseRepository(is);
-
-
-                // resolve referrals
-                hopCount--;
-                if (hopCount > 0 && m_referrals != null)
-                {
-                    for (int i = 0; i < m_referrals.length; i++)
-                    {
-                        Referral referral = m_referrals[i];
-
-                        URL referralUrl = new URL(url, referral.getUrl());
-                        hopCount = (referral.getDepth() > hopCount) ? hopCount : referral.getDepth();
-
-                        m_repoAdmin.addRepository(referralUrl, hopCount);
-                    }
-                }
-            }
-            else
-            {
-                // This should not happen.
-                throw new Exception("Unable to get input stream for repository.");
-            }
-        }
-        finally
-        {
-            try
-            {
-                if (is != null)
-                {
-                    is.close();
-                }
-            }
-            catch (IOException ex)
-            {
-                // Not much we can do.
-            }
-        }
-    }
-
-    protected void parseRepository(InputStream is) throws Exception
-    {
-        RepositoryParser parser = null;
-        try
-        {
-            String className = (String) RepositoryAdminImpl.m_context.getProperty(OBR_PARSER_CLASS);
-            if (className == null || className.length() == 0)
-            {
-                className = OBR_PARSER_CLASS_DEFAULT;
-            }
-            parser = (RepositoryParser) Class.forName(className).newInstance();
-        }
-        catch (Throwable t)
-        {
-        }
-        if (parser == null)
-        {
-            parser = new PullParser();
-
-        }
-        parser.parse(this, is);
-    }
-
-    public interface RepositoryParser
-    {
-        static final String REPOSITORY = "repository";
-        static final String NAME = "name";
-        static final String LASTMODIFIED = "lastmodified";
-        static final String REFERRAL = "referral";
-        static final String RESOURCE = "resource";
-        static final String DEPTH = "depth";
-        static final String URL = "url";
-        static final String CATEGORY = "category";
-        static final String ID = "id";
-        static final String CAPABILITY = "capability";
-        static final String REQUIRE = "require";
-        static final String P = "p";
-        static final String N = "n";
-        static final String T = "t";
-        static final String V = "v";
-        static final String FILTER = "filter";
-        static final String EXTEND = "extend";
-        static final String MULTIPLE = "multiple";
-        static final String OPTIONAL = "optional";
-
-        void parse(RepositoryImpl repository, InputStream is) throws Exception;
-    }
-
 }
\ No newline at end of file

Added: felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/RepositoryParser.java
URL: http://svn.apache.org/viewvc/felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/RepositoryParser.java?rev=925279&view=auto
==============================================================================
--- felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/RepositoryParser.java (added)
+++ felix/trunk/bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/RepositoryParser.java Fri Mar 19 15:32:17 2010
@@ -0,0 +1,86 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.felix.bundlerepository.impl;
+
+import java.io.InputStream;
+import java.io.Reader;
+
+public abstract class RepositoryParser
+{
+    public static final String REPOSITORY = "repository";
+    public static final String NAME = "name";
+    public static final String LASTMODIFIED = "lastmodified";
+    public static final String REFERRAL = "referral";
+    public static final String RESOURCE = "resource";
+    public static final String DEPTH = "depth";
+    public static final String URL = "url";
+    public static final String CATEGORY = "category";
+    public static final String ID = "id";
+    public static final String CAPABILITY = "capability";
+    public static final String REQUIRE = "require";
+    public static final String P = "p";
+    public static final String N = "n";
+    public static final String T = "t";
+    public static final String V = "v";
+    public static final String FILTER = "filter";
+    public static final String EXTEND = "extend";
+    public static final String MULTIPLE = "multiple";
+    public static final String OPTIONAL = "optional";
+
+    public static final String OBR_PARSER_CLASS = "obr.xml.class";
+
+    public static RepositoryParser getParser()
+    {
+        RepositoryParser parser = null;
+        try
+        {
+            String className = Activator.getContext() != null
+                                    ? Activator.getContext().getProperty(OBR_PARSER_CLASS)
+                                    : System.getProperty(OBR_PARSER_CLASS);
+            if (className != null && className.length() > 0)
+            {
+                parser = (RepositoryParser) Class.forName(className).newInstance();
+            }
+        }
+        catch (Throwable t)
+        {
+            // Ignore
+        }
+        if (parser == null)
+        {
+            parser = new PullParser();
+
+        }
+        return parser;
+    }
+
+
+    public abstract RepositoryImpl parseRepository(InputStream is) throws Exception;
+
+    public abstract RepositoryImpl parseRepository(Reader r) throws Exception;
+
+    public abstract ResourceImpl parseResource(Reader reader) throws Exception;
+
+    public abstract CapabilityImpl parseCapability(Reader reader) throws Exception;
+
+    public abstract PropertyImpl parseProperty(Reader reader) throws Exception;
+
+    public abstract RequirementImpl parseRequirement(Reader reader) throws Exception;
+
+}



Mime
View raw message