UrlGeometryInput.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.geometry.io.core.input;

  18. import java.io.BufferedInputStream;
  19. import java.io.InputStream;
  20. import java.net.URL;
  21. import java.nio.charset.Charset;

  22. import org.apache.commons.geometry.io.core.AbstractGeometryIOMetadata;
  23. import org.apache.commons.geometry.io.core.internal.GeometryIOUtils;

  24. /** {@link GeometryInput} implementation for reading content from a URL.
  25.  */
  26. public class UrlGeometryInput extends AbstractGeometryIOMetadata
  27.     implements GeometryInput {

  28.     /** Input URL. */
  29.     private final URL url;

  30.     /** Construct a new instance for reading from the given URL.
  31.      * @param url input url
  32.      */
  33.     public UrlGeometryInput(final URL url) {
  34.         this(url, null);
  35.     }

  36.     /** Construct a new instance for reading from the given URL with the
  37.      * specified charset.
  38.      * @param url input URL
  39.      * @param charset charset to use when reading content
  40.      */
  41.     public UrlGeometryInput(final URL url, final Charset charset) {
  42.         super(GeometryIOUtils.getFileName(url), charset);

  43.         this.url = url;
  44.     }

  45.     /** Get the input URL.
  46.      * @return input URL
  47.      */
  48.     public URL getUrl() {
  49.         return url;
  50.     }

  51.     /** {@inheritDoc}
  52.      *
  53.      * <p>The returned input stream is buffered.</p>
  54.      */
  55.     @Override
  56.     public InputStream getInputStream() {
  57.         return GeometryIOUtils.getUnchecked(() -> new BufferedInputStream(url.openStream()));
  58.     }

  59.     /** {@inheritDoc} */
  60.     @Override
  61.     public String toString() {
  62.         final StringBuilder sb = new StringBuilder();
  63.         sb.append(getClass().getSimpleName())
  64.             .append("[url= ")
  65.             .append(getUrl())
  66.             .append(']');

  67.         return sb.toString();
  68.     }
  69. }