/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.apache.brooklyn.util.core.javalang;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;

import org.apache.brooklyn.util.core.ResourceUtils;
import org.apache.brooklyn.util.exceptions.Exceptions;

/** like URLClassLoader (and delegates to it) but:
 * * has a nice toString
 * * supports var args constructor
 * * supports file://~/xxx semantics (remaps it to user.home); 
 *      ideally we'd also support mvn, classpath, osgi, etc
 */
public class UrlClassLoader extends URLClassLoader {

    private URL[] urls;

    public UrlClassLoader(URL ...urls) {
        super(tidy(urls));
        this.urls = urls;
    }

    public UrlClassLoader(String ...urls) {
        this(asUrls(urls));
    }
    
    private static URL[] asUrls(String[] urls) {
        URL[] urlo = new URL[urls.length];
        try {
        for (int i=0; i<urls.length; i++)
            urlo[i] = new URL(urls[i]);
        } catch (MalformedURLException e) {
            throw Exceptions.propagate(e);
        }
        return urlo;
    }

    private static URL[] tidy(URL[] urls) {
        for (int i=0; i<urls.length; i++)
            urls[i] = ResourceUtils.tidy(urls[i]);
        return urls;
    }

    @Override
    public String toString() {
        return "UrlClassLoader"+Arrays.asList(urls);
    }
}
