org.johansv.maven.plugins.buildproperties.reader.AbstractPropertiesReader.java Source code

Java tutorial

Introduction

Here is the source code for org.johansv.maven.plugins.buildproperties.reader.AbstractPropertiesReader.java

Source

/*
 * Copyright 2011 Johan Svensson
 * 
 * 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 org.johansv.maven.plugins.buildproperties.reader;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.io.Closeables;
import org.johansv.maven.plugins.buildproperties.exception.PropertiesReaderException;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Contains the implementation for reading standard Java properties from an input stream. Used by the concrete implementation classes for different types of sources.
 */
public abstract class AbstractPropertiesReader<T> implements PropertiesReader<T> {

    /**
     * Reads properties from an {@link InputStream}.
     *
     * @param inputStream the input stream to read from.
     * @return the properties that have been read.
     * @throws IOException if thrown from the properties load method.
     */
    private Properties readProperties(InputStream inputStream) throws IOException {
        Properties properties = createProperties();
        properties.load(inputStream);
        return properties;
    }

    /**
     * {@inheritDoc}
     */
    public Properties read(T source) {
        InputStream in = null;
        try {
            in = getInputStream(source);
            return readProperties(in);
        } catch (IOException exc) {
            throw new PropertiesReaderException("Failed reading properties from source: " + source, exc);
        } finally {
            Closeables.closeQuietly(in);
        }
    }

    /**
     * Instantiates a new {@link Properties} instance.
     *
     * @return a properties instance.
     */
    @VisibleForTesting
    Properties createProperties() {
        return new Properties();
    }

    /**
     * Creates an {@link InputStream} from the source.
     *
     * @param source the source use to create the input stream.
     * @return an input stream.
     * @throws IOException
     */
    protected abstract InputStream getInputStream(T source) throws IOException;

}