001/* 002 * (C) Copyright 2006-2010 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * bstefanescu 018 */ 019package org.nuxeo.connect.update.standalone; 020 021import java.io.File; 022import java.io.FileInputStream; 023import java.io.IOException; 024import java.io.InputStream; 025import java.net.MalformedURLException; 026import java.net.URL; 027 028import org.nuxeo.connect.update.LocalPackage; 029import org.nuxeo.connect.update.PackageData; 030import org.nuxeo.connect.update.PackageException; 031import org.nuxeo.runtime.api.SharedResourceLoader; 032 033/** 034 * @author <a href="mailto:[email protected]">Bogdan Stefanescu</a> 035 */ 036public class LocalPackageData implements PackageData { 037 038 protected File root; 039 040 // SharedResourceLoader is a URLClassLoader with a public addURL 041 protected SharedResourceLoader loader; 042 043 public LocalPackageData(ClassLoader parent, File file) throws IOException { 044 this.root = file.getCanonicalFile(); 045 if (parent == null) { 046 parent = Thread.currentThread().getContextClassLoader(); 047 if (parent == null) { 048 parent = getClass().getClassLoader(); 049 } 050 } 051 try { 052 this.loader = new SharedResourceLoader(new URL[] {}, parent); 053 loader.addURL(root.toURI().toURL()); 054 } catch (MalformedURLException e) { 055 throw new RuntimeException("Failed to create package class loader. Invalid package root: " + root, e); 056 } 057 } 058 059 public void setRoot(File file) { 060 this.root = file; 061 } 062 063 public ClassLoader getLoader() { 064 return loader; 065 } 066 067 public File getEntry(String path) { 068 return new File(root, path); 069 } 070 071 public InputStream getEntryAsStream(String path) throws IOException { 072 return new FileInputStream(getEntry(path)); 073 } 074 075 public File getManifest() { 076 return getEntry(LocalPackage.MANIFEST); 077 } 078 079 public File getRoot() { 080 return root; 081 } 082 083 public Class<?> loadClass(String name) throws PackageException { 084 try { 085 return loader.loadClass(name); 086 } catch (ClassNotFoundException e) { 087 throw new PackageException("Failed to load class " + name + " from package: " + root.getName()); 088 } 089 } 090 091}