com.heimuheimu.runningtask.task.service.support.SimpleURLClassLoaderFactory.java Source code

Java tutorial

Introduction

Here is the source code for com.heimuheimu.runningtask.task.service.support.SimpleURLClassLoaderFactory.java

Source

/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 heimuheimu
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.heimuheimu.runningtask.task.service.support;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.heimuheimu.runningtask.task.service.URLClassLoaderFactory;

/**
 * {@link java.net.URLClassLoader}?
 * <p>?{@link #setCommonResource(String)}??ClassLoader
 * ??spring?log4jjar?
 * ?{@link java.net.URLClassLoader}???
 *
 * @author heimuheimu
 * @date 20141112
 */
@Service
public class SimpleURLClassLoaderFactory implements URLClassLoaderFactory {

    private static final Logger LOG = LoggerFactory.getLogger(SimpleURLClassLoaderFactory.class);

    /**
     * ?spring?log4jjar
     * 
     * @see {@link #parentClassLoader}
     */
    private String commonResource = "";

    /**
     * ClassLoader?{@link commonResource}?
     * {@link java.net.URLClassLoader}?ClassLoaderClassLoader
     * <p>{@link commonResource}null?ClassLoader
     */
    private URLClassLoader parentClassLoader = null;

    /**
     * ?spring?log4jjar?null
     * <p>??
     * 
     * @param commonResource
     */
    public void setCommonResource(String commonResource) {
        this.commonResource = commonResource;
    }

    /**
     * ?ClassLoader
     * <p>?
     * 
     * @see {@link #setCommonResource(String)}
     * @see {@link #parentClassLoader}
     */
    @PostConstruct
    public void init() {
        if (commonResource != null && !commonResource.isEmpty()) {
            long startTime = System.currentTimeMillis();
            URL[] urls = getURLArray(commonResource);
            parentClassLoader = new URLClassLoader(urls, parentClassLoader);
            LOG.info("Create parent URLClassLoader success. Cost: `{}` ms. Common resource path: `{}`",
                    System.currentTimeMillis() - startTime, commonResource);
        }
    }

    /**
     * ClassLoader??
     * <p>??
     * 
     * @see {@link #setCommonResource(String)}
     * @see {@link #parentClassLoader}
     * @see {@link URLClassLoader#close()}
     */
    @PreDestroy
    public void shutdown() {
        if (parentClassLoader != null) {
            long startTime = System.currentTimeMillis();
            try {
                parentClassLoader.close();
                LOG.info("Close parent URLClassLoader success. Cost: `{}` ms. Common resource path: `{}`",
                        System.currentTimeMillis() - startTime, commonResource);
            } catch (IOException e) {
                LOG.error("Close parent URLClassLoader fail. Cost: `" + (System.currentTimeMillis() - startTime)
                        + "`ms. Common resource path: `" + commonResource + "`", e);
            }
        }
    }

    @Override
    public URLClassLoader create(boolean useParentClassLoader, String... localFilePaths)
            throws NullPointerException, IllegalArgumentException {
        long startTime = System.currentTimeMillis();
        URL[] urls = getURLArray(localFilePaths);
        URLClassLoader parent = useParentClassLoader ? parentClassLoader : null;
        URLClassLoader loader = new URLClassLoader(urls, parent);
        LOG.info("Create URLClassLoader success. Cost `{}`ms. Local file paths: `{}`.",
                System.currentTimeMillis() - startTime, Arrays.toString(urls));
        return loader;
    }

    private URL[] getURLArray(String... localFilePaths) {
        if (localFilePaths == null) {
            throw new NullPointerException("Local file paths could not be null.");
        }
        if (localFilePaths.length == 0) {
            throw new IllegalArgumentException("Local file paths could not be empty.");
        }
        URL[] urls = new URL[localFilePaths.length];
        for (int i = 0; i < localFilePaths.length; i++) {
            urls[i] = getURL(localFilePaths[i]);
        }
        return urls;
    }

    private URL getURL(String localFilePath) {
        File file = new File(localFilePath);
        if (!file.exists()) {
            throw new IllegalArgumentException("Local file path is not exist: `" + localFilePath + "`");
        }
        try {
            return file.toURI().toURL();
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("Illegal local file path: `" + localFilePath + "`", e);
        }
    }

}