001/*
002 * (C) Copyright 2012 Nuxeo SA (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 *     matic
016 */
017package org.nuxeo.osgi.util.jar;
018
019import java.io.File;
020import java.io.IOException;
021import java.net.URL;
022import java.net.URLClassLoader;
023import java.util.jar.JarFile;
024
025import org.apache.commons.logging.LogFactory;
026import org.nuxeo.runtime.api.Framework;
027import org.nuxeo.runtime.api.SharedResourceLoader;
028
029/**
030 * Given a location, close the corresponding jar files opened by URL class loaders and in jar file cache
031 *
032 * @since 5.6
033 * @author matic
034 */
035public class URLJarFileCloser implements JarFileCloser {
036
037    protected final URLClassLoaderCloser applicationCloser;
038
039    protected final URLJarFileIntrospector introspector;
040
041    public URLJarFileCloser(URLJarFileIntrospector anIntrospector, ClassLoader appCL)
042            throws URLJarFileIntrospectionError {
043        introspector = anIntrospector;
044        applicationCloser = appCL instanceof URLClassLoader ? introspector.newURLClassLoaderCloser((URLClassLoader) appCL)
045                : null;
046    }
047
048    @Override
049    public void close(JarFile file) throws IOException {
050        file.close();
051        URL location = new File(file.getName()).toURI().toURL();
052        boolean closed = false;
053        try {
054            final SharedResourceLoader loader = Framework.getResourceLoader();
055            if (loader != null) {
056                closed = introspector.newURLClassLoaderCloser(loader).close(location);
057            }
058        } catch (URLJarFileIntrospectionError cause) {
059            LogFactory.getLog(URLJarFileCloser.class).error("Cannot introspect shared resource loader", cause);
060
061        }
062        if (closed == false) {
063            if (applicationCloser != null) {
064                closed = applicationCloser.close(location);
065            }
066        }
067        introspector.close(location);
068    }
069}