karaf-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ldywi...@apache.org
Subject svn commit: r1058123 - in /karaf/trunk: features/core/src/main/java/org/apache/karaf/features/internal/ features/core/src/main/resources/org/apache/karaf/features/ tooling/features-maven-plugin/ tooling/features-maven-plugin/src/main/java/org/apache/ka...
Date Wed, 12 Jan 2011 13:16:17 GMT
Author: ldywicki
Date: Wed Jan 12 13:16:16 2011
New Revision: 1058123

URL: http://svn.apache.org/viewvc?rev=1058123&view=rev
Log:
KARAF-379. Schema validation in validate mojo. Updated XML Schema. Now it allows to have empty
descriptor without repository and feature elements. Extracted FeatureValidationUtil used in
Maven plugin.

Added:
    karaf/trunk/features/core/src/main/java/org/apache/karaf/features/internal/FeatureValidationUtil.java
Modified:
    karaf/trunk/features/core/src/main/java/org/apache/karaf/features/internal/FeaturesServiceImpl.java
    karaf/trunk/features/core/src/main/resources/org/apache/karaf/features/karaf-features-1.0.0.xsd
    karaf/trunk/tooling/features-maven-plugin/pom.xml
    karaf/trunk/tooling/features-maven-plugin/src/main/java/org/apache/karaf/tooling/features/ValidateFeaturesMojo.java

Added: karaf/trunk/features/core/src/main/java/org/apache/karaf/features/internal/FeatureValidationUtil.java
URL: http://svn.apache.org/viewvc/karaf/trunk/features/core/src/main/java/org/apache/karaf/features/internal/FeatureValidationUtil.java?rev=1058123&view=auto
==============================================================================
--- karaf/trunk/features/core/src/main/java/org/apache/karaf/features/internal/FeatureValidationUtil.java
(added)
+++ karaf/trunk/features/core/src/main/java/org/apache/karaf/features/internal/FeatureValidationUtil.java
Wed Jan 12 13:16:16 2011
@@ -0,0 +1,75 @@
+/*
+ * 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.karaf.features.internal;
+
+import java.io.InputStream;
+import java.net.URI;
+import java.net.URLConnection;
+
+import javax.xml.XMLConstants;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.validation.Schema;
+import javax.xml.validation.SchemaFactory;
+import javax.xml.validation.Validator;
+
+import org.w3c.dom.Document;
+
+/**
+ * Utility class which fires XML Schema validation.
+ * 
+ * @author ldywicki
+ */
+public class FeatureValidationUtil {
+
+    /**
+     * Runs schema validation.
+     * 
+     * @param uri Uri to validate.
+     * @throws Exception When validation fails.
+     */
+    public static void validate(URI uri) throws Exception {
+        URLConnection conn = uri.toURL().openConnection();
+        conn.setDefaultUseCaches(false);
+
+        InputStream stream = conn.getInputStream();
+
+        // load document and check the root element for namespace declaration
+        DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
+        dFactory.setNamespaceAware(true);
+        Document doc = dFactory.newDocumentBuilder().parse(stream);
+
+        if (doc.getDocumentElement().getNamespaceURI() == null) {
+            return;
+        }
+
+        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+        // root element has namespace - we can use schema validation
+        Schema schema = factory.newSchema(new StreamSource(FeatureValidationUtil.class
+            .getResourceAsStream("/org/apache/karaf/features/karaf-features-1.0.0.xsd")));
+
+        // create schema by reading it from an XSD file:
+        Validator validator = schema.newValidator();
+
+        try {
+            validator.validate(new DOMSource(doc));
+        } catch (Exception e) {
+            throw new IllegalArgumentException("Unable to validate " + uri, e);
+        }        
+    }
+
+}

Modified: karaf/trunk/features/core/src/main/java/org/apache/karaf/features/internal/FeaturesServiceImpl.java
URL: http://svn.apache.org/viewvc/karaf/trunk/features/core/src/main/java/org/apache/karaf/features/internal/FeaturesServiceImpl.java?rev=1058123&r1=1058122&r2=1058123&view=diff
==============================================================================
--- karaf/trunk/features/core/src/main/java/org/apache/karaf/features/internal/FeaturesServiceImpl.java
(original)
+++ karaf/trunk/features/core/src/main/java/org/apache/karaf/features/internal/FeaturesServiceImpl.java
Wed Jan 12 13:16:16 2011
@@ -182,33 +182,7 @@ public class FeaturesServiceImpl impleme
      * Validate repository.
      */
     public void validateRepository(URI uri) throws Exception {
-        URLConnection conn = uri.toURL().openConnection();
-        conn.setDefaultUseCaches(false);
-
-        InputStream stream = conn.getInputStream();
-
-        // load document and check the root element for namespace declaration
-        DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
-        dFactory.setNamespaceAware(true);
-        Document doc = dFactory.newDocumentBuilder().parse(stream);
-
-        if (doc.getDocumentElement().getNamespaceURI() == null) {
-            return;
-        }
-
-        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
-        // root element has namespace - we can use schema validation
-        Schema schema = factory.newSchema(new StreamSource(getClass().getResourceAsStream(
-            "/org/apache/karaf/features/karaf-features-1.0.0.xsd")));
-
-        // create schema by reading it from an XSD file:
-        Validator validator = schema.newValidator();
-
-        try {
-            validator.validate(new DOMSource(doc));
-        } catch (Exception e) {
-            throw new IllegalArgumentException("Unable to validate " + uri, e);
-        }
+        FeatureValidationUtil.validate(uri);
     }
 
     public void addRepository(URI uri) throws Exception {

Modified: karaf/trunk/features/core/src/main/resources/org/apache/karaf/features/karaf-features-1.0.0.xsd
URL: http://svn.apache.org/viewvc/karaf/trunk/features/core/src/main/resources/org/apache/karaf/features/karaf-features-1.0.0.xsd?rev=1058123&r1=1058122&r2=1058123&view=diff
==============================================================================
--- karaf/trunk/features/core/src/main/resources/org/apache/karaf/features/karaf-features-1.0.0.xsd
(original)
+++ karaf/trunk/features/core/src/main/resources/org/apache/karaf/features/karaf-features-1.0.0.xsd
Wed Jan 12 13:16:16 2011
@@ -36,22 +36,22 @@ name of repository. This name will be us
 of given feature.
             ]]></xs:documentation>
         </xs:annotation>
-        <xs:sequence>
-            <xs:element name="repository" type="xs:anyURI" minOccurs="0" maxOccurs="unbounded">
+        <xs:choice minOccurs="0" maxOccurs="unbounded">
+            <xs:element name="repository" type="xs:anyURI">
                 <xs:annotation>
                     <xs:documentation><![CDATA[
 Additional repositories where dependencies are stored.
                     ]]></xs:documentation>
                 </xs:annotation>
             </xs:element>
-            <xs:element name="feature" type="tns:feature" maxOccurs="unbounded">
+            <xs:element name="feature" type="tns:feature">
                 <xs:annotation>
                     <xs:documentation><![CDATA[
 Feature definition.
                     ]]></xs:documentation>
                 </xs:annotation>
             </xs:element>
-        </xs:sequence>
+        </xs:choice>
         <xs:attribute name="name" type="xs:string" />
     </xs:complexType>
 

Modified: karaf/trunk/tooling/features-maven-plugin/pom.xml
URL: http://svn.apache.org/viewvc/karaf/trunk/tooling/features-maven-plugin/pom.xml?rev=1058123&r1=1058122&r2=1058123&view=diff
==============================================================================
--- karaf/trunk/tooling/features-maven-plugin/pom.xml (original)
+++ karaf/trunk/tooling/features-maven-plugin/pom.xml Wed Jan 12 13:16:16 2011
@@ -41,6 +41,10 @@
 
     <dependencies>
       <dependency>
+        <groupId>org.slf4j</groupId>
+        <artifactId>slf4j-jdk14</artifactId>
+      </dependency>
+      <dependency>
         <groupId>org.apache.maven</groupId>
         <artifactId>maven-plugin-api</artifactId>
       </dependency>

Modified: karaf/trunk/tooling/features-maven-plugin/src/main/java/org/apache/karaf/tooling/features/ValidateFeaturesMojo.java
URL: http://svn.apache.org/viewvc/karaf/trunk/tooling/features-maven-plugin/src/main/java/org/apache/karaf/tooling/features/ValidateFeaturesMojo.java?rev=1058123&r1=1058122&r2=1058123&view=diff
==============================================================================
--- karaf/trunk/tooling/features-maven-plugin/src/main/java/org/apache/karaf/tooling/features/ValidateFeaturesMojo.java
(original)
+++ karaf/trunk/tooling/features-maven-plugin/src/main/java/org/apache/karaf/tooling/features/ValidateFeaturesMojo.java
Wed Jan 12 13:16:16 2011
@@ -33,6 +33,7 @@ import java.util.zip.ZipFile;
 import org.apache.karaf.features.BundleInfo;
 import org.apache.karaf.features.Feature;
 import org.apache.karaf.features.Repository;
+import org.apache.karaf.features.internal.FeatureValidationUtil;
 import org.apache.karaf.features.internal.RepositoryImpl;
 import org.apache.felix.utils.manifest.Clause;
 import org.apache.maven.artifact.Artifact;
@@ -140,7 +141,9 @@ public class ValidateFeaturesMojo extend
     public void execute() throws MojoExecutionException, MojoFailureException {
         try {
             prepare();
-            Repository repository = new RepositoryImpl(file.toURI());
+            URI uri = file.toURI();
+            Repository repository = new RepositoryImpl(uri);
+            schemaCheck(repository, uri);
             analyze(repository);
             validate(repository);
         } catch (Exception e) {
@@ -150,6 +153,21 @@ public class ValidateFeaturesMojo extend
 
     }
 
+    /**
+     * Checks feature repository with XML Schema.
+     * @param repository Repository object.
+     * @param uri Display URI.
+     */
+    private void schemaCheck(Repository repository, URI uri) {
+        try {
+            info(" - validation of %s", uri);
+            FeatureValidationUtil.validate(repository.getURI());
+        } catch (Exception e) {
+            error("Failed to validate repository %s. Schema validation fails. Fix errors
to continue validation",
+                e, uri);
+        }
+    }
+
     /*
      * Prepare for validation by determing system and Karaf exports
      */
@@ -173,18 +191,21 @@ public class ValidateFeaturesMojo extend
         
         // add the repositories from the plugin configuration
         if (repositories != null) {
-        	for (String uri : repositories) {
-        		getLog().info(String.format(" - adding repository from %s", uri));
-        		Repository dependency = new RepositoryImpl(URI.create(translateFromMaven(uri)));
-        		features.add(dependency.getFeatures());
-        		validateBundlesAvailable(dependency);
-        		analyzeExports(dependency);
-        	}
+            for (String uri : repositories) {
+                getLog().info(String.format(" - adding repository from %s", uri));
+                Repository dependency = new RepositoryImpl(URI.create(translateFromMaven(uri)));
+                schemaCheck(dependency, URI.create(uri));
+                features.add(dependency.getFeatures());
+                validateBundlesAvailable(dependency);
+                analyzeExports(dependency);
+            }
         }
 
         for (URI uri : repository.getRepositories()) {
             Artifact artifact = (Artifact) resolve(uri.toString());
             Repository dependency  = new RepositoryImpl(new File(localRepo.getBasedir(),
localRepo.pathOf(artifact)).toURI());
+
+            schemaCheck(dependency, uri);
             getLog().info(String.format(" - adding %d known features from %s", dependency.getFeatures().length,
uri));
             features.add(dependency.getFeatures());
             // we need to do this to get all the information ready for further processing
@@ -259,9 +280,9 @@ public class ValidateFeaturesMojo extend
     private void readSystemPackages() throws IOException {
         Properties properties = new Properties();
         if (karafConfig.equals("config.properties")) {
-        	properties.load(getClass().getClassLoader().getResourceAsStream("config.properties"));
+            properties.load(getClass().getClassLoader().getResourceAsStream("config.properties"));
         } else {
-        	properties.load(new FileInputStream(new File(karafConfig)));
+            properties.load(new FileInputStream(new File(karafConfig)));
         }
 
         String packages = (String) properties.get(jreVersion);
@@ -281,7 +302,7 @@ public class ValidateFeaturesMojo extend
         for (Feature feature : repository.getFeatures()) {
             Set<Clause> exports = new HashSet<Clause>();
             for (String bundle : getBundleLocations(feature)) {
-            	exports.addAll(getExports(getManifest(bundle, bundles.get(bundle))));
+                exports.addAll(getExports(getManifest(bundle, bundles.get(bundle))));
             }
             info("    scanning feature %s for exports", feature.getName());
             featureExports.put(feature.getName(), exports);
@@ -294,9 +315,9 @@ public class ValidateFeaturesMojo extend
     private void validateBundlesAvailable(Repository repository) throws Exception {
         for (Feature feature : repository.getFeatures()) {
             for (String bundle : getBundleLocations(feature)) {
-            	if (!isMavenProtocol(bundle) && skipNonMavenProtocols) {
-            		continue;
-            	}
+                if (!isMavenProtocol(bundle) && skipNonMavenProtocols) {
+                    continue;
+                }
                 // this will throw an exception if the artifact can not be resolved
                 final Object artifact = resolve(bundle);
                 bundles.put(bundle, artifact);
@@ -394,7 +415,7 @@ public class ValidateFeaturesMojo extend
      * Check if the artifact is an OSGi bundle
      */
     private boolean isBundle(String bundle, Object artifact) {
-    	if (artifact instanceof Artifact && "bundle".equals(((Artifact) artifact).getArtifactHandler().getPackaging()))
{
+        if (artifact instanceof Artifact && "bundle".equals(((Artifact) artifact).getArtifactHandler().getPackaging()))
{
             return true;
         } else {
             try {
@@ -415,17 +436,17 @@ public class ValidateFeaturesMojo extend
      */
     private Manifest getManifest(String bundle, Object artifact) throws ArtifactResolutionException,
ArtifactNotFoundException, 
                                                            ZipException, IOException {
-    	ZipFile file = null;
-    	if (!(artifact instanceof Artifact)) {
-    		//not resolved as mvn artifact, so it's non-mvn protocol, just use the CustomBundleURLStreamHandlerFactory
-    		// to open stream
-    		InputStream is = null;
-			try {
-				is = new BufferedInputStream(new URL(bundle).openStream());
-			} catch (Exception e){
-				e.printStackTrace();
-			}
-			try {
+        ZipFile file = null;
+        if (!(artifact instanceof Artifact)) {
+            //not resolved as mvn artifact, so it's non-mvn protocol, just use the CustomBundleURLStreamHandlerFactory
+            // to open stream
+            InputStream is = null;
+            try {
+                is = new BufferedInputStream(new URL(bundle).openStream());
+            } catch (Exception e){
+                e.printStackTrace();
+            }
+            try {
                 is.mark(256 * 1024);
                 JarInputStream jar = new JarInputStream(is);
                 Manifest m = jar.getManifest();
@@ -437,39 +458,39 @@ public class ValidateFeaturesMojo extend
             } finally {
                 is.close();
             }
-    	} else {
-    		Artifact mvnArtifact = (Artifact) artifact;
-			File localFile = new File(localRepo.pathOf(mvnArtifact));
-			if (localFile.exists()) {
-				// avoid going over to the repository if the file is already on
-				// the disk
-				file = new ZipFile(localFile);
-			} else {
-				resolver.resolve(mvnArtifact, remoteRepos, localRepo);
-				file = new ZipFile(mvnArtifact.getFile());
-			}
-			// let's replace syserr for now to hide warnings being issues by the Manifest reading
process
-	        PrintStream original = System.err;
-	        try {
-	            System.setErr(new PrintStream(new ByteArrayOutputStream()));
-	            Manifest manifest = new Manifest(file.getInputStream(file.getEntry("META-INF/MANIFEST.MF")));
-	            return manifest; 
-	        } finally {
-	            System.setErr(original);
-	        }
-    	}
+        } else {
+            Artifact mvnArtifact = (Artifact) artifact;
+            File localFile = new File(localRepo.pathOf(mvnArtifact));
+            if (localFile.exists()) {
+                // avoid going over to the repository if the file is already on
+                // the disk
+                file = new ZipFile(localFile);
+            } else {
+                resolver.resolve(mvnArtifact, remoteRepos, localRepo);
+                file = new ZipFile(mvnArtifact.getFile());
+            }
+            // let's replace syserr for now to hide warnings being issues by the Manifest
reading process
+            PrintStream original = System.err;
+            try {
+                System.setErr(new PrintStream(new ByteArrayOutputStream()));
+                Manifest manifest = new Manifest(file.getInputStream(file.getEntry("META-INF/MANIFEST.MF")));
+                return manifest; 
+            } finally {
+                System.setErr(original);
+            }
+        }
     }
 
     /*
      * Resolve an artifact, downloading it from remote repositories when necessary
      */
     private Object resolve(String bundle) throws Exception, ArtifactNotFoundException {
-    	if (!isMavenProtocol(bundle)) {
-    		return bundle;
-    	}
+        if (!isMavenProtocol(bundle)) {
+            return bundle;
+        }
         Artifact artifact = getArtifact(bundle);
         if (bundle.indexOf(MVN_REPO_SEPARATOR) >= 0) {
-        	if (bundle.startsWith(MVN_URI_PREFIX)) {
+            if (bundle.startsWith(MVN_URI_PREFIX)) {
                 bundle = bundle.substring(MVN_URI_PREFIX.length());
             }
             String repo = bundle.substring(0, bundle.indexOf(MVN_REPO_SEPARATOR));
@@ -482,7 +503,7 @@ public class ValidateFeaturesMojo extend
             resolver.resolve(artifact, remoteRepos, localRepo);
         }
         if (artifact == null) {
-        	throw new Exception("Unable to resolve artifact for uri " + bundle);
+            throw new Exception("Unable to resolve artifact for uri " + bundle);
         } else {
             return artifact;
         }
@@ -493,7 +514,7 @@ public class ValidateFeaturesMojo extend
      */
     private Artifact getArtifact(String uri) {
         // remove the mvn: prefix when necessary
-    	if (uri.startsWith(MVN_URI_PREFIX)) {
+        if (uri.startsWith(MVN_URI_PREFIX)) {
             uri = uri.substring(MVN_URI_PREFIX.length());
         }
         // remove the repository url when specified
@@ -517,7 +538,7 @@ public class ValidateFeaturesMojo extend
      * see if bundle url is start with mvn protocol
      */
     private boolean isMavenProtocol(String bundle) {
-    	return bundle.startsWith(MVN_URI_PREFIX);
+        return bundle.startsWith(MVN_URI_PREFIX);
     }
 
     /*



Mime
View raw message