001    /*****************************************************************************
002     * Copyright (C) NanoContainer Organization. All rights reserved.            *
003     * ------------------------------------------------------------------------- *
004     * The software in this package is published under the terms of the BSD      *
005     * style license a copy of which has been included with this distribution in *
006     * the LICENSE.txt file.                                                     *
007     *                                                                           *
008     *****************************************************************************/
009    
010    package org.nanocontainer.script;
011    
012    import org.nanocontainer.ClassPathElement;
013    import org.nanocontainer.NanoContainer;
014    
015    import java.net.URL;
016    import java.net.MalformedURLException;
017    import java.security.AccessController;
018    import java.security.PrivilegedAction;
019    import java.io.File;
020    
021    public class ClassPathElementHelper {
022        public static final String HTTP = "http://";
023    
024        public static ClassPathElement addClassPathElement(final String path, NanoContainer nanoContainer) {
025            URL pathURL = null;
026            try {
027                if (path.toLowerCase().startsWith(HTTP)) {
028                    pathURL = new URL(path);
029                } else {
030                    Object rVal = AccessController.doPrivileged(new PrivilegedAction() {
031                        public Object run() {
032                            try {
033                                File file = new File(path);
034                                if (!file.exists()) {
035                                    return new NanoContainerMarkupException("classpath '" + path + "' does not exist ");
036                                }
037                                return file.toURL();
038                            } catch (MalformedURLException e) {
039                                return e;
040                            }
041    
042                        }
043                    });
044                    if (rVal instanceof MalformedURLException) {
045                        throw (MalformedURLException) rVal;
046                    }
047                    if (rVal instanceof NanoContainerMarkupException) {
048                        throw (NanoContainerMarkupException) rVal;
049                    }
050                    pathURL = (URL) rVal;
051                }
052            } catch (MalformedURLException e) {
053                throw new NanoContainerMarkupException("classpath '" + path + "' malformed ", e);
054            }
055            return nanoContainer.addClassLoaderURL(pathURL);
056        }
057    }