1 /* 2 * Copyright (C) 2012 The Android Open Source Project 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.android.inputmethod.latin.maketext; 18 19 import java.io.IOException; 20 import java.io.InputStream; 21 import java.io.UnsupportedEncodingException; 22 import java.net.URL; 23 import java.net.URLDecoder; 24 import java.util.ArrayList; 25 import java.util.Enumeration; 26 import java.util.jar.JarEntry; 27 import java.util.jar.JarFile; 28 29 public class JarUtils { 30 private static final String MANIFEST = "META-INF/MANIFEST.MF"; 31 32 private JarUtils() { 33 // This utility class is not publicly instantiable. 34 } 35 36 public static JarFile getJarFile(final ClassLoader loader) { 37 final URL resUrl = loader.getResource(MANIFEST); 38 if (!resUrl.getProtocol().equals("jar")) { 39 throw new RuntimeException("Should run as jar"); 40 } 41 final String path = resUrl.getPath(); 42 if (!path.startsWith("file:")) { 43 throw new RuntimeException("Unknown jar path: " + path); 44 } 45 final String jarPath = path.substring("file:".length(), path.indexOf('!')); 46 try { 47 return new JarFile(URLDecoder.decode(jarPath, "UTF-8")); 48 } catch (UnsupportedEncodingException e) { 49 } catch (IOException e) { 50 } 51 return null; 52 } 53 54 public static InputStream openResource(final String name) { 55 return JarUtils.class.getResourceAsStream("/" + name); 56 } 57 58 public interface JarFilter { 59 public boolean accept(String dirName, String name); 60 } 61 62 public static ArrayList<String> getNameListing(final JarFile jar, final JarFilter filter) { 63 final ArrayList<String> result = new ArrayList<String>(); 64 final Enumeration<JarEntry> entries = jar.entries(); 65 while (entries.hasMoreElements()) { 66 final JarEntry entry = entries.nextElement(); 67 final String path = entry.getName(); 68 final int pos = path.lastIndexOf('/'); 69 final String dirName = (pos >= 0) ? path.substring(0, pos) : ""; 70 final String name = (pos >= 0) ? path.substring(pos + 1) : path; 71 if (filter.accept(dirName, name)) { 72 result.add(path); 73 } 74 } 75 return result; 76 } 77 78 public static ArrayList<String> getNameListing(final JarFile jar, final String filterName) { 79 return getNameListing(jar, new JarFilter() { 80 @Override 81 public boolean accept(final String dirName, final String name) { 82 return name.equals(filterName); 83 } 84 }); 85 } 86 } 87