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

com.github.t1.testcontainers.jee.JarDeployable Maven / Gradle / Ivy

The newest version!
package com.github.t1.testcontainers.jee;

import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermission;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;

import static java.nio.file.Files.getPosixFilePermissions;
import static java.nio.file.Files.setPosixFilePermissions;

@Slf4j
@RequiredArgsConstructor
class JarDeployable extends Deployable {
    static JarDeployable of(Deployable deployable) {
        return (deployable instanceof JarDeployable)
            ? (JarDeployable) deployable
            : new JarDeployable(Deployable.copyOf(deployable));
    }

    private final Deployable deployable;
    private final Map, ModStore> mods = new LinkedHashMap<>();

    @Override public String toString() {
        return "JarDeployable[" + deployable + ":" + mods + "]";
    }

    public  T mod(Class type) {
        return type.cast(mods.computeIfAbsent(type, this::createModStore));
    }

    @SneakyThrows(ReflectiveOperationException.class)
    private  T createModStore(Class type) {return type.getConstructor().newInstance();}

    @Override public String getFileName() {return deployable.getFileName();}

    @Override public Path getLocalPath() {
        mods.values().forEach(mod -> inJarFile(mod::apply));
        return deployable.getLocalPath();
    }

    @SneakyThrows(IOException.class)
    private void inJarFile(Consumer operation) {
        Path path = deployable.getLocalPath();
        // opening the jar as a file system loses the file permission for group and other, but we need that
        Set permissions = getPosixFilePermissions(path);
        //noinspection RedundantCast // the cast is required for JDK 13+
        try (FileSystem jar = FileSystems.newFileSystem(path, (ClassLoader) null)) {
            operation.accept(jar);
        }
        setPosixFilePermissions(path, permissions);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy