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 groovy.lang.GroovyClassLoader;
022
023import java.io.File;
024import java.io.FileInputStream;
025import java.io.IOException;
026import java.io.InputStream;
027import java.net.MalformedURLException;
028
029import org.nuxeo.connect.update.LocalPackage;
030import org.nuxeo.connect.update.PackageData;
031import org.nuxeo.connect.update.PackageException;
032
033/**
034 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
035 */
036public class LocalPackageData implements PackageData {
037
038    protected File root;
039
040    protected GroovyClassLoader loader;
041
042    public LocalPackageData(ClassLoader parent, File file) throws IOException {
043        this.root = file.getCanonicalFile();
044        if (parent == null) {
045            parent = Thread.currentThread().getContextClassLoader();
046            if (parent == null) {
047                parent = getClass().getClassLoader();
048            }
049        }
050        try {
051            this.loader = new GroovyClassLoader(parent);
052            loader.addURL(root.toURI().toURL());
053        } catch (MalformedURLException e) {
054            throw new RuntimeException("Failed to create package class loader. Invalid package root: " + root, e);
055        }
056    }
057
058    public void setRoot(File file) {
059        this.root = file;
060    }
061
062    public ClassLoader getLoader() {
063        return loader;
064    }
065
066    public File getEntry(String path) {
067        return new File(root, path);
068    }
069
070    public InputStream getEntryAsStream(String path) throws IOException {
071        return new FileInputStream(getEntry(path));
072    }
073
074    public File getManifest() {
075        return getEntry(LocalPackage.MANIFEST);
076    }
077
078    public File getRoot() {
079        return root;
080    }
081
082    public Class<?> loadClass(String name) throws PackageException {
083        try {
084            return loader.loadClass(name);
085        } catch (ClassNotFoundException e) {
086            throw new PackageException("Failed to load class " + name + " from package: " + root.getName());
087        }
088    }
089
090}