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

ee.schimke.oksocial.output.DownloadHandler Maven / Gradle / Ivy

There is a newer version: 4.19.0
Show newest version
package ee.schimke.oksocial.output;

import java.io.File;
import java.io.IOException;
import okio.BufferedSource;
import okio.Okio;
import okio.Sink;

import static ee.schimke.oksocial.output.util.OutputUtil.systemOut;

public class DownloadHandler implements OutputHandler {
  private ResponseExtractor responseExtractor;

  private File outputFile;

  public DownloadHandler(ResponseExtractor responseExtractor, File outputFile) {
    this.responseExtractor = responseExtractor;
    this.outputFile = outputFile;
  }

  @Override public void showOutput(R response) throws IOException {
    BufferedSource source = responseExtractor.source(response);

    Sink outputSink = getOutputSink(response);
    try {
      writeToSink(source, outputSink);
    } finally {
      if (!isStdout()) {
        outputSink.close();
      }
    }
  }

  public Sink getOutputSink(R response) throws IOException {
    if (isStdout()) {
      return systemOut();
    } else if (outputFile.isDirectory()) {
      File responseOutputFile = new File(outputFile, responseExtractor.filename(response));
      System.err.println("Saving " + responseOutputFile);
      return Okio.sink(responseOutputFile);
    } else {
      if (outputFile.getParentFile() != null && !outputFile.getParentFile().exists()) {
        if (!outputFile.getParentFile().mkdirs()) {
          throw new IOException("unable to create directory " + outputFile);
        }
      }
      return Okio.sink(outputFile);
    }
  }

  private boolean isStdout() {
    return outputFile.getPath().equals("-");
  }

  public static void writeToSink(BufferedSource source, Sink out) throws IOException {
    while (!source.exhausted()) {
      out.write(source.buffer(), source.buffer().size());
      out.flush();
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy