github-actions[bot] commented on code in PR #41083:
URL: https://github.com/apache/beam/pull/41083#discussion_r4585833336


##########
sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/StringCompiler.java:
##########
@@ -49,41 +56,240 @@
 import javax.tools.SimpleJavaFileObject;
 import javax.tools.StandardJavaFileManager;
 import javax.tools.ToolProvider;
+import org.apache.beam.sdk.values.Row;
+import 
org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.annotations.VisibleForTesting;
+import 
org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Splitter;
 import 
org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Suppliers;
 import 
org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 public class StringCompiler {
+  private static final Logger LOG = 
LoggerFactory.getLogger(StringCompiler.class);
+
   @SuppressWarnings({
     "nullness" // TODO(https://github.com/apache/beam/issues/20497)
   })
   private static final Supplier<String> classpathSupplier =
       Suppliers.memoize(
           () -> {
-            List<String> cp = new ArrayList<>();
-            cp.add(System.getProperty("java.class.path"));
-            // Javac doesn't properly handle manifest classpath spec.
             ClassLoader cl = StringCompiler.class.getClassLoader();
             if (cl == null) {
               cl = ClassLoader.getSystemClassLoader();
             }
-            if (cl instanceof URLClassLoader) {
-              for (URL url : ((URLClassLoader) cl).getURLs()) {
-                File file = new File(url.getFile());
-                if (file.exists() && !file.isDirectory()) {
-                  try (ZipFile zipFile = new ZipFile(new File(url.getFile()))) 
{
-                    ZipEntry manifestEntry = 
zipFile.getEntry("META-INF/MANIFEST.MF");
-                    if (manifestEntry != null) {
-                      Manifest manifest = new 
Manifest(zipFile.getInputStream(manifestEntry));
-                      
cp.add(manifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH));
-                    }
-                  } catch (IOException exn) {
-                    throw new RuntimeException(exn);
+            List<String> cp = buildClasspath(cl, 
System.getProperty("java.class.path"));
+            return String.join(File.pathSeparator, cp);
+          });
+
+  @VisibleForTesting
+  static List<String> buildClasspath(@Nullable ClassLoader cl, @Nullable 
String classPathProperty) {
+    Set<String> cp = new LinkedHashSet<>();
+    Set<File> visitedJars = new HashSet<>();
+
+    if (classPathProperty != null) {
+      for (String entry :
+          
Splitter.on(File.pathSeparator).omitEmptyStrings().split(classPathProperty)) {
+        File file = new File(entry);
+        if (file.exists()) {
+          cp.add(file.getAbsolutePath());
+          if (file.isFile() && isJarFile(file)) {
+            extractManifestClasspath(file, cp, visitedJars);
+          }
+        }
+      }
+    }
+
+    if (cl instanceof URLClassLoader) {
+      for (URL url : ((URLClassLoader) cl).getURLs()) {
+        File file;
+        try {
+          file = new File(url.toURI());
+        } catch (Exception e) {
+          file = new File(url.getPath());
+        }
+        if (file.exists()) {
+          cp.add(file.getAbsolutePath());
+          if (file.isFile() && isJarFile(file)) {
+            extractManifestClasspath(file, cp, visitedJars);
+          }
+        }
+      }
+    }
+
+    addClassLocation(Row.class, cp, visitedJars);
+    addClassLocation(StringCompiler.class, cp, visitedJars);
+
+    if (cl != null) {
+      addResourceLocation(cl, "org/apache/beam/sdk/values/Row.class", cp, 
visitedJars);
+      addResourceLocation(
+          cl,
+          
"org/apache/beam/sdk/schemas/transforms/providers/StringCompiler.class",
+          cp,
+          visitedJars);
+    }
+
+    return new ArrayList<>(cp);
+  }
+
+  private static void extractManifestClasspath(
+      File jarFile, Set<String> cp, Set<File> visitedJars) {
+    File canonicalJar;
+    try {
+      canonicalJar = jarFile.getCanonicalFile();
+    } catch (IOException e) {
+      canonicalJar = jarFile.getAbsoluteFile();
+    }
+    if (!visitedJars.add(canonicalJar)) {
+      return;
+    }
+
+    try (ZipFile zipFile = new ZipFile(jarFile)) {
+      ZipEntry manifestEntry = zipFile.getEntry("META-INF/MANIFEST.MF");
+      if (manifestEntry != null) {
+        try (InputStream is = zipFile.getInputStream(manifestEntry)) {
+          if (is != null) {
+            Manifest manifest = new Manifest(is);
+            String classPathAttr =
+                
manifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH);
+            if (classPathAttr != null) {
+              for (String part :
+                  
Splitter.onPattern("\\s+").omitEmptyStrings().split(classPathAttr)) {
+                File targetFile = 
resolveManifestEntry(jarFile.getParentFile(), part);
+                if (targetFile != null && targetFile.exists()) {
+                  cp.add(targetFile.getAbsolutePath());
+                  if (targetFile.isFile() && isJarFile(targetFile)) {
+                    extractManifestClasspath(targetFile, cp, visitedJars);
                   }
                 }
               }
             }
-            return String.join(System.getProperty("path.separator"), cp);
-          });
+          }
+        }
+      }
+    } catch (IOException exn) {
+      LOG.warn("Failed to read manifest from jar: {}", jarFile, exn);
+    }
+  }
+
+  @VisibleForTesting
+  static @Nullable File resolveManifestEntry(@Nullable File parentDir, 
@Nullable String entry) {
+    if (entry == null || entry.isEmpty()) {
+      return null;
+    }
+    try {
+      String uriStr = entry;
+      if (isWindowsAbsoluteDrivePath(uriStr)) {
+        uriStr = "file:///" + uriStr.replace('\\', '/');
+      }
+      URI uri = URI.create(uriStr);
+      String path = uri.getPath();
+      if (path != null && !path.isEmpty()) {
+        if (path.length() >= 3
+            && path.charAt(0) == '/'
+            && Character.isLetter(path.charAt(1))
+            && path.charAt(2) == ':') {
+          path = path.substring(1);
+        }
+        File f = new File(path);
+        if (isRootedOrAbsolute(path, f)) {
+          return f;
+        }
+        return parentDir != null ? new File(parentDir, path) : f;
+      }
+    } catch (IllegalArgumentException e) {
+      // Fallback if entry is not a valid URI (e.g. unencoded special 
characters or raw Windows
+      // path)
+    }
+
+    String rawPath = entry.startsWith("file:") ? 
entry.substring("file:".length()) : entry;
+    File f = new File(rawPath);
+    if (isRootedOrAbsolute(rawPath, f)) {
+      return f;
+    }
+    return parentDir != null ? new File(parentDir, rawPath) : f;
+  }
+
+  private static boolean isRootedOrAbsolute(String path, File f) {
+    if (f.isAbsolute()) {
+      return true;
+    }
+    if (!path.isEmpty()) {
+      char c0 = path.charAt(0);
+      // Leading '/' (Unix root-relative or absolute) or '\' (Windows 
root-relative or UNC '\\')
+      if (c0 == '/' || c0 == '\\') {
+        return true;
+      }
+    }
+    return isWindowsAbsoluteDrivePath(path);
+  }
+
+  private static boolean isWindowsAbsoluteDrivePath(String path) {
+    return path.length() >= 3
+        && Character.isLetter(path.charAt(0))
+        && path.charAt(1) == ':'
+        && (path.charAt(2) == '/' || path.charAt(2) == '\\');
+  }
+
+  private static boolean isJarFile(File file) {
+    String name = file.getName().toLowerCase(Locale.ROOT);
+    return name.endsWith(".jar") || name.endsWith(".zip");
+  }
+
+  private static void addClassLocation(Class<?> clazz, Set<String> cp, 
Set<File> visitedJars) {
+    try {
+      ProtectionDomain pd = clazz.getProtectionDomain();
+      if (pd != null) {
+        CodeSource cs = pd.getCodeSource();
+        if (cs != null && cs.getLocation() != null) {
+          URL location = cs.getLocation();
+          File file;
+          try {
+            file = new File(location.toURI());
+          } catch (Exception e) {
+            file = new File(location.getPath());
+          }
+          if (file.exists()) {
+            cp.add(file.getAbsolutePath());
+            if (file.isFile() && isJarFile(file)) {
+              extractManifestClasspath(file, cp, visitedJars);
+            }
+          }
+        }
+      }
+    } catch (Exception e) {
+      LOG.debug("Unable to determine code source location for {}", clazz, e);
+    }
+  }
+
+  private static void addResourceLocation(
+      ClassLoader cl, String resourcePath, Set<String> cp, Set<File> 
visitedJars) {
+    try {
+      URL res = cl.getResource(resourcePath);
+      if (res != null && "jar".equalsIgnoreCase(res.getProtocol())) {
+        String path = res.getPath();
+        int bang = path.indexOf("!/");
+        if (bang != -1) {
+          String jarPath = path.substring(0, bang);
+          if (jarPath.startsWith("file:")) {
+            try {

Review Comment:
   **🟢 Low**: `URI.create(jarPath).getPath()` returns a leading slash before 
the drive letter on Windows (e.g., `/C:/path/to/file.jar`), whereas `new 
File(URI.create(jarPath))` (or delegating to `resolveManifestEntry(null, 
jarPath)`) properly normalizes `file:` URIs into platform-specific paths across 
both Unix and Windows.
   
   ```suggestion
                 jarPath = new File(URI.create(jarPath)).getPath();
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to