/*
 * The contents of this file are subject to the terms
 * of the Common Development and Distribution License
 * (the License).  You may not use this file except in
 * compliance with the License.
 *
 * You can obtain a copy of the license at
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing
 * permissions and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL
 * Header Notice in each file and include the License file
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.
 * If applicable, add the following below the CDDL Header,
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 *
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */

package com.sun.enterprise.addons.util;

import java.io.File;
import java.io.FilenameFilter;
import java.util.regex.Pattern;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.Map;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.Attributes.Name;

/**
 * @since 9.1
 * @author sreenivas munnangi, msreddy@dev.java.net
 */
public class AddOnUtils {

    public static JarFile getAddonJarFile(
        String addonName, File jarDir, FilenameFilter filter) 
        throws Exception {

        if ((jarDir == null) || (addonName == null) || (filter == null)) {
            throw new Exception("invalid input to getAddonJarFile");
        }

        File[] jars = jarDir.listFiles(filter);
        String str;
        for (File jar:jars) {
            str = jar.getName().split(ConfigurableJarFileFilter.regex)[0];
            if (str.equals(addonName)) {
                return new JarFile(jar);
            }
        }
        return null;
    }

    public static String [] getDependencies(JarFile jar) 
        throws Exception {

        String [] strArr = null;

        if (jar == null) {
            throw new Exception("invalid input to getDependencies");
        }

        Manifest mf = jar.getManifest();
        if (mf == null) return strArr;

        Attributes attrs = mf.getMainAttributes();
        if (attrs == null) return strArr;

        Set<Map.Entry<Object, Object>> mfattrs = attrs.entrySet();
        String key, val;
        for (Map.Entry<Object,Object> entry : mfattrs) {
            key = ((Attributes.Name) entry.getKey()).toString();
            val = (String) entry.getValue();
            if (! key.equals("Add-On-Dependencies")) continue;
            if (val.contains(",")) {
                strArr = val.split(",");
            } else {
                strArr = new String[1];
                strArr[0] = val;
            }
        }
        return strArr;
    }
}
