You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@aries.apache.org by mn...@apache.org on 2009/12/23 15:27:29 UTC

svn commit: r893522 [1/2] - in /incubator/aries/trunk/application: application-api/ application-api/src/main/java/org/apache/aries/application/filesystem/ application-utils/ application-utils/src/main/java/org/apache/aries/application/filesystem/ appli...

Author: mnuttall
Date: Wed Dec 23 14:27:28 2009
New Revision: 893522

URL: http://svn.apache.org/viewvc?rev=893522&view=rev
Log:
ARIES-89: Implement application support: start parsing an enterprise bundle application

Added:
    incubator/aries/trunk/application/application-api/src/main/java/org/apache/aries/application/filesystem/
    incubator/aries/trunk/application/application-api/src/main/java/org/apache/aries/application/filesystem/IDirectory.java
    incubator/aries/trunk/application/application-api/src/main/java/org/apache/aries/application/filesystem/IFile.java
    incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/
    incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/
    incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/FileSystem.java
    incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/IOUtils.java
    incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/impl/
    incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/impl/DirectoryImpl.java
    incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/impl/FileImpl.java
    incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/impl/ZipDirectory.java
    incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/impl/ZipFileImpl.java
    incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/utils/internal/
    incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/utils/internal/MessageUtil.java
    incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/utils/manifest/BundleManifest.java
    incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/utils/manifest/ManifestDefaultsInjector.java
    incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/utils/manifest/ManifestHeaderProcessor.java
    incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/utils/messages/
    incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/utils/messages/APPUTILSmessages.properties
Modified:
    incubator/aries/trunk/application/application-api/pom.xml
    incubator/aries/trunk/application/application-utils/pom.xml

Modified: incubator/aries/trunk/application/application-api/pom.xml
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/application/application-api/pom.xml?rev=893522&r1=893521&r2=893522&view=diff
==============================================================================
--- incubator/aries/trunk/application/application-api/pom.xml (original)
+++ incubator/aries/trunk/application/application-api/pom.xml Wed Dec 23 14:27:28 2009
@@ -48,7 +48,8 @@
                     <instructions>
                         <Bundle-SymbolicName>${pom.groupId}.api</Bundle-SymbolicName>
                         <Export-Package>
-                            org.apache.aries.application;version="${pom.version}"
+                            org.apache.aries.application;version="${pom.version}",
+                            org.apache.aries.application.filesystem;version="${pom.version}"
                         </Export-Package>
                         <_versionpolicy>[$(version;==;$(@)),$(version;+;$(@)))</_versionpolicy>
                         <_removeheaders>Ignore-Package,Include-Resource,Private-Package,Bundle-DocURL</_removeheaders>

Added: incubator/aries/trunk/application/application-api/src/main/java/org/apache/aries/application/filesystem/IDirectory.java
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/application/application-api/src/main/java/org/apache/aries/application/filesystem/IDirectory.java?rev=893522&view=auto
==============================================================================
--- incubator/aries/trunk/application/application-api/src/main/java/org/apache/aries/application/filesystem/IDirectory.java (added)
+++ incubator/aries/trunk/application/application-api/src/main/java/org/apache/aries/application/filesystem/IDirectory.java Wed Dec 23 14:27:28 2009
@@ -0,0 +1,47 @@
+/*
+ * 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 WARRANTIESOR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.aries.application.filesystem;
+
+import java.util.List;
+
+/**
+ * A virtual directory in a file system.
+ */
+public interface IDirectory extends Iterable<IFile>, IFile
+{
+  /**
+   * @return the list of files in this directory. Files must be in this directory
+   *         and not in sub-directories.
+   */
+  public List<IFile> listFiles();
+  /**
+   * Gets the requested file under this directory. The file may be located any
+   * number of levels within this directory. The name is relative to this
+   * directory. If the file cannot be found it will return null.
+   * 
+   * @param name the name of the file.
+   * @return     the IFile, or null if no such file exists.
+   */
+  public IFile getFile(String name);
+  /**
+   * @return true if this IDirectory is the root of the virtual file system.
+   */
+  public boolean isRoot();
+}
\ No newline at end of file

Added: incubator/aries/trunk/application/application-api/src/main/java/org/apache/aries/application/filesystem/IFile.java
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/application/application-api/src/main/java/org/apache/aries/application/filesystem/IFile.java?rev=893522&view=auto
==============================================================================
--- incubator/aries/trunk/application/application-api/src/main/java/org/apache/aries/application/filesystem/IFile.java (added)
+++ incubator/aries/trunk/application/application-api/src/main/java/org/apache/aries/application/filesystem/IFile.java Wed Dec 23 14:27:28 2009
@@ -0,0 +1,83 @@
+/*
+ * 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 WARRANTIESOR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.aries.application.filesystem;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+
+/**
+ * A virtual file on the virtual file system. This may represent a file or a
+ * directory.
+ */
+public interface IFile
+{
+  /**
+   * @return the name of the file relative to the root of the virtual FS.
+   */
+  public String getName();
+  /**
+   * @return true iff this IFile is also an IDirectory
+   */
+  public boolean isDirectory();
+  /**
+   * @return true iff this IFile is not an IDirectory
+   */
+  public boolean isFile();
+  /**
+   * @return the last modified date of the file.
+   */
+  public long getLastModified();
+  /**
+   * @return the size of the file.
+   */
+  public long getSize();
+  
+  /**
+   * @return if this is a directory return this as an IDirectory, otherwise return null.
+   */
+  public IDirectory convert();
+  
+  /**
+   * @return returns the parent directory of this IFile, or null if this is the root.
+   */
+  public IDirectory getParent();
+  
+  /**
+   * The input stream returned by this method should always be closed after use.
+   * 
+   * @return An InputStream to read the file from.
+   * 
+   * @throws IOException
+   * @throws UnsupportedOperationException If the IFile is also an IDirectory.
+   */
+  public InputStream open() throws IOException, UnsupportedOperationException;
+  
+  /**
+   * @return the root of this file system.
+   */
+  public IDirectory getRoot();
+  /**
+   * @return a URL that can be used to get at this file at a later date.
+   * @throws MalformedURLException 
+   */
+  public URL toURL() throws MalformedURLException ;
+}

Modified: incubator/aries/trunk/application/application-utils/pom.xml
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/application/application-utils/pom.xml?rev=893522&r1=893521&r2=893522&view=diff
==============================================================================
--- incubator/aries/trunk/application/application-utils/pom.xml (original)
+++ incubator/aries/trunk/application/application-utils/pom.xml Wed Dec 23 14:27:28 2009
@@ -52,6 +52,11 @@
       	<artifactId>org.apache.aries.application.api</artifactId>
       	<version>1.0.0-incubating-SNAPSHOT</version>
       </dependency>
+      <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>slf4j-api</artifactId>
+            <version>1.4.3</version>
+      </dependency>
   </dependencies>
 
     <build>
@@ -72,10 +77,11 @@
                 <extensions>true</extensions>
                 <configuration>
                     <instructions>
-                        <Bundle-SymbolicName>${pom.groupId}.core</Bundle-SymbolicName>
+                        <Bundle-SymbolicName>${pom.groupId}.utils</Bundle-SymbolicName>
                         <Export-Package>
                             org.apache.aries.application;version="${pom.version}",
-                            org.apache.aries.application.utils;version="${pom.version}"
+                            org.apache.aries.application.utils;version="${pom.version}", 
+                            org.apache.aries.application.filesystem.utils;version="${pom.version}"
                         </Export-Package>
                         <_versionpolicy>[$(version;==;$(@)),$(version;+;$(@)))</_versionpolicy>
                         <_removeheaders>Ignore-Package,Include-Resource,Private-Package,Bundle-DocURL</_removeheaders>

Added: incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/FileSystem.java
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/FileSystem.java?rev=893522&view=auto
==============================================================================
--- incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/FileSystem.java (added)
+++ incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/FileSystem.java Wed Dec 23 14:27:28 2009
@@ -0,0 +1,67 @@
+/*
+ * 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 WARRANTIESOR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.aries.application.filesystem.utils;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+
+import org.apache.aries.application.filesystem.IDirectory;
+import org.apache.aries.application.filesystem.utils.impl.DirectoryImpl;
+import org.apache.aries.application.filesystem.utils.impl.ZipDirectory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * An abstraction of a file system. A file system can be a zip, or a directory.
+ */
+public class FileSystem {
+
+  private static final Logger _logger = LoggerFactory.getLogger("org.apache.aries.application.utils");
+
+  /**
+   * This method gets the IDirectory that represents the root of a virtual file
+   * system. The provided file can either identify a directory, or a zip file.
+   * 
+   * @param fs the zip file.
+   * @return   the root of the virtual FS.
+   */
+  public static IDirectory getFSRoot(File fs)
+  {
+    IDirectory dir = null;
+    
+    if (fs.exists()) {
+      if (fs.isDirectory()) {
+        dir = new DirectoryImpl(fs, fs);
+      } else if (fs.isFile()) {
+        try {
+          dir = new ZipDirectory(fs, fs);
+        } catch (IOException e) {
+          _logger.error ("IOException in IDirectory.getFSRoot", e);
+        }
+      }
+    }
+    else {
+      // since this method does not throw an exception but just returns null, make sure we do not lose the error
+      _logger.error("File not found in IDirectory.getFSRoot", new FileNotFoundException(fs.getPath()));
+    }
+    return dir;
+  }
+}

Added: incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/IOUtils.java
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/IOUtils.java?rev=893522&view=auto
==============================================================================
--- incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/IOUtils.java (added)
+++ incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/IOUtils.java Wed Dec 23 14:27:28 2009
@@ -0,0 +1,198 @@
+/*
+ * 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 WARRANTIESOR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.aries.application.filesystem.utils;
+
+import java.io.Closeable;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.jar.JarOutputStream;
+import java.util.jar.Manifest;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import org.apache.aries.application.utils.internal.MessageUtil;
+
+public class IOUtils
+{
+  /**
+   * Copy an InputStream to an OutputStream and close the InputStream afterwards.
+   */
+  public static void copy(InputStream in, OutputStream out) throws IOException
+  {
+    try {
+      int len;
+      byte[] b = new byte[1024];
+      while ((len = in.read(b)) != -1)
+        out.write(b,0,len);
+    }
+    finally {
+      close(in);
+    }
+  }
+  
+  /**
+   * Close some xStream for good :)
+   */
+  public static void close(Closeable c)
+  {
+    try {
+      if (c != null)
+        c.close();
+    }
+    catch (IOException e) { c=null; } //in other words do nothing in a language findbugs can understand 
+  }
+  
+  public static OutputStream getOutputStream(File outputDir, String relativePath) throws IOException
+  {
+    int lastSeparatorIndex = relativePath.replace(File.separatorChar,'/').lastIndexOf("/");
+    String dirName = null;
+    String fileName = null;
+    
+    File outputDirectory;
+    if (lastSeparatorIndex != -1)
+    {
+      dirName = relativePath.substring(0, lastSeparatorIndex);
+      fileName = relativePath.substring(lastSeparatorIndex + 1);
+
+      outputDirectory = new File(outputDir, dirName);
+      
+      if (!!!outputDirectory.exists() && !!!outputDirectory.mkdirs())
+        throw new IOException(MessageUtil.getMessage("APPUTILS0012E", relativePath));
+    }
+    else
+    {
+      outputDirectory = outputDir;
+      fileName = relativePath;
+    }
+    
+    File outputFile = new File(outputDirectory, fileName);
+    return new FileOutputStream(outputFile);
+  }
+  
+  /**
+   * Write the given InputStream to a file given by a root directory (outputDir) and a relative directory.
+   * Necessary subdirectories will be created. This method will close the supplied InputStream.
+   */
+  public static void writeOut(File outputDir, String relativePath, InputStream content) throws IOException
+  {
+    OutputStream out = null;
+    try {
+      out = getOutputStream(outputDir, relativePath);
+      IOUtils.copy(content, out);
+    }
+    finally {
+      close(out);
+    }
+  }
+  
+  /**
+   * Zip up all contents of rootDir (recursively) into targetFile
+   */
+  @SuppressWarnings("unchecked")
+  public static void zipUp(File rootDir, File targetFile) throws IOException
+  {
+    ZipOutputStream out = null; 
+    try {
+      out = new ZipOutputStream(new FileOutputStream(targetFile));
+      zipUpRecursive(out, "", rootDir, (Set<String>) Collections.EMPTY_SET);
+    }
+    finally {
+      close(out);
+    }
+  }
+  
+  /**
+   * Jar up all the contents of rootDir (recursively) into targetFile and add the manifest
+   */
+  public static void jarUp(File rootDir, File targetFile, Manifest manifest) throws IOException
+  {
+    JarOutputStream out = null;
+    try {
+      out = new JarOutputStream(new FileOutputStream(targetFile), manifest);
+      zipUpRecursive(out, "", rootDir, new HashSet<String>(Arrays.asList("META-INF/MANIFEST.MF")));
+    }
+    finally {
+      close(out);
+    }
+  }
+  
+  /**
+   * Helper method used by zipUp
+   */
+  private static void zipUpRecursive(ZipOutputStream out, String prefix, 
+      File directory, Set<String> filesToExclude) throws IOException
+  {
+    File[] files = directory.listFiles();
+    if (files != null) 
+    {
+      for (File f : files)
+      {        
+        String fileName; 
+        if (f.isDirectory())
+          fileName = prefix + f.getName() + "/";
+        else
+          fileName = prefix + f.getName();
+        
+        if (filesToExclude.contains(fileName))
+          continue;
+        
+        ZipEntry ze = new ZipEntry(fileName);
+        ze.setSize(f.length());
+        ze.setTime(f.lastModified());
+        out.putNextEntry(ze);
+
+        if (f.isDirectory()) 
+          zipUpRecursive(out, fileName, f, filesToExclude);
+        else 
+        {
+          IOUtils.copy(new FileInputStream(f), out);
+        }
+      }
+    }
+  }
+  
+  /**
+   * Do rm -rf
+   */
+  public static boolean deleteRecursive(File root)
+  {
+    if (!!!root.exists())
+      return false;
+    else if (root.isFile())
+      return root.delete();
+    else {
+      boolean result = true;
+      for (File f : root.listFiles())
+      {
+        result = deleteRecursive(f) && result;
+      }
+      return root.delete() && result;
+    }
+  }
+}
+

Added: incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/impl/DirectoryImpl.java
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/impl/DirectoryImpl.java?rev=893522&view=auto
==============================================================================
--- incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/impl/DirectoryImpl.java (added)
+++ incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/impl/DirectoryImpl.java Wed Dec 23 14:27:28 2009
@@ -0,0 +1,116 @@
+/*
+ * 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 WARRANTIESOR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.aries.application.filesystem.utils.impl;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import org.apache.aries.application.filesystem.IDirectory;
+import org.apache.aries.application.filesystem.IFile;
+import org.apache.aries.application.utils.AppConstants;
+
+/**
+ * An IDirectory representing a java.io.File whose isDirectory method returns true.
+ */
+public class DirectoryImpl extends FileImpl implements IDirectory
+{
+  /**
+   * @param dir      the file to represent.
+   * @param rootFile the file that represents the FS root.
+   */
+  public DirectoryImpl(File dir, File rootFile)
+  {
+    super(dir, rootFile);
+  }
+
+  public IFile getFile(String name)
+  {
+    File desiredFile = new File(file, name);
+    IFile result = null;
+    
+    if (desiredFile.exists()) {
+      result = new FileImpl(desiredFile, rootDirFile);
+    }
+    return result;
+  }
+
+  public boolean isRoot()
+  {
+    boolean result = (rootDirFile == file);
+    return result;
+  }
+
+  public List<IFile> listFiles()
+  {
+    List<IFile> files = new ArrayList<IFile>();
+    File[] filesInDir = file.listFiles();
+    if (filesInDir != null) {
+      for (File f : filesInDir) {
+        if (f.isFile()) {
+          files.add(new FileImpl(f, rootDirFile));
+        } else if (f.isDirectory()) {
+          files.add(new DirectoryImpl(f, rootDirFile));
+        }
+      }
+    }
+    return files;
+  }
+
+  public Iterator<IFile> iterator()
+  {
+    Iterator<IFile> result = listFiles().iterator();
+    return result;
+  }
+
+  @Override
+  public IDirectory getParent()
+  {
+    IDirectory result = isRoot() ? null : super.getParent();
+    return result;
+  }
+
+  @Override
+  public IDirectory convert()
+  {
+    return this;
+  }
+
+  @Override
+  public InputStream open() throws IOException
+  {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public long getLastModified()
+  {
+    long result = super.getLastModified();
+    for (IFile aFile : this) {
+      long tmpLastModified = aFile.getLastModified();
+      
+      if (tmpLastModified > result) result = tmpLastModified;
+    }
+    return result;
+  }
+}

Added: incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/impl/FileImpl.java
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/impl/FileImpl.java?rev=893522&view=auto
==============================================================================
--- incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/impl/FileImpl.java (added)
+++ incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/impl/FileImpl.java Wed Dec 23 14:27:28 2009
@@ -0,0 +1,143 @@
+/*
+ * 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 WARRANTIESOR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.aries.application.filesystem.utils.impl;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+
+import org.apache.aries.application.filesystem.IDirectory;
+import org.apache.aries.application.filesystem.IFile;
+
+/**
+ * An implementation of IFile that represents a java.io.File.
+ */
+public class FileImpl implements IFile
+{
+  
+  /** The name of the root directory of the file system */
+  protected String rootDir;
+  /** This file in the file system */
+  protected File file;
+  /** The root File in the file system */
+  protected File rootDirFile;
+  /** The name of this file in the vFS */
+  private String name;
+  
+  /**
+   * @param f        this file.
+   * @param rootFile the root of the vFS.
+   */
+  public FileImpl(File f, File rootFile)
+  {
+    file = f;
+    this.rootDirFile = rootFile;
+    rootDir = rootFile.getAbsolutePath();
+    
+    if (f == rootFile) name = "";
+    else name = file.getAbsolutePath().substring(rootDir.length() + 1);
+  }
+  
+  public IDirectory convert()
+  {
+    return null;
+  }
+
+  public long getLastModified()
+  {
+    long result = file.lastModified();
+    return result;
+  }
+
+  public String getName()
+  {
+    return name;
+  }
+
+  public IDirectory getParent()
+  {
+    IDirectory parent = new DirectoryImpl(file.getParentFile(), rootDirFile);
+    return parent;
+  }
+
+  public long getSize()
+  {
+    long size = file.length();
+    return size;
+  }
+
+  public boolean isDirectory()
+  {
+    boolean result = file.isDirectory();
+    return result;
+  }
+
+  public boolean isFile()
+  {
+    boolean result = file.isFile();
+    return result;
+  }
+
+  public InputStream open() throws IOException
+  {
+    InputStream is = new FileInputStream(file);
+    return is;
+  }
+
+  public IDirectory getRoot()
+  {
+    IDirectory root = new DirectoryImpl(rootDirFile, rootDirFile);
+    return root;
+  }
+
+  public URL toURL() throws MalformedURLException
+  {
+    URL result = file.toURL();
+    return result;
+  }
+
+  @Override
+  public boolean equals(Object obj)
+  {
+    if (obj == null) return false;
+    if (obj == this) return true;
+    
+    if (obj.getClass() == getClass()) {
+      return file.equals(((FileImpl)obj).file);
+    }
+    
+    return false;
+  }
+
+  @Override
+  public int hashCode()
+  {
+    return file.hashCode();
+  }
+  
+  @Override
+  public String toString()
+  {
+    return file.getAbsolutePath();
+  }
+}
\ No newline at end of file

Added: incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/impl/ZipDirectory.java
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/impl/ZipDirectory.java?rev=893522&view=auto
==============================================================================
--- incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/impl/ZipDirectory.java (added)
+++ incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/impl/ZipDirectory.java Wed Dec 23 14:27:28 2009
@@ -0,0 +1,232 @@
+/*
+ * 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 WARRANTIESOR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.aries.application.filesystem.utils.impl;
+
+import java.io.File;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.List;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.aries.application.filesystem.IDirectory;
+import org.apache.aries.application.filesystem.IFile;
+
+/**
+ * A directory in the zip.
+ */
+public class ZipDirectory extends ZipFileImpl implements IDirectory
+{
+  /** The root of the zip FS. */
+  private ZipDirectory root;
+  
+  /**
+   * Constructs a directory in the zip.
+   * 
+   * @param zip1   the zip file.
+   * @param entry1 the entry in the zip representing this dir.
+   * @param parent the parent directory.
+   */
+  public ZipDirectory(File zip1, ZipEntry entry1, ZipDirectory parent)
+  {
+    super(zip1, entry1, parent);
+  }
+
+  /**
+   * This constructor creates the root of the zip.
+   * @param file
+   * @param fs
+   * @throws MalformedURLException 
+   */
+  public ZipDirectory(File file, File fs) throws MalformedURLException
+  {
+    super(file, fs);
+    root = this;
+  }
+
+  public IFile getFile(String name)
+  {
+    IFile result = null;
+    
+    String entryName = isRoot() ? name : getName() + "/" + name;
+    
+    ZipEntry entryFile = getEntry(entryName);
+    
+    if (entryFile != null) {
+      if (!!!entryFile.isDirectory()) {
+        result = new ZipFileImpl(zip, entryFile, buildParent(entryFile));
+      } else {
+        result = new ZipDirectory(zip, entryFile, buildParent(entryFile));
+      }
+    }
+    return result;
+  }
+
+  /**
+   * This method builds the parent directory hierarchy for a file.
+   * @param foundEntry
+   * @return the parent of the entry.
+   */
+  private ZipDirectory buildParent(ZipEntry foundEntry)
+  {
+    ZipDirectory result = this;
+    
+    String name = foundEntry.getName();
+    
+    name = name.substring(getName().length());
+    
+    String[] paths = name.split("/");
+    
+    StringBuilder baseBuilderCrapThingToGetRoundFindBugs = new StringBuilder(getName());
+    
+    if (!!!isRoot()) baseBuilderCrapThingToGetRoundFindBugs.append('/');
+    
+    if (paths != null && paths.length > 1) {
+      for (int i = 0; i < paths.length - 1; i++) {
+        String path = paths[i];
+        baseBuilderCrapThingToGetRoundFindBugs.append(path);
+        ZipEntry dirEntry = getEntry(baseBuilderCrapThingToGetRoundFindBugs.toString());
+        result = new ZipDirectory(zip, dirEntry, result);
+        baseBuilderCrapThingToGetRoundFindBugs.append('/');
+      }
+    }
+    return result;
+  }
+
+  public boolean isRoot()
+  {
+    boolean result = (root == this);
+    return result;
+  }
+
+  public List<IFile> listFiles()
+  {
+    List<IFile> files = new ArrayList<IFile>();
+    
+    ZipFile z = openZipFile();
+    Enumeration<? extends ZipEntry> entries = z.entries();
+    
+    while (entries.hasMoreElements()) {
+      ZipEntry possibleEntry = entries.nextElement();
+      
+      if (isInDir(possibleEntry)) {
+        if (possibleEntry.isDirectory()) {
+          files.add(new ZipDirectory(zip, possibleEntry, this));
+        } else {
+          files.add(new ZipFileImpl(zip, possibleEntry, this));
+        }
+      }
+    }
+    closeZipFile(z);
+    return files;
+  }
+
+  /**
+   * This method works out if the provided entry is inside this directory. It
+   * returns false if it is not, or if it is in a sub-directory.
+   * 
+   * @param possibleEntry
+   * @return true if it is in this directory.
+   */
+  private boolean isInDir(ZipEntry possibleEntry)
+  {
+    boolean result;
+    String name = possibleEntry.getName();
+    String parentDir = getName();
+    if (name.endsWith("/")) name = name.substring(0, name.length() - 1);
+    result = (name.startsWith(parentDir) && !!!name.equals(parentDir) && name.substring(parentDir.length() + 1).indexOf('/') == -1);
+    return result;
+  }
+
+  public Iterator<IFile> iterator()
+  {
+    Iterator<IFile> result = listFiles().iterator();
+    return result;
+  }
+
+  @Override
+  public IDirectory convert()
+  {
+    return this;
+  }
+
+  @Override
+  public IDirectory getParent()
+  {
+    IDirectory result = isRoot() ? null : super.getParent();
+    return result;
+  }
+
+  @Override
+  public boolean isDirectory()
+  {
+    return true;
+  }
+
+  @Override
+  public boolean isFile()
+  {
+    return false;
+  }
+
+  @Override
+  public InputStream open() 
+  {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public IDirectory getRoot()
+  {
+    return root;
+  }
+  
+  // Although we only delegate to our super class if we removed this Findbugs
+  // would correctly point out that we add fields in this class, but do not
+  // take them into account for the equals method. In fact this is not a problem
+  // we do not care about the root when doing an equality check, but by including
+  // an equals or hashCode in here we can clearly document that we did this
+  // on purpose. Hence this comment.
+  @Override
+  public boolean equals(Object other)
+  {
+    return super.equals(other);
+  }
+  
+  @Override
+  public int hashCode()
+  {
+    return super.hashCode();
+  }
+  
+  private ZipEntry getEntry(String entryName){
+    ZipFile z = openZipFile();
+    ZipEntry entryFile = null;
+    
+    if (z != null) {
+      entryFile = z.getEntry(entryName);
+      closeZipFile(z);
+    }
+    return entryFile;
+  }
+}
\ No newline at end of file

Added: incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/impl/ZipFileImpl.java
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/impl/ZipFileImpl.java?rev=893522&view=auto
==============================================================================
--- incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/impl/ZipFileImpl.java (added)
+++ incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/filesystem/utils/impl/ZipFileImpl.java Wed Dec 23 14:27:28 2009
@@ -0,0 +1,238 @@
+/*
+ * 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 WARRANTIESOR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.aries.application.filesystem.utils.impl;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipException;
+import java.util.zip.ZipFile;
+
+import org.apache.aries.application.filesystem.IDirectory;
+import org.apache.aries.application.filesystem.IFile;
+import org.apache.aries.application.utils.AppConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * An implementation of IFile that represents a file entry in a zip.
+ */
+public class ZipFileImpl implements IFile
+{
+  /** A logger */
+  private static final Logger logger = LoggerFactory.getLogger("org.apache.aries.application.utils");
+
+  /** The name of the file */
+  private String name = "";
+  /** The size of the file */
+  private final long size;
+  /** The last time the file was updated */
+  private final long lastModified;
+  /** The zip file this is contained in */
+  protected File zip;
+  /** The entry in the zip this IFile represents */
+  protected ZipEntry entry;
+  /** The parent directory */
+  private ZipDirectory parent;
+  /** The URL of the zip file we are looking inside of */
+  private final String url;
+  
+  /**
+   * This constructor is used to create a file entry within the zip.
+   * 
+   * @param zip1    the zip file the entry is in.
+   * @param entry1  the entry this IFile represents.
+   * @param parent1 the parent directory.
+   */
+  public ZipFileImpl(File zip1, ZipEntry entry1, ZipDirectory parent1)
+  {
+    this.zip = zip1;
+    this.entry = entry1;
+    
+    name = entry1.getName();
+    
+    if (entry1.isDirectory()) name = name.substring(0, name.length() - 1);
+    
+    lastModified = entry1.getTime();
+    size = entry1.getSize();
+    
+    url = ((ZipFileImpl)parent1).url;
+    
+    this.parent = parent1;
+  }
+  
+  /**
+   * This is called to construct the root directory of the zip.
+   * 
+   * @param zip1 the zip file this represents.
+   * @param fs   the file on the fs.
+   * @throws MalformedURLException
+   */
+  protected ZipFileImpl(File zip1, File fs) throws MalformedURLException
+  {
+    this.zip = zip1;
+    this.entry = null;
+    name = "";
+    lastModified = fs.lastModified();
+    size = fs.length();
+    url = fs.toURL().toExternalForm();
+  }
+
+  public IDirectory convert()
+  {
+    return null;
+  }
+
+  public long getLastModified()
+  {
+    return lastModified;
+  }
+
+  public String getName()
+  {
+    return name;
+  }
+
+  public IDirectory getParent()
+  {
+    return parent;
+  }
+
+  public long getSize()
+  {
+    return size;
+  }
+
+  public boolean isDirectory()
+  {
+    return false;
+  }
+
+  public boolean isFile()
+  {
+    return true;
+  }
+
+  public InputStream open() throws IOException
+  {
+    InputStream is = new SpecialZipInputStream(entry);
+    return is;
+  }
+  
+  public IDirectory getRoot()
+  {
+    IDirectory root = parent.getRoot();
+    return root;
+  }
+
+  public URL toURL() throws MalformedURLException
+  {
+    String entryURL = "jar:" + url + "!/" + getParent().getName() + getName();
+    URL result = new URL(entryURL);
+    return result;
+  }
+
+  @Override
+  public boolean equals(Object obj)
+  {
+    if (obj == null) return false;
+    if (obj == this) return true;
+    
+    if (obj.getClass() == getClass()) {
+      return toString().equals(obj.toString());
+    }
+    
+    return false;
+  }
+
+  @Override
+  public int hashCode()
+  {
+    return toString().hashCode();
+  }
+
+  @Override
+  public String toString()
+  {
+    return url.substring(5)+ "/" + name;
+  }
+  
+  ZipFile openZipFile(){
+    ZipFile z = null;
+    try {
+      z = new ZipFile(zip);
+    } catch (ZipException e) {
+      logger.error ("ZipException in ZipFileImpl.openZipFile", e);
+    } catch (IOException e) {
+      logger.error ("IOException in ZipFileImpl.openZipFile", e);
+    }
+    return z;
+  }
+  
+  void closeZipFile(ZipFile z){
+    try{
+      z.close();
+    }
+    catch (IOException e) {
+      logger.error ("IOException in ZipFileImpl.closeZipFile", e);
+    }
+  }
+  
+  /**
+   * A simple class to delegate to the InputStream of the constructor
+   * and to call close on the zipFile when we close the stream.
+   *
+   */
+  private class SpecialZipInputStream extends InputStream{
+
+    private ZipFile zipFile;
+    private InputStream is;
+    
+    public SpecialZipInputStream(ZipEntry anEntry){
+      try{
+      this.zipFile = openZipFile();
+      this.is = zipFile.getInputStream(anEntry);
+      }
+      catch (ZipException e) {
+        logger.error ("ZipException in SpecialZipInputStream()", e);
+      } catch (IOException e) {
+        logger.error ("IOException in SpecialZipInputStream()", e);        
+      }
+    }
+    
+    @Override
+    public int read() throws IOException
+    {
+      return is.read();
+    }
+    
+    @Override
+    public void close() throws IOException{
+        //call close on the input stream, probably does nothing
+        is.close();
+        //call close on the zip file, important for tidying up
+        closeZipFile(zipFile);
+    }
+    
+  }
+}

Added: incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/utils/internal/MessageUtil.java
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/utils/internal/MessageUtil.java?rev=893522&view=auto
==============================================================================
--- incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/utils/internal/MessageUtil.java (added)
+++ incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/utils/internal/MessageUtil.java Wed Dec 23 14:27:28 2009
@@ -0,0 +1,46 @@
+/*
+ * 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 WARRANTIESOR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.aries.application.utils.internal;
+
+import java.text.MessageFormat;
+import java.util.ResourceBundle;
+
+public class MessageUtil
+{
+  /** The resource bundle for blueprint messages */
+  private final static ResourceBundle messages = ResourceBundle.getBundle("org.apache.aries.application.utils.messages.APPUTILSmessages");
+  
+  /**
+   * Resolve a message from the bundle, including any necessary formatting.
+   * 
+   * @param key     the message key.
+   * @param inserts any required message inserts.
+   * @return        the message translated into the server local.
+   */
+  public static final String getMessage(String key, Object ... inserts)
+  {
+    String msg = messages.getString(key);
+    
+    if (inserts.length > 0)
+      msg = MessageFormat.format(msg, inserts);
+    
+    return msg;
+  }
+}

Added: incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/utils/manifest/BundleManifest.java
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/utils/manifest/BundleManifest.java?rev=893522&view=auto
==============================================================================
--- incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/utils/manifest/BundleManifest.java (added)
+++ incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/utils/manifest/BundleManifest.java Wed Dec 23 14:27:28 2009
@@ -0,0 +1,201 @@
+/*
+ * 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 WARRANTIESOR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.aries.application.utils.manifest;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.jar.Attributes;
+import java.util.jar.JarInputStream;
+import java.util.jar.Manifest;
+import java.util.zip.ZipEntry;
+
+import org.apache.aries.application.filesystem.IFile;
+import org.apache.aries.application.filesystem.utils.IOUtils;
+import org.apache.aries.application.utils.internal.MessageUtil;
+import org.apache.aries.application.utils.manifest.ManifestHeaderProcessor.NameValueMap;
+import org.apache.aries.application.utils.manifest.ManifestHeaderProcessor.NameValuePair;
+import org.osgi.framework.Constants;
+import org.osgi.framework.Version;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Entity class to retrieve and represent a bundle manifest (valid or invalid).
+ * 
+ * @author mahrwald
+ *
+ */
+public class BundleManifest
+{
+  private static final String MANIFEST_PATH = "META-INF/MANIFEST.MF";
+  private static final Logger _logger = LoggerFactory.getLogger("org.apache.aries.application.utils");
+
+  /**
+   * Read a manifest from a jar input stream. This will find the manifest even if it is NOT
+   * the first file in the archive.
+   * 
+   * @param is
+   * @return
+   */
+  public static BundleManifest fromBundle(InputStream is) {
+    JarInputStream jarIs = null;
+    try {
+      jarIs = new JarInputStream(is);
+      Manifest m = jarIs.getManifest();
+      if (m != null)
+        return new BundleManifest(m);
+      else {
+        ZipEntry entry;
+        while ((entry = jarIs.getNextEntry()) != null) {
+          if (entry.getName().equals(MANIFEST_PATH))
+            return new BundleManifest(jarIs);
+        }
+        
+        return null;
+      }
+    }
+    catch (IOException e) {
+      _logger.error ("IOException in BundleManifest()", e);
+      return null;
+    }
+    finally {
+      IOUtils.close(jarIs);
+    }
+  }
+  
+  /**
+   * Retrieve a BundleManifest from the given jar file
+   * 
+   * @param f
+   * @return
+   */
+  public static BundleManifest fromBundle(IFile f) {
+    InputStream is = null;
+    try {
+      if (f.isDirectory()) {
+        IFile manFile = f.convert().getFile(MANIFEST_PATH);
+        if (manFile != null)
+          return new BundleManifest(manFile.open());
+        else
+          return null;
+      } else {
+        is = f.open();
+        return fromBundle(is);
+      }
+    } catch (IOException e) {
+      _logger.error ("IOException in BundleManifest.fromBundle(IFile)", e);
+      return null;
+    }
+    finally {
+      IOUtils.close(is);
+    }
+  }
+  
+  /**
+   * Retrieve a bundle manifest from the given jar file, which can be exploded or compressed
+   * 
+   * @param f
+   * @return
+   */
+  public static BundleManifest fromBundle(File f) {
+    if (f.isDirectory()) {
+      File manifestFile = new File(f, MANIFEST_PATH);
+      if (manifestFile.isFile())
+        try {
+          return new BundleManifest(new FileInputStream(manifestFile));
+        }
+        catch (IOException e) {
+          _logger.error ("IOException in BundleManifest.fromBundle(File)", e);
+          return null;
+        }
+      else
+        return null;
+    }
+    else  if (f.isFile()) {
+      try {
+        return fromBundle(new FileInputStream(f));
+      }
+      catch (IOException e) {
+        _logger.error ("IOException in BundleManifest.fromBundle(File)", e);
+        return null;
+      }
+    }
+    else {
+      throw new IllegalArgumentException(MessageUtil.getMessage("APPUTILS0007E", f.getAbsolutePath()));
+    }
+  }
+  
+  private Manifest manifest;
+  
+  /**
+   * Create a BundleManifest object from the InputStream to the manifest (not to the bundle)
+   * @param manifestIs
+   * @throws IOException
+   */
+  public BundleManifest(InputStream manifestIs) throws IOException {
+    this(ManifestProcessor.parseManifest(manifestIs));
+  }
+  
+  /**
+   * Create a BundleManifest object from a common Manifest object
+   * @param m
+   */
+  public BundleManifest(Manifest m) {
+    manifest = m;
+  }
+  
+  public String getSymbolicName() {
+    String rawSymName = manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME);
+
+    String result = null;
+    if (rawSymName != null) {
+      NameValuePair<String, NameValueMap<String, String>> info = ManifestHeaderProcessor.parseBundleSymbolicName(rawSymName);
+      result = info.getName();
+    }
+    
+    return result;
+  }
+  
+  public Version getVersion() {
+    String specifiedVersion = manifest.getMainAttributes().getValue(Constants.BUNDLE_VERSION);
+    Version result = (specifiedVersion == null) ? Version.emptyVersion : new Version(specifiedVersion);
+    
+    return result;
+  }
+  
+  public String getManifestVersion() {
+    return manifest.getMainAttributes().getValue(Constants.BUNDLE_MANIFESTVERSION);
+  }
+  
+  public Attributes getRawAttributes() {
+    return manifest.getMainAttributes();
+  }
+  
+  public Manifest getRawManifest() {
+    return manifest;
+  }
+  
+  public boolean isValid() {
+    return getManifestVersion() != null && getSymbolicName() != null;
+  }
+}
+

Added: incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/utils/manifest/ManifestDefaultsInjector.java
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/utils/manifest/ManifestDefaultsInjector.java?rev=893522&view=auto
==============================================================================
--- incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/utils/manifest/ManifestDefaultsInjector.java (added)
+++ incubator/aries/trunk/application/application-utils/src/main/java/org/apache/aries/application/utils/manifest/ManifestDefaultsInjector.java Wed Dec 23 14:27:28 2009
@@ -0,0 +1,263 @@
+package org.apache.aries.application.utils.manifest;
+
+import java.io.File;
+import java.util.Map;
+import java.util.jar.Manifest;
+
+import org.apache.aries.application.filesystem.IDirectory;
+import org.apache.aries.application.filesystem.IFile;
+import org.apache.aries.application.filesystem.utils.FileSystem;
+import org.apache.aries.application.utils.AppConstants;
+import org.osgi.framework.Version;
+
+public class ManifestDefaultsInjector
+{
+  /**
+   * Quick adapter to update a Manifest, using content of a Zip File.
+   * <p>
+   * This is really a wrapper of updateManifest(Manifest,String,IDirectory), with the
+   * IDirectory being being created from the Zip File. This method avoids other Bundles
+   * requiring IDirectory solely for calling updateManifest.
+   * <p>
+   * @param mf Manifest to be updated
+   * @param appName The name to use for this app, if the name contains 
+   * a '_' char then the portion after the '_' is used, if possible, as 
+   * the application version.
+   * @param zip Content to use for application.
+   * @return true if manifest modified, false otherwise.
+   */
+  public static boolean updateManifest(Manifest mf, String appName, File zip){
+    IDirectory appPathIDir = FileSystem.getFSRoot(zip);
+    boolean result = updateManifest(mf, appName, appPathIDir);
+    return result;
+  }
+  
+  /**
+   * Tests the supplied manifest for the presence of expected 
+   * attributes, and where missing, adds them, and defaults 
+   * their values appropriately.
+   * 
+   * @param mf The manifest to test & update if needed.
+   * @param appName The name to use for this app, if the name contains 
+   * a '_' char then the portion after the '_' is used, if possible, as 
+   * the application version.
+   * @param appDir The IDirectory to scan to build application content
+   * property
+   * @return true if manifest modified, false otherwise.
+   */
+  public static boolean updateManifest(Manifest mf, String appName, IDirectory appDir){ 
+    Map<String, String> props = ManifestProcessor.readManifestIntoMap(mf);
+    String extracted[] = extractAppNameAndVersionFromNameIfPossible(appName);
+    String name = extracted[0];
+    String version = extracted[1];
+
+    boolean updated = false;
+    updated |= defaultAppSymbolicName(mf, props, name);
+    updated |= defaultAppName(mf, props, name);
+    updated |= defaultVersion(mf, props, version);
+    updated |= defaultAppScope(mf, props, name, version);
+    updated |= defaultAppContent(mf, props, appDir);
+    
+    return updated;
+  }
+  
+  /**
+   * Takes a compound name_version string, and returns the Name & Version information. 
+   * <p>
+   * @param name Contains name data related to this app. Expected format is   name_version  
+   * @return Array of String, index 0 is appName, index 1 is Version. 
+   * <br> Name will be the appname retrieved from the 'name' argument, Version will be the 
+   * version if found and valid, otherwise will be defaulted.
+   */
+  private static String[] extractAppNameAndVersionFromNameIfPossible(String name){
+    String retval[] = new String[2];
+    String appName = name;
+    String defaultedVersion;
+
+    int index = name.indexOf('_');
+
+    if (index != -1) {
+      appName = name.substring(0, index);
+      defaultedVersion = name.substring(index + 1);
+
+      try {
+        new Version(defaultedVersion);
+      } catch (IllegalArgumentException e) {
+        // this is not an error condition
+        defaultedVersion = AppConstants.DEFAULT_VERSION;
+      }
+    } else {
+      defaultedVersion = AppConstants.DEFAULT_VERSION;
+    }
+
+    retval[0] = appName;
+    retval[1] = defaultedVersion;
+    
+    return retval;  
+  }
+  
+  /**
+   * Sets the app symbolic name into the manifest, if not already present.
+   * 
+   * @param mf manifest to update
+   * @param props parsed manifest used to test if already present. 
+   * @param appName used for name if missing
+   * @return true if manifest is modified, false otherwise.
+   */
+  private static boolean defaultAppSymbolicName(Manifest mf, Map<String, String> props, String appName){
+    boolean updated = false;
+    if (!props.containsKey(AppConstants.APPLICATION_SYMBOLIC_NAME)) {
+      mf.getMainAttributes().putValue(AppConstants.APPLICATION_SYMBOLIC_NAME, appName);
+      updated = true;
+    }
+    return updated;    
+  }
+  
+  /**
+   * Sets the app name into the manifest, if not already present.
+   * 
+   * @param mf manifest to update
+   * @param props parsed manifest used to test if already present. 
+   * @param appName used for name if missing
+   * @return true if manifest is modified, false otherwise.
+   */  
+  private static boolean defaultAppName(Manifest mf, Map<String, String> props, String appName){
+    boolean updated = false;
+    if (!props.containsKey(AppConstants.APPLICATION_NAME)) {
+      mf.getMainAttributes().putValue(AppConstants.APPLICATION_NAME, appName);
+      updated = true;
+    }
+    return updated;    
+  }
+    
+  /**
+   * Sets the app version into the manifest, if not already present.
+   * 
+   * @param mf manifest to update
+   * @param props parsed manifest used to test if already present. 
+   * @param appVersion used for version if missing
+   * @return true if manifest is modified, false otherwise.
+   */  
+  private static boolean defaultVersion(Manifest mf, Map<String, String> props, String appVersion){
+    boolean updated = false;
+    if (!props.containsKey(AppConstants.APPLICATION_VERSION)) {
+      mf.getMainAttributes().putValue(AppConstants.APPLICATION_VERSION, appVersion);
+      updated = true;
+    }
+    return updated;
+  }
+  
+  /**
+   * Sets the app scope into the manifest, if not already present.
+   * 
+   * @param mf manifest to update
+   * @param props parsed manifest used to test if already present. 
+   * @param name used to build appScope if app symbolic name not set.
+   * @param version used to build appScope if app version missing.
+   * @return true if manifest is modified, false otherwise.
+   */   
+  private static boolean defaultAppScope(Manifest mf, Map<String, String> props, String name, String version){
+    boolean updated = false;
+    if (!props.containsKey(AppConstants.APPLICATION_SCOPE)) {
+
+      String appSymbolicName;
+      if (props.containsKey(AppConstants.APPLICATION_SYMBOLIC_NAME)) {
+        appSymbolicName = props.get(AppConstants.APPLICATION_SYMBOLIC_NAME);
+      } else {
+        appSymbolicName = name;
+      }
+
+      String appVersion;
+      if (props.containsKey(AppConstants.APPLICATION_VERSION)) {
+        appVersion = props.get(AppConstants.APPLICATION_VERSION);
+      } else {
+        appVersion = version;
+      }
+
+      String appScope = appSymbolicName + '_' + appVersion;
+      mf.getMainAttributes().putValue(AppConstants.APPLICATION_SCOPE, appScope);
+      updated = true;
+    }
+    return updated;
+  }
+  
+  /**
+   * Sets the app content into the manifest, if not already present.
+   * <p>
+   * This method will NOT set the appcontent if it is unable to build it.
+   * This is important, as the absence of appcontent is used by some callers
+   * to test if a manifest contains all required content.
+   * 
+   * @param mf manifest to update
+   * @param props parsed manifest used to test if already present. 
+   * @param appDir used to build app content if missing.
+   * @return true if manifest is modified, false otherwise.
+   */    
+  private static boolean defaultAppContent(Manifest mf, Map<String, String> props, IDirectory appDir){
+    boolean updated = false;
+    if (!props.containsKey(AppConstants.APPLICATION_CONTENT)) {
+      String appContent = calculateAppContent(appDir);
+      if (appContent != null) {
+        mf.getMainAttributes().putValue(AppConstants.APPLICATION_CONTENT, appContent);
+        updated = true;
+      }
+    }
+    return updated;    
+  }
+  
+  /**
+   * Processes an IDirectory to find targets that require adding to the application content attrib.
+   * 
+   * @param appDir The IDirectory to scan
+   * @return AppContent string, or null if no content was found.
+   */
+  private static String calculateAppContent(IDirectory appDir){
+    StringBuilder builder = new StringBuilder();
+    for (IFile file : appDir) {
+      processPossibleBundle(file, builder);
+    }
+    String returnVal = null;
+    if (builder.length() > 0) {
+      builder.deleteCharAt(builder.length() - 1);
+      returnVal = builder.toString();
+    }
+    return returnVal;
+  }
+  
+  /**
+   * This method works out if the given IFile represents an OSGi bundle and if
+   * it is then we append a matching rule to the String builder.
+   * 
+   * @param file    to file to check.
+   * @param builder the builder to append to.
+   */
+  private static void processPossibleBundle(IFile file, StringBuilder builder)
+  {
+    if (file.isDirectory() || (file.isFile() && (file.getName().endsWith(".jar") || file.getName().endsWith(".war")))) {
+      BundleManifest bundleMf = BundleManifest.fromBundle(file);
+      if (bundleMf != null) {
+        String manifestVersion = bundleMf.getManifestVersion();
+        String name = bundleMf.getSymbolicName();
+        String version = bundleMf.getVersion().toString();
+
+        // if the bundle manifest version is 2 AND a symbolic name is specified we have a valid bundle
+        if ("2".equals(manifestVersion) && name != null) {
+
+          builder.append(name);
+
+          // bundle version is not a required manifest header
+          if (version != null) {
+            builder.append(";version=\"[");
+            builder.append(version);
+            builder.append(',');
+            builder.append(version);
+            builder.append("]\"");
+          }
+
+          // the last comma will be removed once all content has been added
+          builder.append(",");
+        }
+      }
+    }
+  }
+}