| 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 | 31 | String pathOfClass = codeLocationClass.getName().replace(".", "/") + ".class"; |
| 25 | 31 | URL classResource = codeLocationClass.getClassLoader().getResource(pathOfClass); |
| 26 | 31 | String codeLocationPath = removeEnd(getPathFromURL(classResource), pathOfClass); |
| 27 | 31 | return codeLocationFromPath(codeLocationPath); |
| 28 | |
} |
| 29 | |
|
| 30 | |
|
| 31 | |
|
| 32 | |
|
| 33 | |
|
| 34 | |
|
| 35 | |
|
| 36 | |
|
| 37 | |
public static URL codeLocationFromPath(String filePath) { |
| 38 | |
try { |
| 39 | 375 | return new File(filePath).toURI().toURL(); |
| 40 | 1 | } catch (Exception e) { |
| 41 | 1 | throw new InvalidCodeLocation(filePath); |
| 42 | |
} |
| 43 | |
} |
| 44 | |
|
| 45 | |
|
| 46 | |
|
| 47 | |
|
| 48 | |
|
| 49 | |
|
| 50 | |
|
| 51 | |
|
| 52 | |
public static URL codeLocationFromURL(String url) { |
| 53 | |
try { |
| 54 | 4 | return new URL(url); |
| 55 | 1 | } catch (Exception e) { |
| 56 | 1 | throw new InvalidCodeLocation(url); |
| 57 | |
} |
| 58 | |
} |
| 59 | |
|
| 60 | 1 | @SuppressWarnings("serial") |
| 61 | |
public static class InvalidCodeLocation extends RuntimeException { |
| 62 | |
|
| 63 | |
public InvalidCodeLocation(String path) { |
| 64 | 2 | super(path); |
| 65 | 2 | } |
| 66 | |
|
| 67 | |
} |
| 68 | |
|
| 69 | |
|
| 70 | |
|
| 71 | |
|
| 72 | |
|
| 73 | |
|
| 74 | |
|
| 75 | |
|
| 76 | |
|
| 77 | |
|
| 78 | |
|
| 79 | |
|
| 80 | |
public static String getPathFromURL(URL url) { |
| 81 | |
URI uri; |
| 82 | |
try { |
| 83 | 129 | uri = url.toURI(); |
| 84 | 0 | } catch (URISyntaxException e) { |
| 85 | |
|
| 86 | |
|
| 87 | 0 | throw new InvalidCodeLocation(e.toString()); |
| 88 | 129 | } |
| 89 | |
|
| 90 | 129 | if(uri.toString().startsWith("file:") || uri.toString().startsWith("jar:")) { |
| 91 | 128 | return removeStart(uri.getSchemeSpecificPart(),"file:"); |
| 92 | |
} else { |
| 93 | |
|
| 94 | |
|
| 95 | 1 | return uri.toString(); |
| 96 | |
} |
| 97 | |
} |
| 98 | |
|
| 99 | |
} |