001/*
002 * (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and contributors.
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 *     Nuxeo - initial API and implementation
018 *
019 * $Id$
020 */
021
022package org.nuxeo.common.utils;
023
024import java.io.File;
025import java.io.FileInputStream;
026import java.io.IOException;
027import java.net.URL;
028import java.util.jar.JarFile;
029import java.util.jar.Manifest;
030
031/**
032 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
033 */
034public final class JarUtils {
035
036    // Utility class.
037    private JarUtils() {
038    }
039
040    public static Manifest getManifest(File file) {
041        try {
042            if (file.isDirectory()) {
043                return getDirectoryManifest(file);
044            } else {
045                return getJarManifest(file);
046            }
047        } catch (IOException ignored) {
048            return null;
049        }
050    }
051
052    public static Manifest getDirectoryManifest(File file) throws IOException {
053        FileInputStream fis = null;
054        try {
055            fis = new FileInputStream(new File(file, "META-INF/MANIFEST.MF"));
056            return new Manifest(fis);
057        } finally {
058            if (fis != null) {
059                fis.close();
060            }
061        }
062    }
063
064    public static Manifest getJarManifest(File file) throws IOException {
065        JarFile jar = null;
066        try {
067            jar = new JarFile(file);
068            return jar.getManifest();
069        } finally {
070            if (jar != null) {
071                jar.close();
072            }
073        }
074    }
075
076    public static Manifest getManifest(URL url) {
077        try {
078            return new JarFile(new File(url.getFile())).getManifest();
079        } catch (IOException e) {
080            return null;
081        }
082    }
083
084}