Skip to content

Commit

Permalink
Some fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
electrotype committed Sep 22, 2018
1 parent eb070be commit e981117
Show file tree
Hide file tree
Showing 9 changed files with 201 additions and 50 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package org.spincast.core.utils;

import java.io.Closeable;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
Expand All @@ -10,8 +9,6 @@
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
Expand All @@ -24,7 +21,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spincast.shaded.org.apache.commons.io.IOUtils;
import org.spincast.shaded.org.apache.commons.lang3.StringUtils;
import org.spincast.shaded.org.apache.commons.lang3.time.FastDateFormat;

/**
Expand Down Expand Up @@ -480,29 +476,5 @@ public Long longValueOrNullInstance(Object obj) {
return Long.parseLong(obj.toString());
}

/**
* Gets a file on the classpath.
* The file may not exist.
*/
public static File getClasspathFile(String relativePath) {
return getInstance().getClasspathFileInstance(relativePath);
}

public File getClasspathFileInstance(String relativePath) {
if (relativePath == null) {
return null;
}

try {
relativePath = StringUtils.stripStart(relativePath, "/");
URL url = ClassLoader.getSystemResource(relativePath);
if (url == null) {
return null;
}
return Paths.get(url.toURI()).toFile();
} catch (Exception ex) {
throw runtimize(ex);
}
}

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.spincast.core.utils;

import java.io.File;
import java.io.InputStream;
import java.util.Locale;

/**
Expand Down Expand Up @@ -71,6 +72,14 @@ public String getMimeTypeFromMultipleSources(String responseContentTypeHeader,
*/
public boolean isContentTypeToSkipGziping(String contentType);

/**
* Is the application currently running from
* an executable .jar? An executable .jar is a
* jar with <code>Main-Class</code> in its
* <code>META-INF/MANIFEST.MF</code>.
*/
public boolean isRunningFromExecutableJar();

/**
* If the project is running from an executable
* .jar file, this will return the directory containing
Expand Down Expand Up @@ -157,6 +166,22 @@ public String getMimeTypeFromMultipleSources(String responseContentTypeHeader,
*/
public String readClasspathFile(String path, String encoding);


/**
* Gets the {@link InputStream} from a resource on the classpath.
* <p>
* IMPORTANT : the code is responsible to close the
* inputstream!
* <p>
* Also note that when an application is running from an executable
* .jar, you must use this instead of trying to get a
* {@link File} from the resource!
*
* @return the {@link InputStream} or <code>null</code> if the resource is
* not found.
*/
public InputStream getClasspathInputStream(String classpathPath);

/**
* Valid of a String only contains characters over 31 (or
* DEL (127).
Expand All @@ -183,5 +208,4 @@ public String getMimeTypeFromMultipleSources(String responseContentTypeHeader,
*/
public <T extends Enum<?>> T enumValueOfInsensitive(Class<T> enumClass, String str);


}
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,11 @@ public File getAppJarDirectory() {
return this.appJarDirectory;
}

@Override
public boolean isRunningFromExecutableJar() {
return getAppJarDirectory() != null;
}

@Override
public File getAppRootDirectoryNoJar() {

Expand Down Expand Up @@ -455,10 +460,31 @@ public String getSpincastCurrentVersion() {

String currentVersion = getClass().getPackage().getImplementationVersion();

//==========================================
// We're in an IDE...
//==========================================
if (currentVersion == null) {

if (isRunningFromExecutableJar()) {
this.logger.error("Unable to get the Spincast version! Make sure you have this plugin " +
"in your pom.xml (with an up to date version!):\n\n" +
"<plugin>\n" +
" <groupId>org.apache.maven.plugins</groupId>\n" +
" <artifactId>maven-jar-plugin</artifactId>\n" +
" <version>3.0.2</version>\n" +
" <configuration>\n" +
" <archive> \n" +
" <manifest>\n" +
" <addDefaultImplementationEntries>true</addDefaultImplementationEntries>\n" +
" <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>\n" +
" </manifest>\n" +
" </archive>\n" +
" </configuration>\n" +
"</plugin>\n\n");

return null;
}

//==========================================
// We're in an IDE...
//==========================================
currentVersion = getCurrentVersionFromPom();
}

Expand Down Expand Up @@ -649,22 +675,15 @@ public String readClasspathFile(String path) {
@Override
public String readClasspathFile(String path, String encoding) {

if (path == null) {
InputStream in = getClasspathInputStream(path);
if (in == null) {
return null;
}
if (!path.startsWith("/")) {
path = "/" + path;
}

if (encoding == null) {
encoding = "UTF-8";
}

InputStream in = this.getClass().getResourceAsStream(path);
if (in == null) {
return null;
}

try {
return IOUtils.toString(in, encoding);
} catch (Exception ex) {
Expand All @@ -674,6 +693,19 @@ public String readClasspathFile(String path, String encoding) {
}
}

@Override
public InputStream getClasspathInputStream(String classpathPath) {
if (classpathPath == null) {
return null;
}
if (!classpathPath.startsWith("/")) {
classpathPath = "/" + classpathPath;
}

InputStream in = this.getClass().getResourceAsStream(classpathPath);
return in;
}

@Override
public boolean isContainsSpecialCharacters(String str) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@
import java.util.UUID;

import org.junit.Test;
import org.spincast.core.utils.SpincastStatics;
import org.spincast.plugins.hotswap.fileswatcher.FileToWatch;
import org.spincast.plugins.hotswap.fileswatcher.HotSwapFilesModificationsListener;
import org.spincast.shaded.org.apache.commons.io.FileUtils;
import org.spincast.testing.core.utils.SpincastTestingUtils;

import com.google.common.collect.Sets;

Expand Down Expand Up @@ -516,7 +516,7 @@ public void classpathFile() throws Exception {
final int[] flag1 = new int[]{0};

String classpathFilePath = "spincast-plugins-hotswap-tests/test.txt";
File file = SpincastStatics.getClasspathFile(classpathFilePath);
File file = SpincastTestingUtils.getClasspathFileNotInJar(classpathFilePath);
assertNotNull(file);

HotSwapFilesModificationsListener listener = new HotSwapFilesModificationsListener() {
Expand Down Expand Up @@ -648,7 +648,7 @@ public void regExClasspath() throws Exception {
final int[] flag1 = new int[]{0};

String classpathFilePath = "spincast-plugins-hotswap-tests/test.txt";
File file = SpincastStatics.getClasspathFile(classpathFilePath);
File file = SpincastTestingUtils.getClasspathFileNotInJar(classpathFilePath);
assertNotNull(file);

HotSwapFilesModificationsListener listener = new HotSwapFilesModificationsListener() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

import com.google.inject.Inject;

public class HotSwapTestBase extends NoAppStartHttpServerTestingBase {
public abstract class HotSwapTestBase extends NoAppStartHttpServerTestingBase {

@Inject
private HotSwapManager hotSwapManager;
Expand Down Expand Up @@ -60,4 +60,6 @@ protected Map<WatchKey, Set<HotSwapFilesModificationsListener>> getListenersByWa
}
}



}
Original file line number Diff line number Diff line change
@@ -1,13 +1,27 @@
package org.spincast.plugins.hotswap.fileswatcher;

import java.io.File;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spincast.core.utils.SpincastStatics;
import org.spincast.shaded.org.apache.commons.lang3.StringUtils;

public class FileToWatch {

protected final static Logger logger = LoggerFactory.getLogger(FileToWatch.class);

private static boolean isInJar;
private static boolean isInJarChecked = false;
private static final Object isInJarCheckedLock = new Object();

private final File dir;
private final String fileName;
private final boolean isRegEx;
Expand Down Expand Up @@ -35,13 +49,20 @@ public static FileToWatch ofFileSystem(String fileAbsolutePath) {
}

/**
* ofClasspath
* Note that a file from the classpath can only
* be watched when the application is ran locally
* in development mode, not when it runs from a .jar!
*/
public static FileToWatch ofClasspath(String classpathFilePath) {

Objects.requireNonNull(classpathFilePath, "The classpathFilePath can't be NULL");

File file = SpincastStatics.getClasspathFile(classpathFilePath);
if (isInExecutableJar()) {
throw new RuntimeException("The classpath file \"" + classpathFilePath + "\" cannot be watched when running from " +
"a jar!");
}

File file = getFileFromNotInJarClasspath(classpathFilePath);
if (!file.exists()) {
throw new RuntimeException("The classpath '" + classpathFilePath + "' file doesn't exist. It can't be watched.");
}
Expand All @@ -59,7 +80,13 @@ public static FileToWatch ofRegEx(String dirPath, String fileNameRegEx, boolean

File dir;
if (isClassPath) {
dir = SpincastStatics.getClasspathFile(dirPath);

if (isInExecutableJar()) {
throw new RuntimeException("The classpath file \"" + dirPath + "\" cannot be watched when running from " +
"a jar!");
}

dir = getFileFromNotInJarClasspath(dirPath);
} else {
dir = new File(dirPath);
}
Expand Down Expand Up @@ -89,6 +116,55 @@ public Pattern getRegExPattern() {
return this.regExPattern;
}

protected static File getFileFromNotInJarClasspath(String relativePath) {
if (relativePath == null) {
return null;
}

try {
relativePath = StringUtils.stripStart(relativePath, "/");
URL url = ClassLoader.getSystemResource(relativePath);
if (url == null) {
return null;
}
return Paths.get(url.toURI()).toFile();
} catch (Exception ex) {
throw SpincastStatics.runtimize(ex);
}
}

protected static boolean isInExecutableJar() {
if (!isInJarChecked) {
synchronized (isInJarCheckedLock) {
if (!isInJarChecked) {
isInJarChecked = true;
try {
String jarPath = FileToWatch.class.getProtectionDomain().getCodeSource().getLocation().getPath();
if (jarPath == null) {
throw new RuntimeException("Unable to get the path of " + FileToWatch.class.getName() + "!");
}

jarPath = URLDecoder.decode(jarPath, "UTF-8");
if (!jarPath.toLowerCase().endsWith(".jar")) {
isInJar = false;
} else {
String manifestPath = "jar:file:" + jarPath + "!/META-INF/MANIFEST.MF";
Manifest manifest = new Manifest(new URL(manifestPath).openStream());
Attributes attr = manifest.getMainAttributes();
String mainClass = attr.getValue("Main-Class");
isInJar = mainClass != null;
}

} catch (Exception ex) {
throw SpincastStatics.runtimize(ex);
}
}
}
}

return isInJar;
}

@Override
public String toString() {
return getDir().getAbsolutePath() + " / " + getFileName();
Expand Down
19 changes: 19 additions & 0 deletions spincast-quickstart/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,25 @@
<target>1.8</target>
</configuration>
</plugin>

<!--===================================
This adds the artifact version to the jar Manifest
so it can be read using:
"getClass().getPackage().getImplementationVersion()".
====================================-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version><!--$NO-MVN-MAN-VER$-->
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
</archive>
</configuration>
</plugin>

<!--===================================
Fat jar creation
Expand Down
Loading

0 comments on commit e981117

Please sign in to comment.