Create spring-loader-tools project

Create spring-loader-tools containing utilities that can be used
with both Maven and Gradle plugings.

Refactored existing Maven plugin to use the new project.

Issue: #53129653
This commit is contained in:
Phillip Webb
2013-07-28 21:48:19 -07:00
parent 7ea433dce2
commit 5e4238f38a
35 changed files with 1887 additions and 763 deletions

View File

@@ -0,0 +1,218 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.launcher.tools;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
/**
* Writes JAR content, ensuring valid directory entries are always create and duplicate
* items are ignored.
*
* @author Phillip Webb
*/
class JarWriter {
private static final String NESTED_LOADER_JAR = "/META-INF/loader/spring-boot-loader.jar";
private static final int BUFFER_SIZE = 4096;
private final JarOutputStream jarOutput;
private final Set<String> writtenEntries = new HashSet<String>();
/**
* Create a new {@link JarWriter} instance.
* @param file the file to write
* @throws IOException
* @throws FileNotFoundException
*/
public JarWriter(File file) throws FileNotFoundException, IOException {
this.jarOutput = new JarOutputStream(new FileOutputStream(file));
}
/**
* Write the specified manifest.
* @param manifest the manifest to write
* @throws IOException
*/
public void writeManifest(final Manifest manifest) throws IOException {
JarEntry entry = new JarEntry("META-INF/MANIFEST.MF");
writeEntry(entry, new EntryWriter() {
@Override
public void write(OutputStream outputStream) throws IOException {
manifest.write(outputStream);
}
});
}
/**
* Write all entries from the specified jar file.
* @param jarFile the source jar file
* @throws IOException
*/
public void writeEntries(JarFile jarFile) throws IOException {
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
EntryWriter entryWriter = new InputStreamEntryWriter(
jarFile.getInputStream(entry), true);
writeEntry(entry, entryWriter);
}
}
/**
* Write a nested library.
* @param destination the destination of the library
* @param file the library file
* @throws IOException
*/
public void writeNestedLibrary(String destination, File file) throws IOException {
JarEntry entry = new JarEntry(destination + file.getName());
entry.setSize(file.length());
entry.setCompressedSize(file.length());
entry.setCrc(getCrc(file));
entry.setMethod(ZipEntry.STORED);
writeEntry(entry, new InputStreamEntryWriter(new FileInputStream(file), true));
}
private long getCrc(File file) throws IOException {
FileInputStream inputStream = new FileInputStream(file);
try {
byte[] buffer = new byte[BUFFER_SIZE];
CRC32 crc = new CRC32();
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
crc.update(buffer, 0, bytesRead);
}
return crc.getValue();
}
finally {
inputStream.close();
}
}
/**
* Write the required spring-boot-loader classes to the JAR.
* @throws IOException
*/
public void writeLoaderClasses() throws IOException {
JarInputStream inputStream = new JarInputStream(getClass().getResourceAsStream(
NESTED_LOADER_JAR));
JarEntry entry;
while ((entry = inputStream.getNextJarEntry()) != null) {
if (entry.getName().endsWith(".class")) {
writeEntry(entry, new InputStreamEntryWriter(inputStream, false));
}
}
inputStream.close();
}
/**
* Close the writer.
* @throws IOException
*/
public void close() throws IOException {
this.jarOutput.close();
}
/**
* Perform the actual write of a {@link JarEntry}. All other {@code write} method
* delegate to this one.
* @param entry the entry to write
* @param entryWriter the entry writer or {@code null} if there is no content
* @throws IOException
*/
private void writeEntry(JarEntry entry, EntryWriter entryWriter) throws IOException {
String parent = entry.getName();
if (parent.endsWith("/")) {
parent = parent.substring(0, parent.length() - 1);
}
if (parent.lastIndexOf("/") != -1) {
parent = parent.substring(0, parent.lastIndexOf("/") + 1);
if (parent.length() > 0) {
writeEntry(new JarEntry(parent), null);
}
}
if (this.writtenEntries.add(entry.getName())) {
this.jarOutput.putNextEntry(entry);
if (entryWriter != null) {
entryWriter.write(this.jarOutput);
}
this.jarOutput.closeEntry();
}
}
/**
* Interface used to write jar entry date.
*/
private static interface EntryWriter {
/**
* Write entry data to the specified output stream
* @param outputStream the destination for the data
* @throws IOException
*/
void write(OutputStream outputStream) throws IOException;
}
/**
* {@link EntryWriter} that writes content from an {@link InputStream}.
*/
private static class InputStreamEntryWriter implements EntryWriter {
private final InputStream inputStream;
private final boolean close;
public InputStreamEntryWriter(InputStream inputStream, boolean close) {
this.inputStream = inputStream;
this.close = close;
}
public void write(OutputStream outputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = this.inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
if (this.close) {
this.inputStream.close();
}
}
}
}

View File

@@ -0,0 +1,47 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.launcher.tools;
/**
* Strategy interface used to determine the layout for a particular type of archive.
*
* @author Phillip Webb
* @see Layouts
*/
public interface Layout {
/**
* Returns the launcher class name for this layout.
* @return the launcher class name
*/
String getLauncherClassName();
/**
* Returns the destination path for a given library.
* @param libraryName the name of the library (excluding any path)
* @param scope the scope of the library
* @return the destination relative to the root of the archive (should end with '/')
* or {@code null} if the library should not be included.
*/
String getLibraryDestination(String libraryName, LibraryScope scope);
/**
* Returns the location of classes within the archive.
*/
String getClassesLocation();
}

View File

@@ -0,0 +1,100 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.launcher.tools;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Common {@link Layout}s.
*
* @author Phillip Webb
*/
public class Layouts {
/**
* Return the a layout for the given source file.
* @param file the source file
* @return a {@link Layout}
*/
public static Layout forFile(File file) {
if (file == null) {
throw new IllegalArgumentException("File must not be null");
}
if (file.getName().toLowerCase().endsWith(".jar")) {
return new Jar();
}
if (file.getName().toLowerCase().endsWith(".war")) {
return new War();
}
throw new IllegalStateException("Unable to deduce layout for '" + file + "'");
}
/**
* Executable JAR layout.
*/
public static class Jar implements Layout {
@Override
public String getLauncherClassName() {
return "org.springframework.boot.loader.JarLauncher";
}
@Override
public String getLibraryDestination(String libraryName, LibraryScope scope) {
return "lib/";
}
@Override
public String getClassesLocation() {
return "";
}
}
/**
* Executable WAR layout.
*/
public static class War implements Layout {
private static final Map<LibraryScope, String> SCOPE_DESTINATIONS;
static {
Map<LibraryScope, String> map = new HashMap<LibraryScope, String>();
map.put(LibraryScope.COMPILE, "WEB-INF/lib/");
map.put(LibraryScope.RUNTIME, "WEB-INF/lib/");
map.put(LibraryScope.PROVIDED, "WEB-INF/lib-provided/");
SCOPE_DESTINATIONS = Collections.unmodifiableMap(map);
}
@Override
public String getLauncherClassName() {
return "org.springframework.boot.loader.WarLauncher";
}
@Override
public String getLibraryDestination(String libraryName, LibraryScope scope) {
return SCOPE_DESTINATIONS.get(scope);
}
@Override
public String getClassesLocation() {
return "WEB-INF/classes/";
}
}
}

View File

@@ -0,0 +1,35 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.launcher.tools;
import java.io.IOException;
/**
* Encapsulates information about libraries that may be packed into the archive.
*
* @author Phillip Webb
*/
public interface Libraries {
/**
* Iterate all relevant libraries.
* @param callback a callback for each relevant library.
* @throws IOException
*/
void doWithLibraries(LibraryCallback callback) throws IOException;
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.launcher.tools;
import java.io.File;
import java.io.IOException;
/**
* Callback interface used to iterate {@link Libraries}.
*
* @author Phillip Webb
*/
public interface LibraryCallback {
/**
* Callback to for a single library backed by a {@link File}.
* @param file the library file
* @param scope the scope of the library
* @throws IOException
*/
void library(File file, LibraryScope scope) throws IOException;
}

View File

@@ -0,0 +1,58 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.launcher.tools;
/**
* The scope of a library. The common {@link #COMPILE}, {@link #RUNTIME} and
* {@link #PROVIDED} scopes are defined here and supported by the common {@link Layouts}.
* A custom {@link Layout} can handle additional scopes as required.
*
* @author Phillip Webb
*/
public interface LibraryScope {
/**
* The library is used at compile time and runtime.
*/
public static final LibraryScope COMPILE = new LibraryScope() {
@Override
public String toString() {
return "compile";
};
};
/**
* The library is used at runtime but not needed for compile.
*/
public static final LibraryScope RUNTIME = new LibraryScope() {
@Override
public String toString() {
return "runtime";
};
};
/**
* The library is needed for compile but is usually provided when running.
*/
public static final LibraryScope PROVIDED = new LibraryScope() {
@Override
public String toString() {
return "provided";
};
};
}

View File

@@ -0,0 +1,243 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.launcher.tools;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
/**
* Finds any class with a {@code public static main} method by performing a breadth first
* search.
*
* @author Phillip Webb
*/
public abstract class MainClassFinder {
private static final String DOT_CLASS = ".class";
private static final Type STRING_ARRAY_TYPE = Type.getType(String[].class);
private static final Type MAIN_METHOD_TYPE = Type.getMethodType(Type.VOID_TYPE,
STRING_ARRAY_TYPE);
private static final String MAIN_METHOD_NAME = "main";
private static final FileFilter CLASS_FILE_FILTER = new FileFilter() {
@Override
public boolean accept(File file) {
return (file.isFile() && file.getName().endsWith(DOT_CLASS));
}
};
private static final FileFilter PACKAGE_FOLDER_FILTER = new FileFilter() {
@Override
public boolean accept(File file) {
return file.isDirectory() && !file.getName().startsWith(".");
}
};
/**
* Find the main class from a given folder.
* @param rootFolder the root folder to search
* @return the main class or {@code null}
* @throws IOException
*/
public static String findMainClass(File rootFolder) throws IOException {
if (!rootFolder.isDirectory()) {
throw new IllegalArgumentException("Inavlid root folder '" + rootFolder + "'");
}
File mainClassFile = findMainClassFile(rootFolder);
if (mainClassFile == null) {
return null;
}
String mainClass = mainClassFile.getAbsolutePath();
return convertToClassName(mainClass, rootFolder.getAbsolutePath() + "/");
}
private static File findMainClassFile(File root) throws IOException {
Deque<File> stack = new ArrayDeque<File>();
stack.push(root);
while (!stack.isEmpty()) {
File file = stack.pop();
if (file.isFile()) {
InputStream inputStream = new FileInputStream(file);
try {
if (isMainClass(inputStream)) {
return file;
}
}
finally {
inputStream.close();
}
}
if (file.isDirectory()) {
pushAllSorted(stack, file.listFiles(PACKAGE_FOLDER_FILTER));
pushAllSorted(stack, file.listFiles(CLASS_FILE_FILTER));
}
}
return null;
}
private static void pushAllSorted(Deque<File> stack, File[] files) {
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return o1.getName().compareTo(o2.getName());
}
});
for (File file : files) {
stack.push(file);
}
}
/**
* Find the main class in a given jar file.
* @param jarFile the jar file to search
* @param classesLocation the location within the jar containing classes
* @return the main class or {@code null}
* @throws IOException
*/
public static String findMainClass(JarFile jarFile, String classesLocation)
throws IOException {
List<JarEntry> classEntries = getClassEntries(jarFile, classesLocation);
Collections.sort(classEntries, new ClassEntryComparator());
for (JarEntry entry : classEntries) {
InputStream inputStream = new BufferedInputStream(
jarFile.getInputStream(entry));
try {
if (isMainClass(inputStream)) {
String name = entry.getName();
name = convertToClassName(name, classesLocation);
return name;
}
}
finally {
inputStream.close();
}
}
return null;
}
private static String convertToClassName(String name, String prefix) {
name = name.replace("/", ".");
name = name.replace('\\', '.');
name = name.substring(0, name.length() - DOT_CLASS.length());
if (prefix != null) {
name = name.substring(prefix.length());
}
return name;
}
private static List<JarEntry> getClassEntries(JarFile source, String classesLocation) {
classesLocation = (classesLocation != null ? classesLocation : "");
Enumeration<JarEntry> sourceEntries = source.entries();
List<JarEntry> classEntries = new ArrayList<JarEntry>();
while (sourceEntries.hasMoreElements()) {
JarEntry entry = sourceEntries.nextElement();
if (entry.getName().startsWith(classesLocation)
&& entry.getName().endsWith(DOT_CLASS)) {
classEntries.add(entry);
}
}
return classEntries;
}
private static boolean isMainClass(InputStream inputStream) {
try {
ClassReader classReader = new ClassReader(inputStream);
MainMethodFinder mainMethodFinder = new MainMethodFinder();
classReader.accept(mainMethodFinder, ClassReader.SKIP_CODE);
return mainMethodFinder.isFound();
}
catch (IOException ex) {
return false;
}
}
private static class ClassEntryComparator implements Comparator<JarEntry> {
@Override
public int compare(JarEntry o1, JarEntry o2) {
Integer d1 = getDepth(o1);
Integer d2 = getDepth(o2);
int depthCompare = d1.compareTo(d2);
if (depthCompare != 0) {
return depthCompare;
}
return o1.getName().compareTo(o2.getName());
}
private int getDepth(JarEntry entry) {
return entry.getName().split("/").length;
}
}
private static class MainMethodFinder extends ClassVisitor {
private boolean found;
public MainMethodFinder() {
super(Opcodes.ASM4);
}
@Override
public MethodVisitor visitMethod(int access, String name, String desc,
String signature, String[] exceptions) {
if (isAccess(access, Opcodes.ACC_PUBLIC, Opcodes.ACC_STATIC)
&& MAIN_METHOD_NAME.equals(name)
&& MAIN_METHOD_TYPE.getDescriptor().equals(desc)) {
this.found = true;
}
return null;
}
private boolean isAccess(int access, int... requiredOpsCodes) {
for (int requiredOpsCode : requiredOpsCodes) {
if ((access & requiredOpsCode) == 0) {
return false;
}
}
return true;
}
public boolean isFound() {
return this.found;
}
}
}

View File

@@ -0,0 +1,190 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.launcher.tools;
import java.io.File;
import java.io.IOException;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
/**
* Utility class that can be used to repackage an archive so that it can be executed using
* '{@literal java -jar}'.
*
* @author Phillip Webb
*/
public class Repackager {
private static final String MAIN_CLASS_ATTRIBUTE = "Main-Class";
private static final String START_CLASS_ATTRIBUTE = "Start-Class";
private String mainClass;
private boolean backupSource = true;
private final File source;
private Layout layout;
public Repackager(File source) {
if (source == null || !source.exists() || !source.isFile()) {
throw new IllegalArgumentException("Source must refer to an existing file");
}
this.source = source.getAbsoluteFile();
this.layout = Layouts.forFile(source);
}
/**
* Sets the main class that should be run. If not specified the value from the
* MANIFEST will be used, or if no manifest entry is found a class the archive will be
* searched for a suitable class.
* @param mainClass the main class name
*/
public void setMainClass(String mainClass) {
this.mainClass = mainClass;
}
/**
* Sets if source files should be backed up when they would be overwritten.
* @param backupSource if source files should be backed up
*/
public void setBackupSource(boolean backupSource) {
this.backupSource = backupSource;
}
/**
* Sets the layout to use for the jar. Defaults to {@link Layouts#forFile(File)}.
* @param layout the layout
*/
public void setLayout(Layout layout) {
if (layout == null) {
throw new IllegalArgumentException("Layout must not be null");
}
this.layout = layout;
}
/**
* Repackage the source file so that it can be run using '{@literal java -jar}'
* @param libraries the libraries required to run the archive
* @throws IOException
*/
public void repackage(Libraries libraries) throws IOException {
repackage(this.source, libraries);
}
/**
* Repackage to the given destination so that it can be run using '{@literal java -jar}
* '
* @param destination the destination file (may be the same as the source)
* @param libraries the libraries required to run the archive
* @throws IOException
*/
public void repackage(File destination, Libraries libraries) throws IOException {
if (destination == null || destination.isDirectory()) {
throw new IllegalArgumentException("Invalid destination");
}
if (libraries == null) {
throw new IllegalArgumentException("Libraries must not be null");
}
destination = destination.getAbsoluteFile();
File workingSource = this.source;
if (this.source.equals(destination)) {
workingSource = new File(this.source.getParentFile(), this.source.getName()
+ ".original");
workingSource.delete();
renameFile(this.source, workingSource);
}
destination.delete();
try {
JarFile jarFileSource = new JarFile(workingSource);
try {
repackage(jarFileSource, destination, libraries);
}
finally {
jarFileSource.close();
}
}
finally {
if (!this.backupSource && !this.source.equals(workingSource)) {
deleteFile(workingSource);
}
}
}
private void repackage(JarFile sourceJar, File destination, Libraries libraries)
throws IOException {
final JarWriter writer = new JarWriter(destination);
try {
writer.writeManifest(buildManifest(sourceJar));
writer.writeEntries(sourceJar);
libraries.doWithLibraries(new LibraryCallback() {
@Override
public void library(File file, LibraryScope scope) throws IOException {
String destination = Repackager.this.layout.getLibraryDestination(
file.getName(), scope);
if (destination != null) {
writer.writeNestedLibrary(destination, file);
}
}
});
writer.writeLoaderClasses();
}
finally {
writer.close();
}
}
private Manifest buildManifest(JarFile source) throws IOException {
Manifest manifest = source.getManifest();
if (manifest == null) {
manifest = new Manifest();
manifest.getMainAttributes().putValue("Manifest-Version", "1.0");
}
manifest = new Manifest(manifest);
String startClass = this.mainClass;
if (startClass == null) {
startClass = manifest.getMainAttributes().getValue(MAIN_CLASS_ATTRIBUTE);
}
if (startClass == null) {
startClass = MainClassFinder.findMainClass(source,
this.layout.getClassesLocation());
}
if (startClass == null) {
throw new IllegalStateException("Unable to find main class");
}
manifest.getMainAttributes().putValue(MAIN_CLASS_ATTRIBUTE,
this.layout.getLauncherClassName());
manifest.getMainAttributes().putValue(START_CLASS_ATTRIBUTE, startClass);
return manifest;
}
private void renameFile(File file, File dest) {
if (!file.renameTo(dest)) {
throw new IllegalStateException("Unable to rename '" + file + "' to '" + dest
+ "'");
}
}
private void deleteFile(File file) {
if (!file.delete()) {
throw new IllegalStateException("Unable to delete '" + file + "'");
}
}
}

View File

@@ -0,0 +1,84 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.launcher.tools;
import java.io.File;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertThat;
/**
* Tests for {@link Layouts}.
*
* @author Phillip Webb
*/
public class LayoutsTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void jarFile() throws Exception {
assertThat(Layouts.forFile(new File("test.jar")), instanceOf(Layouts.Jar.class));
assertThat(Layouts.forFile(new File("test.JAR")), instanceOf(Layouts.Jar.class));
assertThat(Layouts.forFile(new File("test.jAr")), instanceOf(Layouts.Jar.class));
assertThat(Layouts.forFile(new File("te.st.jar")), instanceOf(Layouts.Jar.class));
}
@Test
public void warFile() throws Exception {
assertThat(Layouts.forFile(new File("test.war")), instanceOf(Layouts.War.class));
assertThat(Layouts.forFile(new File("test.WAR")), instanceOf(Layouts.War.class));
assertThat(Layouts.forFile(new File("test.wAr")), instanceOf(Layouts.War.class));
assertThat(Layouts.forFile(new File("te.st.war")), instanceOf(Layouts.War.class));
}
@Test
public void unknownFile() throws Exception {
this.thrown.equals(IllegalStateException.class);
this.thrown.expectMessage("Unable to deduce layout for 'test.txt'");
Layouts.forFile(new File("test.txt"));
}
@Test
public void jarLayout() throws Exception {
Layout layout = new Layouts.Jar();
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE),
equalTo("lib/"));
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED),
equalTo("lib/"));
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME),
equalTo("lib/"));
}
@Test
public void warLayout() throws Exception {
Layout layout = new Layouts.War();
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE),
equalTo("WEB-INF/lib/"));
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED),
equalTo("WEB-INF/lib-provided/"));
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME),
equalTo("WEB-INF/lib/"));
}
}

View File

@@ -0,0 +1,108 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.launcher.tools;
import java.io.IOException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.springframework.boot.launcher.tools.sample.ClassWithMainMethod;
import org.springframework.boot.launcher.tools.sample.ClassWithoutMainMethod;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
/**
* Tests for {@link MainClassFinder}.
*
* @author Phillip Webb
*/
public class MainClassFinderTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private TestJarFile testJarFile;
@Before
public void setup() throws IOException {
this.testJarFile = new TestJarFile(this.temporaryFolder);
}
@Test
public void findMainClassInJar() throws Exception {
this.testJarFile.addClass("B.class", ClassWithMainMethod.class);
this.testJarFile.addClass("A.class", ClassWithoutMainMethod.class);
String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), "");
assertThat(actual, equalTo("B"));
}
@Test
public void findMainClassInJarSubFolder() throws Exception {
this.testJarFile.addClass("a/b/c/D.class", ClassWithMainMethod.class);
this.testJarFile.addClass("a/b/c/E.class", ClassWithoutMainMethod.class);
this.testJarFile.addClass("a/b/F.class", ClassWithoutMainMethod.class);
String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), "");
assertThat(actual, equalTo("a.b.c.D"));
}
@Test
public void usesBreadthFirstJarSearch() throws Exception {
this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class);
this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class);
String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), "");
assertThat(actual, equalTo("a.B"));
}
@Test
public void findMainClassInJarSubLocation() throws Exception {
this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class);
this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class);
String actual = MainClassFinder
.findMainClass(this.testJarFile.getJarFile(), "a/");
assertThat(actual, equalTo("B"));
}
@Test
public void findMainClassInFolder() throws Exception {
this.testJarFile.addClass("B.class", ClassWithMainMethod.class);
this.testJarFile.addClass("A.class", ClassWithoutMainMethod.class);
String actual = MainClassFinder.findMainClass(this.testJarFile.getJarSource());
assertThat(actual, equalTo("B"));
}
@Test
public void findMainClassInSubFolder() throws Exception {
this.testJarFile.addClass("a/b/c/D.class", ClassWithMainMethod.class);
this.testJarFile.addClass("a/b/c/E.class", ClassWithoutMainMethod.class);
this.testJarFile.addClass("a/b/F.class", ClassWithoutMainMethod.class);
String actual = MainClassFinder.findMainClass(this.testJarFile.getJarSource());
assertThat(actual, equalTo("a.b.c.D"));
}
@Test
public void usesBreadthFirstFolderSearch() throws Exception {
this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class);
this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class);
String actual = MainClassFinder.findMainClass(this.testJarFile.getJarSource());
assertThat(actual, equalTo("a.B"));
}
}

View File

@@ -0,0 +1,289 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.launcher.tools;
import java.io.File;
import java.io.IOException;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.springframework.boot.launcher.tools.sample.ClassWithMainMethod;
import org.springframework.boot.launcher.tools.sample.ClassWithoutMainMethod;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link Repackager}.
*
* @author Phillip Webb
*/
public class RepackagerTests {
private static final Libraries NO_LIBRARIES = new Libraries() {
@Override
public void doWithLibraries(LibraryCallback callback) throws IOException {
}
};
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExpectedException thrown = ExpectedException.none();
private TestJarFile testJarFile;
@Before
public void setup() throws IOException {
this.testJarFile = new TestJarFile(this.temporaryFolder);
}
@Test
public void nullSource() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
new Repackager(null);
}
@Test
public void missingSource() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
new Repackager(new File("missing"));
}
@Test
public void directorySource() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
new Repackager(this.temporaryFolder.getRoot());
}
@Test
public void specificMainClass() throws Exception {
this.testJarFile.addClass("a.b.C.class", ClassWithoutMainMethod.class);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
repackager.setMainClass("a.b.C");
repackager.repackage(NO_LIBRARIES);
Manifest actualManifest = getManifest(file);
assertThat(actualManifest.getMainAttributes().getValue("Main-Class"),
equalTo("org.springframework.boot.loader.JarLauncher"));
assertThat(actualManifest.getMainAttributes().getValue("Start-Class"),
equalTo("a.b.C"));
assertThat(hasLauncherClasses(file), equalTo(true));
}
@Test
public void mainClassFromManifest() throws Exception {
this.testJarFile.addClass("a.b.C.class", ClassWithoutMainMethod.class);
Manifest manifest = new Manifest();
manifest = new Manifest();
manifest.getMainAttributes().putValue("Manifest-Version", "1.0");
manifest.getMainAttributes().putValue("Main-Class", "a.b.C");
this.testJarFile.addManifest(manifest);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
repackager.repackage(NO_LIBRARIES);
Manifest actualManifest = getManifest(file);
assertThat(actualManifest.getMainAttributes().getValue("Main-Class"),
equalTo("org.springframework.boot.loader.JarLauncher"));
assertThat(actualManifest.getMainAttributes().getValue("Start-Class"),
equalTo("a.b.C"));
assertThat(hasLauncherClasses(file), equalTo(true));
}
@Test
public void mainClassFound() throws Exception {
this.testJarFile.addClass("a.b.C.class", ClassWithMainMethod.class);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
repackager.repackage(NO_LIBRARIES);
Manifest actualManifest = getManifest(file);
assertThat(actualManifest.getMainAttributes().getValue("Main-Class"),
equalTo("org.springframework.boot.loader.JarLauncher"));
assertThat(actualManifest.getMainAttributes().getValue("Start-Class"),
equalTo("a.b.C"));
assertThat(hasLauncherClasses(file), equalTo(true));
}
@Test
public void noMainClass() throws Exception {
this.testJarFile.addClass("a.b.C.class", ClassWithoutMainMethod.class);
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("Unable to find main class");
new Repackager(this.testJarFile.getFile()).repackage(NO_LIBRARIES);
}
@Test
public void sameSourceAndDestinationWithBackup() throws Exception {
this.testJarFile.addClass("a.b.C.class", ClassWithMainMethod.class);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
repackager.repackage(NO_LIBRARIES);
assertThat(new File(file.getParent(), file.getName() + ".original").exists(),
equalTo(true));
assertThat(hasLauncherClasses(file), equalTo(true));
}
@Test
public void sameSourceAndDestinationWithoutBackup() throws Exception {
this.testJarFile.addClass("a.b.C.class", ClassWithMainMethod.class);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
repackager.setBackupSource(false);
repackager.repackage(NO_LIBRARIES);
assertThat(new File(file.getParent(), file.getName() + ".original").exists(),
equalTo(false));
assertThat(hasLauncherClasses(file), equalTo(true));
}
@Test
public void differentDestination() throws Exception {
this.testJarFile.addClass("a.b.C.class", ClassWithMainMethod.class);
File source = this.testJarFile.getFile();
File dest = this.temporaryFolder.newFile("different.jar");
Repackager repackager = new Repackager(source);
repackager.repackage(dest, NO_LIBRARIES);
assertThat(new File(source.getParent(), source.getName() + ".original").exists(),
equalTo(false));
assertThat(hasLauncherClasses(source), equalTo(false));
assertThat(hasLauncherClasses(dest), equalTo(true));
}
@Test
public void nullDestination() throws Exception {
this.testJarFile.addClass("a.b.C.class", ClassWithMainMethod.class);
Repackager repackager = new Repackager(this.testJarFile.getFile());
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Invalid destination");
repackager.repackage(null, NO_LIBRARIES);
}
@Test
public void destinationIsDirectory() throws Exception {
this.testJarFile.addClass("a.b.C.class", ClassWithMainMethod.class);
Repackager repackager = new Repackager(this.testJarFile.getFile());
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Invalid destination");
repackager.repackage(this.temporaryFolder.getRoot(), NO_LIBRARIES);
}
@Test
public void overwriteDestination() throws Exception {
this.testJarFile.addClass("a.b.C.class", ClassWithMainMethod.class);
Repackager repackager = new Repackager(this.testJarFile.getFile());
File dest = this.temporaryFolder.newFile("dest.jar");
dest.createNewFile();
repackager.repackage(dest, NO_LIBRARIES);
assertThat(hasLauncherClasses(dest), equalTo(true));
}
@Test
public void nullLibraries() throws Exception {
this.testJarFile.addClass("a.b.C.class", ClassWithMainMethod.class);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Libraries must not be null");
repackager.repackage(file, null);
}
@Test
public void libraries() throws Exception {
TestJarFile libJar = new TestJarFile(this.temporaryFolder);
libJar.addClass("a.b.C.class", ClassWithoutMainMethod.class);
final File libJarFile = libJar.getFile();
this.testJarFile.addClass("a.b.C.class", ClassWithMainMethod.class);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
repackager.repackage(new Libraries() {
@Override
public void doWithLibraries(LibraryCallback callback) throws IOException {
callback.library(libJarFile, LibraryScope.COMPILE);
}
});
assertThat(hasEntry(file, "lib/" + libJarFile.getName()), equalTo(true));
}
@Test
public void customLayout() throws Exception {
TestJarFile libJar = new TestJarFile(this.temporaryFolder);
libJar.addClass("a.b.C.class", ClassWithoutMainMethod.class);
final File libJarFile = libJar.getFile();
this.testJarFile.addClass("a.b.C.class", ClassWithMainMethod.class);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
Layout layout = mock(Layout.class);
final LibraryScope scope = mock(LibraryScope.class);
given(layout.getLauncherClassName()).willReturn("testLauncher");
given(layout.getLibraryDestination(anyString(), eq(scope))).willReturn("test/");
repackager.setLayout(layout);
repackager.repackage(new Libraries() {
@Override
public void doWithLibraries(LibraryCallback callback) throws IOException {
callback.library(libJarFile, scope);
}
});
assertThat(hasEntry(file, "test/" + libJarFile.getName()), equalTo(true));
assertThat(getManifest(file).getMainAttributes().getValue("Main-Class"),
equalTo("testLauncher"));
}
@Test
public void nullCustomLayout() throws Exception {
this.testJarFile.addClass("a.b.C.class", ClassWithoutMainMethod.class);
Repackager repackager = new Repackager(this.testJarFile.getFile());
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Layout must not be null");
repackager.setLayout(null);
}
private boolean hasLauncherClasses(File file) throws IOException {
return hasEntry(file, "org/springframework/boot/")
&& hasEntry(file, "org/springframework/boot/loader/JarLauncher.class");
}
private boolean hasEntry(File file, String name) throws IOException {
JarFile jarFile = new JarFile(file);
try {
return jarFile.getEntry(name) != null;
}
finally {
jarFile.close();
}
}
private Manifest getManifest(File file) throws IOException {
JarFile jarFile = new JarFile(file);
try {
return jarFile.getManifest();
}
finally {
jarFile.close();
}
}
}

View File

@@ -0,0 +1,98 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.launcher.tools;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import org.junit.rules.TemporaryFolder;
import org.zeroturnaround.zip.ZipUtil;
/**
* @author Phillip Webb
*/
public class TestJarFile {
private final byte[] buffer = new byte[4096];
private TemporaryFolder temporaryFolder;
private File jarSource;
public TestJarFile(TemporaryFolder temporaryFolder) throws IOException {
this.temporaryFolder = temporaryFolder;
this.jarSource = temporaryFolder.newFolder();
}
public void addClass(String filename, Class<?> classToCopy) throws IOException {
String[] paths = filename.split("\\/");
File file = this.jarSource;
for (String path : paths) {
file = new File(file, path);
}
file.getParentFile().mkdirs();
InputStream inputStream = getClass().getResourceAsStream(
"/" + classToCopy.getName().replace(".", "/") + ".class");
OutputStream outputStream = new FileOutputStream(file);
try {
copy(inputStream, outputStream);
}
finally {
outputStream.close();
}
}
public void addManifest(Manifest manifest) throws IOException {
File manifestFile = new File(this.jarSource, "META-INF/MANIFEST.MF");
manifestFile.getParentFile().mkdirs();
OutputStream outputStream = new FileOutputStream(manifestFile);
try {
manifest.write(outputStream);
}
finally {
outputStream.close();
}
}
private void copy(InputStream in, OutputStream out) throws IOException {
int bytesRead = -1;
while ((bytesRead = in.read(this.buffer)) != -1) {
out.write(this.buffer, 0, bytesRead);
}
}
public JarFile getJarFile() throws IOException {
return new JarFile(getFile());
}
public File getJarSource() {
return this.jarSource;
}
public File getFile() throws IOException {
File file = this.temporaryFolder.newFile();
file = new File(file.getParent(), file.getName() + ".jar");
ZipUtil.pack(this.jarSource, file);
return file;
}
}

View File

@@ -0,0 +1,29 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.launcher.tools.sample;
/**
* Sample class with a main method.
*
* @author Phillip Webb
*/
public class ClassWithMainMethod {
public static void main(String[] args) {
}
}

View File

@@ -0,0 +1,26 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.launcher.tools.sample;
/**
* Sample class without a main method.
*
* @author Phillip Webb
*/
public class ClassWithoutMainMethod {
}

View File

@@ -0,0 +1,11 @@
Manifest-Version: 1.0
Implementation-Title: spring-boot-sample-tomcat
Implementation-Version: 0.5.0.BUILD-SNAPSHOT
Implementation-Vendor-Id: org.springframework.boot
Built-By: pwebb
Build-Jdk: 1.7.0_17
Specification-Title: spring-boot-sample-tomcat
Created-By: Apache Maven 3.0.5
Specification-Version: 0.5.0.BUILD-SNAPSHOT
Archiver-Version: Plexus Archiver

View File

@@ -0,0 +1,7 @@
#Generated by Maven Integration for Eclipse
#Fri Jul 26 13:40:41 PDT 2013
version=0.5.0.BUILD-SNAPSHOT
groupId=org.springframework.boot
m2e.projectName=spring-boot-sample-tomcat
m2e.projectLocation=/Users/pwebb/projects/spring/spring-bootstrap/code/spring-boot-samples/spring-boot-sample-tomcat
artifactId=spring-boot-sample-tomcat

View File

@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-samples</artifactId>
<version>0.5.0.BUILD-SNAPSHOT</version>
</parent>
<artifactId>spring-boot-sample-tomcat</artifactId>
<packaging>jar</packaging>
<properties>
<main.basedir>${basedir}/../..</main.basedir>
</properties>
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>spring-boot-up</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>spring-boot-up-tomcat</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>${project.groupId}</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1 @@
p.{}