package org.eclipse.stp.sc.common.utils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;

import org.eclipse.stp.common.logging.LoggingProxy;

public class RuntimeUtils {
private static final LoggingProxy LOG = LoggingProxy.getlogger(RuntimeUtils.class);
	
	/**
	 * get list of jar name defined in MANIFEST.MF/classpath for input jar file   
	 * @param jarFileName, jar file name
	 * @return, jar names defined in MANIFEST.ME/classpath
	 */
	public static String[] getLibEntryInManifest(String jarFileName) {
		File facadeFile = new File(jarFileName);
		ArrayList<String> libs = new ArrayList<String>();
		try {
			JarFile facadeJar = new JarFile(facadeFile);
			Manifest mfst = facadeJar.getManifest();
			Attributes attrs = mfst.getMainAttributes();
			String path = attrs.getValue("Class-Path");
			StringTokenizer tkzr = new StringTokenizer(path);
			String libEntry = null;
			while (tkzr.hasMoreTokens()) {
				libEntry = tkzr.nextToken();
				libs.add(libEntry);
			}
		} catch (IOException e) {
			LOG.debug("Exception getting jar facade", e);
		}
		return libs.toArray(new String[0]);
	}
	
	/**
	 * get all jars under one dir
	 * @param path, the path to look
	 * @return, the list of jars
	 */
	public static String[] getLibEntryByDir(String path) {
		File dir = new File(path);
		ArrayList<String> libs = new ArrayList<String>();
		if (!dir.exists() || !dir.isDirectory()) {
			return new String[0];
		}
		for (String fileName : dir.list()) {
			if (fileName.endsWith(".jar")) {
				libs.add(fileName);
			}
		}
		return libs.toArray(new String[0]);
	}
}
