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

it.anyplace.web.BuildCache Maven / Gradle / Ivy

The newest version!
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.anyplace.web;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
import javax.annotation.Nullable;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author aleph
 */
public class BuildCache {

    private File cacheDir;

    public boolean checkReady() {
        if (cacheDir == null) {
            File tempDir = new File(System.getProperty("java.io.tmpdir"));
            if (tempDir.isDirectory() && tempDir.canWrite()) {
                cacheDir = new File(tempDir, "a-web-maven-plugin-cache");
                cacheDir.mkdirs();
                return true;
            } else {
                return false;
            }
        } else {
            return cacheDir.isDirectory() && cacheDir.canWrite();
        }
    }

    private String buildId(File file, @Nullable String specification) {
        return UUID.nameUUIDFromBytes((file.getPath() + "|" + file.length() + "|" + file.lastModified() + "|" + specification).getBytes()).toString();
    }

//    public void cacheResult(File sourceFile, @Nullable String specification, File resultFile) throws IOException {
//        cacheResult(sourceFile, specification, FileUtils.readFileToByteArray(resultFile));
//    }
    public void cacheResult(File sourceFile, @Nullable String specification, byte[] result) throws IOException {
        if (checkReady()) {
            String id = buildId(sourceFile, specification);
            FileUtils.writeByteArrayToFile(new File(cacheDir, id), result);
        }
    }

//    public @Nullable
//    byte[] getResult(byte[] source) throws IOException {
//        return getResult(source, null);
//    }
    public @Nullable
    File getResult(File sourceFile, @Nullable String specification) throws IOException {
        if (checkReady()) {
            String id = buildId(sourceFile, specification);
//            String id = UUID.nameUUIDFromBytes(source).toString() + "-" + UUID.nameUUIDFromBytes(Strings.nullToEmpty(specification).getBytes(ENC));
            File file = new File(cacheDir, id);
            if (file.exists()) {
                return file;
            }
        }
        return null;
    }

//    public @Nullable
//    String getResult(String source) throws IOException {
//        byte[] result = getResult(source.getBytes(ENC));
//        return result == null ? null : new String(result, ENC);
//    }
//    public void cacheResult(String source, String result) throws IOException {
//        cacheResult(source.getBytes(ENC), result.getBytes(ENC));
//    }
//    private static final String ENC = "UTF-8";
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy