]> git.somenet.org - pub/jan/dst18.git/blob - ass2-aop/src/test/java/dst/ass2/aop/util/JarUtils.java
Add template for assignment 2
[pub/jan/dst18.git] / ass2-aop / src / test / java / dst / ass2 / aop / util / JarUtils.java
1 package dst.ass2.aop.util;
2
3 import static org.apache.commons.io.FileUtils.openOutputStream;
4 import static org.apache.commons.io.IOUtils.copy;
5 import static org.apache.commons.lang3.StringUtils.defaultIfBlank;
6 import static org.apache.commons.lang3.StringUtils.join;
7 import static org.springframework.util.ClassUtils.CLASS_FILE_SUFFIX;
8 import static org.springframework.util.ClassUtils.convertClassNameToResourcePath;
9
10 import java.io.File;
11 import java.io.IOException;
12 import java.util.jar.JarEntry;
13 import java.util.jar.JarOutputStream;
14 import java.util.zip.ZipOutputStream;
15
16 import org.apache.commons.io.input.AutoCloseInputStream;
17 import org.springframework.core.io.ClassPathResource;
18
19 /**
20  * Builds plugin JARs on demand.
21  *
22  * This class is for internal purposes only.
23  * Note that the {@link #main(String...)} method can be adjusted to create other plugins.
24  */
25 public final class JarUtils {
26     private JarUtils() {
27     }
28
29     public static void main(String... args) throws IOException {
30         String path = join(args, " ");
31         File dir = new File(defaultIfBlank(path, "ass2-aop/src/test/resources"));
32
33         createJar(new File(dir, "simple.zip"),
34                 "dst.ass2.aop.sample.SimplePluginExecutable"
35         );
36
37         createJar(new File(dir, "all.zip"),
38                 "dst.ass2.aop.sample.SimplePluginExecutable",
39                 "dst.ass2.aop.sample.IgnoredPluginExecutable"
40         );
41     }
42
43     /**
44      * Creates a new JAR file containing the given classes.
45      *
46      * @param jarFile the destination JAR file
47      * @param classes the classes to add
48      * @throws IOException if an I/O error has occurred
49      */
50     public static void createJar(File jarFile, String... classes) throws IOException {
51         try (JarOutputStream stream = new JarOutputStream(openOutputStream(jarFile))) {
52             stream.setLevel(ZipOutputStream.STORED);
53             for (String clazz : classes) {
54                 String path = convertClassNameToResourcePath(clazz) + CLASS_FILE_SUFFIX;
55                 stream.putNextEntry(new JarEntry(path));
56                 copy(new AutoCloseInputStream(new ClassPathResource(path).getInputStream()), stream);
57             }
58         }
59     }
60 }