001/* 002 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the GNU Lesser General Public License 006 * (LGPL) version 2.1 which accompanies this distribution, and is available at 007 * http://www.gnu.org/licenses/lgpl.html 008 * 009 * This library is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * Contributors: 015 * bstefanescu 016 */ 017package org.nuxeo.connect.update.standalone; 018 019import groovy.lang.GroovyClassLoader; 020 021import java.io.File; 022import java.io.FileInputStream; 023import java.io.IOException; 024import java.io.InputStream; 025import java.net.MalformedURLException; 026 027import org.nuxeo.connect.update.LocalPackage; 028import org.nuxeo.connect.update.PackageData; 029import org.nuxeo.connect.update.PackageException; 030 031/** 032 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> 033 */ 034public class LocalPackageData implements PackageData { 035 036 protected File root; 037 038 protected GroovyClassLoader loader; 039 040 public LocalPackageData(ClassLoader parent, File file) throws IOException { 041 this.root = file.getCanonicalFile(); 042 if (parent == null) { 043 parent = Thread.currentThread().getContextClassLoader(); 044 if (parent == null) { 045 parent = getClass().getClassLoader(); 046 } 047 } 048 try { 049 this.loader = new GroovyClassLoader(parent); 050 loader.addURL(root.toURI().toURL()); 051 } catch (MalformedURLException e) { 052 throw new RuntimeException("Failed to create package class loader. Invalid package root: " + root, e); 053 } 054 } 055 056 public void setRoot(File file) { 057 this.root = file; 058 } 059 060 public ClassLoader getLoader() { 061 return loader; 062 } 063 064 public File getEntry(String path) { 065 return new File(root, path); 066 } 067 068 public InputStream getEntryAsStream(String path) throws IOException { 069 return new FileInputStream(getEntry(path)); 070 } 071 072 public File getManifest() { 073 return getEntry(LocalPackage.MANIFEST); 074 } 075 076 public File getRoot() { 077 return root; 078 } 079 080 public Class<?> loadClass(String name) throws PackageException { 081 try { 082 return loader.loadClass(name); 083 } catch (ClassNotFoundException e) { 084 throw new PackageException("Failed to load class " + name + " from package: " + root.getName()); 085 } 086 } 087 088}