1 /* 2 * Copyright (C) 2010 Google Inc. 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 com.google.doclava; 18 19 import java.io.File; 20 import java.io.FileOutputStream; 21 import java.io.IOException; 22 import java.io.InputStream; 23 import java.net.URL; 24 import java.util.Enumeration; 25 import java.util.jar.JarEntry; 26 import java.util.jar.JarFile; 27 28 public class JarUtils { 29 /** 30 * Returns the jar file used to load class clazz, or defaultJar if clazz was not loaded from a 31 * jar. 32 */ jarForClass(Class<?> clazz, JarFile defaultJar)33 public static JarFile jarForClass(Class<?> clazz, JarFile defaultJar) { 34 String path = "/" + clazz.getName().replace('.', '/') + ".class"; 35 URL jarUrl = clazz.getResource(path); 36 if (jarUrl == null) { 37 return defaultJar; 38 } 39 40 String url = jarUrl.toString(); 41 int bang = url.indexOf("!"); 42 String JAR_URI_PREFIX = "jar:file:"; 43 if (url.startsWith(JAR_URI_PREFIX) && bang != -1) { 44 try { 45 return new JarFile(url.substring(JAR_URI_PREFIX.length(), bang)); 46 } catch (IOException e) { 47 throw new IllegalStateException("Error loading jar file.", e); 48 } 49 } else { 50 return defaultJar; 51 } 52 } 53 54 /** 55 * Copies a directory from a jar file to an external directory. 56 */ copyResourcesToDirectory(JarFile fromJar, String jarDir, String destDir)57 public static void copyResourcesToDirectory(JarFile fromJar, String jarDir, String destDir) 58 throws IOException { 59 for (Enumeration<JarEntry> entries = fromJar.entries(); entries.hasMoreElements();) { 60 JarEntry entry = entries.nextElement(); 61 if (entry.getName().startsWith(jarDir + "/") && !entry.isDirectory()) { 62 File dest = new File(destDir + "/" + entry.getName().substring(jarDir.length() + 1)); 63 File parent = dest.getParentFile(); 64 if (parent != null) { 65 parent.mkdirs(); 66 } 67 68 FileOutputStream out = new FileOutputStream(dest); 69 InputStream in = fromJar.getInputStream(entry); 70 71 try { 72 byte[] buffer = new byte[8 * 1024]; 73 74 int s = 0; 75 while ((s = in.read(buffer)) > 0) { 76 out.write(buffer, 0, s); 77 } 78 } catch (IOException e) { 79 throw new IOException("Could not copy asset from jar file", e); 80 } finally { 81 try { 82 in.close(); 83 } catch (IOException ignored) {} 84 try { 85 out.close(); 86 } catch (IOException ignored) {} 87 } 88 } 89 } 90 91 } 92 JarUtils()93 private JarUtils() {} // non-instantiable 94 } 95