├── src └── main │ └── java │ └── me │ └── lucko │ └── jarrelocator │ ├── ResourceTransformer.java │ ├── RelocatingClassVisitor.java │ ├── RelocatingRemapper.java │ ├── ServicesResourceTransformer.java │ ├── JarRelocator.java │ ├── Relocation.java │ ├── JarRelocatorTask.java │ └── SelectorUtils.java ├── README.md ├── .gitignore ├── pom.xml └── LICENSE.txt /src/main/java/me/lucko/jarrelocator/ResourceTransformer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright Apache Software Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package me.lucko.jarrelocator; 18 | 19 | import java.io.IOException; 20 | import java.io.InputStream; 21 | import java.util.Collection; 22 | import java.util.jar.JarOutputStream; 23 | 24 | interface ResourceTransformer { 25 | 26 | boolean shouldTransformResource(String resource); 27 | 28 | void processResource(String resource, InputStream inputStream, Collection rules) throws IOException; 29 | 30 | void writeOutput(JarOutputStream jarOutputStream) throws IOException; 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/me/lucko/jarrelocator/RelocatingClassVisitor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright Apache Software Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package me.lucko.jarrelocator; 18 | 19 | import org.objectweb.asm.ClassVisitor; 20 | import org.objectweb.asm.ClassWriter; 21 | import org.objectweb.asm.Opcodes; 22 | import org.objectweb.asm.commons.ClassRemapper; 23 | 24 | /** 25 | * A {@link ClassVisitor} that relocates types and names with a {@link RelocatingRemapper}. 26 | */ 27 | final class RelocatingClassVisitor extends ClassRemapper { 28 | private final String packageName; 29 | 30 | RelocatingClassVisitor(ClassWriter writer, RelocatingRemapper remapper, String name) { 31 | super(Opcodes.ASM9, writer, remapper); 32 | this.packageName = name.substring(0, name.lastIndexOf('/') + 1); 33 | } 34 | 35 | @Override 36 | public void visitSource(String source, String debug) { 37 | if (source == null) { 38 | super.visitSource(null, debug); 39 | return; 40 | } 41 | 42 | // visit source file name 43 | String name = this.packageName + source; 44 | String mappedName = super.remapper.map(name); 45 | String mappedFileName = mappedName.substring(mappedName.lastIndexOf('/') + 1); 46 | super.visitSource(mappedFileName, debug); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # jar-relocator 2 | [![Javadocs](https://javadoc.io/badge/me.lucko/jar-relocator.svg)](https://javadoc.io/doc/me.lucko/jar-relocator) 3 | [![Maven Central](https://img.shields.io/maven-metadata/v/https/repo1.maven.org/maven2/me/lucko/jar-relocator/maven-metadata.xml.svg?label=maven%20central&colorB=brightgreen)](https://search.maven.org/artifact/me.lucko/jar-relocator) 4 | 5 | A Java program to relocate classes within a jar archive using ASM. (effectively a standalone implementation of the relocation functionality provided by the [maven-shade-plugin](https://maven.apache.org/plugins/maven-shade-plugin/).) 6 | 7 | Shading allows Java developers to include both their app *and* library dependencies in one "uber" jar archive. This means dependencies are always available without needing to append them onto the classpath manually. However, this can cause problems if duplicate copies of the same class are on the classpath at the same time. 8 | 9 | To address this issue, you can relocate the "shaded" classes to your own package/namespace in order to prevent conflicts. 10 | 11 | ### Why not just use the maven-shade-plugin? 12 | 13 | If you can relocate at build time - you should. 14 | 15 | However, there are times where you might want to relocate at runtime, or at some other stage. My usecase is the app downloading dependencies dynamically from a repository on first startup, and needing to relocate then. 16 | 17 | ### Usage 18 | 19 | jar-relocator is [available from Maven Central, group id: `me.lucko`, artifact id: `jar-relocator`](https://search.maven.org/artifact/me.lucko/jar-relocator). 20 | 21 | jar relocator has two dependencies: ASM and ASM Commons. 22 | 23 | 24 | ```java 25 | import me.lucko.jarrelocator.JarRelocator; 26 | import me.lucko.jarrelocator.Relocation; 27 | 28 | import java.io.File; 29 | import java.io.IOException; 30 | import java.util.ArrayList; 31 | import java.util.List; 32 | 33 | public class Bootstrap { 34 | 35 | public static void main(String[] args) { 36 | File input = new File("input.jar"); 37 | File output = new File("output.jar"); 38 | 39 | List rules = new ArrayList<>(); 40 | rules.add(new Relocation("com.google.common", "me.lucko.test.lib.guava")); 41 | rules.add(new Relocation("com.google.gson", "me.lucko.test.lib.gson")); 42 | 43 | JarRelocator relocator = new JarRelocator(input, output, rules); 44 | 45 | try { 46 | relocator.run(); 47 | } catch (IOException e) { 48 | throw new RuntimeException("Unable to relocate", e); 49 | } 50 | } 51 | 52 | } 53 | ``` 54 | -------------------------------------------------------------------------------- /src/main/java/me/lucko/jarrelocator/RelocatingRemapper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright Apache Software Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package me.lucko.jarrelocator; 18 | 19 | import org.objectweb.asm.commons.Remapper; 20 | 21 | import java.util.Collection; 22 | import java.util.regex.Matcher; 23 | import java.util.regex.Pattern; 24 | 25 | /** 26 | * Remaps class names and types using defined {@link Relocation} rules. 27 | */ 28 | final class RelocatingRemapper extends Remapper { 29 | private static final Pattern CLASS_PATTERN = Pattern.compile("(\\[*)?L(.+);"); 30 | 31 | // https://docs.oracle.com/javase/10/docs/specs/jar/jar.html#multi-release-jar-files 32 | private static final Pattern VERSION_PATTERN = Pattern.compile("^(META-INF/versions/\\d+/)(.*)$"); 33 | 34 | private final Collection rules; 35 | 36 | RelocatingRemapper(Collection rules) { 37 | this.rules = rules; 38 | } 39 | 40 | public Collection getRules() { 41 | return this.rules; 42 | } 43 | 44 | @Override 45 | public String map(String name) { 46 | String relocatedName = relocate(name, false); 47 | if (relocatedName != null) { 48 | return relocatedName; 49 | } 50 | return super.map(name); 51 | } 52 | 53 | @Override 54 | public Object mapValue(Object object) { 55 | if (object instanceof String) { 56 | String relocatedName = relocate((String) object, true); 57 | if (relocatedName != null) { 58 | return relocatedName; 59 | } 60 | } 61 | return super.mapValue(object); 62 | } 63 | 64 | private String relocate(String name, boolean isStringValue) { 65 | String prefix = ""; 66 | String suffix = ""; 67 | 68 | if (isStringValue) { 69 | Matcher m = CLASS_PATTERN.matcher(name); 70 | if (m.matches()) { 71 | prefix = m.group(1) + "L"; 72 | name = m.group(2); 73 | suffix = ";"; 74 | } 75 | } 76 | 77 | Matcher m = VERSION_PATTERN.matcher(name); 78 | if (m.matches()) { 79 | prefix = m.group(1); 80 | name = m.group(2); 81 | } 82 | 83 | for (Relocation r : this.rules) { 84 | if (isStringValue && r.canRelocateClass(name)) { 85 | return prefix + r.relocateClass(name) + suffix; 86 | } else if (r.canRelocatePath(name)) { 87 | return prefix + r.relocatePath(name) + suffix; 88 | } 89 | } 90 | 91 | return null; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io/ 2 | 3 | ### Intellij ### 4 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 5 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 6 | 7 | # User-specific stuff: 8 | .idea/ 9 | *.iws 10 | /out/ 11 | *.iml 12 | .idea_modules/ 13 | 14 | # JIRA plugin 15 | atlassian-ide-plugin.xml 16 | 17 | # Crashlytics plugin (for Android Studio and IntelliJ) 18 | com_crashlytics_export_strings.xml 19 | crashlytics.properties 20 | crashlytics-build.properties 21 | fabric.properties 22 | 23 | 24 | ### Maven ### 25 | target/ 26 | pom.xml.tag 27 | pom.xml.releaseBackup 28 | pom.xml.versionsBackup 29 | pom.xml.next 30 | release.properties 31 | dependency-reduced-pom.xml 32 | buildNumber.properties 33 | .mvn/timing.properties 34 | 35 | 36 | ### Eclipse ### 37 | 38 | .metadata 39 | bin/ 40 | tmp/ 41 | *.tmp 42 | *.bak 43 | *.swp 44 | *~.nib 45 | local.properties 46 | .settings/ 47 | .loadpath 48 | .recommenders 49 | 50 | # Eclipse Core 51 | .project 52 | 53 | # External tool builders 54 | .externalToolBuilders/ 55 | 56 | # Locally stored "Eclipse launch configurations" 57 | *.launch 58 | 59 | # PyDev specific (Python IDE for Eclipse) 60 | *.pydevproject 61 | 62 | # CDT-specific (C/C++ Development Tooling) 63 | .cproject 64 | 65 | # JDT-specific (Eclipse Java Development Tools) 66 | .classpath 67 | 68 | # Java annotation processor (APT) 69 | .factorypath 70 | 71 | # PDT-specific (PHP Development Tools) 72 | .buildpath 73 | 74 | # sbteclipse plugin 75 | .target 76 | 77 | # Tern plugin 78 | .tern-project 79 | 80 | # TeXlipse plugin 81 | .texlipse 82 | 83 | # STS (Spring Tool Suite) 84 | .springBeans 85 | 86 | # Code Recommenders 87 | .recommenders/ 88 | 89 | 90 | ### Linux ### 91 | *~ 92 | 93 | # temporary files which can be created if a process still has a handle open of a deleted file 94 | .fuse_hidden* 95 | 96 | # KDE directory preferences 97 | .directory 98 | 99 | # Linux trash folder which might appear on any partition or disk 100 | .Trash-* 101 | 102 | # .nfs files are created when an open file is removed but is still being accessed 103 | .nfs* 104 | 105 | 106 | ### macOS ### 107 | *.DS_Store 108 | .AppleDouble 109 | .LSOverride 110 | 111 | # Icon must end with two \r 112 | Icon 113 | # Thumbnails 114 | ._* 115 | # Files that might appear in the root of a volume 116 | .DocumentRevisions-V100 117 | .fseventsd 118 | .Spotlight-V100 119 | .TemporaryItems 120 | .Trashes 121 | .VolumeIcon.icns 122 | .com.apple.timemachine.donotpresent 123 | # Directories potentially created on remote AFP share 124 | .AppleDB 125 | .AppleDesktop 126 | Network Trash Folder 127 | Temporary Items 128 | .apdisk 129 | 130 | 131 | ### Windows ### 132 | # Windows image file caches 133 | Thumbs.db 134 | ehthumbs.db 135 | 136 | # Folder config file 137 | Desktop.ini 138 | 139 | # Recycle Bin used on file shares 140 | $RECYCLE.BIN/ 141 | 142 | # Windows Installer files 143 | *.cab 144 | *.msi 145 | *.msm 146 | *.msp 147 | 148 | # Windows shortcuts 149 | *.lnk 150 | 151 | 152 | ### Java ### 153 | *.class 154 | 155 | # Mobile Tools for Java (J2ME) 156 | .mtj.tmp/ 157 | 158 | # Package Files # 159 | *.jar 160 | *.war 161 | *.ear 162 | 163 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 164 | hs_err_pid* -------------------------------------------------------------------------------- /src/main/java/me/lucko/jarrelocator/ServicesResourceTransformer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright Apache Software Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package me.lucko.jarrelocator; 18 | 19 | import java.io.BufferedReader; 20 | import java.io.IOException; 21 | import java.io.InputStream; 22 | import java.io.InputStreamReader; 23 | import java.nio.charset.StandardCharsets; 24 | import java.util.Collection; 25 | import java.util.LinkedHashMap; 26 | import java.util.LinkedHashSet; 27 | import java.util.Map; 28 | import java.util.Set; 29 | import java.util.jar.JarEntry; 30 | import java.util.jar.JarOutputStream; 31 | import java.util.stream.Collectors; 32 | 33 | class ServicesResourceTransformer implements ResourceTransformer { 34 | private static final String SERVICES_PATH = "META-INF/services/"; 35 | 36 | private final Map> serviceEntries = new LinkedHashMap<>(); 37 | 38 | @Override 39 | public boolean shouldTransformResource(String resource) { 40 | return resource.startsWith(SERVICES_PATH); 41 | } 42 | 43 | @Override 44 | public void processResource(String resource, InputStream inputStream, Collection rules) throws IOException { 45 | String serviceClass = relocateIfPossible(resource.substring(SERVICES_PATH.length()), rules); 46 | Set serviceLines = this.serviceEntries.computeIfAbsent(SERVICES_PATH + serviceClass, k -> new LinkedHashSet<>()); 47 | 48 | String[] lines = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)) 49 | .lines() 50 | .collect(Collectors.joining("\n")) 51 | .replace('\r', '|').replace('\n', '|').split("\\|"); 52 | 53 | for (String line : lines) { 54 | if (!line.isEmpty()) { 55 | serviceLines.add(relocateIfPossible(line, rules)); 56 | } 57 | } 58 | } 59 | 60 | private static String relocateIfPossible(String line, Collection rules) { 61 | for (Relocation rule : rules) { 62 | if (rule.canRelocateClass(line)) { 63 | return rule.relocateClass(line); 64 | } 65 | } 66 | return line; 67 | } 68 | 69 | @Override 70 | public void writeOutput(JarOutputStream jarOutputStream) throws IOException { 71 | this.serviceEntries.values().removeIf(Set::isEmpty); 72 | if (this.serviceEntries.isEmpty()) { 73 | return; 74 | } 75 | 76 | for (Map.Entry> entry : this.serviceEntries.entrySet()) { 77 | jarOutputStream.putNextEntry(new JarEntry(entry.getKey())); 78 | 79 | StringBuilder builder = new StringBuilder(); 80 | for (String line : entry.getValue()) { 81 | builder.append(line).append('\n'); 82 | } 83 | jarOutputStream.write(builder.toString().getBytes(StandardCharsets.UTF_8)); 84 | } 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/me/lucko/jarrelocator/JarRelocator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright Apache Software Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package me.lucko.jarrelocator; 18 | 19 | import java.io.BufferedOutputStream; 20 | import java.io.File; 21 | import java.io.FileOutputStream; 22 | import java.io.IOException; 23 | import java.util.ArrayList; 24 | import java.util.Collection; 25 | import java.util.Collections; 26 | import java.util.List; 27 | import java.util.Map; 28 | import java.util.concurrent.atomic.AtomicBoolean; 29 | import java.util.jar.JarFile; 30 | import java.util.jar.JarOutputStream; 31 | 32 | /** 33 | * Relocates classes and resources within a jar file. 34 | */ 35 | public final class JarRelocator { 36 | 37 | /** The input jar */ 38 | private final File input; 39 | /** The output jar */ 40 | private final File output; 41 | /** The relocating remapper */ 42 | private final RelocatingRemapper remapper; 43 | 44 | /** If the {@link #run()} method has been called yet */ 45 | private final AtomicBoolean used = new AtomicBoolean(false); 46 | 47 | /** 48 | * Creates a new instance with the given settings. 49 | * 50 | * @param input the input jar file 51 | * @param output the output jar file 52 | * @param relocations the relocations 53 | */ 54 | public JarRelocator(File input, File output, Collection relocations) { 55 | this.input = input; 56 | this.output = output; 57 | this.remapper = new RelocatingRemapper(relocations); 58 | } 59 | 60 | /** 61 | * Creates a new instance with the given settings. 62 | * 63 | * @param input the input jar file 64 | * @param output the output jar file 65 | * @param relocations the relocations 66 | */ 67 | public JarRelocator(File input, File output, Map relocations) { 68 | this.input = input; 69 | this.output = output; 70 | Collection c = new ArrayList<>(relocations.size()); 71 | for (Map.Entry entry : relocations.entrySet()) { 72 | c.add(new Relocation(entry.getKey(), entry.getValue())); 73 | } 74 | this.remapper = new RelocatingRemapper(c); 75 | } 76 | 77 | /** 78 | * Executes the relocation task 79 | * 80 | * @throws IOException if an exception is encountered whilst performing i/o 81 | * with the input or output file 82 | */ 83 | public void run() throws IOException { 84 | if (this.used.getAndSet(true)) { 85 | throw new IllegalStateException("#run has already been called on this instance"); 86 | } 87 | 88 | List transformers = new ArrayList<>(); 89 | transformers.add(new ServicesResourceTransformer()); 90 | 91 | try (JarOutputStream out = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(this.output)))) { 92 | try (JarFile in = new JarFile(this.input)) { 93 | JarRelocatorTask task = new JarRelocatorTask(this.remapper, out, in, Collections.unmodifiableList(transformers)); 94 | task.processEntries(); 95 | } 96 | } 97 | } 98 | 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/me/lucko/jarrelocator/Relocation.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright Apache Software Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package me.lucko.jarrelocator; 18 | 19 | import java.util.Collection; 20 | import java.util.Collections; 21 | import java.util.LinkedHashSet; 22 | import java.util.Set; 23 | 24 | /** 25 | * A relocation rule 26 | */ 27 | public final class Relocation { 28 | private final String pattern; 29 | private final String relocatedPattern; 30 | private final String pathPattern; 31 | private final String relocatedPathPattern; 32 | 33 | private final Set includes; 34 | private final Set excludes; 35 | 36 | /** 37 | * Creates a new relocation 38 | * 39 | * @param pattern the pattern to match 40 | * @param relocatedPattern the pattern to relocate to 41 | * @param includes a collection of patterns which this rule should specifically include 42 | * @param excludes a collection of patterns which this rule should specifically exclude 43 | */ 44 | public Relocation(String pattern, String relocatedPattern, Collection includes, Collection excludes) { 45 | this.pattern = pattern.replace('/', '.'); 46 | this.pathPattern = pattern.replace('.', '/'); 47 | this.relocatedPattern = relocatedPattern.replace('/', '.'); 48 | this.relocatedPathPattern = relocatedPattern.replace('.', '/'); 49 | 50 | if (includes != null && !includes.isEmpty()) { 51 | this.includes = normalizePatterns(includes); 52 | this.includes.addAll(includes); 53 | } else { 54 | this.includes = null; 55 | } 56 | 57 | if (excludes != null && !excludes.isEmpty()) { 58 | this.excludes = normalizePatterns(excludes); 59 | this.excludes.addAll(excludes); 60 | } else { 61 | this.excludes = null; 62 | } 63 | } 64 | 65 | /** 66 | * Creates a new relocation with no specific includes or excludes 67 | * 68 | * @param pattern the pattern to match 69 | * @param relocatedPattern the pattern to relocate to 70 | */ 71 | public Relocation(String pattern, String relocatedPattern) { 72 | this(pattern, relocatedPattern, Collections.emptyList(), Collections.emptyList()); 73 | } 74 | 75 | private boolean isIncluded(String path) { 76 | if (this.includes == null) { 77 | return true; 78 | } 79 | 80 | for (String include : this.includes) { 81 | if (SelectorUtils.matchPath(include, path, true)) { 82 | return true; 83 | } 84 | } 85 | return false; 86 | } 87 | 88 | private boolean isExcluded(String path) { 89 | if (this.excludes == null) { 90 | return false; 91 | } 92 | 93 | for (String exclude : this.excludes) { 94 | if (SelectorUtils.matchPath(exclude, path, true)) { 95 | return true; 96 | } 97 | } 98 | return false; 99 | } 100 | 101 | boolean canRelocatePath(String path) { 102 | if (path.endsWith(".class")) { 103 | path = path.substring(0, path.length() - 6); 104 | } 105 | 106 | if (!isIncluded(path) || isExcluded(path)) { 107 | return false; 108 | } 109 | 110 | return path.startsWith(this.pathPattern) || path.startsWith("/" + this.pathPattern); 111 | } 112 | 113 | boolean canRelocateClass(String clazz) { 114 | return clazz.indexOf('/') == -1 && canRelocatePath(clazz.replace('.', '/')); 115 | } 116 | 117 | String relocatePath(String path) { 118 | return path.replaceFirst(this.pathPattern, this.relocatedPathPattern); 119 | } 120 | 121 | String relocateClass(String clazz) { 122 | return clazz.replaceFirst(this.pattern, this.relocatedPattern); 123 | } 124 | 125 | private static Set normalizePatterns(Collection patterns) { 126 | Set normalized = new LinkedHashSet<>(); 127 | for (String pattern : patterns) { 128 | String classPattern = pattern.replace('.', '/'); 129 | normalized.add(classPattern); 130 | if (classPattern.endsWith("/*")) { 131 | String packagePattern = classPattern.substring(0, classPattern.lastIndexOf('/')); 132 | normalized.add(packagePattern); 133 | } 134 | } 135 | return normalized; 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | me.lucko 8 | jar-relocator 9 | 1.8-SNAPSHOT 10 | 11 | jar-relocator 12 | Utility to relocate classes within Jar archives 13 | https://github.com/lucko/jar-relocator 14 | 15 | 16 | 17 | Apache License 2.0 18 | https://www.apache.org/licenses/LICENSE-2.0 19 | 20 | 21 | 22 | 23 | 24 | Luck 25 | git@lucko.me 26 | https://github.com/lucko 27 | 28 | 29 | 30 | 31 | scm:git:https://github.com/lucko/jar-relocator.git 32 | scm:git:git@github.com:lucko/jar-relocator.git 33 | https://github.com/lucko/jar-relocator 34 | 35 | 36 | 37 | UTF-8 38 | 1.8 39 | 1.8 40 | 41 | 42 | 43 | 44 | org.ow2.asm 45 | asm 46 | 9.2 47 | compile 48 | 49 | 50 | org.ow2.asm 51 | asm-commons 52 | 9.2 53 | compile 54 | 55 | 56 | 57 | 58 | 59 | sign 60 | 61 | 62 | 63 | org.apache.maven.plugins 64 | maven-gpg-plugin 65 | 1.6 66 | 67 | 68 | sign-artifacts 69 | verify 70 | 71 | sign 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | ossrh 81 | 82 | 83 | ossrh 84 | https://oss.sonatype.org/content/repositories/snapshots 85 | 86 | 87 | ossrh 88 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 89 | 90 | 91 | 92 | 93 | deployment 94 | 95 | 96 | 97 | org.apache.maven.plugins 98 | maven-source-plugin 99 | 3.0.1 100 | 101 | 102 | attach-sources 103 | 104 | jar 105 | 106 | 107 | 108 | 109 | 110 | org.apache.maven.plugins 111 | maven-javadoc-plugin 112 | 2.10.4 113 | 114 | 115 | attach-javadocs 116 | 117 | jar 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | -------------------------------------------------------------------------------- /src/main/java/me/lucko/jarrelocator/JarRelocatorTask.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright Apache Software Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package me.lucko.jarrelocator; 18 | 19 | import org.objectweb.asm.ClassReader; 20 | import org.objectweb.asm.ClassWriter; 21 | 22 | import java.io.IOException; 23 | import java.io.InputStream; 24 | import java.io.OutputStream; 25 | import java.util.Enumeration; 26 | import java.util.HashSet; 27 | import java.util.List; 28 | import java.util.Map; 29 | import java.util.Set; 30 | import java.util.jar.*; 31 | import java.util.regex.Pattern; 32 | 33 | /** 34 | * A task that copies {@link JarEntry jar entries} from a {@link JarFile jar input} to a 35 | * {@link JarOutputStream jar output}, applying the relocations defined by a 36 | * {@link RelocatingRemapper}. 37 | */ 38 | final class JarRelocatorTask { 39 | 40 | /** 41 | * META-INF/*.SF 42 | * META-INF/*.DSA 43 | * META-INF/*.RSA 44 | * META-INF/SIG-* 45 | * 46 | * Specification 47 | */ 48 | private static final Pattern SIGNATURE_FILE_PATTERN = Pattern.compile("META-INF/(?:[^/]+\\.(?:DSA|RSA|SF)|SIG-[^/]+)"); 49 | 50 | /** 51 | * Specification 52 | */ 53 | private static final Pattern SIGNATURE_PROPERTY_PATTERN = Pattern.compile(".*-Digest"); 54 | 55 | private final RelocatingRemapper remapper; 56 | private final JarOutputStream jarOut; 57 | private final JarFile jarIn; 58 | private final List transformers; 59 | 60 | private final Set resources = new HashSet<>(); 61 | 62 | JarRelocatorTask(RelocatingRemapper remapper, JarOutputStream jarOut, JarFile jarIn, List transformers) { 63 | this.remapper = remapper; 64 | this.jarOut = jarOut; 65 | this.jarIn = jarIn; 66 | this.transformers = transformers; 67 | } 68 | 69 | void processEntries() throws IOException { 70 | for (Enumeration entries = this.jarIn.entries(); entries.hasMoreElements(); ) { 71 | JarEntry entry = entries.nextElement(); 72 | 73 | // The 'INDEX.LIST' file is an optional file, containing information about the packages 74 | // defined in a jar. Instead of relocating the entries in it, we delete it, since it is 75 | // optional anyway. 76 | // 77 | // We don't process directory entries, and instead opt to recreate them when adding 78 | // classes/resources. 79 | String name = entry.getName(); 80 | if (name.equals("META-INF/INDEX.LIST") || entry.isDirectory()) { 81 | continue; 82 | } 83 | 84 | // Signatures will become invalid after remapping, so we delete them to avoid making the output useless 85 | if (SIGNATURE_FILE_PATTERN.matcher(name).matches()) { 86 | continue; 87 | } 88 | 89 | try (InputStream entryIn = this.jarIn.getInputStream(entry)) { 90 | processEntry(entry, entryIn); 91 | } 92 | } 93 | 94 | for (ResourceTransformer transformer : this.transformers) { 95 | transformer.writeOutput(this.jarOut); 96 | } 97 | } 98 | 99 | private void processEntry(JarEntry entry, InputStream entryIn) throws IOException { 100 | String name = entry.getName(); 101 | String mappedName = this.remapper.map(name); 102 | 103 | // ensure the parent directory structure exists for the entry. 104 | processDirectory(mappedName, true); 105 | 106 | if (name.endsWith(".class")) { 107 | processClass(name, entryIn); 108 | } else if (name.equals("META-INF/MANIFEST.MF")) { 109 | processManifest(name, entryIn, entry.getTime()); 110 | } else if (!this.resources.contains(mappedName)) { 111 | processResource(mappedName, entryIn, entry.getTime()); 112 | } 113 | } 114 | 115 | private void processDirectory(String name, boolean parentsOnly) throws IOException { 116 | int index = name.lastIndexOf('/'); 117 | if (index != -1) { 118 | String parentDirectory = name.substring(0, index); 119 | if (!this.resources.contains(parentDirectory)) { 120 | processDirectory(parentDirectory, false); 121 | } 122 | } 123 | 124 | if (parentsOnly) { 125 | return; 126 | } 127 | 128 | // directory entries must end in "/" 129 | JarEntry entry = new JarEntry(name + "/"); 130 | this.jarOut.putNextEntry(entry); 131 | this.resources.add(name); 132 | } 133 | 134 | private void processManifest(String name, InputStream entryIn, long lastModified) throws IOException { 135 | Manifest in = new Manifest(entryIn); 136 | Manifest out = new Manifest(); 137 | 138 | out.getMainAttributes().putAll(in.getMainAttributes()); 139 | 140 | for (Map.Entry entry : in.getEntries().entrySet()) { 141 | Attributes outAttributes = new Attributes(); 142 | for (Map.Entry property : entry.getValue().entrySet()) { 143 | String key = property.getKey().toString(); 144 | if (!SIGNATURE_PROPERTY_PATTERN.matcher(key).matches()) { 145 | outAttributes.put(property.getKey(), property.getValue()); 146 | } 147 | } 148 | out.getEntries().put(entry.getKey(), outAttributes); 149 | } 150 | 151 | JarEntry jarEntry = new JarEntry(name); 152 | jarEntry.setTime(lastModified); 153 | this.jarOut.putNextEntry(jarEntry); 154 | 155 | out.write(this.jarOut); 156 | 157 | this.resources.add(name); 158 | } 159 | 160 | private void processResource(String name, InputStream entryIn, long lastModified) throws IOException { 161 | for (ResourceTransformer transformer : this.transformers) { 162 | if (transformer.shouldTransformResource(name)) { 163 | transformer.processResource(name, entryIn, this.remapper.getRules()); 164 | return; 165 | } 166 | } 167 | 168 | JarEntry jarEntry = new JarEntry(name); 169 | jarEntry.setTime(lastModified); 170 | 171 | this.jarOut.putNextEntry(jarEntry); 172 | copy(entryIn, this.jarOut); 173 | 174 | this.resources.add(name); 175 | } 176 | 177 | private void processClass(String name, InputStream entryIn) throws IOException { 178 | ClassReader classReader = new ClassReader(entryIn); 179 | ClassWriter classWriter = new ClassWriter(0); 180 | RelocatingClassVisitor classVisitor = new RelocatingClassVisitor(classWriter, this.remapper, name); 181 | 182 | try { 183 | classReader.accept(classVisitor, ClassReader.EXPAND_FRAMES); 184 | } catch (Throwable e) { 185 | throw new RuntimeException("Error processing class " + name, e); 186 | } 187 | 188 | byte[] renamedClass = classWriter.toByteArray(); 189 | 190 | // Need to take the .class off for remapping evaluation 191 | String mappedName = this.remapper.map(name.substring(0, name.indexOf('.'))); 192 | 193 | // Now we put it back on so the class file is written out with the right extension. 194 | this.jarOut.putNextEntry(new JarEntry(mappedName + ".class")); 195 | this.jarOut.write(renamedClass); 196 | } 197 | 198 | private static void copy(InputStream from, OutputStream to) throws IOException { 199 | byte[] buf = new byte[8192]; 200 | while (true) { 201 | int n = from.read(buf); 202 | if (n == -1) { 203 | break; 204 | } 205 | to.write(buf, 0, n); 206 | } 207 | } 208 | } 209 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /src/main/java/me/lucko/jarrelocator/SelectorUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The Apache Software License, Version 1.1 3 | * 4 | * Copyright (c) 2002-2003 The Apache Software Foundation. All rights 5 | * reserved. 6 | * 7 | * Redistribution and use in source and binary forms, with or without 8 | * modification, are permitted provided that the following conditions 9 | * are met: 10 | * 11 | * 1. Redistributions of source code must retain the above copyright 12 | * notice, this list of conditions and the following disclaimer. 13 | * 14 | * 2. Redistributions in binary form must reproduce the above copyright 15 | * notice, this list of conditions and the following disclaimer in 16 | * the documentation and/or other materials provided with the 17 | * distribution. 18 | * 19 | * 3. The end-user documentation included with the redistribution, if 20 | * any, must include the following acknowlegement: 21 | * "This product includes software developed by the 22 | * Apache Software Foundation (http://www.codehaus.org/)." 23 | * Alternately, this acknowlegement may appear in the software itself, 24 | * if and wherever such third-party acknowlegements normally appear. 25 | * 26 | * 4. The names "Ant" and "Apache Software 27 | * Foundation" must not be used to endorse or promote products derived 28 | * from this software without prior written permission. For written 29 | * permission, please contact codehaus@codehaus.org. 30 | * 31 | * 5. Products derived from this software may not be called "Apache" 32 | * nor may "Apache" appear in their names without prior written 33 | * permission of the Apache Group. 34 | * 35 | * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED 36 | * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 37 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 38 | * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR 39 | * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 40 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 41 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF 42 | * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 43 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 44 | * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 45 | * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 46 | * SUCH DAMAGE. 47 | * ==================================================================== 48 | * 49 | * This software consists of voluntary contributions made by many 50 | * individuals on behalf of the Apache Software Foundation. For more 51 | * information on the Apache Software Foundation, please see 52 | * . 53 | */ 54 | 55 | package me.lucko.jarrelocator; 56 | 57 | import java.io.File; 58 | import java.util.ArrayList; 59 | import java.util.List; 60 | import java.util.StringTokenizer; 61 | 62 | /** 63 | * This is a stripped down version of org.codehaus.plexus.util.SelectorUtils for 64 | * use in {@link Relocation}. 65 | * 66 | * @author Arnout J. Kuiper ajkuiper@wxs.nl 67 | * @author Magesh Umasankar 68 | * @author Bruce Atherton 69 | */ 70 | final class SelectorUtils { 71 | private static final String PATTERN_HANDLER_PREFIX = "["; 72 | private static final String PATTERN_HANDLER_SUFFIX = "]"; 73 | private static final String REGEX_HANDLER_PREFIX = "%regex" + PATTERN_HANDLER_PREFIX; 74 | private static final String ANT_HANDLER_PREFIX = "%ant" + PATTERN_HANDLER_PREFIX; 75 | 76 | private static boolean isAntPrefixedPattern(String pattern) { 77 | return pattern.length() > (ANT_HANDLER_PREFIX.length() + PATTERN_HANDLER_SUFFIX.length() + 1) 78 | && pattern.startsWith(ANT_HANDLER_PREFIX) && pattern.endsWith(PATTERN_HANDLER_SUFFIX); 79 | } 80 | 81 | // When str starts with a File.separator, pattern has to start with a File.separator. 82 | // When pattern starts with a File.separator, str has to start with a File.separator. 83 | private static boolean separatorPatternStartSlashMismatch(String pattern, String str, String separator) { 84 | return str.startsWith(separator) != pattern.startsWith(separator); 85 | } 86 | 87 | public static boolean matchPath(String pattern, String str, boolean isCaseSensitive) { 88 | return matchPath(pattern, str, File.separator, isCaseSensitive); 89 | } 90 | 91 | private static boolean matchPath(String pattern, String str, String separator, boolean isCaseSensitive) { 92 | if (isRegexPrefixedPattern(pattern)) { 93 | pattern = pattern.substring(REGEX_HANDLER_PREFIX.length(), pattern.length() - PATTERN_HANDLER_SUFFIX.length()); 94 | return str.matches(pattern); 95 | } else { 96 | if (isAntPrefixedPattern(pattern)) { 97 | pattern = pattern.substring(ANT_HANDLER_PREFIX.length(), pattern.length() - PATTERN_HANDLER_SUFFIX.length()); 98 | } 99 | return matchAntPathPattern(pattern, str, separator, isCaseSensitive); 100 | } 101 | } 102 | 103 | private static boolean isRegexPrefixedPattern(String pattern) { 104 | return pattern.length() > (REGEX_HANDLER_PREFIX.length() + PATTERN_HANDLER_SUFFIX.length() + 1) 105 | && pattern.startsWith(REGEX_HANDLER_PREFIX) && pattern.endsWith(PATTERN_HANDLER_SUFFIX); 106 | } 107 | 108 | private static boolean matchAntPathPattern(String pattern, String str, String separator, boolean isCaseSensitive) { 109 | if (separatorPatternStartSlashMismatch(pattern, str, separator)) { 110 | return false; 111 | } 112 | String[] patDirs = tokenizePathToString(pattern, separator); 113 | String[] strDirs = tokenizePathToString(str, separator); 114 | return matchAntPathPattern(patDirs, strDirs, isCaseSensitive); 115 | 116 | } 117 | 118 | private static boolean matchAntPathPattern(String[] patDirs, String[] strDirs, boolean isCaseSensitive) { 119 | int patIdxStart = 0; 120 | int patIdxEnd = patDirs.length - 1; 121 | int strIdxStart = 0; 122 | int strIdxEnd = strDirs.length - 1; 123 | 124 | // up to first '**' 125 | while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) { 126 | String patDir = patDirs[patIdxStart]; 127 | if (patDir.equals("**")) { 128 | break; 129 | } 130 | if (!match(patDir, strDirs[strIdxStart], isCaseSensitive)) { 131 | return false; 132 | } 133 | patIdxStart++; 134 | strIdxStart++; 135 | } 136 | if (strIdxStart > strIdxEnd) { 137 | // String is exhausted 138 | for (int i = patIdxStart; i <= patIdxEnd; i++) { 139 | if (!patDirs[i].equals("**")) { 140 | return false; 141 | } 142 | } 143 | return true; 144 | } else { 145 | if (patIdxStart > patIdxEnd) { 146 | // String not exhausted, but pattern is. Failure. 147 | return false; 148 | } 149 | } 150 | 151 | // up to last '**' 152 | while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) { 153 | String patDir = patDirs[patIdxEnd]; 154 | if (patDir.equals("**")) { 155 | break; 156 | } 157 | if (!match(patDir, strDirs[strIdxEnd], isCaseSensitive)) { 158 | return false; 159 | } 160 | patIdxEnd--; 161 | strIdxEnd--; 162 | } 163 | if (strIdxStart > strIdxEnd) { 164 | // String is exhausted 165 | for (int i = patIdxStart; i <= patIdxEnd; i++) { 166 | if (!patDirs[i].equals("**")) { 167 | return false; 168 | } 169 | } 170 | return true; 171 | } 172 | 173 | while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) { 174 | int patIdxTmp = -1; 175 | for (int i = patIdxStart + 1; i <= patIdxEnd; i++) { 176 | if (patDirs[i].equals("**")) { 177 | patIdxTmp = i; 178 | break; 179 | } 180 | } 181 | if (patIdxTmp == patIdxStart + 1) { 182 | // '**/**' situation, so skip one 183 | patIdxStart++; 184 | continue; 185 | } 186 | // Find the pattern between padIdxStart & padIdxTmp in str between 187 | // strIdxStart & strIdxEnd 188 | int patLength = (patIdxTmp - patIdxStart - 1); 189 | int strLength = (strIdxEnd - strIdxStart + 1); 190 | int foundIdx = -1; 191 | strLoop: 192 | for (int i = 0; i <= strLength - patLength; i++) { 193 | for (int j = 0; j < patLength; j++) { 194 | String subPat = patDirs[patIdxStart + j + 1]; 195 | String subStr = strDirs[strIdxStart + i + j]; 196 | if (!match(subPat, subStr, isCaseSensitive)) { 197 | continue strLoop; 198 | } 199 | } 200 | 201 | foundIdx = strIdxStart + i; 202 | break; 203 | } 204 | 205 | if (foundIdx == -1) { 206 | return false; 207 | } 208 | 209 | patIdxStart = patIdxTmp; 210 | strIdxStart = foundIdx + patLength; 211 | } 212 | 213 | for (int i = patIdxStart; i <= patIdxEnd; i++) { 214 | if (!patDirs[i].equals("**")) { 215 | return false; 216 | } 217 | } 218 | 219 | return true; 220 | } 221 | 222 | private static boolean match(String pattern, String str, boolean isCaseSensitive) { 223 | char[] patArr = pattern.toCharArray(); 224 | char[] strArr = str.toCharArray(); 225 | return match(patArr, strArr, isCaseSensitive); 226 | } 227 | 228 | private static boolean match(char[] patArr, char[] strArr, boolean isCaseSensitive) { 229 | int patIdxStart = 0; 230 | int patIdxEnd = patArr.length - 1; 231 | int strIdxStart = 0; 232 | int strIdxEnd = strArr.length - 1; 233 | char ch; 234 | 235 | boolean containsStar = false; 236 | for (char aPatArr : patArr) { 237 | if (aPatArr == '*') { 238 | containsStar = true; 239 | break; 240 | } 241 | } 242 | 243 | if (!containsStar) { 244 | // No '*'s, so we make a shortcut 245 | if (patIdxEnd != strIdxEnd) { 246 | return false; // Pattern and string do not have the same size 247 | } 248 | for (int i = 0; i <= patIdxEnd; i++) { 249 | ch = patArr[i]; 250 | if (ch != '?' && !equals(ch, strArr[i], isCaseSensitive)) { 251 | return false; // Character mismatch 252 | } 253 | } 254 | return true; // String matches against pattern 255 | } 256 | 257 | if (patIdxEnd == 0) { 258 | return true; // Pattern contains only '*', which matches anything 259 | } 260 | 261 | // Process characters before first star 262 | while ((ch = patArr[patIdxStart]) != '*' && strIdxStart <= strIdxEnd) { 263 | if (ch != '?' && !equals(ch, strArr[strIdxStart], isCaseSensitive)) { 264 | return false; // Character mismatch 265 | } 266 | patIdxStart++; 267 | strIdxStart++; 268 | } 269 | if (strIdxStart > strIdxEnd) { 270 | // All characters in the string are used. Check if only '*'s are 271 | // left in the pattern. If so, we succeeded. Otherwise failure. 272 | for (int i = patIdxStart; i <= patIdxEnd; i++) { 273 | if (patArr[i] != '*') { 274 | return false; 275 | } 276 | } 277 | return true; 278 | } 279 | 280 | // Process characters after last star 281 | while ((ch = patArr[patIdxEnd]) != '*' && strIdxStart <= strIdxEnd) { 282 | if (ch != '?' && !equals(ch, strArr[strIdxEnd], isCaseSensitive)) { 283 | return false; // Character mismatch 284 | } 285 | patIdxEnd--; 286 | strIdxEnd--; 287 | } 288 | if (strIdxStart > strIdxEnd) { 289 | // All characters in the string are used. Check if only '*'s are 290 | // left in the pattern. If so, we succeeded. Otherwise failure. 291 | for (int i = patIdxStart; i <= patIdxEnd; i++) { 292 | if (patArr[i] != '*') { 293 | return false; 294 | } 295 | } 296 | return true; 297 | } 298 | 299 | // process pattern between stars. padIdxStart and patIdxEnd point 300 | // always to a '*'. 301 | while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) { 302 | int patIdxTmp = -1; 303 | for (int i = patIdxStart + 1; i <= patIdxEnd; i++) { 304 | if (patArr[i] == '*') { 305 | patIdxTmp = i; 306 | break; 307 | } 308 | } 309 | if (patIdxTmp == patIdxStart + 1) { 310 | // Two stars next to each other, skip the first one. 311 | patIdxStart++; 312 | continue; 313 | } 314 | // Find the pattern between padIdxStart & padIdxTmp in str between 315 | // strIdxStart & strIdxEnd 316 | int patLength = (patIdxTmp - patIdxStart - 1); 317 | int strLength = (strIdxEnd - strIdxStart + 1); 318 | int foundIdx = -1; 319 | strLoop: 320 | for (int i = 0; i <= strLength - patLength; i++) { 321 | for (int j = 0; j < patLength; j++) { 322 | ch = patArr[patIdxStart + j + 1]; 323 | if (ch != '?' && !equals(ch, strArr[strIdxStart + i + j], isCaseSensitive)) { 324 | continue strLoop; 325 | } 326 | } 327 | 328 | foundIdx = strIdxStart + i; 329 | break; 330 | } 331 | 332 | if (foundIdx == -1) { 333 | return false; 334 | } 335 | 336 | patIdxStart = patIdxTmp; 337 | strIdxStart = foundIdx + patLength; 338 | } 339 | 340 | // All characters in the string are used. Check if only '*'s are left 341 | // in the pattern. If so, we succeeded. Otherwise failure. 342 | for (int i = patIdxStart; i <= patIdxEnd; i++) { 343 | if (patArr[i] != '*') { 344 | return false; 345 | } 346 | } 347 | return true; 348 | } 349 | 350 | /** 351 | * Tests whether two characters are equal. 352 | */ 353 | private static boolean equals(char c1, char c2, boolean isCaseSensitive) { 354 | if (c1 == c2) { 355 | return true; 356 | } 357 | if (!isCaseSensitive) { 358 | // NOTE: Try both upper case and lower case as done by String.equalsIgnoreCase() 359 | if (Character.toUpperCase(c1) == Character.toUpperCase(c2) 360 | || Character.toLowerCase(c1) == Character.toLowerCase(c2)) { 361 | return true; 362 | } 363 | } 364 | return false; 365 | } 366 | 367 | private static String[] tokenizePathToString(String path, String separator) { 368 | List ret = new ArrayList(); 369 | StringTokenizer st = new StringTokenizer(path, separator); 370 | while (st.hasMoreTokens()) { 371 | ret.add(st.nextToken()); 372 | } 373 | return ret.toArray(new String[ret.size()]); 374 | } 375 | 376 | /** 377 | * Private Constructor 378 | */ 379 | private SelectorUtils() { 380 | } 381 | } 382 | --------------------------------------------------------------------------------