001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.xbean.classpath;
018
019import java.net.URLClassLoader;
020import java.net.URL;
021import java.io.File;
022
023public class SystemClassPath extends SunURLClassPath {
024
025    private URLClassLoader sysLoader;
026
027    public void addJarsToPath(File dir) throws Exception {
028        this.addJarsToPath(dir, getSystemLoader());
029        this.rebuildJavaClassPathVariable();
030    }
031
032    public void addJarToPath(URL jar) throws Exception {
033        //System.out.println("[|] SYSTEM "+jar.toExternalForm());
034        this.addJarToPath(jar, getSystemLoader());
035        this.rebuildJavaClassPathVariable();
036    }
037
038    public ClassLoader getClassLoader() {
039        try {
040            return getSystemLoader();
041        } catch (Exception e) {
042            throw new RuntimeException(e);
043        }
044    }
045
046    private URLClassLoader getSystemLoader() throws Exception {
047        if (sysLoader == null) {
048            sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
049        }
050        return sysLoader;
051    }
052
053    private void rebuildJavaClassPathVariable() throws Exception {
054        sun.misc.URLClassPath cp = getURLClassPath(getSystemLoader());
055        URL[] urls = cp.getURLs();
056        //for (int i=0; i < urls.length; i++){
057        //    System.out.println(urls[i].toExternalForm());
058        //}
059        if (urls.length < 1)
060            return;
061
062        StringBuffer path = new StringBuffer(urls.length * 32);
063
064        File s = new File(urls[0].getFile());
065        path.append(s.getPath());
066        //System.out.println(s.getPath());
067
068        for (int i = 1; i < urls.length; i++) {
069            path.append(File.pathSeparator);
070
071            s = new File(urls[i].getFile());
072            //System.out.println(s.getPath());
073            path.append(s.getPath());
074        }
075        try {
076            System.setProperty("java.class.path", path.toString());
077        } catch (Exception e) {
078        }
079    }
080}