public void publicizeResources(File arscFile) throws AndrolibException { byte[] data = new byte[(int) arscFile.length()]; InputStream in = null; OutputStream out = null; try { in = new FileInputStream(arscFile); in.read(data); publicizeResources(data); out = new FileOutputStream(arscFile); out.write(data); } catch (IOException ex) { throw new AndrolibException(ex); } finally { if (in != null) { try { in.close(); } catch (IOException ex) { } } if (out != null) { try { out.close(); } catch (IOException ex) { } } } }
private void fixConfigSchema() { File configFile; File ctpDir = new File(directory, "CTP"); if (ctpDir.exists()) configFile = new File(ctpDir, "config.xml"); else configFile = new File(directory, "config.xml"); if (configFile.exists()) { try { Document doc = getDocument(configFile); Element root = doc.getDocumentElement(); Element server = getFirstNamedChild(root, "Server"); moveAttributes(server, sslAttrs, "SSL"); moveAttributes(server, proxyAttrs, "ProxyServer"); moveAttributes(server, ldapAttrs, "LDAP"); if (programName.equals("ISN")) fixRSNAROOT(server); if (isMIRC(root)) fixFileServiceAnonymizerID(root); setFileText(configFile, toString(doc)); } catch (Exception ex) { cp.appendln(Color.red, "\nUnable to convert the config file schema."); cp.appendln(Color.black, ""); } } else { cp.appendln(Color.red, "\nUnable to find the config file to check the schema."); cp.appendln(Color.black, ""); } }
private String canonicalPath() { try { return source.getCanonicalPath(); } catch (IOException e) { return source.getAbsolutePath(); } }
// Grabs assets off the intarwebz and saves them to a local store/jail for hydration. private void fetch(JSONArray args) { String url; String username; String password; String id; try { id = args.getString(0); url = args.getString(1); username = args.getString(2); password = args.getString(3); // Create directory for app. local_path = "/data/data/" + ctx.getPackageName() + "/remote_app/" + id + "/"; File fp = new File(local_path); fp.mkdirs(); if (fetchApp(url, username, password)) { this.success( new PluginResult(PluginResult.Status.OK, "file://" + local_path + "index.html"), this.callback); } else { this.error( new PluginResult( PluginResult.Status.ERROR, "Error during app saving or fetching; protocol or IO error likely."), this.callback); } } catch (JSONException e) { this.error( new PluginResult( PluginResult.Status.JSON_EXCEPTION, "JSON exception during argument parsing; make sure the app ID, URL, username and password were passed as an argument."), this.callback); } }
/** Maintain the versions of the file we are about to for writing. */ private static boolean shuffleVersions(String file) { File f = new File(file); if (!f.exists()) { return true; } int version = 99; boolean found = false; do { String fileVersion = file + String.format("_%02d", version); File vf = new File(fileVersion); if (vf.exists()) { found = true; } else { version--; } } while (!found && version >= 0); version++; String fileVersion = file + String.format("_%02d", version); File newf = new File(fileVersion); return f.renameTo(newf); }
/** Try and make path relative to current directory. */ public static String getRelativePath(String path) { try { File currentDir = new File("."); String currentPath = null; currentPath = currentDir.getCanonicalPath(); if (currentPath != null) { // get canonical path of file, to // fix case problems with drive letters in Windows. File pathFile = new File(path); String canonicalPath = pathFile.getCanonicalPath(); if (canonicalPath.startsWith(currentPath)) { String relativePath = canonicalPath.substring(currentPath.length()); // hmm, unix doesn't have trailing / on // current dir canonical path, so remove any // that are left on the front of the path here. while (relativePath.charAt(0) == '/' || relativePath.charAt(0) == '\\') { relativePath = relativePath.substring(1); } return relativePath; } return path; } } catch (Exception e) { return path; } return path; }
public static boolean download( URL url, String file, int prefix, int totalFilesize, IProgressUpdater updater) { File fFile = new File(new File(file).getParentFile().getPath()); if (!fFile.exists()) fFile.mkdirs(); boolean downloaded = true; BufferedInputStream in = null; FileOutputStream out = null; BufferedOutputStream bout = null; try { int count; int totalCount = 0; byte data[] = new byte[BUFFER]; in = new BufferedInputStream(url.openStream()); out = new FileOutputStream(file); bout = new BufferedOutputStream(out); while ((count = in.read(data, 0, BUFFER)) != -1) { bout.write(data, 0, count); totalCount += count; if (updater != null) updater.update(prefix + totalCount, totalFilesize); } } catch (Exception e) { e.printStackTrace(); Utils.logger.log(Level.SEVERE, "Download error!"); downloaded = false; } finally { try { close(in); close(bout); close(out); } catch (Exception e) { e.printStackTrace(); } } return downloaded; }
/* -- This is a helper methid to run the morph files */ private static void runMorphDataSet() throws Exception { String morph_directory = "../../thesis-datasets/morph/"; // directory where all the morph code is stored File d = new File(morph_directory); // get all the files from a directory File[] fList = d.listFiles(); List<String> dir_list = new ArrayList<String>(); for (File file : fList) { if (file.isDirectory()) { dir_list.add(file.getName()); } } for (String dir : dir_list) { directory = morph_directory + dir + "/"; System.out.println("Running TDDD " + directory); ReadFile.readFile(directory, fileList); // read the two files System.out.println(fileList.get(0) + " " + fileList.get(1)); preliminaryStep(directory); startCDC(); fileList.clear(); fileArray.clear(); hashed_File_List.clear(); } }
/** Computes the crc32 of a File. This is necessary when the ZipOutputStream is in STORED mode. */ private void crc32File(ZipEntry e, File f) throws IOException { CRC32OutputStream os = new CRC32OutputStream(); copy(f, os); if (os.n != f.length()) { throw new JarException(formatMsg("error.incorrect.length", f.getPath())); } os.updateEntry(e); }
void updateLastModifiedTime(Set<ZipEntry> zes) throws IOException { for (ZipEntry ze : zes) { long lastModified = ze.getTime(); if (lastModified != -1) { File f = new File(ze.getName().replace('/', File.separatorChar)); f.setLastModified(lastModified); } } }
/** * Method to build an absolute path * * @param dir the root dir * @param name the name of the new directory * @return if name is an absolute directory, returns name, else returns dir+name */ public static String getDir(String dir, String name) { if (!dir.endsWith(File.separator)) dir = dir + File.separator; File mv = new File(name); String new_dir = null; if (!mv.isAbsolute()) { new_dir = dir + name; } else new_dir = name; return new_dir; }
public RegionFile(File file) { lastModified = 0L; fileName = file; debugln((new StringBuilder()).append("REGION LOAD ").append(fileName).toString()); sizeDelta = 0; try { if (file.exists()) { lastModified = file.lastModified(); } dataFile = new RandomAccessFile(file, "rw"); if (dataFile.length() < 4096L) { for (int i = 0; i < 1024; i++) { dataFile.writeInt(0); } for (int j = 0; j < 1024; j++) { dataFile.writeInt(0); } sizeDelta += 8192; } if ((dataFile.length() & 4095L) != 0L) { for (int k = 0; (long) k < (dataFile.length() & 4095L); k++) { dataFile.write(0); } } int l = (int) dataFile.length() / 4096; sectorFree = new ArrayList(l); for (int i1 = 0; i1 < l; i1++) { sectorFree.add(Boolean.valueOf(true)); } sectorFree.set(0, Boolean.valueOf(false)); sectorFree.set(1, Boolean.valueOf(false)); dataFile.seek(0L); for (int j1 = 0; j1 < 1024; j1++) { int l1 = dataFile.readInt(); offsets[j1] = l1; if (l1 == 0 || (l1 >> 8) + (l1 & 0xff) > sectorFree.size()) { continue; } for (int j2 = 0; j2 < (l1 & 0xff); j2++) { sectorFree.set((l1 >> 8) + j2, Boolean.valueOf(false)); } } for (int k1 = 0; k1 < 1024; k1++) { int i2 = dataFile.readInt(); chunkTimestamps[k1] = i2; } } catch (IOException ioexception) { ioexception.printStackTrace(); } }
/** * Loop through the ZIP file, copying its entries into a new, temporary ZIP file, skipping the * entry to be deleted. Then replace the original file with the new one. */ protected Integer deleteEntry() throws XMLDataStoreException { try { ZipInputStream inStream = this.buildZipInputStream(); File outFile = this.buildTempFile(); ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(outFile)); byte[] buffer = new byte[32768]; int inCount = 0; int outCount = 0; // copy all the entries except the one to be deleted ZipEntry entry = inStream.getNextEntry(); while (entry != null) { inCount++; if (!this.getZipEntryName().equals(entry.getName())) { outCount++; outStream.putNextEntry(entry); int byteCount; while ((byteCount = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, byteCount); } outStream.closeEntry(); } entry = inStream.getNextEntry(); } inStream.close(); if (outCount == 0) { // add a dummy record to an empty file so we can close it // this is required by ZipOutputStream outStream.putNextEntry(new ZipEntry("delete.txt")); outStream.write( "This file is a place-holder. The containing ZIP file should be deleted.".getBytes()); outStream.closeEntry(); } outStream.close(); if (outCount == inCount) { // no entries were removed - just delete the temp file outFile.delete(); } else { // at least one entry removed - delete the original file this.getFile().delete(); if (outCount == 0) { // NO entries remain - just delete the temp file too outFile.delete(); } else { // entries remain - replace original file with temp file outFile.renameTo(this.getFile()); } } return new Integer(inCount - outCount); // should be 0 or 1 } catch (IOException ex) { throw XMLDataStoreException.ioException(ex); } }
public static void clearFolder(File folder) { if (folder.exists()) { for (File child : folder.listFiles()) { if (child.isDirectory()) clearFolder(child); if (!child.delete()) throw new RuntimeException("Cannot delete " + child); } } }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { String filePickerResult = ""; if (data != null && resultCode == RESULT_OK) { try { ContentResolver cr = getContentResolver(); Uri uri = data.getData(); Cursor cursor = GeckoApp.mAppContext .getContentResolver() .query(uri, new String[] {OpenableColumns.DISPLAY_NAME}, null, null, null); String name = null; if (cursor != null) { try { if (cursor.moveToNext()) { name = cursor.getString(0); } } finally { cursor.close(); } } String fileName = "tmp_"; String fileExt = null; int period; if (name == null || (period = name.lastIndexOf('.')) == -1) { String mimeType = cr.getType(uri); fileExt = "." + GeckoAppShell.getExtensionFromMimeType(mimeType); } else { fileExt = name.substring(period); fileName = name.substring(0, period); } File file = File.createTempFile(fileName, fileExt, sGREDir); FileOutputStream fos = new FileOutputStream(file); InputStream is = cr.openInputStream(uri); byte[] buf = new byte[4096]; int len = is.read(buf); while (len != -1) { fos.write(buf, 0, len); len = is.read(buf); } fos.close(); filePickerResult = file.getAbsolutePath(); } catch (Exception e) { Log.e(LOG_FILE_NAME, "showing file picker", e); } } try { mFilePickerResult.put(filePickerResult); } catch (InterruptedException e) { Log.i(LOG_FILE_NAME, "error returning file picker result", e); } }
/** * Rename the ZIP file to a temporary file, then copy its entries back into the original ZIP file, * leaving the stream open and returning it. */ protected Writer buildWriteStream(boolean entryShouldExist) throws XMLDataStoreException { try { File inFile = this.buildTempFile(); inFile.delete(); // the file actually gets created - delete it boolean renameSucceeded = this.getFile().renameTo(inFile); ZipInputStream inStream = this.buildZipInputStream(inFile); ZipOutputStream outStream = this.buildZipOutputStream(); boolean entryActuallyExists = false; byte[] buffer = new byte[32768]; ZipEntry entry = inStream.getNextEntry(); while (entry != null) { boolean weWantToWriteTheEntry = true; if (this.getZipEntryName().equals(entry.getName())) { entryActuallyExists = true; // if we were expecting the entry, skip it; // if we were NOT expecting the entry, allow it to be rewritten // so the file is restored to its original condition if (entryShouldExist) { weWantToWriteTheEntry = false; } } if (weWantToWriteTheEntry) { outStream.putNextEntry(entry); int byteCount; while ((byteCount = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, byteCount); } outStream.closeEntry(); } entry = inStream.getNextEntry(); } // close and delete the temporary file inStream.close(); inFile.delete(); // check for invalid state if (entryShouldExist != entryActuallyExists) { outStream.close(); // close it since we will not be returning it // need more helpful exceptions here if (entryActuallyExists) { throw XMLDataStoreException.fileAlreadyExists(new File(this.getZipEntryName())); } else { throw XMLDataStoreException.fileNotFound(new File(this.getZipEntryName()), null); } } outStream.putNextEntry(new ZipEntry(this.getZipEntryName())); return new OutputStreamWriter(outStream); } catch (IOException ex) { throw XMLDataStoreException.ioException(ex); } }
/** Adds a new file entry to the ZIP output stream. */ void addFile(ZipOutputStream zos, File file) throws IOException { String name = file.getPath(); boolean isDir = file.isDirectory(); if (isDir) { name = name.endsWith(File.separator) ? name : (name + File.separator); } name = entryName(name); if (name.equals("") || name.equals(".") || name.equals(zname)) { return; } else if ((name.equals(MANIFEST_DIR) || name.equals(MANIFEST_NAME)) && !Mflag) { if (vflag) { output(formatMsg("out.ignore.entry", name)); } return; } long size = isDir ? 0 : file.length(); if (vflag) { out.print(formatMsg("out.adding", name)); } ZipEntry e = new ZipEntry(name); e.setTime(file.lastModified()); if (size == 0) { e.setMethod(ZipEntry.STORED); e.setSize(0); e.setCrc(0); } else if (flag0) { crc32File(e, file); } zos.putNextEntry(e); if (!isDir) { copy(file, zos); } zos.closeEntry(); /* report how much compression occurred. */ if (vflag) { size = e.getSize(); long csize = e.getCompressedSize(); out.print(formatMsg2("out.size", String.valueOf(size), String.valueOf(csize))); if (e.getMethod() == ZipEntry.DEFLATED) { long ratio = 0; if (size != 0) { ratio = ((size - csize) * 100) / size; } output(formatMsg("out.deflated", String.valueOf(ratio))); } else { output(getMsg("out.stored")); } } }
public static String loadStringFromFile(String filename) { String line = ""; File file = new File(filename); if (!file.exists()) return line; try { BufferedReader reader = new BufferedReader(new FileReader(file)); line = reader.readLine(); reader.close(); } catch (Exception e) { e.printStackTrace(); } return line; }
void removeFiles() throws IOException { BufferedReader reader = new BufferedReader(new FileReader(new File(sGREDir, "removed-files"))); try { for (String removedFileName = reader.readLine(); removedFileName != null; removedFileName = reader.readLine()) { File removedFile = new File(sGREDir, removedFileName); if (removedFile.exists()) removedFile.delete(); } } finally { reader.close(); } }
/** * Puts the uninstaller. * * @exception Exception Description of the Exception */ private void putUninstaller() throws Exception { // Me make the .uninstaller directory String dest = translatePath("$INSTALL_PATH") + File.separator + "Uninstaller"; String jar = dest + File.separator + "uninstaller.jar"; File pathMaker = new File(dest); pathMaker.mkdirs(); // We log the uninstaller deletion information UninstallData udata = UninstallData.getInstance(); udata.setUninstallerJarFilename(jar); udata.setUninstallerPath(dest); // We open our final jar file FileOutputStream out = new FileOutputStream(jar); ZipOutputStream outJar = new ZipOutputStream(out); idata.uninstallOutJar = outJar; outJar.setLevel(9); udata.addFile(jar); // We copy the uninstaller InputStream in = getClass().getResourceAsStream("/res/IzPack.uninstaller"); ZipInputStream inRes = new ZipInputStream(in); ZipEntry zentry = inRes.getNextEntry(); while (zentry != null) { // Puts a new entry outJar.putNextEntry(new ZipEntry(zentry.getName())); // Byte to byte copy int unc = inRes.read(); while (unc != -1) { outJar.write(unc); unc = inRes.read(); } // Next one please inRes.closeEntry(); outJar.closeEntry(); zentry = inRes.getNextEntry(); } inRes.close(); // We put the langpack in = getClass().getResourceAsStream("/langpacks/" + idata.localeISO3 + ".xml"); outJar.putNextEntry(new ZipEntry("langpack.xml")); int read = in.read(); while (read != -1) { outJar.write(read); read = in.read(); } outJar.closeEntry(); }
private boolean unpackFile(ZipFile zip, byte[] buf, ZipEntry fileEntry, String name) throws IOException, FileNotFoundException { if (fileEntry == null) fileEntry = zip.getEntry(name); if (fileEntry == null) throw new FileNotFoundException("Can't find " + name + " in " + zip.getName()); File outFile = new File(sGREDir, name); if (outFile.lastModified() == fileEntry.getTime() && outFile.length() == fileEntry.getSize()) return false; File dir = outFile.getParentFile(); if (!dir.exists()) dir.mkdirs(); InputStream fileStream; fileStream = zip.getInputStream(fileEntry); OutputStream outStream = new FileOutputStream(outFile); while (fileStream.available() > 0) { int read = fileStream.read(buf, 0, buf.length); outStream.write(buf, 0, read); } fileStream.close(); outStream.close(); outFile.setLastModified(fileEntry.getTime()); return true; }
// Take a tree of files starting in a directory in a zip file // and copy them to a disk directory, recreating the tree. private int unpackZipFile( File inZipFile, String directory, String parent, boolean suppressFirstPathElement) { int count = 0; if (!inZipFile.exists()) return count; parent = parent.trim(); if (!parent.endsWith(File.separator)) parent += File.separator; if (!directory.endsWith(File.separator)) directory += File.separator; File outFile = null; try { ZipFile zipFile = new ZipFile(inZipFile); Enumeration zipEntries = zipFile.entries(); while (zipEntries.hasMoreElements()) { ZipEntry entry = (ZipEntry) zipEntries.nextElement(); String name = entry.getName().replace('/', File.separatorChar); if (name.startsWith(directory)) { if (suppressFirstPathElement) name = name.substring(directory.length()); outFile = new File(parent + name); // Create the directory, just in case if (name.indexOf(File.separatorChar) >= 0) { String p = name.substring(0, name.lastIndexOf(File.separatorChar) + 1); File dirFile = new File(parent + p); dirFile.mkdirs(); } if (!entry.isDirectory()) { System.out.println("Installing " + outFile); // Copy the file BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFile)); BufferedInputStream in = new BufferedInputStream(zipFile.getInputStream(entry)); int size = 1024; int n = 0; byte[] b = new byte[size]; while ((n = in.read(b, 0, size)) != -1) out.write(b, 0, n); in.close(); out.flush(); out.close(); // Count the file count++; } } } zipFile.close(); } catch (Exception e) { System.err.println("...an error occured while installing " + outFile); e.printStackTrace(); System.err.println("Error copying " + outFile.getName() + "\n" + e.getMessage()); return -count; } System.out.println(count + " files were installed."); return count; }
private File getFrameworkDir() throws AndrolibException { File dir = new File( System.getProperty("user.home") + File.separatorChar + "apktool" + File.separatorChar + "framework"); if (!dir.exists()) { if (!dir.mkdirs()) { throw new AndrolibException("Can't create directory: " + dir); } } return dir; }
public static boolean deleteAll(File file) { boolean b = true; if ((file != null) && file.exists()) { if (file.isDirectory()) { try { File[] files = file.listFiles(); for (File f : files) b &= deleteAll(f); } catch (Exception e) { return false; } } b &= file.delete(); } return b; }
/** @throws Exception If failed. */ @SuppressWarnings({"TypeMayBeWeakened"}) public void testCorrectAntGarTask() throws Exception { String tmpDirName = GridTestProperties.getProperty("ant.gar.tmpdir"); String srcDirName = GridTestProperties.getProperty("ant.gar.srcdir"); String baseDirName = tmpDirName + File.separator + System.currentTimeMillis() + "_0"; String metaDirName = baseDirName + File.separator + "META-INF"; String garFileName = baseDirName + ".gar"; String garDescDirName = U.resolveIgnitePath(GridTestProperties.getProperty("ant.gar.descriptor.dir")) .getAbsolutePath() + File.separator + "ignite.xml"; // Make base and META-INF dir. boolean mkdir = new File(baseDirName).mkdirs(); assert mkdir; mkdir = new File(metaDirName).mkdirs(); assert mkdir; // Make Gar file U.copy(new File(garDescDirName), new File(metaDirName + File.separator + "ignite.xml"), true); // Copy files to basedir U.copy(new File(srcDirName), new File(baseDirName), true); IgniteDeploymentGarAntTask garTask = new IgniteDeploymentGarAntTask(); Project garProject = new Project(); garProject.setName("Gar test project"); garTask.setDestFile(new File(garFileName)); garTask.setBasedir(new File(baseDirName)); garTask.setProject(garProject); garTask.execute(); File garFile = new File(garFileName); assert garFile.exists(); boolean res = checkStructure(garFile, true); assert res; }
/** * @param garFile GAR file. * @param hasDescr Whether GAR file has descriptor. * @throws IOException If GAR file is not found. * @return Whether GAR file structure is correct. */ private boolean checkStructure(File garFile, boolean hasDescr) throws IOException { ZipFile zip = new ZipFile(garFile); String descr = "META-INF/ignite.xml"; ZipEntry entry = zip.getEntry(descr); if (entry == null && !hasDescr) { if (log().isInfoEnabled()) { log() .info( "Process deployment without descriptor file [path=" + descr + ", file=" + garFile.getAbsolutePath() + ']'); } return true; } else if (entry != null && hasDescr) { InputStream in = null; try { in = new BufferedInputStream(zip.getInputStream(entry)); return true; } finally { U.close(in, log()); } } else return false; }
public static File writeFile(String content) { try { return writeFile(File.createTempFile("h2o", null), content); } catch( IOException e ) { throw Log.errRTExcept(e); } }
/** * Returns the system temporary folder, e.g. /tmp */ public static File tmp() { try { return File.createTempFile("h2o", null).getParentFile(); } catch( IOException e ) { throw new RuntimeException(e); } }
/** Outputs the class index table to the INDEX.LIST file of the root jar file. */ void dumpIndex(String rootjar, JarIndex index) throws IOException { File jarFile = new File(rootjar); Path jarPath = jarFile.toPath(); Path tmpPath = createTempFileInSameDirectoryAs(jarFile).toPath(); try { if (update(Files.newInputStream(jarPath), Files.newOutputStream(tmpPath), null, index)) { try { Files.move(tmpPath, jarPath, REPLACE_EXISTING); } catch (IOException e) { throw new IOException(getMsg("error.write.file"), e); } } } finally { Files.deleteIfExists(tmpPath); } }
public boolean detectWhetherAppIsFramework(File appDir) throws AndrolibException { File publicXml = new File(appDir, "res/values/public.xml"); if (!publicXml.exists()) { return false; } Iterator<String> it; try { it = IOUtils.lineIterator(new FileReader(new File(appDir, "res/values/public.xml"))); } catch (FileNotFoundException ex) { throw new AndrolibException("Could not detect whether app is framework one", ex); } it.next(); it.next(); return it.next().contains("0x01"); }