| 1 | |
package org.jbehave.core.io; |
| 2 | |
|
| 3 | |
import static org.apache.commons.lang.StringUtils.removeEnd; |
| 4 | |
import static org.apache.commons.lang.StringUtils.removeStart; |
| 5 | |
|
| 6 | |
import java.io.File; |
| 7 | |
import java.net.URI; |
| 8 | |
import java.net.URISyntaxException; |
| 9 | |
import java.net.URL; |
| 10 | |
|
| 11 | |
|
| 12 | |
|
| 13 | |
|
| 14 | 1 | public class CodeLocations { |
| 15 | |
|
| 16 | |
|
| 17 | |
|
| 18 | |
|
| 19 | |
|
| 20 | |
|
| 21 | |
|
| 22 | |
|
| 23 | |
public static URL codeLocationFromClass(Class<?> codeLocationClass) { |
| 24 | 32 | String pathOfClass = codeLocationClass.getName().replace(".", "/") + ".class"; |
| 25 | 32 | URL classResource = codeLocationClass.getClassLoader().getResource(pathOfClass); |
| 26 | 32 | String codeLocationPath = removeEnd(getPathFromURL(classResource), pathOfClass); |
| 27 | 32 | if(codeLocationPath.endsWith(".jar!/")) { |
| 28 | 1 | codeLocationPath=removeEnd(codeLocationPath,"!/"); |
| 29 | |
} |
| 30 | 32 | return codeLocationFromPath(codeLocationPath); |
| 31 | |
} |
| 32 | |
|
| 33 | |
|
| 34 | |
|
| 35 | |
|
| 36 | |
|
| 37 | |
|
| 38 | |
|
| 39 | |
|
| 40 | |
public static URL codeLocationFromPath(String filePath) { |
| 41 | |
try { |
| 42 | 360 | return new File(filePath).toURI().toURL(); |
| 43 | 1 | } catch (Exception e) { |
| 44 | 1 | throw new InvalidCodeLocation(filePath); |
| 45 | |
} |
| 46 | |
} |
| 47 | |
|
| 48 | |
|
| 49 | |
|
| 50 | |
|
| 51 | |
|
| 52 | |
|
| 53 | |
|
| 54 | |
|
| 55 | |
public static URL codeLocationFromURL(String url) { |
| 56 | |
try { |
| 57 | 4 | return new URL(url); |
| 58 | 1 | } catch (Exception e) { |
| 59 | 1 | throw new InvalidCodeLocation(url); |
| 60 | |
} |
| 61 | |
} |
| 62 | |
|
| 63 | 1 | @SuppressWarnings("serial") |
| 64 | |
public static class InvalidCodeLocation extends RuntimeException { |
| 65 | |
|
| 66 | |
public InvalidCodeLocation(String path) { |
| 67 | 2 | super(path); |
| 68 | 2 | } |
| 69 | |
|
| 70 | |
} |
| 71 | |
|
| 72 | |
|
| 73 | |
|
| 74 | |
|
| 75 | |
|
| 76 | |
|
| 77 | |
|
| 78 | |
|
| 79 | |
|
| 80 | |
|
| 81 | |
|
| 82 | |
|
| 83 | |
public static String getPathFromURL(URL url) { |
| 84 | |
URI uri; |
| 85 | |
try { |
| 86 | 133 | uri = url.toURI(); |
| 87 | 0 | } catch (URISyntaxException e) { |
| 88 | |
|
| 89 | |
|
| 90 | 0 | throw new InvalidCodeLocation(e.toString()); |
| 91 | 133 | } |
| 92 | |
|
| 93 | 133 | if(uri.toString().startsWith("file:") || uri.toString().startsWith("jar:")) { |
| 94 | 132 | return removeStart(uri.getSchemeSpecificPart(),"file:"); |
| 95 | |
} else { |
| 96 | |
|
| 97 | |
|
| 98 | 1 | return uri.toString(); |
| 99 | |
} |
| 100 | |
} |
| 101 | |
|
| 102 | |
} |