001: // ========================================================================
002: // Copyright (c) 2002 Mort Bay Consulting (Australia) Pty. Ltd.
003: // $Id: Classpath.java 6177 2007-02-19 10:11:27Z aaime $
004: // ========================================================================
005: package org.mortbay.start;
006:
007: import java.io.File;
008: import java.io.IOException;
009: import java.net.MalformedURLException;
010: import java.net.URL;
011: import java.net.URLClassLoader;
012: import java.util.StringTokenizer;
013: import java.util.Vector;
014:
015: /**
016: * Class to handle CLASSPATH construction
017: * @author Jan Hlavat�
018: */
019: public class Classpath {
020: Vector _elements = new Vector();
021:
022: public Classpath() {
023: }
024:
025: public Classpath(String initial) {
026: addClasspath(initial);
027: }
028:
029: public boolean addComponent(String component) {
030: if ((component != null) && (component.length() > 0)) {
031: try {
032: File f = new File(component);
033:
034: if (f.exists()) {
035: File key = f.getCanonicalFile();
036:
037: if (!_elements.contains(key)) {
038: _elements.add(key);
039:
040: return true;
041: }
042: }
043: } catch (IOException e) {
044: }
045: }
046:
047: return false;
048: }
049:
050: public boolean addComponent(File component) {
051: if (component != null) {
052: try {
053: if (component.exists()) {
054: File key = component.getCanonicalFile();
055:
056: if (!_elements.contains(key)) {
057: _elements.add(key);
058:
059: return true;
060: }
061: }
062: } catch (IOException e) {
063: }
064: }
065:
066: return false;
067: }
068:
069: public boolean addClasspath(String s) {
070: boolean added = false;
071:
072: if (s != null) {
073: StringTokenizer t = new StringTokenizer(s,
074: File.pathSeparator);
075:
076: while (t.hasMoreTokens()) {
077: added |= addComponent(t.nextToken());
078: }
079: }
080:
081: return added;
082: }
083:
084: public String toString() {
085: StringBuffer cp = new StringBuffer(1024);
086: int cnt = _elements.size();
087:
088: if (cnt >= 1) {
089: cp.append(((File) (_elements.elementAt(0))).getPath());
090: }
091:
092: for (int i = 1; i < cnt; i++) {
093: cp.append(File.pathSeparatorChar);
094: cp.append(((File) (_elements.elementAt(i))).getPath());
095: }
096:
097: return cp.toString();
098: }
099:
100: public ClassLoader getClassLoader() {
101: int cnt = _elements.size();
102: URL[] urls = new URL[cnt];
103:
104: for (int i = 0; i < cnt; i++) {
105: try {
106: urls[i] = ((File) (_elements.elementAt(i))).toURL();
107: } catch (MalformedURLException e) {
108: }
109: }
110:
111: ClassLoader parent = Thread.currentThread()
112: .getContextClassLoader();
113:
114: if (parent == null) {
115: parent = Classpath.class.getClassLoader();
116: }
117:
118: if (parent == null) {
119: parent = ClassLoader.getSystemClassLoader();
120: }
121:
122: return new URLClassLoader(urls, parent);
123: }
124: }
|