001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.geometry.io.core.input;
018
019import java.io.BufferedInputStream;
020import java.io.InputStream;
021import java.net.URL;
022import java.nio.charset.Charset;
023
024import org.apache.commons.geometry.io.core.AbstractGeometryIOMetadata;
025import org.apache.commons.geometry.io.core.internal.GeometryIOUtils;
026
027/** {@link GeometryInput} implementation for reading content from a URL.
028 */
029public class UrlGeometryInput extends AbstractGeometryIOMetadata
030    implements GeometryInput {
031
032    /** Input URL. */
033    private final URL url;
034
035    /** Construct a new instance for reading from the given URL.
036     * @param url input url
037     */
038    public UrlGeometryInput(final URL url) {
039        this(url, null);
040    }
041
042    /** Construct a new instance for reading from the given URL with the
043     * specified charset.
044     * @param url input URL
045     * @param charset charset to use when reading content
046     */
047    public UrlGeometryInput(final URL url, final Charset charset) {
048        super(GeometryIOUtils.getFileName(url), charset);
049
050        this.url = url;
051    }
052
053    /** Get the input URL.
054     * @return input URL
055     */
056    public URL getUrl() {
057        return url;
058    }
059
060    /** {@inheritDoc}
061     *
062     * <p>The returned input stream is buffered.</p>
063     */
064    @Override
065    public InputStream getInputStream() {
066        return GeometryIOUtils.getUnchecked(() -> new BufferedInputStream(url.openStream()));
067    }
068
069    /** {@inheritDoc} */
070    @Override
071    public String toString() {
072        final StringBuilder sb = new StringBuilder();
073        sb.append(getClass().getSimpleName())
074            .append("[url= ")
075            .append(getUrl())
076            .append(']');
077
078        return sb.toString();
079    }
080}