net.scriptability.core.url.DefaultURLResolver.java Source code

Java tutorial

Introduction

Here is the source code for net.scriptability.core.url.DefaultURLResolver.java

Source

/*
 * Copyright 2013 Hayden Bakkum
 *
 *  Licensed 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 net.scriptability.core.url;

import com.google.common.base.Preconditions;
import net.scriptability.core.util.ResourceLoader;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Default URL resolver. Uses {@link java.net.URL#openStream()} to load resources so this loader will
 * support any protocols that have a registered protocol handler. In addition to this, it also supports
 * the loading of class path resources using the <b>classpath:</b> protocol prefix.
 *
 * @author Hayden Bakkum
 */
public class DefaultURLResolver implements URLResolver {

    /**
     * SLF4J logger
     */
    private static final Logger LOG = LoggerFactory.getLogger(URLResolver.class);

    /**
     * Protocol prefix used for class path URLs
     */
    private static final String CLASSPATH_URL_PREFIX = "classpath:";

    /**
     * Resolves a URL and returns an input stream to its resource.
     *
     * @param url url to resolve
     * @return input stream to the resource addressed by the received URL
     * @throws URLResolutionException if the URL cannot be resolved
     */
    @Override
    public InputStream resolve(final URL url) throws URLResolutionException {
        Preconditions.checkNotNull(url, "URL cannot be null.");

        LOG.debug("Resolving URL: [{}].", url.toString());

        return openURLStream(url);
    }

    /**
     * Resolves a URL and returns an input stream to its resource.
     *
     * @param url url to resolve
     * @return input stream to the resource addressed by the received URL
     * @throws URLResolutionException if the URL cannot be resolved
     */
    @Override
    public InputStream resolve(final String url) throws URLResolutionException {
        Preconditions.checkArgument(StringUtils.isNotBlank(url), "URL cannot be blank.");

        LOG.debug("Resolving URL: [{}].", url);

        final InputStream urlInputStream;
        if (url.startsWith(CLASSPATH_URL_PREFIX)) {
            urlInputStream = ResourceLoader
                    .getResourceAsStream(StringUtils.substringAfter(url, CLASSPATH_URL_PREFIX));
            if (urlInputStream == null) {
                throw new URLResolutionException("Resource does not exist: [" + url + "].");
            }
        } else {
            try {
                urlInputStream = openURLStream(new URL(url));
            } catch (final MalformedURLException malformedUrlEx) {
                throw new URLResolutionException("URL is malformed: [" + malformedUrlEx + "].", malformedUrlEx);
            }
        }

        return urlInputStream;
    }

    /**
     * Resolves a URL and returns a string representation of the resource.
     *
     * @param url url to resolve
     * @return string representation of the resource addressed by the received URL
     * @throws URLResolutionException if the URL cannot be resolved
     */
    @Override
    public String resolveAsString(final URL url) throws URLResolutionException {
        final InputStream input = resolve(url);

        try {
            return IOUtils.toString(input);
        } catch (final IOException ioEx) {
            throw new URLResolutionException("Error opening input stream to URL: [" + url.toString() + "].", ioEx);
        } finally {
            IOUtils.closeQuietly(input);
        }
    }

    /**
     * Resolves a URL and returns a string representation of the resource.
     *
     * @param url url to resolve
     * @return string representation of the resource addressed by the received URL
     * @throws URLResolutionException if the URL cannot be resolved
     */
    @Override
    public String resolveAsString(final String url) throws URLResolutionException {
        final InputStream input = resolve(url);

        try {
            return IOUtils.toString(input);
        } catch (final IOException ioEx) {
            throw new URLResolutionException("Error opening input stream to URL: [" + url + "].", ioEx);
        } finally {
            IOUtils.closeQuietly(input);
        }
    }

    private InputStream openURLStream(final URL url) throws URLResolutionException {
        try {
            return url.openStream();

        } catch (final IOException ioEx) {
            throw new URLResolutionException("Error opening input stream to URL: [" + url.toString() + "].", ioEx);
        }
    }

}