io.cloudine.rhq.plugins.worker.ResourceUtils.java Source code

Java tutorial

Introduction

Here is the source code for io.cloudine.rhq.plugins.worker.ResourceUtils.java

Source

/**
 * 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 io.cloudine.rhq.plugins.worker;

import org.apache.commons.io.IOUtils;
import org.slf4j.helpers.MessageFormatter;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.ClassUtils;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;

/**
 * Resource Utilty. ?  ? ?  ?  URL ? ?    .
 * ?  ? Spring Framework? {@link org.springframework.util.ResourceUtils} ?  ?? 
 *  ?.
 *
 * @author Byoung Gon, Kim
 * @see {@link org.springframework.util.ResourceUtils}
 * @since 2.0
 */
public class ResourceUtils {

    /**
     * ClASSPATH? ? ? Pseudo URL prefix : "classpath:"
     */
    public static final String CLASSPATH_URL_PREFIX = "classpath:";

    /**
     * ? ? ? ? URL prefix : "file:"
     */
    public static final String FILE_URL_PREFIX = "file:";

    /**
     * ?  ? ??  URL protocol : "file"
     */
    public static final String URL_PROTOCOL_FILE = "file";

    /**
     * Jar ??   URL protocol : "jar"
     */
    public static final String URL_PROTOCOL_JAR = "jar";

    /**
     * Zip ??   URL protocol : "zip"
     */
    public static final String URL_PROTOCOL_ZIP = "zip";

    /**
     * JAR ? ? ?  JAR URL ? seperator
     */
    public static final String JAR_URL_SEPARATOR = "!/";

    /**
     *    ?(Spring Framework)
     */
    public static final ResourceLoader resourceLoader = new DefaultResourceLoader();

    /**
     *  ?  URL?  ?.   "classpath" ?  URL? ?? .
     *
     * @param resourceLocation  
     * @return URL?  <tt>true</tt>
     * @see #CLASSPATH_URL_PREFIX
     * @see java.net.URL
     */
    public static boolean isUrl(String resourceLocation) {
        if (resourceLocation == null) {
            return false;
        }
        if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
            return true;
        }
        try {
            new URL(resourceLocation);
            return true;
        } catch (MalformedURLException e) {
            return false;
        }
    }

    /**
     *  ? URL?  {@link java.net.URL}? .
     *
     * @param resourceLocation ? URL
     * @return ?? {@link java.net.URL} ?
     * @throws java.io.FileNotFoundException ?? ?   
     */
    public static URL getURL(String resourceLocation) throws FileNotFoundException {
        if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
            String path = resourceLocation.substring(CLASSPATH_URL_PREFIX.length());
            URL url = ClassUtils.getDefaultClassLoader().getResource(path);
            if (url == null) {
                String description = "CLASSPATH  [" + path + "]";
                throw new FileNotFoundException(description
                        + "? URL? ?  .  URL? ??  ?.");
            }
            return url;
        }
        try {
            // URL ?
            return new URL(resourceLocation);
        } catch (MalformedURLException e) {
            // no URL -> ?  
            try {
                return new URL(FILE_URL_PREFIX + resourceLocation);
            } catch (MalformedURLException mue) {
                throw new FileNotFoundException("  [" + resourceLocation
                        + "]? URL?  ??? ? ? .");
            }
        }
    }

    /**
     *  ?  ? ? {@link java.io.File} .  ??   .
     *
     * @param resourceLocation ? . ?   ? "classpath:", "file:" ? ? ?  .
     * @return ?? {@link java.io.File} ?
     * @throws java.io.FileNotFoundException ?? ?   
     */
    public static File getFile(String resourceLocation) throws FileNotFoundException {
        if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
            String path = resourceLocation.substring(CLASSPATH_URL_PREFIX.length());
            String description = "CLASSPATH  [" + path + "]";
            URL url = getDefaultClassLoader().getResource(path);
            if (url == null) {
                throw new FileNotFoundException(description
                        + "?  ?  . ? ? ?   .");
            }
            return getFile(url, description);
        }
        try {
            // URL ?
            return getFile(new URL(resourceLocation));
        } catch (MalformedURLException e) {
            // no URL -> ?  
            return new File(resourceLocation);
        }
    }

    /**
     *  ? ? . ?    ? ?  ? ? ? ?  ?  ? ? ? <tt>null</tt>?? ? ? 
     * ? ? .
     *
     * @return ? ?
     */
    private static ClassLoader getDefaultClassLoader() {
        ClassLoader cl = null;
        try {
            cl = Thread.currentThread().getContextClassLoader();
        } catch (Throwable e) {
            e.printStackTrace();
            System.out.println("Cannot access context loader of thread. Use system class loader");
        }
        if (cl == null) {
            //  ? ? ? ? -> ? ?? ? ?  
            cl = ResourceUtils.class.getClassLoader();
        }
        return cl;
    }

    /**
     *  ?  ? ? {@link java.io.File} .
     *
     * @param resourceUrl ? 
     * @return ?? {@link java.io.File} ?
     * @throws java.io.FileNotFoundException ?? ?   
     */
    public static File getFile(URL resourceUrl) throws FileNotFoundException {
        return getFile(resourceUrl, "URL");
    }

    /**
     *  ?  ? ? {@link java.io.File} .
     *
     * @param resourceUrl ? 
     * @param description ?  ?  (; ?  )
     * @return ?? {@link java.io.File} ?
     * @throws java.io.FileNotFoundException ?? ?   
     */
    @SuppressWarnings({ "deprecation" })
    public static File getFile(URL resourceUrl, String description) throws FileNotFoundException {
        if (!URL_PROTOCOL_FILE.equals(resourceUrl.getProtocol())) {
            String message = MessageFormatter
                    .format("'{}' is not absolute path because does not exists.", description, resourceUrl)
                    .getMessage();
            throw new FileNotFoundException(message);
        }
        return new File(URLDecoder.decode(resourceUrl.getFile()));
    }

    /**
     *  URL? Jar ? ?   ? ?. , "jar", "zip"?   ? ?. "zip"? WebLogic?  Jar ? .
     *
     * @param url  URL
     * @return JAR ?? 
     */
    public static boolean isJarURL(URL url) {
        String protocol = url.getProtocol();
        return (URL_PROTOCOL_JAR.equals(protocol) || URL_PROTOCOL_ZIP.equals(protocol));
    }

    /**
     *  URL(Jar ??   ? Jar ?  ?)   Jar ??  URL? (Jar ?  ? ? Jar ? ?   ?).
     *
     * @param jarUrl ?  
     * @return ?? {@link java.net.URL} ?
     * @throws java.net.MalformedURLException URL ?? ? 
     */
    public static URL extractJarFileURL(URL jarUrl) throws MalformedURLException {
        String urlFile = jarUrl.getFile();
        int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR);
        if (separatorIndex != -1) {
            String jarFile = urlFile.substring(0, separatorIndex);
            try {
                return new URL(jarFile);
            } catch (MalformedURLException e) {
                // ? ? Jar URL ? ?   ?(; "jar:C:/mypath/myjar.jar").
                // ? ?  Jar ??   ?
                if (!jarFile.startsWith("/")) {
                    jarFile = "/" + jarFile;
                }
                return new URL(FILE_URL_PREFIX + jarFile);
            }
        } else {
            return jarUrl;
        }
    }

    /**
     *  ?  {@link org.springframework.core.io.Resource} .
     *
     * @param location  
     * @return {@link org.springframework.core.io.Resource}
     */
    public static Resource getResource(String location) {
        return resourceLoader.getResource(location);
    }

    /**
     *  ?  {@link org.springframework.core.io.Resource}? ? ? .
     *
     * @param location  
     * @return {@link org.springframework.core.io.Resource}? ? 
     * @throws java.io.IOException     
     */
    public static String getResourceTextContents(String location) throws IOException {
        Resource resource = resourceLoader.getResource(location);
        InputStream inputStream = resource.getInputStream();
        return getResourceTextContents(inputStream);
    }

    /**
     *  ?  {@link org.springframework.core.io.Resource}? ? ? .
     *
     * @param inputStream   
     * @return {@link org.springframework.core.io.Resource}? ? 
     * @throws java.io.IOException  ?    
     */
    public static String getResourceTextContents(InputStream inputStream) throws IOException {
        StringWriter stringWriter = new StringWriter();
        IOUtils.copy(inputStream, stringWriter);
        return stringWriter.toString();
    }

    /**
     *  ?  {@link org.springframework.core.io.Resource}? ? ?  .
     *
     * @param location  
     * @return {@link org.springframework.core.io.Resource}? ?  
     * @throws java.io.IOException     
     */
    public static byte[] getResourceByteContents(String location) throws IOException {
        Resource resource = resourceLoader.getResource(location);
        return getResourceByteContents(resource);
    }

    /**
     *  ?  {@link org.springframework.core.io.Resource}? ? ? .
     *
     * @param resource 
     * @return {@link org.springframework.core.io.Resource}? ?  
     * @throws java.io.IOException     
     */
    public static String getResourceTextContents(Resource resource) throws IOException {
        byte[] resourceByteContents = getResourceByteContents(resource);
        return new String(resourceByteContents, "UTF-8");
    }

    /**
     *  ?  {@link org.springframework.core.io.Resource}? ? ?  .
     *
     * @param resource 
     * @return {@link org.springframework.core.io.Resource}? ?  
     * @throws java.io.IOException ??    
     */
    public static byte[] getResourceByteContents(Resource resource) throws IOException {
        InputStream inputStream = resource.getInputStream();
        int size = inputStream.available();
        byte[] bytes = new byte[size];
        inputStream.read(bytes);
        return bytes;
    }
}