001/*
002 * To change this license header, choose License Headers in Project Properties.
003 * To change this template file, choose Tools | Templates
004 * and open the template in the editor.
005 */
006package org.anarres.qemu.examples;
007
008import com.google.common.base.Charsets;
009import com.google.common.hash.HashCode;
010import com.google.common.hash.Hashing;
011import com.google.common.io.Closeables;
012import com.google.common.io.Files;
013import java.io.File;
014import java.io.IOException;
015import java.io.InputStream;
016import java.net.URI;
017import javax.annotation.Nonnegative;
018import javax.annotation.Nonnull;
019import org.anarres.qemu.exec.QEmuMemoryOption;
020import org.anarres.qemu.image.QEmuImage;
021import org.anarres.qemu.image.QEmuImageFormat;
022import org.anarres.qemu.manager.QEmuManager;
023
024/**
025 *
026 * @author shevek
027 */
028public abstract class AbstractQEmuExample implements QEmuExample {
029
030    protected final QEmuManager manager = new QEmuManager();
031
032    @Nonnull
033    protected QEmuImage newImage(@Nonnull String name) throws IOException {
034        File dir = new File("build/images/local");
035        dir.mkdirs();
036        return new QEmuImage(new File(dir, getClass().getSimpleName() + "-" + name));
037    }
038
039    @Nonnull
040    protected QEmuImage newImage(@Nonnull String name, @Nonnegative long size, @Nonnull QEmuMemoryOption.Magnitude magnitude) throws IOException {
041        QEmuImageFormat format = QEmuImageFormat.qcow2;
042        QEmuImage image = newImage(name + "." + format);
043        image.create(format, magnitude.toUnit(size));
044        return image;
045    }
046
047    @Nonnull
048    private File download(@Nonnull URI source) throws IOException {
049        File dir = new File("build/images/downloaded");
050        HashCode hash = Hashing.md5().hashString(source.toString(), Charsets.UTF_8);
051        File file = new File(dir, hash.toString());
052        if (!file.exists()) {
053            InputStream in = source.toURL().openStream();
054            try {
055                Files.asByteSink(file).writeFrom(in);
056            } finally {
057                Closeables.close(in, false);
058            }
059        }
060        return file;
061    }
062
063    @Nonnull
064    protected QEmuImage newImage(@Nonnull String name, @Nonnull URI source) throws IOException {
065        QEmuImageFormat format = QEmuImageFormat.qcow2;
066        QEmuImage image = newImage(name + "." + format);
067
068        File file = download(source);
069        image.create(QEmuImageFormat.qcow2, file);
070        return image;
071    }
072
073}