All Downloads are FREE. Search and download functionalities are using the official Maven repository.

br.com.objectos.core.net.Wget Maven / Gradle / Ivy

There is a newer version: 0.5.0
Show newest version
/*
 * Copyright 2015 Objectos, Fábrica de Software LTDA.
 *
 * 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 br.com.objectos.core.net;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

import br.com.objectos.core.io.Directory;
import br.com.objectos.core.io.File;

/**
 * @author [email protected] (Marcio Endo)
 */
public class Wget {

  private final URL url;
  private final Timeout timeout;
  private final Naming naming;

  Wget(URL url, Timeout timeout, Naming naming) {
    this.url = url;
    this.timeout = timeout;
    this.naming = naming;
  }

  public static WgetBuilder url(String urlSpec) {
    return WgetBuilderPojo.url(urlSpec);
  }

  public Download downloadTo(Directory dir) {
    File file = naming.fileAt(dir);
    try {
      Task task = new Task(file);
      return timeout.get(task);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
      return new ExceptionDownload(file, e);
    }
  }

  private class Task implements Callable {

    private final File file;

    public Task(File file) {
      this.file = file;
    }

    @Override
    public Download call() throws Exception {
      try (InputStream in = url.openStream()) {
        file.writeChecked(in);
        return new SimpleDownload(file);
      } catch (IOException e) {
        return new ExceptionDownload(file, e);
      }
    }

  }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy