List of usage examples for java.util.zip ZipFile getEntry
public ZipEntry getEntry(String name)
From source file:simonlang.coastdove.core.detection.AppDetectionDataSetup.java
/** * Constructs a new layout collection from the given .apk file * @param apkFile APK file to process *///from w w w. j ava 2 s .c om public static AppDetectionData fromAPK(Context context, File apkFile, String appPackageName, LoadingInfo loadingInfo) { // Map if how often IDs occur Map<String, Integer> idCounts = new HashMap<>(); // Set of activities available from the Android launcher Set<String> mainActivities = new TreeSet<>(new CollatorWrapper()); loadingInfo.setNotificationData(context.getString(R.string.add_app_notification_loading), appPackageName, R.drawable.notification_template_icon_bg); loadingInfo.setTitle(context.getString(R.string.add_app_parsing_resources)); loadingInfo.start(true); ZipFile apk; try { apk = new ZipFile(apkFile); } catch (IOException e) { Log.e("AppDetectionDataSetup", "Cannot open ZipFile: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } Log.d("AppDetectionDataSetup", "Parsing resources.arsc and AndroidManifest.xml"); ARSCFileParser resourceParser = new ARSCFileParser(); ZipEntry arscEntry = apk.getEntry("resources.arsc"); APKToolHelper apktoolHelper = new APKToolHelper(apkFile); InputStream manifestInputStream = apktoolHelper.manifestInputStream(); try { resourceParser.parse(apk.getInputStream(arscEntry)); if (Thread.currentThread().isInterrupted()) { loadingInfo.end(); apk.close(); return null; } XmlPullParserFactory fac = XmlPullParserFactory.newInstance(); XmlPullParser p = fac.newPullParser(); p.setInput(manifestInputStream, "UTF-8"); mainActivities = parseMainActivities(p); manifestInputStream.close(); if (Thread.currentThread().isInterrupted()) { loadingInfo.end(); apk.close(); return null; } } catch (IOException e) { Log.e("AppDetectionDataSetup", "Cannot get InputStream: " + e.getMessage()); } catch (XmlPullParserException e) { Log.e("AppDetectionDataSetup", "Cannot get XmlPullParser: " + e.getMessage()); } AppMetaInformation appMetaInformation = new AppMetaInformation(appPackageName, mainActivities); // Read APK file loadingInfo.setTitle(context.getString(R.string.add_app_reading_apk)); loadingInfo.update(); Log.d("AppDetectionDataSetup", "Reading APK file"); Enumeration<?> zipEntries = apk.entries(); List<Pair<String, Set<String>>> layoutIDSets = new LinkedList<>(); while (zipEntries.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) zipEntries.nextElement(); try { if (Thread.currentThread().isInterrupted()) { loadingInfo.end(); apk.close(); return null; } String entryName = zipEntry.getName(); if (entryName.contains("res/layout/") && Misc.isBinaryXML(apk.getInputStream(zipEntry))) { String name = entryName.replaceAll(".*/", "").replace(".xml", ""); AXmlResourceParser parser = new AXmlResourceParser(); parser.open(apk.getInputStream(zipEntry)); Set<String> androidIDs = parseAndroidIDs(parser, resourceParser); layoutIDSets.add(new Pair<>(name, androidIDs)); // Count all IDs for (String id : androidIDs) { if (idCounts.containsKey(id)) { int count = idCounts.get(id); idCounts.put(id, count + 1); } else idCounts.put(id, 1); } } } catch (IOException e) { Log.e("AppDetectionDataSetup", "Error reading APK file: " + e.getMessage()); } } try { apk.close(); } catch (IOException e) { Log.e("AppDetectionDataSetup", "Unable to close APK file: " + e.getMessage()); } // get unique IDs and reverse map loadingInfo.setTitle(context.getString(R.string.add_app_setting_up_layouts)); loadingInfo.update(); // Build the final map we actually need (id -> layout) Map<String, String> idToLayoutMap = new HashMap<>(); for (Pair<String, Set<String>> layoutIDSet : layoutIDSets) { for (String id : layoutIDSet.second) { if (idCounts.get(id) == 1) idToLayoutMap.put(id, layoutIDSet.first); } } loadingInfo.setNotificationData(context.getString(R.string.add_app_notification_finished_loading), null, null); loadingInfo.end(); return new AppDetectionData(appPackageName, idToLayoutMap, appMetaInformation); }
From source file:org.eclipse.thym.core.internal.util.FileUtils.java
/** * Copies the contents of a source file to the destination file. * It replaces the value pairs passed on the templatesValues while * copying. // w ww . ja va 2 s . c o m * * @param source file on the file system or jar file * @param destination file on the file system * @param templateValues value pairs to be replaced * @throws IOException * @throws IllegalArgumentException * <ul> * <li>source or destination is null or not a file</li> * <li>destination is not a file URL</li> * </ul> */ public static void templatedFileCopy(URL source, URL destination, Map<String, String> templateValues) throws IOException { checkCanCopy(source, destination); if (templateValues == null) throw new IllegalArgumentException("Template values can not be null"); source = getFileURL(source); destination = getFileURL(destination); File dstFile = new File(destination.getFile()); BufferedReader in = null; BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter(dstFile)); if ("file".equals(source.getProtocol())) { File srcFile = new File(source.getFile()); in = new BufferedReader(new FileReader(srcFile)); } else if ("jar".equals(source.getProtocol())) { ZipFile zipFile = getZipFile(source); String file = source.getFile(); int exclamation = file.indexOf('!'); String jarLocation = file.substring(exclamation + 2); // remove jar separator !/ ZipEntry zipEntry = zipFile.getEntry(jarLocation); if (zipEntry == null) { throw new IllegalArgumentException(source + " can not be found on the zip file"); } InputStream zipStream = zipFile.getInputStream(zipEntry); in = new BufferedReader(new InputStreamReader(zipStream)); } String line; while ((line = in.readLine()) != null) { for (Map.Entry<String, String> entry : templateValues.entrySet()) { line = line.replace(entry.getKey(), entry.getValue()); } out.write(line); out.newLine(); } } finally { if (out != null) out.close(); if (in != null) in.close(); } }
From source file:com.aurel.track.admin.server.dbbackup.DatabaseBackupBL.java
public static Properties getBackupInfo(File backupFile) throws DatabaseBackupBLException { Properties prop = new Properties(); ZipFile zipFile = null; try {// w ww . j av a 2 s. c o m zipFile = new ZipFile(backupFile, ZipFile.OPEN_READ); } catch (IOException e) { throw new DatabaseBackupBLException(e.getMessage(), e); } ZipEntry zipEntryInfo = zipFile.getEntry(DataReader.FILE_NAME_INFO); if (zipEntryInfo == null) { try { zipFile.close(); } catch (IOException e) { throw new DatabaseBackupBLException(e.getMessage(), e); } throw new DatabaseBackupBLException("Invalid backup. No file info"); } try { prop.load(zipFile.getInputStream(zipEntryInfo)); } catch (IOException e) { throw new DatabaseBackupBLException(e.getMessage(), e); } try { zipFile.close(); } catch (IOException e) { throw new DatabaseBackupBLException(e.getMessage(), e); } return prop; }
From source file:org.opencms.module.CmsModuleImportExportHandler.java
/** * Reads a module object from an external file source.<p> * /* ww w .java 2 s .c om*/ * @param importResource the name of the input source * * @return the imported module * * @throws CmsConfigurationException if the module could not be imported */ public static CmsModule readModuleFromImport(String importResource) throws CmsConfigurationException { // instantiate Digester and enable XML validation Digester digester = new Digester(); digester.setUseContextClassLoader(true); digester.setValidating(false); digester.setRuleNamespaceURI(null); digester.setErrorHandler(new CmsXmlErrorHandler(importResource)); // add this class to the Digester CmsModuleImportExportHandler handler = new CmsModuleImportExportHandler(); digester.push(handler); CmsModuleXmlHandler.addXmlDigesterRules(digester); InputStream stream = null; ZipFile importZip = null; try { File file = new File(importResource); if (file.isFile()) { importZip = new ZipFile(importResource); ZipEntry entry = importZip.getEntry(CmsImportExportManager.EXPORT_MANIFEST); if (entry != null) { stream = importZip.getInputStream(entry); } else { CmsMessageContainer message = Messages.get().container(Messages.ERR_NO_MANIFEST_MODULE_IMPORT_1, importResource); LOG.error(message.key()); throw new CmsConfigurationException(message); } } else if (file.isDirectory()) { file = new File(file, CmsImportExportManager.EXPORT_MANIFEST); stream = new FileInputStream(file); } // start the parsing process digester.parse(stream); } catch (IOException e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_IO_MODULE_IMPORT_1, importResource); LOG.error(message.key(), e); throw new CmsConfigurationException(message, e); } catch (SAXException e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_SAX_MODULE_IMPORT_1, importResource); LOG.error(message.key(), e); throw new CmsConfigurationException(message, e); } finally { try { if (importZip != null) { importZip.close(); } if (stream != null) { stream.close(); } } catch (Exception e) { // noop } } CmsModule importedModule = handler.getModule(); // the digester must have set the module now if (importedModule == null) { throw new CmsConfigurationException( Messages.get().container(Messages.ERR_IMPORT_MOD_ALREADY_INSTALLED_1, importResource)); } return importedModule; }
From source file:util.ModuleChecker.java
private static void checkIsRunnable(File uploadsDir, String carName, Module m, List<Module> modules) { try {/* w ww . j a va2s . c o m*/ ZipFile car = new ZipFile(new File(uploadsDir, carName)); try { ZipEntry moduleEntry = car.getEntry(m.name.replace('.', '/') + "/run.class"); if (moduleEntry == null) { return; } DataInputStream inputStream = new DataInputStream(car.getInputStream(moduleEntry)); ClassFile classFile = new ClassFile(inputStream); inputStream.close(); AnnotationsAttribute visible = (AnnotationsAttribute) classFile .getAttribute(AnnotationsAttribute.visibleTag); m.isRunnable = false; Annotation methodAnnotation = visible .getAnnotation("com.redhat.ceylon.compiler.java.metadata.Method"); if (methodAnnotation != null) { MethodInfo runMethodInfo = (MethodInfo) classFile.getMethod("run"); MethodInfo mainMethodInfo = (MethodInfo) classFile.getMethod("main"); if (runMethodInfo != null && mainMethodInfo != null && mainMethodInfo.toString().endsWith("V")) { m.isRunnable = AccessFlag.isPublic(mainMethodInfo.getAccessFlags()); } } } finally { car.close(); } } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } if (m.isRunnable) { m.diagnostics.add(new Diagnostic("success", "Module is runnable.")); } }
From source file:com.samczsun.helios.Helios.java
private static boolean ensureJavaRtSet0(boolean forceCheck) { String javaRtLocation = Settings.RT_LOCATION.get().asString(); if (javaRtLocation.isEmpty()) { SWTUtil.showMessage("You need to set the location of Java's rt.jar", true); setLocationOf(Settings.RT_LOCATION); javaRtLocation = Settings.RT_LOCATION.get().asString(); }//from ww w . j a v a 2s. c o m if (javaRtLocation.isEmpty()) { return false; } if (javaRtVerified == null || forceCheck) { ZipFile zipFile = null; try { File rtjar = new File(javaRtLocation); if (rtjar.exists()) { zipFile = new ZipFile(rtjar); ZipEntry object = zipFile.getEntry("java/lang/Object.class"); if (object != null) { javaRtVerified = true; } } } catch (Throwable t) { StringWriter sw = new StringWriter(); t.printStackTrace(new PrintWriter(sw)); SWTUtil.showMessage("The selected Java rt.jar is invalid." + Constants.NEWLINE + Constants.NEWLINE + sw.toString()); t.printStackTrace(); javaRtVerified = false; } finally { IOUtils.closeQuietly(zipFile); if (javaRtVerified == null) { javaRtVerified = false; } } } return javaRtVerified; }
From source file:it.mb.whatshare.Dialogs.java
private static String getBuildDate(final Activity activity) { String buildDate = ""; ZipFile zf = null; try {//from ww w . j a v a 2 s . c o m ApplicationInfo ai = activity.getPackageManager().getApplicationInfo(activity.getPackageName(), 0); zf = new ZipFile(ai.sourceDir); ZipEntry ze = zf.getEntry("classes.dex"); long time = ze.getTime(); buildDate = SimpleDateFormat.getInstance().format(new java.util.Date(time)); } catch (Exception e) { } finally { if (zf != null) { try { zf.close(); } catch (IOException e) { e.printStackTrace(); } } } return buildDate; }
From source file:cat.ereza.customactivityoncrash.CustomActivityOnCrash.java
/** * INTERNAL method that returns the build date of the current APK as a string, or null if unable to determine it. * * @param context A valid context. Must not be null. * @param dateFormat DateFormat to use to convert from Date to String * @return The formatted date, or "Unknown" if unable to determine it. *//*ww w.j a v a 2s.c om*/ private static String getBuildDateAsString(Context context, DateFormat dateFormat) { String buildDate; try { ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0); ZipFile zf = new ZipFile(ai.sourceDir); ZipEntry ze = zf.getEntry("classes.dex"); long time = ze.getTime(); buildDate = dateFormat.format(new Date(time)); zf.close(); } catch (Exception e) { buildDate = "Unknown"; } return buildDate; }
From source file:org.openstreetmap.josm.tools.ImageProvider.java
private static ImageResource getIfAvailableZip(String full_name, File archive, ImageType type) { ZipFile zipFile = null; try {/*from ww w . ja v a2 s . c o m*/ zipFile = new ZipFile(archive); ZipEntry entry = zipFile.getEntry(full_name); if (entry != null) { int size = (int) entry.getSize(); int offs = 0; byte[] buf = new byte[size]; InputStream is = null; try { is = zipFile.getInputStream(entry); switch (type) { case SVG: URI uri = getSvgUniverse().loadSVG(is, full_name); SVGDiagram svg = getSvgUniverse().getDiagram(uri); return svg == null ? null : new ImageResource(svg); case OTHER: while (size > 0) { int l = is.read(buf, offs, size); offs += l; size -= l; } BufferedImage img = null; try { img = ImageIO.read(new ByteArrayInputStream(buf)); } catch (IOException e) { } return img == null ? null : new ImageResource(img); default: throw new AssertionError(); } } finally { if (is != null) { is.close(); } } } } catch (Exception e) { System.err.println(tr("Warning: failed to handle zip file ''{0}''. Exception was: {1}", archive.getName(), e.toString())); } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException ex) { } } } return null; }
From source file:util.ModuleChecker.java
private static void loadModuleInfo(File uploadsDir, String carName, Module m, List<Module> modules) { try {/* ww w . ja va 2 s. c o m*/ ZipFile car = new ZipFile(new File(uploadsDir, carName)); try { // try first with M4 format ZipEntry moduleEntry = car.getEntry(m.name.replace('.', '/') + "/module_.class"); if (moduleEntry == null) { // try with pre-M4 format moduleEntry = car.getEntry(m.name.replace('.', '/') + "/module.class"); if (moduleEntry == null) { m.diagnostics.add(new Diagnostic("error", ".car file does not contain module information")); return; } } m.diagnostics.add(new Diagnostic("success", ".car file contains module descriptor")); DataInputStream inputStream = new DataInputStream(car.getInputStream(moduleEntry)); ClassFile classFile = new ClassFile(inputStream); inputStream.close(); AnnotationsAttribute visible = (AnnotationsAttribute) classFile .getAttribute(AnnotationsAttribute.visibleTag); // ceylon version info Annotation ceylonAnnotation = visible .getAnnotation("com.redhat.ceylon.compiler.java.metadata.Ceylon"); if (ceylonAnnotation == null) { m.diagnostics.add( new Diagnostic("error", ".car does not contain @Ceylon annotation on module.class")); return; } m.diagnostics.add(new Diagnostic("success", ".car file module descriptor has @Ceylon annotation")); Integer major = getOptionalInt(ceylonAnnotation, "major", 0, m); Integer minor = getOptionalInt(ceylonAnnotation, "minor", 0, m); if (major == null || minor == null) { return; } m.ceylonMajor = major; m.ceylonMinor = minor; // module info Annotation moduleAnnotation = visible .getAnnotation("com.redhat.ceylon.compiler.java.metadata.Module"); if (moduleAnnotation == null) { m.diagnostics.add( new Diagnostic("error", ".car does not contain @Module annotation on module.class")); return; } m.diagnostics.add(new Diagnostic("success", ".car file module descriptor has @Module annotation")); String name = getString(moduleAnnotation, "name", m, false); String version = getString(moduleAnnotation, "version", m, false); if (name == null || version == null) { return; } if (!name.equals(m.name)) { m.diagnostics.add(new Diagnostic("error", ".car file contains unexpected module: " + name)); return; } if (!version.equals(m.version)) { m.diagnostics.add( new Diagnostic("error", ".car file contains unexpected module version: " + version)); return; } m.diagnostics.add(new Diagnostic("success", ".car file module descriptor has valid name/version")); // metadata m.license = getString(moduleAnnotation, "license", m, true); if (m.license != null) { m.diagnostics.add(new Diagnostic("success", "License: " + m.license)); } m.doc = getString(moduleAnnotation, "doc", m, true); if (m.doc != null) { m.diagnostics.add(new Diagnostic("success", "Has doc string")); } m.authors = getStringArray(moduleAnnotation, "by", m, true); if (m.authors != null && m.authors.length != 0) { m.diagnostics.add(new Diagnostic("success", "Has authors")); } // dependencies MemberValue dependencies = moduleAnnotation.getMemberValue("dependencies"); if (dependencies == null) { m.diagnostics.add(new Diagnostic("success", "Module has no dependencies")); return; // we're good } if (!(dependencies instanceof ArrayMemberValue)) { m.diagnostics.add( new Diagnostic("error", "Invalid 'dependencies' annotation value (expecting array)")); return; } MemberValue[] dependencyValues = ((ArrayMemberValue) dependencies).getValue(); if (dependencyValues.length == 0) { m.diagnostics.add(new Diagnostic("success", "Module has no dependencies")); return; // we're good } for (MemberValue dependencyValue : dependencyValues) { checkDependency(dependencyValue, m, modules); } } finally { car.close(); } } catch (IOException e) { e.printStackTrace(); m.diagnostics.add(new Diagnostic("error", "Invalid car file: " + e.getMessage())); } }