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