Loader changes

pull/59/merge
Phillip Webb 11 years ago committed by Dave Syer
parent 053c072155
commit e9fd7c96b8

@ -195,8 +195,4 @@ public abstract class Launcher {
return (Runnable) constructor.newInstance(mainClass, args);
}
protected boolean isArchive(String name) {
return name.endsWith(".jar") || name.endsWith(".zip");
}
}

@ -23,22 +23,19 @@ import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;
import org.springframework.boot.loader.util.SystemPropertyUtils;
import org.springframework.util.ResourceUtils;
/**
* <p>
* {@link Launcher} for archives with user-configured classpath and main class via a
* properties file. This model is often more flexible and more amenable to creating
* well-behaved OS-level services than a model based on executable jars.
* </p>
*
* <p>
* Looks in various places for a properties file to extract loader settings, defaulting to
@ -48,7 +45,7 @@ import org.springframework.util.ResourceUtils;
* will look for <code>foo.properties</code>. If that file doesn't exist then tries
* <code>loader.config.location</code> (with allowed prefixes <code>classpath:</code> and
* <code>file:</code> or any valid URL). Once that file is located turns it into
* Properties and extracts optional values (which can also be provided oroverridden as
* Properties and extracts optional values (which can also be provided overridden as
* System properties in case the file doesn't exist):
*
* <ul>
@ -59,16 +56,13 @@ import org.springframework.util.ResourceUtils;
* loader is set up. No default, but will fall back to looking in a
* <code>MANIFEST.MF</code> if there is one.</li>
* </ul>
* </p>
*
* <p>
*
* </p>
*
* @author Dave Syer
*/
public class PropertiesLauncher extends Launcher {
private Logger logger = Logger.getLogger(Launcher.class.getName());
/**
* Properties key for main class
*/
@ -81,11 +75,9 @@ public class PropertiesLauncher extends Launcher {
public static final String HOME = "loader.home";
public static String CONFIG_NAME = "loader.config.name";
public static final String CONFIG_NAME = "loader.config.name";
public static String CONFIG_LOCATION = "loader.config.location";
private Logger logger = Logger.getLogger(Launcher.class.getName());
public static final String CONFIG_LOCATION = "loader.config.location";
private static final List<String> DEFAULT_PATHS = Arrays.asList("lib/");
@ -94,51 +86,20 @@ public class PropertiesLauncher extends Launcher {
private Properties properties = new Properties();
@Override
public void launch(String[] args) {
try {
launch(args, new ExplodedArchive(new File(getHomeDirectory())));
}
catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
protected String getHomeDirectory() {
return SystemPropertyUtils.resolvePlaceholders(System.getProperty(HOME,
"${user.dir}"));
}
@Override
protected boolean isNestedArchive(Archive.Entry entry) {
String name = entry.getName();
if (entry.isDirectory()) {
for (String path : this.paths) {
if (path.length() > 0 && name.equals(path)) {
return true;
}
}
}
else {
for (String path : this.paths) {
if (path.length() > 0 && name.startsWith(path) && isArchive(name)) {
return true;
}
}
}
return false;
protected void launch(String[] args, ProtectionDomain protectionDomain)
throws Exception {
launch(args, new ExplodedArchive(getHomeDirectory()));
}
@Override
protected void postProcessLib(Archive archive, List<Archive> lib) throws Exception {
lib.add(0, archive);
protected File getHomeDirectory() {
return new File(SystemPropertyUtils.resolvePlaceholders(System.getProperty(HOME,
"${user.dir}")));
}
/**
* Look in various places for a properties file to extract loader settings. Default to
* <code>application.properties</code> either on the current classpath or in the
* current working directory.
*
* @see org.springframework.boot.loader.Launcher#launch(java.lang.String[],
* org.springframework.boot.loader.Archive)
*/
@ -149,56 +110,83 @@ public class PropertiesLauncher extends Launcher {
}
protected void initialize() throws Exception {
initializeProperties();
initializePaths();
}
private void initializeProperties() throws Exception, IOException {
String config = SystemPropertyUtils.resolvePlaceholders(System.getProperty(
CONFIG_NAME, "application")) + ".properties";
while (config.startsWith("/")) {
config = config.substring(1);
}
this.logger.fine("Trying default location: " + config);
InputStream resource = getClass().getResourceAsStream("/" + config);
InputStream resource = getClasspathResource(config);
if (resource == null) {
config = SystemPropertyUtils.resolvePlaceholders(System.getProperty(
CONFIG_LOCATION, config));
if (config.startsWith("classpath:")) {
config = config.substring("classpath:".length());
while (config.startsWith("/")) {
config = config.substring(1);
resource = getResource(config);
}
config = "/" + config;
this.logger.fine("Trying classpath: " + config);
resource = getClass().getResourceAsStream(config);
if (resource != null) {
this.logger.info("Found: " + config);
try {
this.properties.load(resource);
}
finally {
resource.close();
}
}
else {
this.logger.info("Not found: " + config);
}
}
if (config.startsWith("file:")) {
private InputStream getResource(String config) throws Exception {
if (config.startsWith("classpath:")) {
return getClasspathResource(config.substring("classpath:".length()));
}
config = stripFileUrlPrefix(config);
if (isUrl(config)) {
return getURLResource(config);
}
return getFileResource(config);
}
private String stripFileUrlPrefix(String config) {
if (config.startsWith("file:")) {
config = config.substring("file:".length());
if (config.startsWith("//")) {
config = config.substring(2);
}
}
return config;
}
private boolean isUrl(String config) {
return config.contains("://");
}
if (!config.contains(":")) {
private InputStream getClasspathResource(String config) {
while (config.startsWith("/")) {
config = config.substring(1);
}
config = "/" + config;
this.logger.fine("Trying classpath: " + config);
return getClass().getResourceAsStream(config);
}
private InputStream getFileResource(String config) throws Exception {
File file = new File(config);
this.logger.fine("Trying file: " + config);
if (file.canRead()) {
resource = new FileInputStream(file);
return new FileInputStream(file);
}
return null;
}
else {
private InputStream getURLResource(String config) throws Exception {
URL url = new URL(config);
if (exists(url)) {
URLConnection con = url.openConnection();
try {
resource = con.getInputStream();
return con.getInputStream();
}
catch (IOException ex) {
// Close the HTTP connection (if applicable).
@ -208,79 +196,93 @@ public class PropertiesLauncher extends Launcher {
throw ex;
}
}
return null;
}
private boolean exists(URL url) throws IOException {
// Try a URL connection content-length header...
URLConnection connection = url.openConnection();
try {
connection.setUseCaches(connection.getClass().getSimpleName()
.startsWith("JNLP"));
if (connection instanceof HttpURLConnection) {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("HEAD");
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
return true;
}
else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
return false;
}
}
if (resource != null) {
this.logger.info("Found: " + config);
this.properties.load(resource);
try {
return (connection.getContentLength() >= 0);
}
finally {
if (connection instanceof HttpURLConnection) {
((HttpURLConnection) connection).disconnect();
}
}
}
private void initializePaths() throws IOException {
String path = System.getProperty(PATH);
if (path == null) {
path = this.properties.getProperty(PATH);
}
if (path != null) {
path = SystemPropertyUtils.resolvePlaceholders(path);
this.paths = new ArrayList<String>(Arrays.asList(path.split(",")));
for (int i = 0; i < this.paths.size(); i++) {
this.paths.set(i, this.paths.get(i).trim());
}
this.paths = parsePathsProperty(SystemPropertyUtils.resolvePlaceholders(path));
}
this.logger.info("Nested archive paths: " + this.paths);
}
finally {
resource.close();
private List<String> parsePathsProperty(String commaSeparatedPaths) {
List<String> paths = new ArrayList<String>();
for (String path : commaSeparatedPaths.split(",")) {
path = cleanupPath(path);
// Empty path is always on the classpath so no need for it to be explicitly
// listed here
if (!(path.equals(".") || path.equals(""))) {
paths.add(path);
}
}
else {
this.logger.info("Not found: " + config);
return paths;
}
for (int i = 0; i < this.paths.size(); i++) {
if (!this.paths.get(i).endsWith("/")) {
private String cleanupPath(String path) {
path = path.trim();
// Always a directory
this.paths.set(i, this.paths.get(i) + "/");
if (!path.endsWith("/")) {
path = path + "/";
}
if (this.paths.get(i).startsWith("./")) {
// No need for current dir path
this.paths.set(i, this.paths.get(i).substring(2));
}
if (path.startsWith("./")) {
path = path.substring(2);
}
for (Iterator<String> iter = this.paths.iterator(); iter.hasNext();) {
String path = iter.next();
if (path.equals(".") || path.equals("")) {
// Empty path is always on the classpath so no need for it to be
// explicitly listed here
iter.remove();
return path;
}
}
this.logger.info("Nested archive paths: " + this.paths);
}
private boolean exists(URL url) throws IOException {
// Try a URL connection content-length header...
URLConnection con = url.openConnection();
ResourceUtils.useCachesIfNecessary(con);
HttpURLConnection httpCon = (con instanceof HttpURLConnection ? (HttpURLConnection) con
: null);
if (httpCon != null) {
httpCon.setRequestMethod("HEAD");
int code = httpCon.getResponseCode();
if (code == HttpURLConnection.HTTP_OK) {
@Override
protected boolean isNestedArchive(Archive.Entry entry) {
String name = entry.getName();
for (String path : this.paths) {
if (path.length() > 0) {
if ((entry.isDirectory() && name.equals(path))
|| (!entry.isDirectory() && name.startsWith(path) && isArchive(name))) {
return true;
}
else if (code == HttpURLConnection.HTTP_NOT_FOUND) {
return false;
}
}
if (con.getContentLength() >= 0) {
return true;
return false;
}
if (httpCon != null) {
// no HTTP OK status, and no content-length header: give up
httpCon.disconnect();
private boolean isArchive(String name) {
return name.endsWith(".jar") || name.endsWith(".zip");
}
return false;
@Override
protected void postProcessLib(Archive archive, List<Archive> lib) throws Exception {
lib.add(0, archive);
}
@Override

@ -19,8 +19,6 @@ package org.springframework.boot.loader.util;
import java.util.HashSet;
import java.util.Set;
import org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver;
/**
* Helper class for resolving placeholders in texts. Usually applied to file paths.
*
@ -50,7 +48,7 @@ public abstract class SystemPropertyUtils {
/** Value separator for system property placeholders: ":" */
public static final String VALUE_SEPARATOR = ":";
private static final PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper();
private static final String SIMPLE_PREFIX = PLACEHOLDER_PREFIX.substring(1);
/**
* Resolve ${...} placeholders in the given text, replacing them with corresponding
@ -62,25 +60,13 @@ public abstract class SystemPropertyUtils {
* @throws IllegalArgumentException if there is an unresolvable placeholder
*/
public static String resolvePlaceholders(String text) {
return helper.replacePlaceholders(text);
if (text == null) {
throw new IllegalArgumentException("Argument 'value' must not be null.");
}
static protected class PropertyPlaceholderHelper {
private static final String simplePrefix = PLACEHOLDER_PREFIX.substring(1);
/**
* Replaces all placeholders of format {@code $ name} with the value returned from
* the supplied {@link PlaceholderResolver}.
* @param value the value containing the placeholders to be replaced.
* @return the supplied value with placeholders replaced inline.
*/
public String replacePlaceholders(String value) {
Assert.notNull(value, "Argument 'value' must not be null.");
return parseStringValue(value, value, new HashSet<String>());
return parseStringValue(text, text, new HashSet<String>());
}
private String parseStringValue(String value, String current,
private static String parseStringValue(String value, String current,
Set<String> visitedPlaceholders) {
StringBuilder buf = new StringBuilder(current);
@ -93,15 +79,13 @@ public abstract class SystemPropertyUtils {
startIndex + PLACEHOLDER_PREFIX.length(), endIndex);
String originalPlaceholder = placeholder;
if (!visitedPlaceholders.add(originalPlaceholder)) {
throw new IllegalArgumentException(
"Circular placeholder reference '" + originalPlaceholder
+ "' in property definitions");
throw new IllegalArgumentException("Circular placeholder reference '"
+ originalPlaceholder + "' in property definitions");
}
// Recursive invocation, parsing placeholders contained in the
// placeholder
// key.
placeholder = parseStringValue(value, placeholder,
visitedPlaceholders);
placeholder = parseStringValue(value, placeholder, visitedPlaceholders);
// Now obtain the value for the fully resolved key...
String propVal = resolvePlaceholder(value, placeholder);
if (propVal == null && VALUE_SEPARATOR != null) {
@ -141,7 +125,7 @@ public abstract class SystemPropertyUtils {
return buf.toString();
}
private String resolvePlaceholder(String text, String placeholderName) {
private static String resolvePlaceholder(String text, String placeholderName) {
try {
String propVal = System.getProperty(placeholderName);
if (propVal == null) {
@ -157,7 +141,7 @@ public abstract class SystemPropertyUtils {
}
}
private int findPlaceholderEndIndex(CharSequence buf, int startIndex) {
private static int findPlaceholderEndIndex(CharSequence buf, int startIndex) {
int index = startIndex + PLACEHOLDER_PREFIX.length();
int withinNestedPlaceholder = 0;
while (index < buf.length()) {
@ -170,10 +154,9 @@ public abstract class SystemPropertyUtils {
return index;
}
}
else if (substringMatch(buf, index,
PropertyPlaceholderHelper.simplePrefix)) {
else if (substringMatch(buf, index, SIMPLE_PREFIX)) {
withinNestedPlaceholder++;
index = index + PropertyPlaceholderHelper.simplePrefix.length();
index = index + SIMPLE_PREFIX.length();
}
else {
index++;
@ -193,16 +176,4 @@ public abstract class SystemPropertyUtils {
return true;
}
private static class Assert {
public static void notNull(Object target, String message) {
if (target == null) {
throw new IllegalStateException(message);
}
}
}
}
}

@ -16,6 +16,8 @@
package org.springframework.boot.loader;
import java.io.File;
import org.junit.After;
import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;
@ -40,7 +42,8 @@ public class PropertiesLauncherTests {
@Test
public void testDefaultHome() {
assertEquals(System.getProperty("user.dir"), this.launcher.getHomeDirectory());
assertEquals(new File(System.getProperty("user.dir")),
this.launcher.getHomeDirectory());
}
@Test

Loading…
Cancel
Save