/** * 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); } }
/** * 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); } }
/** * Takes an input File containing the pack file, and generates a JarOutputStream. * * <p>Does not close its output. (The output can accumulate more elements.) * * @param in a File. * @param out a JarOutputStream. * @exception IOException if an error is encountered. */ public void unpack(File in, JarOutputStream out) throws IOException { // Use the stream-based implementation. // %%% Reconsider if native unpacker learns to memory-map the file. FileInputStream instr = new FileInputStream(in); unpack(instr, out); if (_props.getBoolean(Utils.UNPACK_REMOVE_PACKFILE)) { in.delete(); } }
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); } } }
private boolean deleteDirectory(File path) { File[] files = path.listFiles(); for (int i = 0; i < files.length; i++) { File f = files[i]; if (f.isFile()) { if (!f.delete()) { return false; } } else { if (!deleteDirectory(f)) { return false; } } } if (path.delete()) { return true; } else { return false; } }
private void adjustConfiguration(Element root, File dir) { // If this is an ISN installation and the Edge Server // keystore and truststore files do not exist, then set the configuration // to use the keystore.jks and truststore.jks files instead of the ones // in the default installation. If the Edge Server files do exist, then // delete the keystore.jks and truststore.jks files, just to avoid // confusion. if (programName.equals("ISN")) { Element server = getFirstNamedChild(root, "Server"); Element ssl = getFirstNamedChild(server, "SSL"); String rsnaroot = System.getenv("RSNA_ROOT"); rsnaroot = (rsnaroot == null) ? "/usr/local/edgeserver" : rsnaroot.trim(); String keystore = rsnaroot + "/conf/keystore.jks"; String truststore = rsnaroot + "/conf/truststore.jks"; File keystoreFile = new File(keystore); File truststoreFile = new File(truststore); cp.appendln(Color.black, "Looking for " + keystore); if (keystoreFile.exists() || truststoreFile.exists()) { cp.appendln(Color.black, "...found it [This is an EdgeServer installation]"); // Delete the default files, just to avoid confusion File ks = new File(dir, "keystore.jks"); File ts = new File(dir, "truststore.jks"); boolean ksok = ks.delete(); boolean tsok = ts.delete(); if (ksok && tsok) cp.appendln(Color.black, "...Unused default SSL files were removed"); else { if (!ksok) cp.appendln(Color.black, "...Unable to delete " + ks); if (!tsok) cp.appendln(Color.black, "...Unable to delete " + ts); } } else { cp.appendln(Color.black, "...not found [OK, this is a non-EdgeServer installation]"); ssl.setAttribute("keystore", "keystore.jks"); ssl.setAttribute("keystorePassword", "edge1234"); ssl.setAttribute("truststore", "truststore.jks"); ssl.setAttribute("truststorePassword", "edge1234"); cp.appendln( Color.black, "...SSL attributes were updated for a non-EdgeServer installation"); } } }
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(); } }
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; }
@Override public void save() { NBTOutputStream stream = null; try { Files.createParentDirs(this.file); final File temporaryFile = File.createTempFile(this.file.getName(), null, this.file.getParentFile()); temporaryFile.deleteOnExit(); stream = new NBTOutputStream(new FileOutputStream(temporaryFile)); stream.writeTag(new CompoundTag(this.name, this.root)); stream.close(); this.file.delete(); temporaryFile.renameTo(this.file); temporaryFile.delete(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { stream.close(); } catch (IOException ex2) { } } }
private boolean saveAndVerify(ZipInputStream data) throws IOException { try { ZipEntry ze; while ((ze = data.getNextEntry()) != null) { // Filename + reference to file. String filename = ze.getName(); File output = new File(local_path + filename); if (filename.endsWith("/")) { output.mkdirs(); } else { if (output.exists()) { // Delete the file if it already exists. if (!output.delete()) { return false; } } if (output.createNewFile()) { FileOutputStream out = new FileOutputStream(output); byte[] buffer = new byte[1024]; int count; while ((count = data.read(buffer)) != -1) { out.write(buffer, 0, count); } } else { return false; } } } } catch (Exception e) { e.printStackTrace(); return false; } finally { data.close(); } return true; }
private void cleanup(File directory) { // Clean up from old installations, removing or renaming files. // Note that directory is the parent of the CTP directory // unless the original installation was done by Bill Weadock's // all-in-one installer for Windows. // Get a file pointing to the CTP directory. // This might be the current directory, or // it might be the CTP child. File dir; if (directory.getName().equals("RSNA")) dir = directory; else dir = new File(directory, "CTP"); // If CTP.jar exists in this directory, it is a really // old CTP main file - not used anymore File ctp = new File(dir, "CTP.jar"); if (ctp.exists()) ctp.delete(); // These are old names for the Launcher.jar file File launcher = new File(dir, "CTP-launcher.jar"); if (launcher.exists()) launcher.delete(); launcher = new File(dir, "TFS-launcher.jar"); if (launcher.exists()) launcher.delete(); // Delete the obsolete CTP-runner.jar file File runner = new File(dir, "CTP-runner.jar"); if (runner.exists()) runner.delete(); // Delete the obsolete MIRC-copier.jar file File copier = new File(dir, "MIRC-copier.jar"); if (copier.exists()) copier.delete(); // Rename the old versions of the properties files File oldprops = new File(dir, "CTP-startup.properties"); File newprops = new File(dir, "CTP-launcher.properties"); File correctprops = new File(dir, "Launcher.properties"); if (oldprops.exists()) { if (newprops.exists() || correctprops.exists()) oldprops.delete(); else oldprops.renameTo(correctprops); } if (newprops.exists()) { if (correctprops.exists()) newprops.delete(); else newprops.renameTo(correctprops); } // Get rid of obsolete startup and shutdown programs File startup = new File(dir, "CTP-startup.jar"); if (startup.exists()) startup.delete(); File shutdown = new File(dir, "CTP-shutdown.jar"); if (shutdown.exists()) shutdown.delete(); // Get rid of the obsolete linux directory File linux = new File(dir, "linux"); if (linux.exists()) { startup = new File(linux, "CTP-startup.jar"); if (startup.exists()) startup.delete(); shutdown = new File(linux, "CTP-shutdown.jar"); if (shutdown.exists()) shutdown.delete(); linux.delete(); } // clean up the libraries directory File libraries = new File(dir, "libraries"); if (libraries.exists()) { // remove obsolete versions of the slf4j libraries // and the dcm4che-imageio libraries File[] files = libraries.listFiles(); for (File file : files) { if (file.isFile()) { String name = file.getName(); if (name.startsWith("slf4j-") || name.startsWith("dcm4che-imageio-rle")) { file.delete(); } } } // remove the email subdirectory File email = new File(libraries, "email"); deleteAll(email); // remove the xml subdirectory File xml = new File(libraries, "xml"); deleteAll(xml); // remove the sftp subdirectory File sftp = new File(libraries, "sftp"); deleteAll(xml); // move edtftpj.jar to the ftp directory File edtftpj = new File(libraries, "edtftpj.jar"); if (edtftpj.exists()) { File ftp = new File(libraries, "ftp"); ftp.mkdirs(); File ftpedtftpj = new File(ftp, "edtftpj.jar"); edtftpj.renameTo(ftpedtftpj); } } // remove the obsolete xml library under dir File xml = new File(dir, "xml"); deleteAll(xml); // remove the dicom profiles so any // obsolete files will disappear File profiles = new File(dir, "profiles"); File dicom = new File(profiles, "dicom"); deleteAll(dicom); dicom.mkdirs(); // Remove the index.html file so it will be rebuilt from // example-index.html when the system next starts. File root = new File(dir, "ROOT"); if (root.exists()) { File index = new File(root, "index.html"); index.delete(); } }
/** The run method. */ public void run() { instances.add(this); try { listener.startUnpack(); String currentOs = System.getProperty("os.name").toLowerCase(); // // Initialisations FileOutputStream out = null; ArrayList parsables = new ArrayList(); ArrayList executables = new ArrayList(); List packs = idata.selectedPacks; int npacks = packs.size(); udata = UninstallData.getInstance(); // Specific to the web installers if (idata.kind.equalsIgnoreCase("web") || idata.kind.equalsIgnoreCase("web-kunststoff")) { InputStream kin = getClass().getResourceAsStream("/res/WebInstallers.url"); BufferedReader kreader = new BufferedReader(new InputStreamReader(kin)); jarLocation = kreader.readLine(); } // We unpack the selected packs for (int i = 0; i < npacks; i++) { // We get the pack stream int n = idata.allPacks.indexOf(packs.get(i)); ObjectInputStream objIn = new ObjectInputStream(getPackAsStream(n)); // We unpack the files int nfiles = objIn.readInt(); listener.changeUnpack(0, nfiles, ((Pack) packs.get(i)).name); for (int j = 0; j < nfiles; j++) { // We read the header PackFile pf = (PackFile) objIn.readObject(); if (null == pf.os || matchOS(currentOs, pf.os.toLowerCase())) { // We translate & build the path String path = translatePath(pf.targetPath); File pathFile = new File(path); String fname = pathFile.getName(); int z = fname.length(); File dest = pathFile.getParentFile(); if (!dest.exists()) dest.mkdirs(); // We add the path to the log, udata.addFile(path); listener.progressUnpack(j, path); // if this file exists and shouldnot override skip this file if (((pf.override == false) && (pathFile.exists()))) { objIn.skip(pf.length); continue; } // We copy the file out = new FileOutputStream(path); byte[] buffer = new byte[5120]; long bytesCopied = 0; while (bytesCopied < pf.length) { int maxBytes = (pf.length - bytesCopied < buffer.length ? (int) (pf.length - bytesCopied) : buffer.length); int bytesInBuffer = objIn.read(buffer, 0, maxBytes); if (bytesInBuffer == -1) throw new IOException("Unexpected end of stream"); out.write(buffer, 0, bytesInBuffer); bytesCopied += bytesInBuffer; } // Cleanings out.close(); // Empty dirs restoring String _n = pathFile.getName(); if (_n.startsWith("izpack-keepme") && _n.endsWith(".tmp")) pathFile.delete(); } else objIn.skip(pf.length); } // Load information about parsable files int numParsables = objIn.readInt(); int k; for (k = 0; k < numParsables; k++) { ParsableFile pf = (ParsableFile) objIn.readObject(); pf.path = translatePath(pf.path); parsables.add(pf); } // Load information about executable files int numExecutables = objIn.readInt(); for (k = 0; k < numExecutables; k++) { ExecutableFile ef = (ExecutableFile) objIn.readObject(); ef.path = translatePath(ef.path); if (null != ef.argList && !ef.argList.isEmpty()) { String arg = null; for (int j = 0; j < ef.argList.size(); j++) { arg = (String) ef.argList.get(j); arg = translatePath(arg); ef.argList.set(j, arg); } } executables.add(ef); if (ef.executionStage == ExecutableFile.UNINSTALL) { udata.addExecutable(ef); } } objIn.close(); } // We use the scripts parser ScriptParser parser = new ScriptParser(parsables, vs); parser.parseFiles(); // We use the file executor FileExecutor executor = new FileExecutor(executables); if (executor.executeFiles(ExecutableFile.POSTINSTALL) != 0) javax.swing.JOptionPane.showMessageDialog( null, "The installation was not completed.", "Installation warning", javax.swing.JOptionPane.WARNING_MESSAGE); // We put the uninstaller putUninstaller(); // The end :-) listener.stopUnpack(); } catch (Exception err) { listener.stopUnpack(); listener.errorUnpack(err.toString()); } instances.remove(instances.indexOf(this)); }
public static void deleteIfExists(File file) { if (file.exists()) file.delete(); }
public static void deleteDirectory(File f) throws IOException { if (f.isDirectory()) { for (File c : f.listFiles()) deleteDirectory(c); } if (!f.delete()) throw new FileNotFoundException("Failed to delete file: " + f); }
/** Starts main program with the specified arguments. */ public synchronized boolean run(String args[]) { ok = true; if (!parseArgs(args)) { return false; } try { if (cflag || uflag) { if (fname != null) { // The name of the zip file as it would appear as its own // zip file entry. We use this to make sure that we don't // add the zip file to itself. zname = fname.replace(File.separatorChar, '/'); if (zname.startsWith("./")) { zname = zname.substring(2); } } } if (cflag) { Manifest manifest = null; InputStream in = null; if (!Mflag) { if (mname != null) { in = new FileInputStream(mname); manifest = new Manifest(new BufferedInputStream(in)); } else { manifest = new Manifest(); } addVersion(manifest); addCreatedBy(manifest); if (isAmbiguousMainClass(manifest)) { if (in != null) { in.close(); } return false; } if (ename != null) { addMainClass(manifest, ename); } if (pname != null) { if (!addProfileName(manifest, pname)) { if (in != null) { in.close(); } return false; } } } OutputStream out; if (fname != null) { out = new FileOutputStream(fname); } else { out = new FileOutputStream(FileDescriptor.out); if (vflag) { // Disable verbose output so that it does not appear // on stdout along with file data // error("Warning: -v option ignored"); vflag = false; } } expand(null, files, false); create(new BufferedOutputStream(out, 4096), manifest); if (in != null) { in.close(); } out.close(); } else if (uflag) { File inputFile = null, tmpFile = null; FileInputStream in; FileOutputStream out; if (fname != null) { inputFile = new File(fname); tmpFile = createTempFileInSameDirectoryAs(inputFile); in = new FileInputStream(inputFile); out = new FileOutputStream(tmpFile); } else { in = new FileInputStream(FileDescriptor.in); out = new FileOutputStream(FileDescriptor.out); vflag = false; } InputStream manifest = (!Mflag && (mname != null)) ? (new FileInputStream(mname)) : null; expand(null, files, true); boolean updateOk = update(in, new BufferedOutputStream(out), manifest, null); if (ok) { ok = updateOk; } in.close(); out.close(); if (manifest != null) { manifest.close(); } if (ok && fname != null) { // on Win32, we need this delete inputFile.delete(); if (!tmpFile.renameTo(inputFile)) { tmpFile.delete(); throw new IOException(getMsg("error.write.file")); } tmpFile.delete(); } } else if (tflag) { replaceFSC(files); if (fname != null) { list(fname, files); } else { InputStream in = new FileInputStream(FileDescriptor.in); try { list(new BufferedInputStream(in), files); } finally { in.close(); } } } else if (xflag) { replaceFSC(files); if (fname != null && files != null) { extract(fname, files); } else { InputStream in = (fname == null) ? new FileInputStream(FileDescriptor.in) : new FileInputStream(fname); try { extract(new BufferedInputStream(in), files); } finally { in.close(); } } } else if (iflag) { genIndex(rootjar, files); } } catch (IOException e) { fatalError(e); ok = false; } catch (Error ee) { ee.printStackTrace(); ok = false; } catch (Throwable t) { t.printStackTrace(); ok = false; } out.flush(); err.flush(); return ok; }