Project

Profile

Help

Bug #6565 » SaxonDocumentKeyFix.java

Philipp Nanz, 2024-10-23 10:13

 
package de.docufy.topicpilot.microservices.commons.saxon;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;
import net.sf.saxon.om.DocumentKey;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.Paths;

@Slf4j
@Component
@ConditionalOnClass(ByteBuddyAgent.class)
public class SaxonDocumentKeyFix {

@PostConstruct
public void init() {
log.info("Installing fix for Saxon #6565");
ByteBuddyAgent.install();
new ByteBuddy()
.redefine(DocumentKey.class)
.method(ElementMatchers.named("normalizeURI"))
.intercept(MethodDelegation.to(DocumentKeyFixed.class))
.make()
.load(DocumentKey.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
}

public static class DocumentKeyFixed {
public static final boolean CASE_BLIND_FILES = (new File("a")).equals(new File("A"));

public static String normalizeURI(String uri) {
if (uri == null) {
return null;
}
if (uri.startsWith("FILE:")) {
uri = "file:" + uri.substring(5);
}
if (uri.startsWith("file:")) {
if (uri.startsWith("file:///")) {
uri = "file:/" + uri.substring(8);
}
if (uri.startsWith("file:/")) {
// Work-around for Saxon #6565
String cpath = Paths.get(uri.substring(6)).normalize().toString();
uri = "file:" + cpath;
}
if (CASE_BLIND_FILES) {
uri = uri.toLowerCase();
}
}
return uri;
}
}
}
(2-2/2)