Java Code Examples for org.openide.filesystems.FileObject#getSize()

The following examples show how to use org.openide.filesystems.FileObject#getSize() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProfileSupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@CheckForNull
Key createKey(@NonNull final URL rootURL) {
    final URL fileURL = FileUtil.getArchiveFile(rootURL);
    if (fileURL == null) {
        //Not an archive
        return null;
    }
    final FileObject fileFo = URLMapper.findFileObject(fileURL);
    if (fileFo == null) {
        return null;
    }
    return new Key(
        fileFo.toURI(),
        fileFo.lastModified().getTime(),
        fileFo.getSize());
}
 
Example 2
Source File: FolderComparator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Sort folders alphabetically first. Then files, biggest to smallest.
 */
private static int compareSize(Object o1, Object o2) {
    boolean f1 = findFileObject(o1).isFolder();
    boolean f2 = findFileObject(o2).isFolder();

    if (f1 != f2) {
        return f1 ? -1 : 1;
    }

    FileObject fo1 = findFileObject(o1);
    FileObject fo2 = findFileObject(o2);
    long s1 = fo1.getSize();
    long s2 = fo2.getSize();
    if (s1 > s2) {
        return -1;
    } else if (s2 > s1) {
        return 1;
    } else {
        return fo1.getNameExt().compareTo(fo2.getNameExt());
    }
}
 
Example 3
Source File: FastMatcher.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
    public Def checkMeasuredInternal(FileObject file,
            SearchListener listener) {

        if (trivial) {
            return new Def(file, null, null);
        }

        listener.fileContentMatchingStarted(file.getPath());

        long start = System.currentTimeMillis();
        Def def;
        File f = FileUtil.toFile(file);
        if (file.getSize() > SIZE_LIMIT || f == null) {
//            LOG.log(Level.INFO,
//                    "Falling back to default matcher: {0}, {1} kB", //NOI18N
//                    new Object[]{file.getPath(), file.getSize() / 1024});
//            def = getDefaultMatcher().check(file, listener);
            def = checkBig(file, f, listener);
        } else {
            def = checkSmall(file, f, listener);
        }
        totalTime += System.currentTimeMillis() - start;
        return def;
    }
 
Example 4
Source File: ImageViewer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Initializes member variables and set listener for name changes on DataObject. */
private void initialize(ImageDataObject obj) {
    TopComponent.NodeName.connect (this, obj.getNodeDelegate ());
    setToolTipText(FileUtil.getFileDisplayName(obj.getPrimaryFile()));
    
    storedObject = obj;
    
    FileObject imageFile = storedObject.getPrimaryFile();
    
    if (imageFile.isValid()) {
        imageSize = imageFile.getSize();
    } else {
        imageSize = -1;
    }
        
    // force closing panes in all workspaces, default is in current only
    setCloseOperation(TopComponent.CLOSE_EACH);
    
    getAccessibleContext().setAccessibleDescription(NbBundle.getMessage(ImageViewer.class, "ACS_ImageViewer"));        
    
    nameChangeL = new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            if (DataObject.PROP_COOKIE.equals(evt.getPropertyName()) ||
            DataObject.PROP_NAME.equals(evt.getPropertyName())) {
                updateNameInEDT();
            }
        }
    };
    
    obj.addPropertyChangeListener(WeakListeners.propertyChange(nameChangeL, obj));        
    setFocusable(true);
     /* try to load the image: */
    loadImage(storedObject);
}
 
Example 5
Source File: CustomIconEditor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
IconFileItem(FileObject file) {
    this.file = file;
    try {
        try {
            Image image = (file.getSize() < SIZE_LIMIT) ? ImageIO.read(file.toURL()) : null;
            icon = (image != null) ? new ImageIcon(image) : null;
        } catch (IllegalArgumentException iaex) { // Issue 178906
            Logger.getLogger(CustomIconEditor.class.getName()).log(Level.INFO, null, iaex);
            icon = new ImageIcon(file.toURL());
        }
    } catch (IOException ex) {
        Logger.getLogger(CustomIconEditor.class.getName()).log(Level.WARNING, null, ex);
    }
}
 
Example 6
Source File: DataEditorSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Obtains the input stream.
* @exception IOException if an I/O error occurs
*/
public InputStream inputStream() throws IOException {
    final FileObject fo = getFileImpl ();
    boolean warned = warnedFiles.contains(fo);
    long size = -1;
    if (!warned && (size = fo.getSize ()) > BIG_FILE_THRESHOLD_MB) {
        throw new ME (size);
    } else if (!sentBigFileInfo && ((size >= 0) ? size : fo.getSize()) > BIG_FILE_THRESHOLD_MB) {
        // warned can contain any file after deserialization
        notifyBigFileLoaded();
    }
    initCanWrite(false);
    InputStream is = getFileImpl ().getInputStream ();
    return is;
}
 
Example 7
Source File: LayerHandleTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testLayerHandle() throws Exception {
    NbModuleProject project = TestBase.generateStandaloneModule(getWorkDir(), "module");
    LayerHandle handle = LayerHandle.forProject(project);
    FileObject expectedLayerXML = project.getProjectDirectory().getFileObject("src/org/example/module/resources/layer.xml");
    assertNotNull(expectedLayerXML);
    FileObject layerXML = handle.getLayerFile();
    assertNotNull("layer.xml already exists", layerXML);
    assertEquals("right layer file", expectedLayerXML, layerXML);
    FileSystem fs = handle.layer(true);
    assertEquals("initially empty", 0, fs.getRoot().getChildren().length);
    long initialSize = layerXML.getSize();
    fs.getRoot().createData("foo");
    assertEquals("not saved yet", initialSize, layerXML.getSize());
    fs = handle.layer(true);
    assertNotNull("still have in-memory mods", fs.findResource("foo"));
    fs.getRoot().createData("bar");
    handle.save();
    assertTrue("now it is saved", layerXML.getSize() > initialSize);
    String xml =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
            "<!DOCTYPE filesystem PUBLIC \"-//NetBeans//DTD Filesystem 1.2//EN\" \"http://www.netbeans.org/dtds/filesystem-1_2.dtd\">\n" +
            "<filesystem>\n" +
            "    <file name=\"bar\"/>\n" +
            "    <file name=\"foo\"/>\n" +
            "</filesystem>\n";
    assertEquals("right contents too", xml, TestBase.slurp(layerXML));
    // XXX test that nbres: file contents work
}
 
Example 8
Source File: NbInstallerTestBase.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected static String slurp(String path) throws IOException {
    Main.getModuleSystem(); // #26451
    FileObject fo = FileUtil.getConfigFile(path);
    if (fo == null) return null;
    InputStream is = fo.getInputStream();
    StringBuilder text = new StringBuilder((int)fo.getSize());
    byte[] buf = new byte[1024];
    int read;
    while ((read = is.read(buf)) != -1) {
        text.append(new String(buf, 0, read, "US-ASCII"));
    }
    return text.toString();
}
 
Example 9
Source File: ProjectEar.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private IT(ProjectEar pe, FileObject f) {
    J2eeModule mods[] = pe.getModules();
    // build filter
    Set<String> filter = new HashSet<String>(mods.length);
    for (int i = 0; i < mods.length; i++) {
        FileObject modArchive = null;
        try {
            modArchive = mods[i].getArchive();
        } catch (java.io.IOException ioe) {
            Logger.getLogger(ProjectEar.class.getName()).log(Level.FINER,
                    null,ioe);
            continue;
        }
        if (modArchive != null) {
            String modName = modArchive.getNameExt();
            long modSize = modArchive.getSize();
            filter.add(modName+"."+modSize);        // NOI18N
        }
    }
    
    ArrayList<FileObject> filteredContent = new ArrayList<FileObject>(5);
    Enumeration ch = f.getChildren(true);
    while (ch.hasMoreElements()) {
        FileObject fo = (FileObject) ch.nextElement();
        String fileName = fo.getNameExt();
        long fileSize = fo.getSize();
        if (filter.contains(fileName+"."+fileSize)) {   // NOI18N
            continue;
        }
        filteredContent.add(fo);
    }
    this.root = f;
    it = filteredContent.iterator();
}
 
Example 10
Source File: MatchingObject.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Check validity status of this item.
 * 
 * @return  an invalidity status of this item if it is invalid,
 *          or {@code null} if this item is valid
 * @author  Tim Boudreau
 * @author  Marian Petras
 */
private InvalidityStatus getFreshInvalidityStatus() {
    log(FINER, "getInvalidityStatus()");                            //NOI18N
    FileObject f = getFileObject();
    if (!f.isValid()) {
        log(FINEST, " - DELETED");            
        return InvalidityStatus.DELETED;
    }
    if (f.isFolder()) {
        log(FINEST, " - BECAME_DIR");            
        return InvalidityStatus.BECAME_DIR;
    }
    
    long stamp = f.lastModified().getTime();
    if ((!refreshed && stamp > resultModel.getStartTime())
            || (refreshed && stamp > timestamp)) {
        log(SEVERE, "file's timestamp changed since start of the search");
        if (LOG.isLoggable(FINEST)) {
            final java.util.Calendar cal = java.util.Calendar.getInstance();
            cal.setTimeInMillis(stamp);
            log(FINEST, " - file stamp:           " + stamp + " (" + cal.getTime() + ')');
            cal.setTimeInMillis(resultModel.getStartTime());
            log(FINEST, " - result model created: " + resultModel.getStartTime() + " (" + cal.getTime() + ')');
        }            
        return InvalidityStatus.CHANGED;
    }
    
    if (f.getSize() > Integer.MAX_VALUE) {            
        return InvalidityStatus.TOO_BIG;
    }
    
    if (!f.canRead()) {           
        return InvalidityStatus.CANT_READ;
    }
    
    return null;
}
 
Example 11
Source File: DefaultMatcher.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether the given file is a text file. The current implementation
 * does the check by the file's MIME-type.
 *
 * @param fileObj file to be checked
 * @return {@code true} if the file is a text file; {@code false} if it is a
 * binary file
 */
private static boolean isTextFile(FileObject fileObj) {
    String mimeType = fileObj.getMIMEType();

    if (mimeType.equals("content/unknown")) {                       //NOI18N
        if (searchableExtensions.contains(fileObj.getExt().toLowerCase())) {
            return true;
        } else {
            return fileObj.getSize() <= MAX_UNRECOGNIZED_FILE_SIZE ||
                    hasTextContent(fileObj);
        }
    }

    if (mimeType.startsWith("text/")) {                             //NOI18N
        return true;
    }

    if (mimeType.startsWith("application/")) {                      //NOI18N
        final String subtype = mimeType.substring(12);
        return subtype.equals("rtf") //NOI18N
                || subtype.equals("sgml") //NOI18N
                || subtype.startsWith("xml-") //NOI18N
                || subtype.endsWith("+xml") //NOI18N
                || isApplicationXSource(subtype, fileObj);
    }

    return mimeType.endsWith("+xml");                               //NOI18N
}
 
Example 12
Source File: GsfUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Load the document for the given fileObject.
 * @param fileObject the file whose document we want to obtain
 * @param openIfNecessary If true, block if necessary to open the document. If false, will only return the
 *    document if it is already open.
 * @param skipLarge If true, check the file size, and if the file is really large (defined by
 *    openide.loaders), then skip it (otherwise we could end up with a large file warning).
 * @return
 */
public static BaseDocument getDocument(FileObject fileObject, boolean openIfNecessary, boolean skipLarge) {
    if (skipLarge) {
        // Make sure we're not dealing with a huge file!
        // Causes issues like 132306
        // openide.loaders/src/org/openide/text/DataEditorSupport.java
        // has an Env#inputStream method which posts a warning to the user
        // if the file is greater than 1Mb...
        //SG_ObjectIsTooBig=The file {1} seems to be too large ({2,choice,0#{2}b|1024#{3} Kb|1100000#{4} Mb|1100000000#{5} Gb}) to safely open. \n\
        //  Opening the file could cause OutOfMemoryError, which would make the IDE unusable. Do you really want to open it?

        // Apparently there is a way to handle this
        // (see issue http://www.netbeans.org/issues/show_bug.cgi?id=148702 )
        // but for many cases, the user probably doesn't want really large files as indicated
        // by the skipLarge parameter).
        if (fileObject.getSize () > 1024 * 1024) {
            return null;
        }
    }

    try {
        EditorCookie ec = fileObject.isValid() ? DataLoadersBridge.getDefault().getCookie(fileObject, EditorCookie.class) : null;
        if (ec != null) {
            if (openIfNecessary) {
                try {
                    return (BaseDocument) ec.openDocument();
                } catch (UserQuestionException uqe) {
                    uqe.confirmed();
                    return (BaseDocument) ec.openDocument();
                }
            } else {
                return (BaseDocument) ec.getDocument();
            }
        }
    } catch (IOException ex) {
        LOG.log(Level.WARNING, null, ex);
    }

    return null;
}
 
Example 13
Source File: SCFTHandlerTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testTemplateWizardCopiesItsPropertiesToMapForOverridenEntryOnMoreEntries() throws Exception {
    LocalFileSystem fs = new LocalFileSystem();
    fs.setRootDirectory(getWorkDir());
    
    FileObject root = fs.getRoot();
    FileObject fo = FileUtil.createData(root, "simpleObject.java");
    FileObject fo2 = FileUtil.createData(root, "simpleObject.form");
    fo.setAttribute(ScriptingCreateFromTemplateHandler.SCRIPT_ENGINE_ATTR, "js");
    fo2.setAttribute(ScriptingCreateFromTemplateHandler.SCRIPT_ENGINE_ATTR, "js");

    Charset set = Charset.forName("iso-8859-2");
    OutputStream os = fo2.getOutputStream();
    OutputStreamWriter w = new OutputStreamWriter(os, set);
    String txt = "print('skvělej tým, co nikdy neusíná - ěščřžýáíéúů')";
    w.write(txt);
    w.close();
    
    
    DataObject obj = DataObject.find(fo);
    assertEquals(TwoPartObject.class, obj.getClass());
    TwoPartObject tpo = (TwoPartObject)obj;
    tpo.encoding = set;
    
    FileObject root2 = FileUtil.createMemoryFileSystem().getRoot();
    DataFolder folder = DataFolder.findFolder(FileUtil.createFolder(root2, "target"));
    
    Map<String,String> parameters = Collections.singletonMap("type", "empty");
    
    FEQI.fs = root2.getFileSystem();
    FEQI.result = Charset.forName("UTF-8");
    
    DataObject n = obj.createFromTemplate(folder, "complex", parameters);
    Integer cnt = TwoPartLoader.queried.get(n.getPrimaryFile());
    assertEquals("No query", null, cnt);
    
    assertEquals("Created in right place", folder, n.getFolder());
    assertEquals("Created with right name", "complex", n.getName());
    Iterator<FileObject> it = n.files().iterator();
    it.next();
    FileObject snd = it.next();
    
    long length = snd.getSize();
    if (length <= 0) {
        fail("Too small file: " + length + " for " + snd);
    }
    
    String normRead = readChars(snd, Charset.forName("UTF-8"));

    txt = txt.replaceAll("print\\('", "").replaceAll("'\\)", "") + "\n";
    
    assertEquals(txt, normRead);
}
 
Example 14
Source File: PageFlowView.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void deserializeNodeLocation(FileObject navDataFile) {
    if (navDataFile != null && navDataFile.isValid() && navDataFile.getSize() > 0) {
        SceneSerializer.deserialize(sceneData, navDataFile);
    }
}
 
Example 15
Source File: SCFTHandlerTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static String readFile(FileObject fo) throws IOException {
    byte[] arr = new byte[(int)fo.getSize()];
    int len = fo.getInputStream().read(arr);
    assertEquals("Fully read", arr.length, len);
    return new String(arr);
}
 
Example 16
Source File: SanitizingParser.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * This method try to analyze the text and says whether the snapshot should be file
 * @param snapshot
 * @return whether the snapshot should be parsed
 */
private boolean isParsable (Snapshot snapshot) {
    FileObject fo = snapshot.getSource().getFileObject();
    boolean isEmbeded = !getMimeType().equals(snapshot.getMimePath().getPath());
    Long size;
    CharSequence text = snapshot.getText();
    String scriptName;
    scriptName = (fo != null) ? snapshot.getSource().getFileObject().getNameExt() : getDefaultScriptName();
    size = (fo != null && !isEmbeded) ? fo.getSize() : (long)text.length();

    if (!PARSE_BIG_FILES) {
        if (size > MAX_FILE_SIZE_TO_PARSE) {
            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.log(Level.FINE, "The file {0} was not parsed because the size is too big.", scriptName);
            }
            return false;
        }

        if (size > MAX_MINIMIZE_FILE_SIZE_TO_PARSE && !(snapshot.getMimeType().equals(JsTokenId.JSON_MIME_TYPE) || snapshot.getMimeType().equals(JsTokenId.PACKAGE_JSON_MIME_TYPE)||snapshot.getMimeType().equals(JsTokenId.BOWER_JSON_MIME_TYPE))) {
            // try to find only for the file that has size bigger then 1/3 of the max size
            boolean isMinified = false;
            TokenSequence<? extends JsTokenId> ts = LexUtilities.getTokenSequence(snapshot, 0, language);
            if (ts != null) {
                int offset = 0;
                int countedLines = 0;
                int countChars = 0;
                while (!isMinified && ts.moveNext() && countedLines < 5) {
                    LexUtilities.findNext(ts, Arrays.asList(JsTokenId.DOC_COMMENT, JsTokenId.BLOCK_COMMENT, JsTokenId.LINE_COMMENT, JsTokenId.EOL, JsTokenId.WHITESPACE));
                    offset = ts.offset();
                    LexUtilities.findNextToken(ts, Arrays.asList(JsTokenId.EOL));
                    countChars += (ts.offset() - offset);
                    countedLines++;
                }
                if (countedLines > 0 && (countChars / countedLines) > 200) {
                    if (LOGGER.isLoggable(Level.FINE)) {
                        LOGGER.log(Level.FINE, "The file {0} was not parsed because it is minimized and the size is too big.", scriptName);
                    }
                    return false;
                }
            }
        } else if (snapshot.getMimeType().equals(JsTokenId.JSON_MIME_TYPE)) {
            int index = text.length() - 1;
            if (index < 0) {
                // NETBEANS-2881
                return false;
            }
            char ch = text.charAt(index);
            while (index > 0 && ch != '}') {
                index--;
                ch = text.charAt(index);
            }
            int count = 0;
            while (index > 0 && ch == '}' && count <= MAX_RIGHT_CURLY_BRACKETS) {
                index--;
                count++;
                ch = text.charAt(index);
                
            }
            if (count >= MAX_RIGHT_CURLY_BRACKETS) {   // See issue 247274
                return false;
            }
        }
    }
    return true;
}
 
Example 17
Source File: IndentEngineIntTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static String readFile(FileObject fo) throws IOException {
    byte[] arr = new byte[(int)fo.getSize()];
    int len = fo.getInputStream().read(arr);
    assertEquals("Fully read", arr.length, len);
    return new String(arr);
}
 
Example 18
Source File: PhpEmbeddingProvider.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private long getTextSize(@NullAllowed FileObject fileObject, Snapshot snapshot) {
    if (fileObject != null) {
        return fileObject.getSize();
    }
    return snapshot.getText().length();
}
 
Example 19
Source File: JPDAReload.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public void execute() throws BuildException {
    if (logger.isLoggable(Level.FINE)) {
        logger.fine("JPDAReload.execute(), filesets = "+filesets);
    }
    if (filesets.size() == 0) {
        throw new BuildException ("A nested fileset with class to refresh in VM must be specified.");
    }
    
    // check debugger state
    DebuggerEngine debuggerEngine = DebuggerManager.getDebuggerManager ().
        getCurrentEngine ();
    if (debuggerEngine == null) {
        throw new BuildException ("No debugging sessions was found.");
    }
    JPDADebugger debugger = debuggerEngine.lookupFirst(null, JPDADebugger.class);
    if (debugger == null) {
        throw new BuildException("Current debugger is not JPDA one.");
    }
    if (!debugger.canFixClasses ()) {
        throw new BuildException("The debugger does not support Fix action.");
    }
    if (debugger.getState () == JPDADebugger.STATE_DISCONNECTED) {
        throw new BuildException ("The debugger is not running");
    }
    
    System.out.println ("Classes to be reloaded:");
    
    FileUtils fileUtils = FileUtils.getFileUtils();
    Map map = new HashMap ();
    EditorContext editorContext = DebuggerManager.getDebuggerManager().lookupFirst(null, EditorContext.class);

    Iterator it = filesets.iterator ();
    while (it.hasNext ()) {
        FileSet fs = (FileSet) it.next ();
        DirectoryScanner ds = fs.getDirectoryScanner (getProject ());
        String fileNames[] = ds.getIncludedFiles ();
        File baseDir = fs.getDir (getProject ());
        int i, k = fileNames.length;
        for (i = 0; i < k; i++) {
            File f = fileUtils.resolveFile (baseDir, fileNames [i]);
            if (f != null) {
                FileObject fo = FileUtil.toFileObject(f);
                if (fo != null) {
                    try {
                        String url = classToSourceURL (fo);
                        if (url != null)
                            editorContext.updateTimeStamp (debugger, url);
                        InputStream is = fo.getInputStream ();
                        long fileSize = fo.getSize ();
                        byte[] bytecode = new byte [(int) fileSize];
                        is.read (bytecode);
                        // remove ".class" from and use dots for for separator
                        String className = fileNames [i].substring (
                                0, 
                                fileNames [i].length () - 6
                            ).replace (File.separatorChar, '.');
                        map.put (
                            className, 
                            bytecode
                        );
                        System.out.println (" " + className);
                    } catch (IOException ex) {
                        ex.printStackTrace ();
                    }
                }
            }
        }
    }
    if (logger.isLoggable(Level.FINE)) {
        logger.fine("Reloaded classes: "+map.keySet());
    }
    if (map.size () == 0) {
        System.out.println (" No class to reload");
        return;
    }
    String error = null;
    try {
        debugger.fixClasses (map);
    } catch (UnsupportedOperationException uoex) {
        error = "The virtual machine does not support this operation: "+uoex.getLocalizedMessage();
    } catch (NoClassDefFoundError ncdfex) {
        error = "The bytes don't correspond to the class type (the names don't match): "+ncdfex.getLocalizedMessage();
    } catch (VerifyError ver) {
        error = "A \"verifier\" detects that a class, though well formed, contains an internal inconsistency or security problem: "+ver.getLocalizedMessage();
    } catch (UnsupportedClassVersionError ucver) {
        error = "The major and minor version numbers in bytes are not supported by the VM. "+ucver.getLocalizedMessage();
    } catch (ClassFormatError cfer) {
        error = "The bytes do not represent a valid class. "+cfer.getLocalizedMessage();
    } catch (ClassCircularityError ccer) {
        error = "A circularity has been detected while initializing a class: "+ccer.getLocalizedMessage();
    } catch (VMOutOfMemoryException oomex) {
        error = "Out of memory in the target VM has occurred during class reload.";
    }
    if (error != null) {
        getProject().log(error, Project.MSG_ERR);
        throw new BuildException(error);
    }
}
 
Example 20
Source File: PatchAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Removes the backup copies of files upon the successful application 
 * of a patch (.orig files).
 * @param files a list of files, to which the patch was successfully applied
 * @param backups a map of a form original file -> backup file
 */
private static void removeBackups(List<FileObject> files, Map<FileObject, FileObject> backups, boolean onExit) {
    StringBuffer filenames=new StringBuffer(), 
                 exceptions=new StringBuffer();
    for (int i = 0; i < files.size(); i++) {
        FileObject targetFileObject = files.get(i);
        FileObject backup= backups.get(targetFileObject);

        // delete files that become empty and they have a backup file
        if (targetFileObject != null && targetFileObject.getSize() == 0) {
            if (backup != null && backup.isValid() && backup.getSize() > 0) {
                if (onExit) {
                    deleteOnExit(targetFileObject);
                } else {
                    try {
                        targetFileObject.delete();
                    } catch (IOException e) {
                        ErrorManager err = ErrorManager.getDefault();
                        err.annotate(e, "Patch can not delete file, skipping...");
                        err.notify(ErrorManager.INFORMATIONAL, e);
                    }
                }
            }
        }

        if (backup != null && backup.isValid()) {
            if (onExit) {
                deleteOnExit(backup);
            } else {
                try {
                    backup.delete();
                }
                catch (IOException ex) {
                    filenames.append(FileUtil.getFileDisplayName(backup));
                    filenames.append('\n');
                    exceptions.append(ex.getLocalizedMessage());
                    exceptions.append('\n');
                }
            }
        }
    }
    if (filenames.length()>0)
        ErrorManager.getDefault().notify(
            ErrorManager.getDefault().annotate(new IOException(),
                NbBundle.getMessage(PatchAction.class, 
                    "EXC_CannotRemoveBackup", filenames, exceptions)));
}