diff --git a/platform/masterfs/nbproject/project.properties b/platform/masterfs/nbproject/project.properties index 16dd0ea601cc..4802dd36c0a3 100644 --- a/platform/masterfs/nbproject/project.properties +++ b/platform/masterfs/nbproject/project.properties @@ -16,7 +16,7 @@ # under the License. javac.compilerargs=-Xlint -Xlint:-serial -javac.source=1.8 +javac.release=17 javadoc.arch=${basedir}/arch.xml javadoc.apichanges=${basedir}/apichanges.xml diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/ExLocalFileSystem.java b/platform/masterfs/src/org/netbeans/modules/masterfs/ExLocalFileSystem.java index 0c53b6674df9..dd2d53513a77 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/ExLocalFileSystem.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/ExLocalFileSystem.java @@ -60,6 +60,7 @@ public OneFileAttributeAttachedToRoot( } + @Override public String[] children(String f) { return super.children(f); } @@ -69,6 +70,7 @@ public String[] children(String f) { * @param attrName name of the attribute * @return appropriate (serializable) value or null if the attribute is unset (or could not be properly restored for some reason) */ + @Override public Object readAttribute(String name, String attrName) { return super.readAttribute(transformName (name), attrName); } @@ -79,6 +81,7 @@ public Object readAttribute(String name, String attrName) { * @param value new value or null to clear the attribute. Must be serializable, although particular filesystems may or may not use serialization to store attribute values. * @exception IOException if the attribute cannot be set. If serialization is used to store it, this may in fact be a subclass such as {@link NotSerializableException}. */ + @Override public void writeAttribute(String name, String attrName, Object value) throws IOException { super.writeAttribute(transformName (name), attrName, value); @@ -88,6 +91,7 @@ public void writeAttribute(String name, String attrName, Object value) * @param name the file * @return enumeration of keys (as strings) */ + @Override public synchronized Enumeration attributes(String name) { return super.attributes(transformName (name)); } @@ -97,6 +101,7 @@ public synchronized Enumeration attributes(String name) { * @param oldName old name of the file * @param newName new name of the file */ + @Override public synchronized void renameAttributes(String oldName, String newName) { super.renameAttributes(transformName (oldName), transformName (newName)); } @@ -105,6 +110,7 @@ public synchronized void renameAttributes(String oldName, String newName) { * * @param name name of the file */ + @Override public synchronized void deleteAttributes(String name) { super.deleteAttributes(transformName (name)); } @@ -112,7 +118,7 @@ public synchronized void deleteAttributes(String name) { private String transformName (String name) { char replaceChar = '|';//NOI18N if (name.indexOf(replaceChar) != -1 ) { - StringBuffer transformed = new StringBuffer(name.length() + 50); + StringBuilder transformed = new StringBuilder(name.length() + 50); for (int i = 0; i < name.length(); i++) { transformed.append(name.charAt(i)); if (name.charAt(i) == replaceChar) @@ -120,7 +126,7 @@ private String transformName (String name) { } name = transformed.toString(); } - return name.replace('/',replaceChar);//NOI18N + return name.replace('/', replaceChar);//NOI18N } } } diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/GlobalVisibilityQueryImpl.java b/platform/masterfs/src/org/netbeans/modules/masterfs/GlobalVisibilityQueryImpl.java index 94daf9448d08..1932f8ff74b4 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/GlobalVisibilityQueryImpl.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/GlobalVisibilityQueryImpl.java @@ -75,6 +75,7 @@ private static Preferences getPreferences() { return NbPreferences.root().node("/org/netbeans/core"); } + @Override public boolean isVisible(FileObject file) { String name = file.getNameExt(); if (isIgnoreHiddenInHome() && isHidden(name) && isInHomeFolder(file)) { @@ -84,6 +85,7 @@ public boolean isVisible(FileObject file) { } } + @Override public boolean isVisible(File file) { String name = file.getName(); if (isIgnoreHiddenInHome() && isHidden(name) && isInHomeFolder(file)) { @@ -103,6 +105,7 @@ boolean isVisible(final String fileName) { * Add a listener to changes. * @param l a listener to add */ + @Override public void addChangeListener(ChangeListener l) { cs.addChangeListener(l); } @@ -111,6 +114,7 @@ public void addChangeListener(ChangeListener l) { * Stop listening to changes. * @param l a listener to remove */ + @Override public void removeChangeListener(ChangeListener l) { cs.removeChangeListener(l); } diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/MasterURLMapper.java b/platform/masterfs/src/org/netbeans/modules/masterfs/MasterURLMapper.java index e9424b50f1db..1919a2ade09c 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/MasterURLMapper.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/MasterURLMapper.java @@ -36,10 +36,12 @@ public final class MasterURLMapper extends URLMapper { public MasterURLMapper() { } + @Override public FileObject[] getFileObjects(final URL url) { return delegate.getFileObjects(url); } + @Override public URL getURL(final FileObject fo, final int type) { return delegate.getURL(fo, type); } diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/ProvidedExtensionsProxy.java b/platform/masterfs/src/org/netbeans/modules/masterfs/ProvidedExtensionsProxy.java index 66e09ca0728a..0644a5c90cbc 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/ProvidedExtensionsProxy.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/ProvidedExtensionsProxy.java @@ -40,11 +40,12 @@ * @author Radek Matous */ public class ProvidedExtensionsProxy extends ProvidedExtensions { - private Collection annotationProviders; - private static ThreadLocal reentrantCheck = new ThreadLocal<>(); + + private final Collection annotationProviders; + private static final ThreadLocal reentrantCheck = new ThreadLocal<>(); /** Creates a new instance of ProvidedExtensionsProxy */ - public ProvidedExtensionsProxy(Collection/*AnnotationProvider*/ annotationProviders) { + public ProvidedExtensionsProxy(Collection annotationProviders) { this.annotationProviders = annotationProviders; } @@ -57,40 +58,43 @@ public IOHandler getCopyHandler(File from, File to) { for (Iterator it = annotationProviders.iterator(); it.hasNext() && retValue == null;) { BaseAnnotationProvider provider = it.next(); final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; - if (iListener instanceof ProvidedExtensions) { - ProvidedExtensions.IOHandler delgate = ((ProvidedExtensions)iListener).getCopyHandler(from, to); + if (iListener instanceof ProvidedExtensions pe) { + ProvidedExtensions.IOHandler delgate = pe.getCopyHandler(from, to); retValue = delgate != null ? new DelegatingIOHandler(delgate) : null; } } return retValue; } + @Override public ProvidedExtensions.DeleteHandler getDeleteHandler(final File f) { ProvidedExtensions.DeleteHandler retValue = null; for (Iterator it = annotationProviders.iterator(); it.hasNext() && retValue == null;) { BaseAnnotationProvider provider = it.next(); final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; - if (iListener instanceof ProvidedExtensions) { - ProvidedExtensions.DeleteHandler delegate = ((ProvidedExtensions)iListener).getDeleteHandler(f); + if (iListener instanceof ProvidedExtensions pe) { + ProvidedExtensions.DeleteHandler delegate = pe.getDeleteHandler(f); retValue = delegate != null ? new DelegatingDeleteHandler(delegate) : null; } } return retValue; } + @Override public ProvidedExtensions.IOHandler getRenameHandler(final File from, final String newName) { IOHandler retValue = null; for (Iterator it = annotationProviders.iterator(); it.hasNext() && retValue == null;) { BaseAnnotationProvider provider = it.next(); final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; - if (iListener instanceof ProvidedExtensions) { - ProvidedExtensions.IOHandler delgate = ((ProvidedExtensions)iListener).getRenameHandler(from, newName); + if (iListener instanceof ProvidedExtensions pe) { + ProvidedExtensions.IOHandler delgate = pe.getRenameHandler(from, newName); retValue = delgate != null ? new DelegatingIOHandler(delgate) : null; } } return retValue; } + @Override public ProvidedExtensions.IOHandler getMoveHandler(final File from, final File to) { if (to == null) { return null; @@ -99,162 +103,137 @@ public ProvidedExtensions.IOHandler getMoveHandler(final File from, final File t for (Iterator it = annotationProviders.iterator(); it.hasNext() && retValue == null;) { BaseAnnotationProvider provider = it.next(); InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; - if (iListener instanceof ProvidedExtensions) { - ProvidedExtensions.IOHandler delgate = ((ProvidedExtensions)iListener).getMoveHandler(from, to); + if (iListener instanceof ProvidedExtensions pe) { + ProvidedExtensions.IOHandler delgate = pe.getMoveHandler(from, to); retValue = delgate != null ? new DelegatingIOHandler(delgate) : null; } } return retValue; } + @Override public void createFailure(final FileObject parent, final String name, final boolean isFolder) { - for (Iterator it = annotationProviders.iterator(); it.hasNext();) { - BaseAnnotationProvider provider = it.next(); + for (BaseAnnotationProvider provider : annotationProviders) { final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; if (iListener != null) { - runCheckCode(new Runnable() { - public void run() { - iListener.createFailure(parent, name, isFolder); - } - }); + runCheckCode((Runnable) () -> + iListener.createFailure(parent, name, isFolder) + ); } } } + @Override public void beforeCreate(final FileObject parent, final String name, final boolean isFolder) { - for (Iterator it = annotationProviders.iterator(); it.hasNext();) { - BaseAnnotationProvider provider = it.next(); + for (BaseAnnotationProvider provider : annotationProviders) { final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; if (iListener != null) { - runCheckCode(new Runnable() { - public void run() { - iListener.beforeCreate(parent, name, isFolder); - } - }); + runCheckCode((Runnable) () -> + iListener.beforeCreate(parent, name, isFolder) + ); } } } + @Override public void deleteSuccess(final FileObject fo) { - for (Iterator it = annotationProviders.iterator(); it.hasNext();) { - BaseAnnotationProvider provider = it.next(); + for (BaseAnnotationProvider provider : annotationProviders) { final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; if (iListener != null) { - runCheckCode(new Runnable() { - public void run() { - iListener.deleteSuccess(fo); - } - }); + runCheckCode((Runnable) () -> + iListener.deleteSuccess(fo) + ); } } } + @Override public void deleteFailure(final FileObject fo) { - for (Iterator it = annotationProviders.iterator(); it.hasNext();) { - BaseAnnotationProvider provider = it.next(); + for (BaseAnnotationProvider provider : annotationProviders) { final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; if (iListener != null) { - runCheckCode(new Runnable() { - public void run() { - iListener.deleteFailure(fo); - } - }); + runCheckCode((Runnable) () -> + iListener.deleteFailure(fo) + ); } } } + @Override public void createSuccess(final FileObject fo) { - for (Iterator it = annotationProviders.iterator(); it.hasNext();) { - BaseAnnotationProvider provider = it.next(); + for (BaseAnnotationProvider provider : annotationProviders) { final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; if (iListener != null) { - runCheckCode(new Runnable() { - public void run() { - iListener.createSuccess(fo); - } - }); + runCheckCode((Runnable) () -> + iListener.createSuccess(fo) + ); } } } + @Override public void beforeDelete(final FileObject fo) { - for (Iterator it = annotationProviders.iterator(); it.hasNext();) { - BaseAnnotationProvider provider = it.next(); + for (BaseAnnotationProvider provider : annotationProviders) { final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; if (iListener != null) { - runCheckCode(new Runnable() { - public void run() { - iListener.beforeDelete(fo); - } - }); + runCheckCode((Runnable) () -> + iListener.beforeDelete(fo) + ); } } } + @Override public boolean canWrite(final File f) { - final Boolean ret[] = new Boolean [] { null }; - for (Iterator it = annotationProviders.iterator(); it.hasNext();) { - BaseAnnotationProvider provider = it.next(); + final Boolean[] ret = new Boolean[] { null }; + for (BaseAnnotationProvider provider : annotationProviders) { final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; - if (iListener instanceof ProvidedExtensions) { - runCheckCode(new Runnable() { - public void run() { - ProvidedExtensions extension = (ProvidedExtensions)iListener; - if(ProvidedExtensionsAccessor.IMPL != null && - ProvidedExtensionsAccessor.IMPL.providesCanWrite(extension)) - { - ret[0] = ((ProvidedExtensions)iListener).canWrite(f); - } + if (iListener instanceof ProvidedExtensions pe) { + runCheckCode((Runnable) () -> { + ProvidedExtensions extension = pe; + if(ProvidedExtensionsAccessor.IMPL != null && ProvidedExtensionsAccessor.IMPL.providesCanWrite(extension)) { + ret[0] = pe.canWrite(f); } }); if(ret[0] != null && ret[0]) { break; + } } } - } return ret[0] != null ? ret[0] : super.canWrite(f); } - + @Override public void beforeChange(final FileObject f) { - for (Iterator it = annotationProviders.iterator(); it.hasNext();) { - BaseAnnotationProvider provider = it.next(); + for (BaseAnnotationProvider provider : annotationProviders) { final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; - if (iListener instanceof ProvidedExtensions) { - runCheckCode(new Runnable() { - public void run() { - ((ProvidedExtensions)iListener).beforeChange(f); - } - }); + if (iListener instanceof ProvidedExtensions pe) { + runCheckCode((Runnable) () -> + pe.beforeChange(f) + ); } } } @Override public void fileLocked(final FileObject fo) throws IOException { - for (Iterator it = annotationProviders.iterator(); it.hasNext();) { - BaseAnnotationProvider provider = it.next(); + for (BaseAnnotationProvider provider : annotationProviders) { final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; - if (iListener instanceof ProvidedExtensions) { - runCheckCode(new FileSystem.AtomicAction() { - @Override - public void run() throws IOException { - ((ProvidedExtensions) iListener).fileLocked(fo); - } - }); + if (iListener instanceof ProvidedExtensions pe) { + runCheckCode((FileSystem.AtomicAction) () -> + pe.fileLocked(fo) + ); } } } + @Override public void fileUnlocked(final FileObject fo) { - for (Iterator it = annotationProviders.iterator(); it.hasNext();) { - BaseAnnotationProvider provider = it.next(); + for (BaseAnnotationProvider provider : annotationProviders) { final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; - if (iListener instanceof ProvidedExtensions) { - runCheckCode(new Runnable() { - public void run() { - ((ProvidedExtensions)iListener).fileUnlocked(fo); - } + if (iListener instanceof ProvidedExtensions pe) { + runCheckCode((Runnable) () -> { + pe.fileUnlocked(fo); }); } } @@ -265,11 +244,9 @@ public Object getAttribute(final File file, final String attrName) { final AtomicReference value = new AtomicReference<>(); for (BaseAnnotationProvider provider : annotationProviders) { final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; - if (iListener instanceof ProvidedExtensions) { - runCheckCode(new Runnable() { - public void run() { - value.set(((ProvidedExtensions) iListener).getAttribute(file, attrName)); - } + if (iListener instanceof ProvidedExtensions pe) { + runCheckCode((Runnable) () -> { + value.set(pe.getAttribute(file, attrName)); }); } if (value.get() != null) { @@ -281,11 +258,9 @@ public void run() { @Override public long refreshRecursively(File dir, long lastTimeStamp, List children) { - for (Iterator it = annotationProviders.iterator(); it.hasNext();) { - BaseAnnotationProvider provider = it.next(); + for (BaseAnnotationProvider provider : annotationProviders) { final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; - if (iListener instanceof ProvidedExtensions) { - ProvidedExtensions pe = (ProvidedExtensions)iListener; + if (iListener instanceof ProvidedExtensions pe) { int prev = children.size(); long ret = pe.refreshRecursively(dir, lastTimeStamp, children); assert ret != -1 || prev == children.size() : "When returning -1 from refreshRecursively, you cannot modify children: " + pe; @@ -303,14 +278,11 @@ public long refreshRecursively(File dir, long lastTimeStamp, List @Override public void createdExternally(final FileObject fo) { - for (Iterator it = annotationProviders.iterator(); it.hasNext();) { - BaseAnnotationProvider provider = it.next(); + for (BaseAnnotationProvider provider : annotationProviders) { final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; - if (iListener instanceof ProvidedExtensions) { - runCheckCode(new Runnable() { - public void run() { - ((ProvidedExtensions)iListener).createdExternally(fo); - } + if (iListener instanceof ProvidedExtensions pe) { + runCheckCode((Runnable) () -> { + pe.createdExternally(fo); }); } } @@ -318,14 +290,11 @@ public void run() { @Override public void deletedExternally(final FileObject fo) { - for (Iterator it = annotationProviders.iterator(); it.hasNext();) { - BaseAnnotationProvider provider = it.next(); + for (BaseAnnotationProvider provider : annotationProviders) { final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; - if (iListener instanceof ProvidedExtensions) { - runCheckCode(new Runnable() { - public void run() { - ((ProvidedExtensions)iListener).deletedExternally(fo); - } + if (iListener instanceof ProvidedExtensions pe) { + runCheckCode((Runnable) () -> { + pe.deletedExternally(fo); }); } } @@ -333,14 +302,11 @@ public void run() { @Override public void fileChanged(final FileObject fo) { - for (Iterator it = annotationProviders.iterator(); it.hasNext();) { - BaseAnnotationProvider provider = it.next(); + for (BaseAnnotationProvider provider : annotationProviders) { final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; - if (iListener instanceof ProvidedExtensions) { - runCheckCode(new Runnable() { - public void run() { - ((ProvidedExtensions)iListener).fileChanged(fo); - } + if (iListener instanceof ProvidedExtensions pe) { + runCheckCode((Runnable) () -> { + pe.fileChanged(fo); }); } } @@ -351,14 +317,11 @@ public void beforeMove(final FileObject from, final File to) { if (to == null) { return; } - for (Iterator it = annotationProviders.iterator(); it.hasNext();) { - BaseAnnotationProvider provider = it.next(); + for (BaseAnnotationProvider provider : annotationProviders) { final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; - if (iListener instanceof ProvidedExtensions) { - runCheckCode(new Runnable() { - public void run() { - ((ProvidedExtensions)iListener).beforeMove(from, to); - } + if (iListener instanceof ProvidedExtensions pe) { + runCheckCode((Runnable) () -> { + pe.beforeMove(from, to); }); } } @@ -369,14 +332,11 @@ public void moveSuccess(final FileObject from, final File to) { if (to == null) { return; } - for (Iterator it = annotationProviders.iterator(); it.hasNext();) { - BaseAnnotationProvider provider = it.next(); + for (BaseAnnotationProvider provider : annotationProviders) { final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; - if (iListener instanceof ProvidedExtensions) { - runCheckCode(new Runnable() { - public void run() { - ((ProvidedExtensions)iListener).moveSuccess(from, to); - } + if (iListener instanceof ProvidedExtensions pe) { + runCheckCode((Runnable) () -> { + pe.moveSuccess(from, to); }); } } @@ -387,14 +347,11 @@ public void moveFailure(final FileObject from, final File to) { if (to == null) { return; } - for (Iterator it = annotationProviders.iterator(); it.hasNext();) { - BaseAnnotationProvider provider = it.next(); + for (BaseAnnotationProvider provider : annotationProviders) { final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; - if (iListener instanceof ProvidedExtensions) { - runCheckCode(new Runnable() { - public void run() { - ((ProvidedExtensions)iListener).moveFailure(from, to); - } + if (iListener instanceof ProvidedExtensions pe) { + runCheckCode((Runnable) () -> { + pe.moveFailure(from, to); }); } } @@ -405,14 +362,11 @@ public void beforeCopy(final FileObject from, final File to) { if (to == null) { return; } - for (Iterator it = annotationProviders.iterator(); it.hasNext();) { - BaseAnnotationProvider provider = it.next(); + for (BaseAnnotationProvider provider : annotationProviders) { final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; - if (iListener instanceof ProvidedExtensions) { - runCheckCode(new Runnable() { - public void run() { - ((ProvidedExtensions)iListener).beforeCopy(from, to); - } + if (iListener instanceof ProvidedExtensions pe) { + runCheckCode((Runnable) () -> { + pe.beforeCopy(from, to); }); } } @@ -423,14 +377,11 @@ public void copySuccess(final FileObject from, final File to) { if (to == null) { return; } - for (Iterator it = annotationProviders.iterator(); it.hasNext();) { - BaseAnnotationProvider provider = it.next(); + for (BaseAnnotationProvider provider : annotationProviders) { final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; - if (iListener instanceof ProvidedExtensions) { - runCheckCode(new Runnable() { - public void run() { - ((ProvidedExtensions)iListener).copySuccess(from, to); - } + if (iListener instanceof ProvidedExtensions pe) { + runCheckCode((Runnable) () -> { + pe.copySuccess(from, to); }); } } @@ -441,14 +392,11 @@ public void copyFailure(final FileObject from, final File to) { if (to == null) { return; } - for (Iterator it = annotationProviders.iterator(); it.hasNext();) { - BaseAnnotationProvider provider = it.next(); + for (BaseAnnotationProvider provider : annotationProviders) { final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null; - if (iListener instanceof ProvidedExtensions) { - runCheckCode(new Runnable() { - public void run() { - ((ProvidedExtensions)iListener).copyFailure(from, to); - } + if (iListener instanceof ProvidedExtensions pe) { + runCheckCode((Runnable) () -> { + pe.copyFailure(from, to); }); } } @@ -479,35 +427,33 @@ private static void runCheckCode(FileSystem.AtomicAction code) throws IOExceptio } private class DelegatingDeleteHandler implements ProvidedExtensions.DeleteHandler { - private ProvidedExtensions.DeleteHandler delegate; + private final ProvidedExtensions.DeleteHandler delegate; private DelegatingDeleteHandler(final ProvidedExtensions.DeleteHandler delegate) { this.delegate = delegate; } + @Override public boolean delete(final File file) { final boolean[] retval = new boolean[1]; - runCheckCode(new Runnable() { - public void run() { - retval[0] = delegate.delete(file); - } + runCheckCode((Runnable) () -> { + retval[0] = delegate.delete(file); }); return retval[0]; } } private class DelegatingIOHandler implements ProvidedExtensions.IOHandler { - private ProvidedExtensions.IOHandler delegate; + private final ProvidedExtensions.IOHandler delegate; private DelegatingIOHandler(final ProvidedExtensions.IOHandler delegate) { this.delegate = delegate; } + @Override public void handle() throws IOException { final IOException[] retval = new IOException[1]; - runCheckCode(new Runnable() { - public void run() { - try { - delegate.handle(); - } catch (IOException ex) { - retval[0] = ex; - } + runCheckCode((Runnable) () -> { + try { + delegate.handle(); + } catch (IOException ex) { + retval[0] = ex; } }); if (retval[0] != null) { diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/FileBasedFileSystem.java b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/FileBasedFileSystem.java index 5a9343b5fc93..4e543e200bca 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/FileBasedFileSystem.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/FileBasedFileSystem.java @@ -18,10 +18,10 @@ */ package org.netbeans.modules.masterfs.filebasedfs; -import java.awt.Image; import java.io.File; import java.io.IOException; import java.io.ObjectStreamException; +import java.io.Serial; import java.io.Serializable; import java.nio.file.Files; import java.util.ArrayList; @@ -32,7 +32,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.logging.Logger; import org.netbeans.modules.masterfs.ProvidedExtensionsProxy; import org.netbeans.modules.masterfs.filebasedfs.fileobjects.BaseFileObj; import org.netbeans.modules.masterfs.filebasedfs.fileobjects.FileObjectFactory; @@ -54,24 +53,23 @@ * @author Radek Matous */ public class FileBasedFileSystem extends FileSystem { - private static final Logger LOG = Logger.getLogger(FileBasedFileSystem.class.getName()); private static volatile FileBasedFileSystem INSTANCE; - private transient RootObj root; + private final transient RootObj root; private final transient StatusImpl status = new StatusImpl(); - private static transient int modificationInProgress; + private static transient int modificationInProgress; public FileBasedFileSystem() { if (BaseUtilities.isWindows()) { RootObjWindows realRoot = new RootObjWindows(); - root = new RootObj(realRoot); + root = new RootObj<>(realRoot); } else { FileObjectFactory factory = FileObjectFactory.getInstance(new File("/"));//NOI18N - root = new RootObj(factory.getRoot()); + root = new RootObj<>(factory.getRoot()); } } public static synchronized boolean isModificationInProgress() { - return modificationInProgress == 0 ? false : true; + return modificationInProgress != 0; } private static synchronized void setModificationInProgress(boolean started) { @@ -145,18 +143,12 @@ public static FileBasedFileSystem getInstance() { @Override public void refresh(final boolean expected) { - final Runnable r = new Runnable() { - @Override - public void run() { - refreshImpl(expected); - } + final Runnable r = () -> { + refreshImpl(expected); }; try { - FileBasedFileSystem.getInstance().runAtomicAction(new FileSystem.AtomicAction() { - @Override - public void run() throws IOException { - FileBasedFileSystem.runAsInconsistent(r); - } + FileBasedFileSystem.getInstance().runAtomicAction(() -> { + FileBasedFileSystem.runAsInconsistent(r); }); } catch (IOException ex) { Exceptions.printStackTrace(ex); @@ -165,8 +157,8 @@ public void run() throws IOException { public void refreshImpl(boolean expected) { FileObject fo = root.getRealRoot(); - if (fo instanceof BaseFileObj) { - ((BaseFileObj)fo).getFactory().refresh(expected); + if (fo instanceof BaseFileObj baseFileObj) { + baseFileObj.getFactory().refresh(expected); } else if (fo instanceof RootObjWindows) { Collection fcs = factories().values(); for (FileObjectFactory fileObjectFactory : fcs) { @@ -246,7 +238,7 @@ public class StatusImpl implements StatusDecorator, org.openide.util.LookupListener, org.openide.filesystems.FileStatusListener { /** result with providers */ - protected org.openide.util.Lookup.Result annotationProviders; + protected final org.openide.util.Lookup.Result annotationProviders; private Collection previousProviders; { @@ -260,17 +252,17 @@ public class StatusImpl implements StatusDecorator, } catch (ClassNotFoundException e) { //pass - no masterfs.ui module no @ServiceProvider(service=AnnotationProvider.class) hack needed. } - annotationProviders = Lookup.getDefault().lookup(new Lookup.Template(BaseAnnotationProvider.class)); + annotationProviders = Lookup.getDefault().lookup(new Lookup.Template<>(BaseAnnotationProvider.class)); annotationProviders.addLookupListener(this); resultChanged(null); } public ProvidedExtensions getExtensions() { - Collection c; + Collection c; if (previousProviders != null) { c = Collections.unmodifiableCollection(previousProviders); } else { - c = Collections.emptyList(); + c = List.of(); } return new ProvidedExtensionsProxy(c); } @@ -284,18 +276,15 @@ public void resultChanged(org.openide.util.LookupEvent ev) { add = new HashSet(now); add.removeAll(previousProviders); - HashSet toRemove = new HashSet(previousProviders); + HashSet toRemove = new HashSet<>(previousProviders); toRemove.removeAll(now); for (BaseAnnotationProvider ap : toRemove) { ap.removeFileStatusListener(this); } - } else { add = now; } - - for (BaseAnnotationProvider ap : add) { try { ap.addFileStatusListener(this); @@ -308,14 +297,14 @@ public void resultChanged(org.openide.util.LookupEvent ev) { } public Lookup findExtrasFor(Set foSet) { - List arr = new ArrayList(); + List arr = new ArrayList<>(); for (BaseAnnotationProvider ap : annotationProviders.allInstances()) { final Lookup lkp = ap.findExtrasFor(foSet); if (lkp != null) { arr.add(lkp); } } - return new ProxyLookup(arr.toArray(new Lookup[0])); + return new ProxyLookup(arr.toArray(Lookup[]::new)); } @Override @@ -350,13 +339,15 @@ public String annotateNameHtml(String name, Set files) { } } + @Serial public Object writeReplace() throws ObjectStreamException { return new SerReplace(); } private static class SerReplace implements Serializable { - /** serial version UID */ + @Serial static final long serialVersionUID = -3714631266626840241L; + @Serial public Object readResolve() throws ObjectStreamException { return FileBasedFileSystem.getInstance(); } diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/FileBasedURLMapper.java b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/FileBasedURLMapper.java index c30698a76d85..cfcc9e638da8 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/FileBasedURLMapper.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/FileBasedURLMapper.java @@ -43,21 +43,17 @@ public final URL getURL(final FileObject fo, final int type) { if (type == URLMapper.NETWORK) { return null; } - URL retVal = null; try { - if (fo instanceof BaseFileObj) { - final BaseFileObj bfo = (BaseFileObj) fo; - retVal = FileBasedURLMapper.fileToURL(bfo.getFileName().getFile(), fo); - } else if (fo instanceof RootObj) { - final RootObj rfo = (RootObj) fo; + if (fo instanceof BaseFileObj bfo) { + return FileBasedURLMapper.fileToURL(bfo.getFileName().getFile(), fo); + } else if (fo instanceof RootObj rfo) { return getURL(rfo.getRealRoot(), type); } - } catch (MalformedURLException e) { - retVal = null; - } - return retVal; + } catch (MalformedURLException e) {} + return null; } + @Override public final FileObject[] getFileObjects(final URL url) { if (!"file".equals(url.getProtocol())) { //NOI18N return null; @@ -67,20 +63,16 @@ public final FileObject[] getFileObjects(final URL url) { return null; } //TODO: review and simplify - FileObject retVal = null; File file; try { file = FileUtil.normalizeFile(BaseUtilities.toFile(url.toURI())); - } catch (URISyntaxException e) { + } catch (URISyntaxException | IllegalArgumentException e) { LOG.log(Level.INFO, "URL=" + url, e); // NOI18N return null; - } catch (IllegalArgumentException iax) { - LOG.log(Level.INFO, "URL=" + url, iax); // NOI18N - return null; } - - retVal = FileBasedFileSystem.getFileObject(file, FileObjectFactory.Caller.ToFileObject); - return new FileObject[]{retVal}; + return new FileObject[] { + FileBasedFileSystem.getFileObject(file, FileObjectFactory.Caller.ToFileObject) + }; } private static URL fileToURL(final File file, final FileObject fo) throws MalformedURLException { diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/children/ChildrenSupport.java b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/children/ChildrenSupport.java index 546905ced45a..2edf055e2c2f 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/children/ChildrenSupport.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/children/ChildrenSupport.java @@ -56,7 +56,7 @@ public static boolean isLock() { } public synchronized Set getCachedChildren() { - return new HashSet(getExisting(false)); + return new HashSet<>(getExisting(false)); } public synchronized Set getChildren(final FileNaming folderName, final boolean rescan, Runnable[] task) { @@ -119,12 +119,12 @@ private synchronized void addChild(final FileNaming folderName, final FileNaming public synchronized Map refresh(final FileNaming folderName, Runnable[] task) { - Map retVal = new HashMap(); - Set e = new HashSet(getExisting(false)); - Set nE = new HashSet(getNotExisting(false)); + Map retVal = new HashMap<>(); + Set e = new HashSet<>(getExisting(false)); + Set nE = new HashSet<>(getNotExisting(false)); if (isStatus(ChildrenSupport.SOME_CHILDREN_CACHED)) { - Set existingToCheck = new HashSet(e); + Set existingToCheck = new HashSet<>(e); for (FileNaming fnToCheck : existingToCheck) { FileNaming fnRescanned = rescanChild(folderName, fnToCheck.getName(), true, true); if (fnRescanned == null) { @@ -132,7 +132,7 @@ public synchronized Map refresh(final FileNaming folderName } } - Set notExistingToCheck = new HashSet(nE); + Set notExistingToCheck = new HashSet<>(nE); for (FileNaming fnToCheck : notExistingToCheck) { assert fnToCheck != null; FileNaming fnRescanned = rescanChild(folderName, fnToCheck.getName(), true, false); @@ -230,7 +230,7 @@ public boolean isFile() { } private Map rescanChildren(final FileNaming folderName, final boolean ignoreCache, Runnable[] task) { - final Map retval = new IdentityHashMap(); + final Map retval = new IdentityHashMap<>(); final File folder = folderName.getFile(); assert folderName.getFile().getAbsolutePath().equals(folderName.toString()); @@ -242,7 +242,7 @@ class IOJob implements Runnable { public void run() { final File[] children = folder.listFiles(); if (children != null) { - newChildren = new LinkedHashSet(); + newChildren = new LinkedHashSet<>(); for (int i = 0; i < children.length; i++) { final FileInfo fInfo = new FileInfo(children[i], 1); if (fInfo.isConvertibleToFileObject()) { @@ -258,8 +258,8 @@ public void run() { } } IOJob job; - if (task[0] instanceof IOJob) { - job = (IOJob)task[0]; + if (task[0] instanceof IOJob iOJob) { + job = iOJob; } else { task[0] = new IOJob(); return null; @@ -270,7 +270,7 @@ public void run() { // folder.listFiles() failed with I/O exception - do not remove children return retval; } - job.newChildren = new LinkedHashSet(); + job.newChildren = new LinkedHashSet<>(); } Set deleted = deepMinus(getExisting(false), job.newChildren); @@ -289,7 +289,7 @@ public void run() { } private static Set deepMinus(Set base, Set minus) { - HashMap detract = new HashMap(base.size() * 2); + HashMap detract = new HashMap<>(base.size() * 2); for (FileNaming fn : base) { detract.put(fn, fn); } @@ -305,28 +305,34 @@ private static Set deepMinus(Set base, Set m private FileNaming lookupChildInCache(final FileNaming folder, final String childName, boolean lookupExisting) { final File f = new File(folder.getFile(), childName); - final Integer id = NamingFactory.createID(f); + final FileNaming.ID id = NamingFactory.createID(f); class FakeNaming implements FileNaming { public FileNaming lastEqual; + @Override public String getName() { return childName; } + @Override public FileNaming getParent() { return folder; } + @Override public boolean isRoot() { return false; } + @Override public File getFile() { return f; } - public Integer getId() { + @Override + public FileNaming.ID getId() { return id; } + @Override public FileNaming rename(String name, ProvidedExtensions.IOHandler h) { // not implemented, as it will not be called throw new IllegalStateException(); @@ -336,8 +342,8 @@ public FileNaming rename(String name, ProvidedExtensions.IOHandler h) { public boolean equals(Object obj) { if (hashCode() == obj.hashCode() && getName().equals(((FileNaming)obj).getName())) { assert lastEqual == null : "Just one can be there"; // NOI18N - if (obj instanceof FileNaming) { - lastEqual = (FileNaming)obj; + if (obj instanceof FileNaming fileNaming) { + lastEqual = fileNaming; } return true; } @@ -346,13 +352,15 @@ public boolean equals(Object obj) { @Override public int hashCode() { - return id.intValue(); + return id.value(); } + @Override public boolean isFile() { return this.getFile().isFile(); } + @Override public boolean isDirectory() { return !isFile(); } @@ -375,7 +383,7 @@ private synchronized Set getExisting() { private synchronized Set getExisting(boolean init) { if (init && existingChildren == null) { - existingChildren = new HashSet(); + existingChildren = new HashSet<>(); } return existingChildren != null ? existingChildren : Collections.emptySet(); } @@ -386,7 +394,7 @@ private synchronized Set getNotExisting() { private synchronized Set getNotExisting(boolean init) { if (init && notExistingChildren == null) { - notExistingChildren = new HashSet(); + notExistingChildren = new HashSet<>(); } return notExistingChildren != null ? notExistingChildren : Collections.emptySet(); } diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/BaseFileObj.java b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/BaseFileObj.java index 616967fc58dd..413cfe86db79 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/BaseFileObj.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/BaseFileObj.java @@ -19,7 +19,6 @@ package org.netbeans.modules.masterfs.filebasedfs.fileobjects; -import org.netbeans.modules.masterfs.filebasedfs.FileBasedFileSystem.FSCallable; import org.netbeans.modules.masterfs.filebasedfs.Statistics; import org.netbeans.modules.masterfs.filebasedfs.children.ChildrenCache; import org.netbeans.modules.masterfs.filebasedfs.naming.FileNaming; @@ -39,7 +38,6 @@ import java.nio.file.InvalidPathException; import java.nio.file.NoSuchFileException; import java.nio.file.Path; -import java.nio.file.Paths; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; @@ -51,7 +49,6 @@ import java.util.HashSet; import java.util.NoSuchElementException; import java.util.Set; -import java.util.Stack; import java.util.logging.Level; import java.util.logging.Logger; import org.netbeans.modules.masterfs.filebasedfs.FileBasedFileSystem; @@ -76,8 +73,7 @@ public abstract class BaseFileObj extends FileObject { private static final String PATH_SEPARATOR = File.separator;//NOI18N private static final char EXT_SEP = '.';//NOI18N static final Logger LOG = Logger.getLogger(BaseFileObj.class.getName()); - static final ThreadLocal MOVED_FILE_TIMESTAMP //#244286: move in progress - = new ThreadLocal(); + static final ThreadLocal MOVED_FILE_TIMESTAMP = new ThreadLocal<>(); //#244286: move in progress //static fields static final long serialVersionUID = -1244650210876356809L; @@ -154,14 +150,17 @@ public boolean canWrite() { return extension.canWrite(file); } + @Override public final boolean isData() { return !isFolder(); } + @Override public final String getName() { return FileInfo.getName(getNameExt()); } + @Override public final String getExt() { return FileInfo.getExt(getNameExt()); } @@ -169,7 +168,7 @@ public final String getExt() { @Override public final String getPath() { FileNaming fileNaming = getFileName(); - Deque stack = new ArrayDeque(); + Deque stack = new ArrayDeque<>(); while (fileNaming != null) { stack.addFirst(fileNaming.getName()); fileNaming = fileNaming.getParent(); @@ -193,14 +192,17 @@ public final String getPath() { return path.toString(); } + @Override public final FileSystem getFileSystem() throws FileStateInvalidException { return FileBasedFileSystem.getInstance(); } + @Override public final boolean isRoot() { return false; } + @Override public final java.util.Date lastModified() { final File f = getFileName().getFile(); final long lastModified = f.lastModified(); @@ -225,8 +227,8 @@ public FileObject copy(FileObject target, String name, String ext) throws IOExce } final IOHandler copyHandler = extensions.getCopyHandler(getFileName().getFile(), to); if (copyHandler != null) { - if (target instanceof FolderObj) { - result = handleMoveCopy((FolderObj)target, name, ext, copyHandler); + if (target instanceof FolderObj folderObj) { + result = handleMoveCopy(folderObj, name, ext, copyHandler); } else { copyHandler.handle(); refresh(true); @@ -274,8 +276,8 @@ public final FileObject move(FileLock lock, FileObject target, String name, Stri Watcher.lock(getParent()); final IOHandler moveHandler = extensions.getMoveHandler(getFileName().getFile(), to); if (moveHandler != null) { - if (target instanceof FolderObj) { - result = move(lock, (FolderObj)target, name, ext,moveHandler); + if (target instanceof FolderObj folderObj) { + result = move(lock, folderObj, name, ext,moveHandler); } else { moveHandler.handle(); refresh(true); @@ -442,7 +444,7 @@ void rename(final FileLock lock, final String name, final String ext, final Prov } assert allRenamed[0] != null; fileName = allRenamed[0]; - Set toRename = new HashSet(allRenamed.length * 2); + Set toRename = new HashSet<>(allRenamed.length * 2); toRename.add(this); BaseFileObj.attribs.renameAttributes(file.getAbsolutePath().replace('\\', '/'), file2Rename.getAbsolutePath().replace('\\', '/'));//NOI18N for (int i = 0; i < allRenamed.length; i++) { @@ -453,8 +455,7 @@ void rename(final FileLock lock, final String name, final String ext, final Prov toRename.add(obj); } FileObject tmpPar = allRenamed[i].getParent() != null ? fs.getCachedOnly(affected.getParentFile(), false) : null; - if (tmpPar instanceof FolderObj) { - FolderObj par = (FolderObj)tmpPar; + if (tmpPar instanceof FolderObj par) { ChildrenCache childrenCache = par.getChildrenCache(); final Mutex.Privileged mutexPrivileged = (childrenCache != null) ? childrenCache.getMutexPrivileged() : null; if (mutexPrivileged != null) { @@ -488,18 +489,16 @@ void rename(final FileLock lock, final String name, final String ext, final Prov protected void afterRename() { } + @Override public final void rename(final FileLock lock, final String name, final String ext) throws IOException { - FSCallable c = new FSCallable() { - public Boolean call() throws IOException { - ProvidedExtensions extensions = getProvidedExtensions(); - rename(lock, name, ext, extensions.getRenameHandler(getFileName().getFile(), FileInfo.composeName(name, ext))); - return true; - } - }; - FileBasedFileSystem.runAsInconsistent(c); + FileBasedFileSystem.runAsInconsistent(() -> { + ProvidedExtensions extensions = getProvidedExtensions(); + rename(lock, name, ext, extensions.getRenameHandler(getFileName().getFile(), FileInfo.composeName(name, ext))); + return true; + }); } - + @Override public Object getAttribute(final String attrName) { if (attrName.equals("FileSystem.rootPath")) { return "";//NOI18N @@ -516,12 +515,14 @@ public Object getAttribute(final String attrName) { return BaseFileObj.attribs.readAttribute(getFileName().getFile().getAbsolutePath().replace('\\', '/'), attrName);//NOI18N } + @Override public final void setAttribute(final String attrName, final Object value) throws java.io.IOException { final Object oldValue = BaseFileObj.attribs.readAttribute(getFileName().getFile().getAbsolutePath().replace('\\', '/'), attrName);//NOI18N BaseFileObj.attribs.writeAttribute(getFileName().getFile().getAbsolutePath().replace('\\', '/'), attrName, value);//NOI18N fireFileAttributeChangedEvent(attrName, oldValue, value); } + @Override public final java.util.Enumeration getAttributes() { return BaseFileObj.attribs.attributes(getFileName().getFile().getAbsolutePath().replace('\\', '/'));//NOI18N } @@ -566,20 +567,24 @@ private Enumeration getListeners() { } + @Override public final long getSize() { return getFileName().getFile().length(); } + @Override public final void setImportant(final boolean b) { } + @Override public boolean isReadOnly() { final File f = getFileName().getFile(); ProvidedExtensions extension = getProvidedExtensions(); return !extension.canWrite(f) && FileChangedManager.getInstance().exists(f); } + @Override public final FileObject getParent() { FileObject retVal = null; if (!isRoot()) { @@ -764,22 +769,20 @@ public final FileNaming getFileName() { return fileName; } + @Override public final void delete(final FileLock lock) throws IOException { - FSCallable c = new FSCallable() { - public Boolean call() throws IOException { - ProvidedExtensions pe = getProvidedExtensions(); - pe.beforeDelete(BaseFileObj.this); - try { - delete(lock, pe.getDeleteHandler(getFileName().getFile())); - } catch (IOException iex) { - getProvidedExtensions().deleteFailure(BaseFileObj.this); - throw iex; - } - getProvidedExtensions().deleteSuccess(BaseFileObj.this); - return true; - } - }; - FileBasedFileSystem.runAsInconsistent(c); + FileBasedFileSystem.runAsInconsistent(() -> { + ProvidedExtensions pe = getProvidedExtensions(); + pe.beforeDelete(BaseFileObj.this); + try { + delete(lock, pe.getDeleteHandler(getFileName().getFile())); + } catch (IOException iex) { + getProvidedExtensions().deleteFailure(BaseFileObj.this); + throw iex; + } + getProvidedExtensions().deleteSuccess(BaseFileObj.this); + return true; + }); } public void delete(final FileLock lock, ProvidedExtensions.DeleteHandler deleteHandler) throws IOException { @@ -930,16 +933,16 @@ final void notifyDeleted(final boolean expected) { } private void updateFileName(FileNaming oldName, FileNaming oldRoot, FileNaming newRoot) { - Stack names = new Stack(); + Deque names = new ArrayDeque<>(); while (oldRoot != oldName && oldName != null) { - names.add(oldName.getName()); + names.addLast(oldName.getName()); oldName = oldName.getParent(); } File prev = newRoot.getFile(); while (!names.isEmpty()) { - String n = names.pop(); + String n = names.removeLast(); newRoot = NamingFactory.fromFile(newRoot, prev = new File(prev, n), true); } assert newRoot != null; @@ -962,56 +965,68 @@ private void updateFileName(FileNaming oldName, FileNaming oldRoot, FileNaming n * */ private static final class BridgeForAttributes implements AbstractFileSystem.List, AbstractFileSystem.Change, AbstractFileSystem.Info { + @Override public final Date lastModified(final String name) { final File file = new File(name); return new Date(file.lastModified()); } + @Override public final boolean folder(final String name) { final File file = new File(name); return file.isDirectory(); } + @Override public final boolean readOnly(final String name) { final File file = new File(name); return !file.canWrite(); } + @Override public final String mimeType(final String name) { return "content/unknown"; // NOI18N; } + @Override public final long size(final String name) { final File file = new File(name); return file.length(); } + @Override public final InputStream inputStream(final String name) throws FileNotFoundException { final File file = new File(name); return new FileInputStream(file); } + @Override public final OutputStream outputStream(final String name) throws IOException { - final Path path = Paths.get(name); + final Path path = Path.of(name); return Files.newOutputStream(path); } + @Override public final void lock(final String name) throws IOException { } + @Override public final void unlock(final String name) { } + @Override public final void markUnimportant(final String name) { } + @Override public final String[] children(final String f) { final File file = new File(f); return file.list(); } + @Override public final void createFolder(final String name) throws IOException { final File file = new File(name); if (!file.mkdirs()) { @@ -1020,6 +1035,7 @@ public final void createFolder(final String name) throws IOException { } } + @Override public final void createData(final String name) throws IOException { final File file = new File(name); if (!file.createNewFile()) { @@ -1027,6 +1043,7 @@ public final void createData(final String name) throws IOException { } } + @Override public final void rename(final String oldName, final String newName) throws IOException { final File file = new File(oldName); final File dest = new File(newName); @@ -1036,6 +1053,7 @@ public final void rename(final String oldName, final String newName) throws IOEx } } + @Override public final void delete(final String name) throws IOException { final File file = new File(name); final boolean isDeleted = (file.isFile()) ? deleteFile(file) : deleteFolder(file); diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/FileObj.java b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/FileObj.java index de4faf98379f..c8f2a6ff5a17 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/FileObj.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/FileObj.java @@ -54,7 +54,7 @@ */ public class FileObj extends BaseFileObj { static final long serialVersionUID = -1133540210876356809L; - private static final MutualExclusionSupport MUT_EXCL_SUPPORT = new MutualExclusionSupport(); + private static final MutualExclusionSupport MUT_EXCL_SUPPORT = new MutualExclusionSupport<>(); private long lastModified = -1; private boolean realLastModifiedCached; private static final Logger LOGGER = Logger.getLogger(FileObj.class.getName()); @@ -70,6 +70,7 @@ protected boolean noFolderListeners() { return p == null ? true : p.noFolderListeners(); } + @Override public OutputStream getOutputStream(final FileLock lock) throws IOException { ProvidedExtensions extensions = getProvidedExtensions(); File file = getFileName().getFile(); @@ -224,7 +225,7 @@ public void close() throws IOException { closeableReference.close(); } - FileNotFoundException fex = null; + FileNotFoundException fex; if (!FileChangedManager.getInstance().exists(f)) { fex = (FileNotFoundException)new FileNotFoundException(e.getLocalizedMessage()).initCause(e); } else if (!f.canRead()) { @@ -281,19 +282,23 @@ final void setLastModified(long lastModified, File forFile, boolean readOnly) { } + @Override public final FileObject createFolder(final String name) throws IOException { throw new IOException(getPath());//isn't directory - cannot create neither file nor folder } + @Override public final FileObject createData(final String name, final String ext) throws IOException { throw new IOException(getPath());//isn't directory - cannot create neither file nor folder } + @Override public final FileObject[] getChildren() { return new FileObject[]{};//isn't directory - no children } + @Override public final FileObject getFileObject(final String name, final String ext) { return null; } @@ -306,6 +311,7 @@ public boolean isValid() { return retval && super.isValid(); } + @Override protected void setValid(boolean valid) { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "setValid: " + valid + " (" + this + ")", new Exception("Stack trace")); //NOI18N @@ -319,6 +325,7 @@ protected void setValid(boolean valid) { } } + @Override public final boolean isFolder() { return false; } @@ -414,6 +421,7 @@ public final boolean isLocked() { return l != null && l.isValid(); } + @Override final boolean checkLock(final FileLock lock) throws IOException { final File f = getFileName().getFile(); return ((lock instanceof LockForFile) && Utils.equals(((LockForFile) lock).getFile(), f)); @@ -461,18 +469,12 @@ private void setLastModified(File file, boolean readOnly) { if (lastMod == 0) { lastMod = 1; } - } catch (UnsupportedOperationException ex) { - if (file.exists()) { - lastMod = 1; - } - } catch (SecurityException ex) { + } catch (UnsupportedOperationException | SecurityException ex) { if (file.exists()) { lastMod = 1; } - } catch (IOException ex) { + } catch (IOException | InvalidPathException ex) { // lastMod stays 0, the file is invalid. - } catch (InvalidPathException ex) { - // lastMod stays 0, the path is invalid. } } setLastModified(lastMod, file, readOnly); diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/FileObjectFactory.java b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/FileObjectFactory.java index 4328f9966b58..362164ce201b 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/FileObjectFactory.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/FileObjectFactory.java @@ -52,38 +52,31 @@ import org.openide.util.Mutex; import org.openide.util.BaseUtilities; +import static org.netbeans.modules.masterfs.filebasedfs.naming.FileNaming.ID; + /** * @author Radek Matous */ public final class FileObjectFactory { - public static final Map AllFactories = new HashMap(); + public static final Map AllFactories = new HashMap<>(); public static boolean WARNINGS = true; + + // values are Reference or List> for ID conflicts + // if a BaseFileObj is no longer strongly reachable it shall dissappear from this Map //@GuardedBy("allIBaseLock") - final Map allIBaseFileObjects = new WeakHashMap(); + final Map allIBaseFileObjects = new WeakHashMap<>(); + final ReadWriteLock allIBaseLock = new ReentrantReadWriteLock(); - private BaseFileObj root; + private final BaseFileObj root; private static final Logger LOG_REFRESH = Logger.getLogger("org.netbeans.modules.masterfs.REFRESH"); // NOI18N public static enum Caller { ToFileObject, GetFileObject, GetChildern, GetParent, Refresh, Others; boolean asynchFire() { - if (this == Refresh || this == Others) { - return false; - } else { - return true; - } + return this != Refresh && this != Others; } } - - private FileObjectFactory(final File rootFile) { - this(new FileInfo(rootFile)); - } - - private FileObjectFactory(final FileInfo fInfo) { - this(fInfo, null); - } - private FileObjectFactory(FileInfo fInfo, Object msg) { final BaseFileObj realRoot = create(fInfo); if (realRoot == null) { // #252580 @@ -100,7 +93,7 @@ public static FileObjectFactory getInstance(final File file) { } public static FileObjectFactory getInstance(final File file, boolean addMising) { - FileObjectFactory retVal = null; + FileObjectFactory retVal; final FileInfo rootInfo = new FileInfo(file).getRoot(); final File rootFile = rootInfo.getFile(); @@ -123,7 +116,7 @@ public static FileObjectFactory getInstance(final File file, boolean addMising) public static Collection getInstances() { synchronized (FileObjectFactory.AllFactories) { - return new ArrayList(AllFactories.values()); + return new ArrayList<>(AllFactories.values()); } } @@ -139,27 +132,24 @@ public static int getFactoriesSize() { } private List existingFileObjects() { - List list = new ArrayList(); + List list = new ArrayList<>(); allIBaseLock.readLock().lock(); try { list.addAll(allIBaseFileObjects.values()); } finally { allIBaseLock.readLock().unlock(); } - List res = new ArrayList(); + List res = new ArrayList<>(); for (Object obj : list) { Collection all; if (obj instanceof Reference) { - all = Collections.singleton(obj); + all = List.of(obj); } else { - all = (List)obj; + all = (List)obj; // TODO iteration without read lock? } - for (Object r : all) { - Reference ref = (Reference)r; - Object fo = ref == null ? null : ref.get(); - if (fo instanceof FileObject) { - res.add((FileObject)fo); + if (r instanceof Reference ref && ref.get() instanceof FileObject fo) { + res.add(fo); } } } @@ -255,8 +245,8 @@ private void printWarning(File file) { } private BaseFileObj issueIfExist(File file, Caller caller, final FileObject parent, FileNaming child, int initTouch, boolean asyncFire, boolean onlyExisting) { - boolean exist = false; - BaseFileObj foForFile = null; + boolean exist; + BaseFileObj foForFile; Integer realExists = initTouch; final FileChangedManager fcb = FileChangedManager.getInstance(); @@ -352,9 +342,9 @@ private BaseFileObj issueIfExist(File file, Caller caller, final FileObject pare } if (!exist) { switch (caller) { - case GetParent: + case GetParent -> { //guarantee issuing parent - BaseFileObj retval = null; + BaseFileObj retval; if (foForFile != null && !foForFile.isRoot()) { retval = foForFile; } else { @@ -369,14 +359,15 @@ private BaseFileObj issueIfExist(File file, Caller caller, final FileObject pare } assert checkCacheState(exist, file, caller); return retval; - case ToFileObject: + } + case ToFileObject -> { //guarantee issuing for existing file exist = touchExists(file, realExists); if (exist && parent != null && parent.isValid()) { refreshFromGetter(parent,asyncFire); } assert checkCacheState(exist, file, caller); - break; + } } } //ratio 59993/507 (means 507 touches for 59993 calls) @@ -391,18 +382,17 @@ private BaseFileObj issueIfExist(File file, Caller caller, final FileObject pare } } + @SuppressWarnings("AssignmentToMethodParameter") private static boolean touchExists(File f, Integer state) { if (state == -1) { state = FileChangedManager.getInstance().exists(f) ? 1 : 0; } assert state != -1; - return (state == 1) ? true : false; + return state == 1; } private BaseFileObj getOrCreate(final FileInfo fInfo) { - BaseFileObj retVal = null; File f = fInfo.getFile(); - boolean issue45485 = fInfo.isWindows() && f.getName().endsWith(".") && !f.getName().matches("[.]{1,2}");//NOI18N if (issue45485) { File f2 = FileUtil.normalizeFile(f); @@ -413,7 +403,7 @@ private BaseFileObj getOrCreate(final FileInfo fInfo) { } allIBaseLock.writeLock().lock(); try { - retVal = this.getCachedOnly(f); + BaseFileObj retVal = this.getCachedOnly(f); if (retVal == null || !retVal.isValid()) { final File parent = f.getParentFile(); if (parent != null) { @@ -421,7 +411,6 @@ private BaseFileObj getOrCreate(final FileInfo fInfo) { } else { retVal = this.getRoot(); } - } return retVal; } finally { @@ -430,7 +419,7 @@ private BaseFileObj getOrCreate(final FileInfo fInfo) { } void invalidateSubtree(BaseFileObj root, boolean fire, boolean expected) { - List notify = fire ? new ArrayList() : Collections.emptyList(); + List notify = fire ? new ArrayList<>() : List.of(); allIBaseLock.writeLock().lock(); try { for (FileNaming fn : NamingFactory.findSubTree(root.getFileName())) { @@ -496,29 +485,23 @@ private Set collectForRefresh(boolean noRecListeners) { allIBaseLock.writeLock().lock(); try { all2Refresh = Collections.newSetFromMap(new WeakHashMap<>(allIBaseFileObjects.size() * 3 + 11)); - final Iterator it = allIBaseFileObjects.values().iterator(); - while (it.hasNext()) { - final Object obj = it.next(); - if (obj instanceof List) { - for (Iterator iterator = ((List) obj).iterator(); iterator.hasNext();) { + for (Object obj : allIBaseFileObjects.values()) { + if (obj instanceof Reference item) { + @SuppressWarnings("unchecked") + Reference ref = (Reference) item; + BaseFileObj fo = shallBeChecked(ref != null ? ref.get() : null, noRecListeners); + if (fo != null) { + all2Refresh.add(fo); + } + } else if (obj instanceof List list) { + for (Object item : list) { @SuppressWarnings("unchecked") - WeakReference ref = (WeakReference) iterator.next(); - BaseFileObj fo = shallBeChecked( - ref != null ? ref.get() : null, noRecListeners - ); + Reference ref = (Reference) item; + BaseFileObj fo = shallBeChecked(ref != null ? ref.get() : null, noRecListeners); if (fo != null) { all2Refresh.add(fo); } } - } else { - @SuppressWarnings("unchecked") - final WeakReference ref = (WeakReference) obj; - BaseFileObj fo = shallBeChecked( - ref != null ? ref.get() : null, noRecListeners - ); - if (fo != null) { - all2Refresh.add(fo); - } } } } finally { @@ -533,7 +516,7 @@ private BaseFileObj shallBeChecked(BaseFileObj fo, boolean noRecListeners) { FolderObj p = (FolderObj) (fo instanceof FolderObj ? fo : fo.getExistingParent()); if (p != null && Watcher.isWatched(fo)) { LOG_REFRESH.log(Level.FINER, "skip: {0}", fo); - fo = null; + return null; } } return fo; @@ -604,40 +587,29 @@ public static boolean isParentOf(final File dir, final File file) { } public final void rename(Set changeId) { - final Map toRename = new HashMap(); + Map toRename = new HashMap<>(); allIBaseLock.writeLock().lock(); try { - final Iterator> it = allIBaseFileObjects.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry entry = it.next(); - final Object obj = entry.getValue(); - final Integer key = entry.getKey(); - if (!(obj instanceof List)) { - @SuppressWarnings("unchecked") - final WeakReference ref = (WeakReference) obj; - - final BaseFileObj fo = (ref != null) ? ref.get() : null; - if (changeId.contains(fo)) { + for (Map.Entry entry : allIBaseFileObjects.entrySet()) { + Object obj = entry.getValue(); + ID key = entry.getKey(); + if (obj instanceof Reference ref) { + if (ref.get() instanceof BaseFileObj fo && changeId.contains(fo)) { toRename.put(key, fo); } - } else { - for (Iterator iterator = ((List) obj).iterator(); iterator.hasNext();) { - @SuppressWarnings("unchecked") - WeakReference ref = (WeakReference) iterator.next(); - final BaseFileObj fo = (ref != null) ? ref.get() : null; - if (changeId.contains(fo)) { + } else if (obj instanceof List list) { + for (Object item : list) { + if (item instanceof Reference ref + && ref.get() instanceof BaseFileObj fo && changeId.contains(fo)) { toRename.put(key, ref); } } - } } - - for (Map.Entry entry : toRename.entrySet()) { - Integer key = entry.getKey(); + for (Map.Entry entry : toRename.entrySet()) { + ID key = entry.getKey(); Object previous = allIBaseFileObjects.remove(key); - if (previous instanceof List) { - List list = (List) previous; + if (previous instanceof List list) { list.remove(entry.getValue()); allIBaseFileObjects.put(key, previous); } else { @@ -653,94 +625,73 @@ public final void rename(Set changeId) { public final BaseFileObj getCachedOnly(final File file) { return getCachedOnly(file, true); } - public final BaseFileObj getCachedOnly(final File file, boolean checkExtension) { - BaseFileObj retval; - final Integer id = NamingFactory.createID(file); + + public final BaseFileObj getCachedOnly(File file, boolean checkExtension) { + BaseFileObj retval = null; + ID id = NamingFactory.createID(file); allIBaseLock.readLock().lock(); try { - final Object value = allIBaseFileObjects.get(id); - if (value instanceof Reference) { - retval = getReference(Collections.nCopies(1, value), file); - } else { - retval = getReference((List) value, file); + Object value = allIBaseFileObjects.get(id); + if (value instanceof Reference ref) { + retval = getReference(List.of(ref), file); + } else if (value instanceof List list) { + retval = getReference(list, file); } } finally { allIBaseLock.readLock().unlock(); } if (retval != null && checkExtension) { - if (!file.getName().equals(retval.getNameExt())) { - if (!Utils.equals(file, retval.getFileName().getFile())) { - retval = null; - } + if (!file.getName().equals(retval.getNameExt()) && !Utils.equals(file, retval.getFileName().getFile())) { + retval = null; } } return retval; } - private static BaseFileObj getReference(final List list, final File file) { - BaseFileObj retVal = null; - if (list != null) { - for (int i = 0; retVal == null && i < list.size(); i++) { - Object item = list.get(i); - if (!(item instanceof Reference)) { - continue; - } - final Object ce = ((Reference)item).get(); - if (!(ce instanceof BaseFileObj)) { - continue; - } - final BaseFileObj cachedElement = (BaseFileObj)ce; - if (cachedElement != null && cachedElement.getFileName().getFile().compareTo(file) == 0) { - retVal = cachedElement; - } + private static BaseFileObj getReference(List list, File file) { + for (Object item : list) { + if (item instanceof Reference ref && ref.get() instanceof BaseFileObj cached + && cached.getFileName().getFile().compareTo(file) == 0) { + return cached; } } - return retVal; + return null; } - private BaseFileObj putInCache(final BaseFileObj newValue, final Integer id) { + @SuppressWarnings("unchecked") + private BaseFileObj putInCache(BaseFileObj newValue, ID id) { allIBaseLock.writeLock().lock(); try { - final WeakReference newRef = new WeakReference(newValue); - final Object listOrReference = allIBaseFileObjects.put(id, newRef); - - if (listOrReference != null) { - if (listOrReference instanceof List) { - @SuppressWarnings("unchecked") - List> list = (List>) listOrReference; - list.add(newRef); - allIBaseFileObjects.put(id, listOrReference); - } else { - assert (listOrReference instanceof WeakReference); - @SuppressWarnings("unchecked") - final Reference oldRef = (Reference) listOrReference; - BaseFileObj oldValue = (oldRef != null) ? oldRef.get() : null; - - if (oldValue != null && !newValue.getFileName().equals(oldValue.getFileName())) { - final List> l = new ArrayList>(); - l.add(oldRef); - l.add(newRef); - allIBaseFileObjects.put(id, l); - } - } + WeakReference newRef = new WeakReference<>(newValue); + Object listOrReference = allIBaseFileObjects.put(id, newRef); + + if (listOrReference instanceof Reference oldRef + && oldRef.get() instanceof BaseFileObj oldValue + && !newValue.getFileName().equals(oldValue.getFileName())) { + List> list = new ArrayList<>(); + list.add((Reference) oldRef); + list.add(newRef); + allIBaseFileObjects.put(id, list); + } else if (listOrReference instanceof List) { + ((List>) listOrReference).add(newRef); + allIBaseFileObjects.put(id, listOrReference); } } finally { allIBaseLock.writeLock().unlock(); } - return newValue; } @Override public String toString() { - List list = new ArrayList(); + List list = new ArrayList<>(); allIBaseLock.readLock().lock(); try { list.addAll(allIBaseFileObjects.values()); } finally { allIBaseLock.readLock().unlock(); } - List l2 = new ArrayList(); + List l2 = new ArrayList<>(); for (Iterator it = list.iterator(); it.hasNext();) { @SuppressWarnings("unchecked") Reference ref = (Reference) it.next(); @@ -753,7 +704,7 @@ public String toString() { } public static synchronized Map factories() { - return new HashMap(AllFactories); + return new HashMap<>(AllFactories); } public boolean isWarningEnabled() { @@ -765,8 +716,6 @@ public static void reinitForTests() { FileObjectFactory.AllFactories.clear(); } - - public final BaseFileObj getValidFileObject(final File f, FileObjectFactory.Caller caller, boolean onlyExisting) { final BaseFileObj retVal = (getFileObject(new FileInfo(f), caller, onlyExisting)); if (onlyExisting) { @@ -784,11 +733,8 @@ void refresh(RefreshSlow slow, boolean expected) { } final void refresh(final RefreshSlow slow, final boolean ignoreRecursiveListeners, final boolean expected) { Statistics.StopWatch stopWatch = Statistics.getStopWatch(Statistics.REFRESH_FS); - final Runnable r = new Runnable() { - @Override - public void run() { - refreshAll(slow, ignoreRecursiveListeners, expected); - } + final Runnable r = () -> { + refreshAll(slow, ignoreRecursiveListeners, expected); }; stopWatch.start(); @@ -796,12 +742,9 @@ public void run() { if (slow != null) { FileBasedFileSystem.runAsInconsistent(r); } else { - FileBasedFileSystem.getInstance().runAtomicAction(new FileSystem.AtomicAction() { - @Override - public void run() throws IOException { - FileBasedFileSystem.runAsInconsistent(r); - } - }); + FileBasedFileSystem.getInstance().runAtomicAction(() -> + FileBasedFileSystem.runAsInconsistent(r) + ); } } catch (IOException iex) {/*method refreshAll doesn't throw IOException*/ @@ -831,16 +774,13 @@ public void run() throws IOException { final void refreshFor(final RefreshSlow slow, final boolean ignoreRecursiveListeners, final File... files) { Statistics.StopWatch stopWatch = Statistics.getStopWatch(Statistics.REFRESH_FS); - final Runnable r = new Runnable() { - @Override - public void run() { - Set all2Refresh = collectForRefresh(ignoreRecursiveListeners); - refresh(all2Refresh, slow, files); - if (LOG_REFRESH.isLoggable(Level.FINER)) { - LOG_REFRESH.log(Level.FINER, "Refresh for {0} objects", all2Refresh.size()); - for (BaseFileObj baseFileObj : all2Refresh) { - LOG_REFRESH.log(Level.FINER, " {0}", baseFileObj); - } + final Runnable r = () -> { + Set all2Refresh = collectForRefresh(ignoreRecursiveListeners); + refresh(all2Refresh, slow, files); + if (LOG_REFRESH.isLoggable(Level.FINER)) { + LOG_REFRESH.log(Level.FINER, "Refresh for {0} objects", all2Refresh.size()); + for (BaseFileObj baseFileObj : all2Refresh) { + LOG_REFRESH.log(Level.FINER, " {0}", baseFileObj); } } }; @@ -849,12 +789,9 @@ public void run() { if (slow != null) { FileBasedFileSystem.runAsInconsistent(r); } else { - FileBasedFileSystem.getInstance().runAtomicAction(new FileSystem.AtomicAction() { - @Override - public void run() throws IOException { - FileBasedFileSystem.runAsInconsistent(r); - } - }); + FileBasedFileSystem.getInstance().runAtomicAction(() -> + FileBasedFileSystem.runAsInconsistent(r) + ); } } catch (IOException iex) {/*method refreshAll doesn't throw IOException*/ @@ -882,8 +819,8 @@ public void run() throws IOException { Statistics.REFRESH_FILE.reset(); } - private static class AsyncRefreshAtomicAction implements FileSystem.AtomicAction { - private FileObject fo; + private static class AsyncRefreshAtomicAction implements FileSystem.AtomicAction { + private final FileObject fo; AsyncRefreshAtomicAction(FileObject fo) { this.fo = fo; } @@ -894,7 +831,7 @@ public void run() throws IOException { } - private void refreshFromGetter(final FileObject parent,boolean asyncFire) { + private void refreshFromGetter(final FileObject parent, boolean asyncFire) { try { if (asyncFire) { FileUtil.runAtomicAction(new AsyncRefreshAtomicAction(parent)); diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/FileObjectKeeper.java b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/FileObjectKeeper.java index 9e6054a4b5e9..ae2468f3fa52 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/FileObjectKeeper.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/FileObjectKeeper.java @@ -65,7 +65,7 @@ public FileObjectKeeper(FolderObj root) { public synchronized void addRecursiveListener(FileChangeListener fcl) { if (listeners == null) { - listeners = new CopyOnWriteArraySet(); + listeners = new CopyOnWriteArraySet<>(); } LOG.log(Level.FINEST, "addRecursiveListener for {0} isEmpty: {1}", new Object[]{root, listeners.isEmpty()}); if (listeners.isEmpty()) { @@ -80,10 +80,7 @@ public synchronized void addRecursiveListener(FileChangeListener fcl) { } try { listenToAll(stop, filter); - } catch (Error e) { - LOG.log(Level.WARNING, null, e); - throw e; - } catch (RuntimeException e) { + } catch (Error | RuntimeException e) { LOG.log(Level.WARNING, null, e); throw e; } @@ -100,10 +97,7 @@ public synchronized void removeRecursiveListener(FileChangeListener fcl) { if (listeners.isEmpty()) { try { listenNoMore(); - } catch (Error e) { - LOG.log(Level.WARNING, null, e); - throw e; - } catch (RuntimeException e) { + } catch (Error | RuntimeException e) { LOG.log(Level.WARNING, null, e); throw e; } @@ -122,7 +116,7 @@ public List init(long previous, FileObjectFactory factory, boolean expecte } File file = Watcher.wrap(root.getFileName().getFile(), root); - List arr = new ArrayList(); + List arr = new ArrayList<>(); long ts = root.getProvidedExtensions().refreshRecursively(file, previous, arr); try { for (File f : arr) { @@ -176,8 +170,7 @@ private void listenTo(FileObject fo, boolean add, Collection child Set k; if (add) { fo.addFileChangeListener(this); - if (fo instanceof FolderObj) { - FolderObj folder = (FolderObj)fo; + if (fo instanceof FolderObj folder) { folder.getKeeper(children); folder.getChildren(); assert Thread.holdsLock(FileObjectKeeper.this); @@ -196,7 +189,7 @@ private void listenTo(FileObject fo, boolean add, Collection child private void listenToAll(Callable stop, FileFilter filter) { assert Thread.holdsLock(FileObjectKeeper.this); assert kept == null : "Already listening to " + kept + " now requested for " + root; - kept = new HashSet(); + kept = new HashSet<>(); listenToAllRecursion(root, null, stop, filter, 0); } @@ -224,7 +217,7 @@ private boolean listenToAllRecursion(FolderObj obj, new Object[] {RECURSION_LIMIT, obj}); return true; } - List it = new ArrayList(); + List it = new ArrayList<>(); listenTo(obj, true, it); FileObjectFactory factory = knownFactory; for (File f : it) { @@ -237,8 +230,7 @@ private boolean listenToAllRecursion(FolderObj obj, } FileObject fo = factory.getValidFileObject(f, Caller.Others, true); LOG.log(Level.FINEST, "listenToAll, check {0} for stop {1}", new Object[] { fo, stop }); - if (fo instanceof FolderObj) { - FolderObj child = (FolderObj) fo; + if (fo instanceof FolderObj child) { if (filter != null && !filter.accept(child.getFileName().getFile())) { continue; } @@ -279,8 +271,7 @@ private void listenNoMore() { public void fileFolderCreated(FileEvent fe) { Collection arr = listeners; final FileObject folder = fe.getFile(); - if (folder instanceof FolderObj) { - FolderObj obj = (FolderObj)folder; + if (folder instanceof FolderObj obj) { synchronized (this) { fileFolderCreatedRecursion(obj, null); } @@ -307,7 +298,7 @@ public void fileFolderCreated(FileEvent fe) { */ private void fileFolderCreatedRecursion(FolderObj obj, FileObjectFactory knownFactory) { - List it = new ArrayList(); + List it = new ArrayList<>(); listenTo(obj, true, it); FileObjectFactory factory = knownFactory; for (File f : it) { @@ -315,8 +306,8 @@ private void fileFolderCreatedRecursion(FolderObj obj, factory = FileObjectFactory.getInstance(f); } FileObject fo = factory.getValidFileObject(f, Caller.Others, true); - if (fo instanceof FolderObj) { - fileFolderCreatedRecursion((FolderObj) fo, factory); + if (fo instanceof FolderObj folderObj) { + fileFolderCreatedRecursion(folderObj, factory); } } } @@ -352,8 +343,7 @@ public void fileDeleted(FileEvent fe) { return; } - if (f instanceof FolderObj) { - FolderObj obj = (FolderObj)f; + if (f instanceof FolderObj obj) { synchronized (this) { assert Thread.holdsLock(FileObjectKeeper.this); if (kept != null) { diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/FolderObj.java b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/FolderObj.java index 3051e1028492..c313ab49b0ad 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/FolderObj.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/FolderObj.java @@ -75,6 +75,7 @@ public FolderObj(final File file, final FileNaming name) { //valid = true; } + @Override public final boolean isFolder() { return true; } @@ -105,6 +106,7 @@ public FileObject getFileObject(String relativePath, boolean onlyExisting) { } + @Override public final FileObject getFileObject(final String name, final String ext) { File file = BaseFileObj.getFile(getFileName().getFile(), name, ext); FileObjectFactory factory = getFactory(); @@ -115,8 +117,7 @@ public final FileObject getFileObject(final String name, final String ext) { protected boolean noFolderListeners() { if (noListeners()) { for (FileObject f : computeChildren(true)) { - if (f instanceof BaseFileObj) { - BaseFileObj bfo = (BaseFileObj)f; + if (f instanceof BaseFileObj bfo) { if (!bfo.noListeners()) { return false; } @@ -134,7 +135,7 @@ public final FileObject[] getChildren() { private FileObject[] computeChildren(boolean onlyExisting) { LOOP: for (int counter = 0; ; counter++) { - final Map results = new LinkedHashMap(); + final Map results = new LinkedHashMap<>(); final ChildrenCache childrenCache = getChildrenCache(); final Mutex.Privileged mutexPrivileged = childrenCache.getMutexPrivileged(); @@ -149,7 +150,7 @@ private FileObject[] computeChildren(boolean onlyExisting) { try { Set res = childrenCache.getChildren(counter >= 10, task); if (res != null) { - fileNames = new HashSet(res); + fileNames = new HashSet<>(res); } } finally { mutexPrivileged.exitWriteAccess(); @@ -190,7 +191,7 @@ private FileObject[] computeChildren(boolean onlyExisting) { results.put(fileName, fo); } } - return results.values().toArray(new FileObject[0]); + return results.values().toArray(FileObject[]::new); } } @@ -204,8 +205,8 @@ private static String dumpFileNaming(FileNaming fn) { append(Integer.toHexString(System.identityHashCode(fn))) .append("\n"); - if (fn instanceof FileName) { - ((FileName)fn).dumpCreation(sb); + if (fn instanceof FileName fileName) { + fileName.dumpCreation(sb); } return sb.toString(); } @@ -247,8 +248,8 @@ public final FileObject createFolderImpl(final String name) throws java.io.IOExc final FileObjectFactory factory = getFactory(); if (factory != null) { BaseFileObj exists = factory.getValidFileObject(folder2Create, FileObjectFactory.Caller.Others, true); - if (exists instanceof FolderObj) { - retVal = (FolderObj)exists; + if (exists instanceof FolderObj folderObj) { + retVal = folderObj; } else { FSException.io("EXC_CannotCreateFolder", folder2Create.getName(), getPath());// NOI18N } @@ -284,22 +285,14 @@ private void createFolder(final File folder2Create, final String name) throws IO Logger.getLogger("org.netbeans.modules.masterfs.filebasedfs.fileobjects.FolderObj").log(r); } + @Override public final FileObject createData(final String name, final String ext) throws java.io.IOException { - FSCallable c = new FSCallable() { - public FileObject call() throws IOException { - return createDataImpl(name, ext); - } - }; - return FileBasedFileSystem.runAsInconsistent(c); + return FileBasedFileSystem.runAsInconsistent(() -> createDataImpl(name, ext)); } + @Override public final FileObject createFolder(final String name) throws java.io.IOException { - FSCallable c = new FSCallable() { - public FileObject call() throws IOException { - return createFolderImpl(name); - } - }; - return FileBasedFileSystem.runAsInconsistent(c); + return FileBasedFileSystem.runAsInconsistent(() -> createFolderImpl(name)); } @@ -389,7 +382,7 @@ private void createData(final File file2Create) throws IOException { @Override public void delete(final FileLock lock, ProvidedExtensions.DeleteHandler deleteHandler) throws IOException { - final Deque all = new ArrayDeque(); + final Deque all = new ArrayDeque<>(); final File file = getFileName().getFile(); if (!deleteFile(file, all, getFactory(), deleteHandler)) { @@ -487,9 +480,9 @@ public void refreshImpl(final boolean expected, boolean fire) { } else if (ChildrenCache.REMOVED_CHILD.equals(operationId)) { if (newChild != null) { if (newChild.isValid()) { - if (newChild instanceof FolderObj) { + if (newChild instanceof FolderObj folderObj) { getProvidedExtensions().deletedExternally(newChild); - ((FolderObj)newChild).refreshImpl(expected, fire); + folderObj.refreshImpl(expected, fire); newChild.setValid(false); } else { newChild.setValid(false); @@ -582,6 +575,7 @@ private boolean deleteFile(final File file, final Deque all, final F return true; } + @Override protected void setValid(final boolean valid) { if (valid) { //I can't make valid fileobject when it was one invalidated @@ -598,19 +592,23 @@ public boolean isValid() { return valid && super.isValid(); } + @Override public final InputStream getInputStream() throws FileNotFoundException { throw new FileNotFoundException(getPath()); } + @Override public final OutputStream getOutputStream(final FileLock lock) throws IOException { throw new IOException(getPath()); } + @Override public final FileLock lock() throws IOException { return new FileLock(); } + @Override final boolean checkLock(final FileLock lock) throws IOException { return true; } diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/LockForFile.java b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/LockForFile.java index 1f4d03122637..659ac2c69c5b 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/LockForFile.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/LockForFile.java @@ -20,7 +20,6 @@ import java.io.File; import java.io.FileInputStream; -import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -29,7 +28,6 @@ import java.nio.file.Files; import java.util.Collection; import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Logger; import org.netbeans.modules.masterfs.filebasedfs.utils.FileChangedManager; import org.netbeans.modules.masterfs.filebasedfs.utils.Utils; import org.openide.filesystems.FileAlreadyLockedException; @@ -44,11 +42,9 @@ */ public class LockForFile extends FileLock { - private static final ConcurrentHashMap name2Namesakes = - new ConcurrentHashMap(); + private static final ConcurrentHashMap name2Namesakes = new ConcurrentHashMap<>(); private static final String PREFIX = ".LCK"; private static final String SUFFIX = "~"; - private static final Logger LOGGER = Logger.getLogger(LockForFile.class.getName()); private File file; private File lock; private boolean valid = false; @@ -159,12 +155,9 @@ boolean hardLock() throws IOException { File hardLock = getLock(); hardLock.getParentFile().mkdirs(); hardLock.createNewFile(); - OutputStream os = Files.newOutputStream(hardLock.toPath()); - try { + try (OutputStream os = Files.newOutputStream(hardLock.toPath())) { os.write(getFile().getAbsolutePath().getBytes()); return true; - } finally { - os.close(); } } @@ -264,8 +257,8 @@ final void releaseLock(boolean notify) { super.releaseLock(); if (notify) { FileObject fo = FileUtil.toFileObject(FileUtil.normalizeFile(file)); - if (fo instanceof BaseFileObj) { - ((BaseFileObj) fo).getProvidedExtensions().fileUnlocked(fo); + if (fo instanceof BaseFileObj baseFileObj) { + baseFileObj.getProvidedExtensions().fileUnlocked(fo); } } } @@ -282,7 +275,8 @@ private LockForFile putInstance(File file, LockForFile lock) throws IOException hardLock(); lock.hardLock(); } - Reference old = putIfAbsent(file, new WeakReference(lock)); + // don't change to computeIfAbsent() since it would hold a reference to lock + Reference old = putIfAbsent(file, new WeakReference<>(lock)); return (old != null) ? null : lock; } diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/MutualExclusionSupport.java b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/MutualExclusionSupport.java index a86ecb404e73..e29e0493c7e1 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/MutualExclusionSupport.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/MutualExclusionSupport.java @@ -38,8 +38,8 @@ public final class MutualExclusionSupport { private static final int TRIES = Integer.getInteger( //#229903 "org.netbeans.modules.masterfs.mutualexclusion.tries", 10); //NOI18N - private final Map> exclusive = Collections.synchronizedMap(new WeakHashMap>()); - private final Map> shared = Collections.synchronizedMap(new WeakHashMap>()); + private final Map> exclusive = Collections.synchronizedMap(new WeakHashMap<>()); + private final Map> shared = Collections.synchronizedMap(new WeakHashMap<>()); public MutualExclusionSupport() { } @@ -144,7 +144,7 @@ public final class Closeable { private Closeable(final K key, final boolean isShared) { this.isShared = isShared; - this.keyRef = new WeakReference(key); + this.keyRef = new WeakReference<>(key); assert populateStack(); } diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/RefreshSlow.java b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/RefreshSlow.java index c8eba830de2b..e9993155f2f4 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/RefreshSlow.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/RefreshSlow.java @@ -31,7 +31,7 @@ final class RefreshSlow extends AtomicBoolean implements Runnable { private BaseFileObj preferrable; private int size; private int index; - private boolean ignoreRecursiveListener; + private final boolean ignoreRecursiveListener; public RefreshSlow() { super(); @@ -80,16 +80,16 @@ void progress(int add, FileObject obj) { arr[4] = preferrable.getExistingParent(); } ref.setSource(arr); - if (arr[4] instanceof BaseFileObj) { - preferrable = (BaseFileObj)arr[4]; + if (arr[4] instanceof BaseFileObj baseFileObj) { + preferrable = baseFileObj; } } } @Override public boolean equals(Object obj) { - if (obj instanceof ActionEvent) { - this.ref = (ActionEvent)obj; + if (obj instanceof ActionEvent actionEvent) { + this.ref = actionEvent; } return super.equals(obj); } diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/ReplaceForSerialization.java b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/ReplaceForSerialization.java index a4de15e4ec4a..5346379c14db 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/ReplaceForSerialization.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/ReplaceForSerialization.java @@ -45,7 +45,7 @@ public ReplaceForSerialization(final File file) { public final Object readResolve() { final File file = new File(absolutePath); - final FileObject retVal = FileBasedFileSystem.getInstance().getFileObject(file); + final FileObject retVal = FileBasedFileSystem.getFileObject(file); return (retVal != null) ? retVal : new Invalid (file); } @@ -58,12 +58,15 @@ public void delete(FileLock lock, ProvidedExtensions.IOHandler io) throws IOExce throw new IOException(getPath()); } + @Override boolean checkLock(FileLock lock) throws IOException { return false; } + @Override protected void setValid(boolean valid) {} + @Override public boolean isFolder() { return false; } @@ -73,38 +76,47 @@ public boolean isFolder() { * * @return true if the file object is valid */ + @Override public boolean isValid() { return false; } + @Override public InputStream getInputStream() throws FileNotFoundException { throw new FileNotFoundException (getPath()); } + @Override public OutputStream getOutputStream(FileLock lock) throws IOException { throw new IOException (getPath()); } + @Override public FileLock lock() throws IOException { throw new IOException (getPath()); } + @Override public FileObject[] getChildren() { return new FileObject[] {}; } + @Override public FileObject getFileObject(String name, String ext) { return null; } + @Override public FileObject createFolder(String name) throws IOException { throw new IOException (getPath()); } + @Override public FileObject createData(String name, String ext) throws IOException { throw new IOException (getPath()); } + @Override public void refreshImpl(final boolean expected, boolean fire) { } diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/RootObj.java b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/RootObj.java index 8f7d15b262cb..8d70647c622b 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/RootObj.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/RootObj.java @@ -19,8 +19,6 @@ package org.netbeans.modules.masterfs.filebasedfs.fileobjects; -import java.awt.event.ActionEvent; -import java.beans.PropertyChangeEvent; import java.io.File; import org.netbeans.modules.masterfs.filebasedfs.utils.FSException; import org.openide.filesystems.*; @@ -46,34 +44,42 @@ public RootObj(final T realRoot) { this.realRoot = realRoot; } + @Override public final String getName() { return getRealRoot().getName();//NOI18N } + @Override public final String getExt() { return getRealRoot().getExt();//NOI18N } + @Override public final FileSystem getFileSystem() throws FileStateInvalidException { return getRealRoot().getFileSystem(); } + @Override public final FileObject getParent() { return null; } + @Override public final boolean isFolder() { return true; } + @Override public final boolean isData() { return !isFolder(); } + @Override public final Date lastModified() { return new Date(0); } + @Override public final boolean isRoot() { return true; } @@ -84,20 +90,24 @@ public final boolean isRoot() { * * @return true if the file object is valid */ + @Override public final boolean isValid() { return true; } + @Override public final void rename(final FileLock lock, final String name, final String ext) throws IOException { //throw new IOException(getPath()); FSException.io("EXC_CannotRenameRoot", getFileSystem().getDisplayName()); // NOI18N } + @Override public final void delete(final FileLock lock) throws IOException { //throw new IOException(getPath()); FSException.io("EXC_CannotDeleteRoot", getFileSystem().getDisplayName()); // NOI18N } + @Override public final Object getAttribute(final String attrName) { if (attrName.equals("SupportsRefreshForNoPublicAPI")) { return true; @@ -108,6 +118,7 @@ public final Object getAttribute(final String attrName) { return getRealRoot().getAttribute(attrName); } + @Override public final void setAttribute(final String attrName, final Object value) throws IOException { if ("request_for_refreshing_files_be_aware_this_is_not_public_api".equals(attrName) && (value instanceof File[])) {//NOI18N invokeRefreshFor(null, (File[])value); @@ -125,7 +136,7 @@ static void invokeRefreshFor(RefreshSlow slow, File[] files, boolean ignoreRecur File file = files[i]; files[i] = FileUtil.normalizeFile(file); } - Map> files2Factory = new HashMap>(); + Map> files2Factory = new HashMap<>(); Map roots2Factory = FileBasedFileSystem.factories(); Arrays.sort(files); for (File file : files) { @@ -137,7 +148,7 @@ static void invokeRefreshFor(RefreshSlow slow, File[] files, boolean ignoreRecur if (factory != null) { List lf = files2Factory.get(factory); if (lf == null) { - lf = new ArrayList(); + lf = new ArrayList<>(); files2Factory.put(factory, lf); } else { File tmp = file; @@ -175,7 +186,7 @@ static void invokeRefreshFor(RefreshSlow slow, File[] files, boolean ignoreRecur } } } else if (lf.size() > 1) { - final File[] arr = lf.toArray(new File[0]); + final File[] arr = lf.toArray(File[]::new); Arrays.sort(arr); factory.refreshFor(slow, ignoreRecursiveListeners, arr); } @@ -183,43 +194,53 @@ static void invokeRefreshFor(RefreshSlow slow, File[] files, boolean ignoreRecur } + @Override public final Enumeration getAttributes() { return getRealRoot().getAttributes(); } + @Override public final void addFileChangeListener(final FileChangeListener fcl) { getRealRoot().addFileChangeListener(fcl); } + @Override public final void removeFileChangeListener(final FileChangeListener fcl) { getRealRoot().removeFileChangeListener(fcl); } + @Override public final long getSize() { return 0; } + @Override public final InputStream getInputStream() throws FileNotFoundException { return getRealRoot().getInputStream(); } + @Override public final OutputStream getOutputStream(final FileLock lock) throws IOException { return getRealRoot().getOutputStream(lock); } + @Override public final FileLock lock() throws IOException { return getRealRoot().lock(); } @Deprecated + @Override public final void setImportant(final boolean b) { getRealRoot().setImportant(b); } + @Override public final FileObject[] getChildren() { return getRealRoot().getChildren(); } + @Override public final FileObject getFileObject(final String name, final String ext) { return getRealRoot().getFileObject(name, ext); } @@ -229,15 +250,18 @@ public final FileObject getFileObject(String relativePath) { return getRealRoot().getFileObject(relativePath); } + @Override public final FileObject createFolder(final String name) throws IOException { return getRealRoot().createFolder(name); } + @Override public final FileObject createData(final String name, final String ext) throws IOException { return getRealRoot().createData(name, ext); } @Deprecated + @Override public final boolean isReadOnly() { return getRealRoot().isReadOnly(); } diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/RootObjWindows.java b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/RootObjWindows.java index 9387aa54a302..18e2a63f181a 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/RootObjWindows.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/RootObjWindows.java @@ -39,14 +39,17 @@ public final class RootObjWindows extends FileObject { public RootObjWindows() { } + @Override public final String getName() { return "";//NOI18N } + @Override public final String getExt() { return "";//NOI18N } + @Override public final FileSystem getFileSystem() throws FileStateInvalidException { return FileBasedFileSystem.getInstance(); } @@ -57,22 +60,27 @@ public FileObject getFileObject(String relativePath) { } + @Override public final FileObject getParent() { return null; } + @Override public final boolean isFolder() { return true; } + @Override public final boolean isData() { return !isFolder(); } + @Override public final Date lastModified() { return new Date(0); } + @Override public final boolean isRoot() { return true; } @@ -83,69 +91,83 @@ public final boolean isRoot() { * * @return true if the file object is valid */ + @Override public final boolean isValid() { return true; } + @Override public final void rename(final FileLock lock, final String name, final String ext) throws IOException { //throw new IOException(getPath()); FSException.io("EXC_CannotRenameRoot", getFileSystem().getDisplayName()); // NOI18N } + @Override public final void delete(final FileLock lock) throws IOException { //throw new IOException(getPath()); FSException.io("EXC_CannotDeleteRoot", getFileSystem().getDisplayName()); // NOI18N } + @Override public final Object getAttribute(final String attrName) { return null; } + @Override public final void setAttribute(final String attrName, final Object value) throws IOException { throw new FileStateInvalidException(); // NOI18N } + @Override public final Enumeration getAttributes() { return Enumerations.empty(); } + @Override public final void addFileChangeListener(final FileChangeListener fcl) { //TODO: adding new FileBasedFS into allInstances should lead to firing event } + @Override public final void removeFileChangeListener(final FileChangeListener fcl) { //TODO: adding new FileBasedFS into allInstances should lead to firing event } + @Override public final long getSize() { return 0; } + @Override public final InputStream getInputStream() throws FileNotFoundException { throw new FileNotFoundException(); // NOI18N } + @Override public final OutputStream getOutputStream(final FileLock lock) throws IOException { throw new FileNotFoundException(); // NOI18N } + @Override public final FileLock lock() throws IOException { throw new FileStateInvalidException(); // NOI18N } + @Override public final void setImportant(final boolean b) { } + @Override public final FileObject[] getChildren() { Collection all = FileBasedFileSystem.factories().values(); - ArrayList rootChildren = new ArrayList(); + ArrayList rootChildren = new ArrayList<>(); for (FileObjectFactory fs : all) { BaseFileObj root = fs.getRoot(); if (root != null) { // #252580 rootChildren.add(root); } } - return rootChildren.toArray(new FileObject[0]); + return rootChildren.toArray(FileObject[]::new); } @Override @@ -182,14 +204,17 @@ private FileObject getFileObjectImpl(String name, String ext) { } + @Override public final FileObject createFolder(final String name) throws IOException { throw new FileStateInvalidException(); // NOI18N } + @Override public final FileObject createData(final String name, final String ext) throws IOException { throw new FileStateInvalidException(); // NOI18N } + @Override public final boolean isReadOnly() { return true; } diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/naming/FileName.java b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/naming/FileName.java index fb5e590437a7..98d49cb40254 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/naming/FileName.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/naming/FileName.java @@ -34,10 +34,10 @@ public class FileName implements FileNaming { private final CharSequence name; private final FileNaming parent; - private final Integer id; + private final ID id; private CharSequence currentName; - protected FileName(final FileNaming parent, final File file, Integer theKey) { + protected FileName(final FileNaming parent, final File file, ID theKey) { this.parent = parent; this.name = CharSequences.create(parseName(parent, file)); this.id = theKey == null ? NamingFactory.createID(file) : theKey; @@ -55,7 +55,7 @@ private static String parseName(final FileNaming parent, final File file) { @Override public FileNaming rename(String name, ProvidedExtensions.IOHandler handler) throws IOException { - boolean success = false; + boolean success; final File f = getFile(); if (FileChangedManager.getInstance().exists(f)) { @@ -93,13 +93,12 @@ public FileNaming rename(String name, ProvidedExtensions.IOHandler handler) thro return parent; } - public final @Override Integer getId() { + public final @Override ID getId() { return id; } public final @Override boolean equals(final Object obj) { - if (obj instanceof FileName ) { - FileName fn = (FileName)obj; + if (obj instanceof FileName fn) { if (obj.hashCode() != hashCode()) { return false; } @@ -120,7 +119,7 @@ public FileNaming rename(String name, ProvidedExtensions.IOHandler handler) thro } public final @Override int hashCode() { - return id.intValue(); + return id.value(); } public @Override boolean isFile() { @@ -134,27 +133,27 @@ public FileNaming rename(String name, ProvidedExtensions.IOHandler handler) thro void updateCase(String name) { assert String.CASE_INSENSITIVE_ORDER.compare(name, this.name.toString()) == 0: "Only case can be changed. Was: " + this.name + " name: " + name; final CharSequence value = CharSequences.create(name); - if (this.currentName instanceof Creation) { - ((Creation)this.currentName).delegate = value; + if (this.currentName instanceof Creation creation) { + creation.delegate = value; } else { this.currentName = value; } } public void dumpCreation(StringBuilder sb) { - if (this.currentName instanceof Creation) { + if (this.currentName instanceof Creation creation) { StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - ((Creation)this.currentName).printStackTrace(pw); - pw.close(); + try (PrintWriter pw = new PrintWriter(sw)) { + creation.printStackTrace(pw); + } sb.append(sw.toString()); } } final void recordCleanup(String msg) { Throwable ex = null; - if (this.currentName instanceof Creation) { - ex = ((Creation)this.currentName); + if (this.currentName instanceof Creation creation) { + ex = creation; } if (ex != null) { while (ex.getCause() != null) { diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/naming/FileNaming.java b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/naming/FileNaming.java index aedb5ad893e7..a701f846d5d9 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/naming/FileNaming.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/naming/FileNaming.java @@ -40,7 +40,15 @@ public interface FileNaming { boolean isFile(); boolean isDirectory(); - Integer getId(); + ID getId(); FileNaming rename(String name, ProvidedExtensions.IOHandler handler) throws IOException; + + + /// FileObject ID as identity object. + /// FileName and FileInfo objects may hold a strong reference to it. + /// Don't let it escape, since FileObjectFactory uses it as WeakHashMap key to track + /// the lifecycle of BaseFileObj instances. + public record ID(int value) {} + } diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/naming/FolderName.java b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/naming/FolderName.java index 114a51612fb8..28e611953a18 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/naming/FolderName.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/naming/FolderName.java @@ -28,11 +28,11 @@ * @author Radek Matous */ public class FolderName extends FileName { - private static Map fileCache = new WeakHashMap(); + private static Map fileCache = new WeakHashMap<>(); @SuppressWarnings("LeakingThisInConstructor") - FolderName(final FileNaming parent, final File file, Integer theKey) { + FolderName(final FileNaming parent, final File file, ID theKey) { super(parent, file, theKey); synchronized (FolderName.class) { FolderName.fileCache.put(this, file); @@ -64,9 +64,8 @@ void updateCase(String name) { static void freeCaches() { synchronized (FolderName.class) { - FolderName.fileCache = new WeakHashMap(); + FolderName.fileCache = new WeakHashMap<>(); } - } public @Override boolean isFile() { diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/naming/NameRef.java b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/naming/NameRef.java index 44051a71ff76..e81f51cc1cb8 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/naming/NameRef.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/naming/NameRef.java @@ -27,18 +27,18 @@ final class NameRef extends WeakReference { /** either reference to NameRef or to Integer as an index to names array */ private Object next; - static final ReferenceQueue QUEUE = new ReferenceQueue(); + static final ReferenceQueue QUEUE = new ReferenceQueue<>(); public NameRef(FileNaming referent) { super(referent, QUEUE); } - public Integer getIndex() { + public int getIndex() { assert Thread.holdsLock(NamingFactory.class); NameRef nr = this; while (nr != null) { - if (nr.next instanceof Integer) { - return (Integer) nr.next; + if (nr.next instanceof Integer integer) { + return integer; } nr = nr.next(); } @@ -94,7 +94,7 @@ final void skip(NameRef ref) { final Iterable disconnectAll() { assert Thread.holdsLock(NamingFactory.class); - List all = new ArrayList(); + List all = new ArrayList<>(); NameRef nr = this; while (nr != null) { NameRef nn = nr.next(); diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/naming/NamingFactory.java b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/naming/NamingFactory.java index 9d4a495fa06e..ef53e99e1621 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/naming/NamingFactory.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/naming/NamingFactory.java @@ -38,14 +38,14 @@ public static FileNaming fromFile(File file) { if (BaseUtilities.isWindows() && file.getPath().length() == 2 && file.getPath().charAt(1) == ':') { file = new File(file.getPath() + File.separator); } - final Deque queue = new ArrayDeque(); + final Deque queue = new ArrayDeque<>(); File current = file; while (current != null) { queue.addFirst(new FileInfo(current)); current = current.getParentFile(); } - List checkDirs = new ArrayList(); + List checkDirs = new ArrayList<>(); FileNaming fileName = null; final List list = new ArrayList<>(queue); for (int i = 0; i < list.size(); ) { @@ -97,7 +97,7 @@ public static FileNaming fromFile(final FileNaming parentFn, final File file, boolean ignoreCache, boolean canonicalName) { FileInfo info = new FileInfo(file); - List checkDirs = new ArrayList(); + List checkDirs = new ArrayList<>(); for (;;) { for (FileInfo fileInfo : checkDirs) { fileInfo.isDirectory(); @@ -134,7 +134,7 @@ public static synchronized FileNaming checkCaseSensitivity(final FileNaming chil * {@code fNaming} (before renaming). */ public static FileNaming[] rename (FileNaming fNaming, String newName, ProvidedExtensions.IOHandler handler) throws IOException { - final Collection all = new LinkedHashSet(); + final Collection all = new LinkedHashSet<>(); FileNaming newNaming = fNaming.rename(newName, handler); boolean retVal = newNaming != fNaming; @@ -161,7 +161,7 @@ private static FileNaming[] createArray(FileNaming first, } public static Collection findSubTree(FileNaming root) { - final Collection all = new LinkedHashSet(); + final Collection all = new LinkedHashSet<>(); synchronized (NamingFactory.class) { collectSubnames(root, all); } @@ -170,12 +170,12 @@ public static Collection findSubTree(FileNaming root) { private static void collectSubnames(FileNaming root, Collection all) { assert Thread.holdsLock(NamingFactory.class); - Collection not = new HashSet(names.length); + Collection not = new HashSet<>((int) Math.ceil(names.length / 0.75)); for (int i = 0; i < names.length; i++) { NameRef value = names[i]; while (value != null) { FileNaming fN = value.get(); - Deque above = new ArrayDeque(); + Deque above = new ArrayDeque<>(); for (FileNaming up = fN;;) { if (up == null || not.contains(up)) { not.addAll(above); @@ -193,8 +193,8 @@ private static void collectSubnames(FileNaming root, Collection all) } } - public static Integer createID(final File file) { - return Utils.hashCode(file); + public static FileNaming.ID createID(final File file) { + return new FileNaming.ID(Utils.hashCode(file)); } private static FileNaming registerInstanceOfFileNaming( FileNaming parentName, FileInfo file, FileType type, @@ -218,8 +218,8 @@ private static void rehash(int newSize) { if (fn == null) { continue; } - Integer id = createID(fn.getFile()); - int index = Math.abs(id) % arr.length; + FileNaming.ID id = createID(fn.getFile()); + int index = Math.abs(id.value()) % arr.length; NameRef prev = arr[index]; arr[index] = nr; if (prev == null) { @@ -246,8 +246,8 @@ private static FileNaming registerInstanceOfFileNaming( cleanQueue(); FileNaming retVal; - Integer key = createID(file.getFile()); - int index = Math.abs(key) % names.length; + FileNaming.ID key = createID(file.getFile()); + int index = Math.abs(key.value()) % names.length; NameRef ref = getReference(names[index], file.getFile()); FileNaming cachedElement = (ref != null) ? ref.get() : null; @@ -305,8 +305,8 @@ private static FileNaming registerInstanceOfFileNaming( for (;;) { if (nr.next() == ref) { FileNaming orig = ref.get(); - if (orig instanceof FileName) { - ((FileName)orig).recordCleanup( + if (orig instanceof FileName fileName) { + fileName.recordCleanup( "cachedElement: " + cachedElement + // NOI18N " ref: " + orig + // NOI18N " file: " + file + // NOI18N @@ -347,35 +347,30 @@ private static NameRef getReference(NameRef value, File f) { static enum FileType {file, directory, unknown} private static FileNaming createFileNaming( - final FileInfo f, Integer theKey, final FileNaming parentName, FileType type + final FileInfo f, FileNaming.ID theKey, final FileNaming parentName, FileType type ) { - FileName retVal = null; //TODO: check all tests for isFile & isDirectory if (type == FileType.unknown) { if (f.isDirectory()) { type = FileType.directory; } else { //important for resolving named pipes - type = FileType.file; + type = FileType.file; } } - switch(type) { - case file: - retVal = new FileName(parentName, f.getFile(), theKey); - break; - case directory: - retVal = new FolderName(parentName, f.getFile(), theKey); - break; - } - return retVal; + return switch(type) { + case file -> new FileName(parentName, f.getFile(), theKey); + case directory -> new FolderName(parentName, f.getFile(), theKey); + default -> null; + }; } - public static String dumpId(Integer id) { - return dump(id, null); + public static String dumpId(FileNaming.ID id) { + return dump(id.value(), null); } public static synchronized boolean isValid(FileNaming fn) { - int index = Math.abs(fn.getId()) % names.length; + int index = Math.abs(fn.getId().value()) % names.length; NameRef value = names[index]; while (value != null) { if (value.get() == fn) { @@ -419,8 +414,8 @@ private static void dumpFileNaming(StringBuilder sb, Object fn) { .append(Integer.toHexString(fn.hashCode())).append("@") .append(Integer.toHexString(System.identityHashCode(fn))) .append("\n"); - if (fn instanceof FileName) { - ((FileName)fn).dumpCreation(sb); + if (fn instanceof FileName fileName) { + fileName.dumpCreation(sb); } } diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/utils/FileChangedManager.java b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/utils/FileChangedManager.java index 4bad9f067cf7..138c3c8e7728 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/utils/FileChangedManager.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/utils/FileChangedManager.java @@ -321,7 +321,7 @@ private Integer remove(int id) { } private static int getKey(File f) { - return NamingFactory.createID(f); + return NamingFactory.createID(f).value(); } private static int getKey(String f) { return getKey(new File(f)); diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/utils/FileInfo.java b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/utils/FileInfo.java index 12ccd8226945..3ea439d51f2f 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/utils/FileInfo.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/utils/FileInfo.java @@ -39,7 +39,7 @@ public final class FileInfo { private int isUNC = -1; private int isConvertibleToFileObject = -1; - private Integer id = null; + private FileNaming.ID id = null; private FileInfo root = null; private final File file; @@ -190,7 +190,7 @@ public File getFile() { return file; } - public Integer getID() { + public FileNaming.ID getID() { if (id == null) { id = NamingFactory.createID(getFile()); } diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/providers/Attributes.java b/platform/masterfs/src/org/netbeans/modules/masterfs/providers/Attributes.java index 23d8bcbfa733..5c6a447b056d 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/providers/Attributes.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/providers/Attributes.java @@ -50,7 +50,7 @@ public class Attributes extends DefaultAttributes { private static DefaultAttributes sharedUserAttributes; private final String attributePrefix; - private AbstractFileSystem.List list; + private final AbstractFileSystem.List list; private static final boolean BACKWARD_COMPATIBILITY = false; private static File rootForAttributes; @@ -205,9 +205,7 @@ private DefaultAttributes getPreferedAttributes() { ExLocalFileSystem exLFs = null; try { exLFs = ExLocalFileSystem.getInstance(getRootForAttributes()); - } catch (PropertyVetoException e) { - Exceptions.printStackTrace(e); - } catch (IOException e) { + } catch (PropertyVetoException | IOException e) { Exceptions.printStackTrace(e); } sharedUserAttributes = exLFs.getAttributes(); diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/providers/BaseAnnotationProvider.java b/platform/masterfs/src/org/netbeans/modules/masterfs/providers/BaseAnnotationProvider.java index 9687524302c4..f35a68749d61 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/providers/BaseAnnotationProvider.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/providers/BaseAnnotationProvider.java @@ -36,7 +36,7 @@ */ public abstract class BaseAnnotationProvider { /** listeners */ - private List fsStatusListener = new ArrayList(); + private final List fsStatusListener = new ArrayList<>(); /** lock for modification of listeners */ private static final Object LOCK = new Object(); @@ -120,7 +120,7 @@ public final void removeFileStatusListener(FileStatusListener listener) { * @param event The event to be fired */ protected final void fireFileStatusChanged(FileStatusEvent event) { - List listeners = new ArrayList(); + List listeners = new ArrayList<>(); synchronized (LOCK) { listeners.addAll(fsStatusListener); } diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/providers/Notifier.java b/platform/masterfs/src/org/netbeans/modules/masterfs/providers/Notifier.java index 1fabf27590a3..a788f3167e3b 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/providers/Notifier.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/providers/Notifier.java @@ -85,6 +85,7 @@ protected void stop() throws IOException { } static { + @SuppressWarnings("unused") NotifierAccessor impl = new NotifierAccessor() { @Override protected KEY addWatch(Notifier n, String path) throws IOException { diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/providers/ProvidedExtensions.java b/platform/masterfs/src/org/netbeans/modules/masterfs/providers/ProvidedExtensions.java index f5a43da10d3e..f710d32823fd 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/providers/ProvidedExtensions.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/providers/ProvidedExtensions.java @@ -163,11 +163,17 @@ public interface DeleteHandler { } + @Override public void createSuccess(FileObject fo) {} + @Override public void createFailure(FileObject parent, String name, boolean isFolder) {} + @Override public void beforeCreate(FileObject parent, String name, boolean isFolder) {} + @Override public void deleteSuccess(FileObject fo) {} + @Override public void deleteFailure(FileObject fo) {} + @Override public void beforeDelete(FileObject fo) {} /** diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/watcher/NotifierKeyRef.java b/platform/masterfs/src/org/netbeans/modules/masterfs/watcher/NotifierKeyRef.java index d7a68a068119..55c1ae9df2fa 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/watcher/NotifierKeyRef.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/watcher/NotifierKeyRef.java @@ -55,7 +55,7 @@ public boolean equals(Object obj) { return true; } try { - NotifierKeyRef kr = (NotifierKeyRef) obj; + NotifierKeyRef kr = (NotifierKeyRef) obj; FileObject mine = get(); FileObject theirs = kr.get(); if (mine == null) { diff --git a/platform/masterfs/src/org/netbeans/modules/masterfs/watcher/Watcher.java b/platform/masterfs/src/org/netbeans/modules/masterfs/watcher/Watcher.java index 4b32f1ed7840..31867f1d66d5 100644 --- a/platform/masterfs/src/org/netbeans/modules/masterfs/watcher/Watcher.java +++ b/platform/masterfs/src/org/netbeans/modules/masterfs/watcher/Watcher.java @@ -20,7 +20,6 @@ package org.netbeans.modules.masterfs.watcher; import org.netbeans.modules.masterfs.providers.Notifier; -import java.awt.Image; import java.io.File; import java.io.IOException; import java.lang.ref.ReferenceQueue; @@ -54,7 +53,7 @@ }) public final class Watcher extends BaseAnnotationProvider { static final Logger LOG = Logger.getLogger(Watcher.class.getName()); - private static final Map MODIFIED = new WeakHashMap(); + private static final Map MODIFIED = new WeakHashMap<>(); private final Ext ext; public Watcher() { @@ -139,16 +138,14 @@ public static void shutdown() { if (isEnabled()) { try { ext().shutdown(); - } catch (IOException ex) { - LOG.log(Level.INFO, "Error on shutdown", ex); - } catch (InterruptedException ex) { + } catch (IOException | InterruptedException ex) { LOG.log(Level.INFO, "Error on shutdown", ex); } } } private Ext make(Notifier impl) { - return impl == null ? null : new Ext(impl); + return impl == null ? null : new Ext<>(impl); } final void clearQueue() throws IOException { @@ -199,7 +196,7 @@ private boolean isWatched(FileObject fo) { LOG.log(Level.INFO, "Exception while clearing the queue", ex); } synchronized (LOCK) { - NotifierKeyRef kr = new NotifierKeyRef(fo, null, null, impl); + NotifierKeyRef kr = new NotifierKeyRef<>(fo, null, null, impl); return getReferences().contains(kr); } } @@ -213,11 +210,8 @@ final void register(final FileObject fo) { } catch (IOException ex) { LOG.log(Level.INFO, "Exception while clearing the queue", ex); } - FileChangedManager.waitNowAndRun(new Runnable() { - @Override - public void run() { - registerSynchronized(fo); - } + FileChangedManager.waitNowAndRun(() -> { + registerSynchronized(fo); }); } @@ -228,13 +222,13 @@ public void run() { */ private void registerSynchronized(FileObject fo) { synchronized (LOCK) { - NotifierKeyRef kr = new NotifierKeyRef(fo, null, null, impl); + NotifierKeyRef kr = new NotifierKeyRef<>(fo, null, null, impl); if (getReferences().contains(kr)) { return; } try { - getReferences().add(new NotifierKeyRef(fo, NotifierAccessor.getDefault().addWatch(impl, fo.getPath()), REF, impl)); + getReferences().add(new NotifierKeyRef<>(fo, NotifierAccessor.getDefault().addWatch(impl, fo.getPath()), REF, impl)); } catch (IOException ex) { Level l = getLogLevelForRegisterException(fo); // XXX: handle resource overflow gracefully @@ -304,7 +298,7 @@ public int hashCode() { final void clearQueue() throws IOException { for (;;) { - NotifierKeyRef kr = (NotifierKeyRef)REF.poll(); + NotifierKeyRef kr = (NotifierKeyRef)REF.poll(); if (kr == null) { break; } @@ -322,9 +316,9 @@ final void clearQueue() throws IOException { String path = NotifierAccessor.getDefault().nextEvent(impl); LOG.log(Level.FINEST, "nextEvent: {0}", path); if (path == null) { // all dirty - Set set = new HashSet(); + Set set = new HashSet<>(); synchronized (LOCK) { - for (NotifierKeyRef kr : getReferences()) { + for (NotifierKeyRef kr : getReferences()) { final FileObject ref = kr.get(); if (ref != null) { set.add(ref); @@ -349,8 +343,6 @@ final void clearQueue() throws IOException { } } } - } catch (ThreadDeath td) { - throw td; } catch (InterruptedException ie) { if (!shutdown) { LOG.log(Level.INFO, "Interrupted", ie); diff --git a/platform/masterfs/test/unit/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/FileObjectFactorySizeTest.java b/platform/masterfs/test/unit/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/FileObjectFactorySizeTest.java index f99f04141968..0123045ab19c 100644 --- a/platform/masterfs/test/unit/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/FileObjectFactorySizeTest.java +++ b/platform/masterfs/test/unit/src/org/netbeans/modules/masterfs/filebasedfs/fileobjects/FileObjectFactorySizeTest.java @@ -59,6 +59,7 @@ public void testIssuingFileObject() throws IOException { //root + workdir assertEquals(2, fbs.getSize()); assertEquals(2, fbs.getSize()); + Reference rf = new WeakReference<>(workDir.getParent()); assertGC("", rf); assertNull(((BaseFileObj)workDir).getExistingParent());