diff --git a/apisupport.project/src/org/netbeans/modules/apisupport/project/api/LayerHandle.java b/apisupport.project/src/org/netbeans/modules/apisupport/project/api/LayerHandle.java --- a/apisupport.project/src/org/netbeans/modules/apisupport/project/api/LayerHandle.java +++ b/apisupport.project/src/org/netbeans/modules/apisupport/project/api/LayerHandle.java @@ -49,6 +49,8 @@ import java.io.InputStream; import java.io.OutputStream; import java.lang.ref.WeakReference; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -71,6 +73,7 @@ import org.openide.filesystems.FileUtil; import org.openide.filesystems.MultiFileSystem; import org.openide.filesystems.XMLFileSystem; +import org.openide.util.Exceptions; import org.openide.util.Parameters; import org.openide.util.Utilities; import org.openide.util.actions.SystemAction; @@ -301,6 +304,32 @@ public @Override void fileAttributeChanged(FileAttributeEvent fe) {} } + private static final SystemAction[] NO_ACTIONS = new SystemAction[0]; + + /** + * Extracts actions from a FileSystem that implements the old contract. + * + * @param fs the filesystem + * @return FD actions, or an empty array. + */ + private static SystemAction[] getFSActions(FileSystem fs) { + try { + Method m = fs.getClass().getMethod("getActions"); + return (SystemAction[])m.invoke(fs); + } catch (NoSuchMethodException ex) { + // OK, no such method exists + } catch (SecurityException ex) { + Exceptions.printStackTrace(ex); + } catch (IllegalAccessException ex) { + Exceptions.printStackTrace(ex); + } catch (IllegalArgumentException ex) { + Exceptions.printStackTrace(ex); + } catch (InvocationTargetException ex) { + Exceptions.printStackTrace(ex); + } + return NO_ACTIONS; + } + private final class SingleLayer extends FileSystem implements FileChangeListener { private final FileSystem explicit; SingleLayer(FileSystem explicit) { @@ -348,9 +377,9 @@ return this.explicit!=null?this.explicit.findResource(name):null; } - @Override +// @Override public SystemAction[] getActions() { - return this.explicit!=null?this.explicit.getActions():null; + return this.explicit!=null?getFSActions(this.explicit):null; } } diff --git a/apisupport.project/src/org/netbeans/modules/apisupport/project/layers/LayerNode.java b/apisupport.project/src/org/netbeans/modules/apisupport/project/layers/LayerNode.java --- a/apisupport.project/src/org/netbeans/modules/apisupport/project/layers/LayerNode.java +++ b/apisupport.project/src/org/netbeans/modules/apisupport/project/layers/LayerNode.java @@ -239,7 +239,7 @@ public String getDisplayName() { return FileUtil.getFileDisplayName(layer); } - @Override + public SystemAction[] getActions(Set foSet) { return new SystemAction[] { SystemAction.get(PickNameAction.class), diff --git a/cnd.apt/test/unit/src/org/netbeans/modules/cnd/apt/support/APTConditionResolverTest.java b/cnd.apt/test/unit/src/org/netbeans/modules/cnd/apt/support/APTConditionResolverTest.java --- a/cnd.apt/test/unit/src/org/netbeans/modules/cnd/apt/support/APTConditionResolverTest.java +++ b/cnd.apt/test/unit/src/org/netbeans/modules/cnd/apt/support/APTConditionResolverTest.java @@ -189,10 +189,5 @@ public FileObject findResource(String name) { throw new UnsupportedOperationException(); } - - @Override - public org.openide.util.actions.SystemAction[] getActions() { - throw new UnsupportedOperationException(); - } } } diff --git a/cnd.apt/test/unit/src/org/netbeans/modules/cnd/apt/support/GuardDetectorTestCase.java b/cnd.apt/test/unit/src/org/netbeans/modules/cnd/apt/support/GuardDetectorTestCase.java --- a/cnd.apt/test/unit/src/org/netbeans/modules/cnd/apt/support/GuardDetectorTestCase.java +++ b/cnd.apt/test/unit/src/org/netbeans/modules/cnd/apt/support/GuardDetectorTestCase.java @@ -263,9 +263,5 @@ throw new UnsupportedOperationException("Not supported yet."); } - @Override - public SystemAction[] getActions() { - throw new UnsupportedOperationException("Not supported yet."); - } } } diff --git a/cnd.folding/test/unit/src/org/netbeans/modules/cnd/folding/APTFoldingProviderTestCase.java b/cnd.folding/test/unit/src/org/netbeans/modules/cnd/folding/APTFoldingProviderTestCase.java --- a/cnd.folding/test/unit/src/org/netbeans/modules/cnd/folding/APTFoldingProviderTestCase.java +++ b/cnd.folding/test/unit/src/org/netbeans/modules/cnd/folding/APTFoldingProviderTestCase.java @@ -138,11 +138,6 @@ public FileObject findResource(String name) { throw new UnsupportedOperationException(); } - - @Override - public org.openide.util.actions.SystemAction[] getActions() { - throw new UnsupportedOperationException(); - } } } diff --git a/core.osgi/nbproject/project.xml b/core.osgi/nbproject/project.xml --- a/core.osgi/nbproject/project.xml +++ b/core.osgi/nbproject/project.xml @@ -24,7 +24,15 @@ - 7.36 + 9.0 + + + + org.openide.filesystems.compat8 + + + + 9.0 diff --git a/core.osgi/src/org/netbeans/core/osgi/OSGiRepository.java b/core.osgi/src/org/netbeans/core/osgi/OSGiRepository.java --- a/core.osgi/src/org/netbeans/core/osgi/OSGiRepository.java +++ b/core.osgi/src/org/netbeans/core/osgi/OSGiRepository.java @@ -54,6 +54,7 @@ import java.util.logging.Level; import java.util.logging.Logger; import org.openide.filesystems.FileStatusListener; +import org.openide.filesystems.FileSystem$Environment; import org.openide.filesystems.FileSystem; import org.openide.filesystems.FileUtil; import org.openide.filesystems.LocalFileSystem; @@ -141,7 +142,7 @@ private static final class SFS extends MultiFileSystem implements LookupListener { static { - @SuppressWarnings("deprecation") Object _1 = FileSystem.Environment.class; // FELIX-2128 + @SuppressWarnings("deprecation") Object _1 = FileSystem$Environment.class; // FELIX-2128 @SuppressWarnings("deprecation") Object _2 = org.openide.filesystems.FileSystemCapability.class; Object _3 = FileStatusListener.class; Object _4 = LookupEvent.class; // FELIX-3477 diff --git a/core.startup/src/org/netbeans/core/startup/layers/SystemFileSystem.java b/core.startup/src/org/netbeans/core/startup/layers/SystemFileSystem.java --- a/core.startup/src/org/netbeans/core/startup/layers/SystemFileSystem.java +++ b/core.startup/src/org/netbeans/core/startup/layers/SystemFileSystem.java @@ -118,7 +118,6 @@ home = fss.length > 1 ? (ModuleLayeredFileSystem) fss[1] : null; setSystemName(SYSTEM_NAME); - setHidden(true); addFileChangeListener(this); } @@ -188,13 +187,6 @@ return super.createLocksOn (name); } - /** This filesystem cannot be removed from pool, it is persistent. - */ - @Deprecated - public @Override boolean isPersistent() { - return true; - } - /** Initializes and creates new repository. This repository's system fs is * based on the content of ${HOME_DIR}/system and ${USER_DIR}/system directories * diff --git a/dlight.libs.common/src/org/netbeans/modules/dlight/libs/common/InvalidFileObjectSupport.java b/dlight.libs.common/src/org/netbeans/modules/dlight/libs/common/InvalidFileObjectSupport.java --- a/dlight.libs.common/src/org/netbeans/modules/dlight/libs/common/InvalidFileObjectSupport.java +++ b/dlight.libs.common/src/org/netbeans/modules/dlight/libs/common/InvalidFileObjectSupport.java @@ -135,11 +135,6 @@ } @Override - public SystemAction[] getActions() { - return new SystemAction[0]; - } - - @Override public String getDisplayName() { return "Dummy"; //NOI18N } diff --git a/dlight.remote.impl/src/org/netbeans/modules/remote/impl/fs/RemoteFileSystem.java b/dlight.remote.impl/src/org/netbeans/modules/remote/impl/fs/RemoteFileSystem.java --- a/dlight.remote.impl/src/org/netbeans/modules/remote/impl/fs/RemoteFileSystem.java +++ b/dlight.remote.impl/src/org/netbeans/modules/remote/impl/fs/RemoteFileSystem.java @@ -358,11 +358,6 @@ } - @Override - public SystemAction[] getActions() { - return NO_SYSTEM_ACTIONS; - } - public void addPendingFile(RemoteFileObjectBase fo) { remoteFileSupport.addPendingFile(fo); fireProblemListeners(fo.getPath()); @@ -665,7 +660,7 @@ } } - @Override +// @Override -- overrides at runtime public final SystemAction[] getActions(final Set foSet) { SystemAction[] result = status.getActions (foSet); SystemAction refreshAction = isManualRefresh() ? null : FileSystemRefreshAction.get(FileSystemRefreshAction.class); diff --git a/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/FileBasedFileSystem.java b/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/FileBasedFileSystem.java --- a/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/FileBasedFileSystem.java +++ b/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/FileBasedFileSystem.java @@ -237,12 +237,6 @@ throw new IOException("Cannot create temporary file"); // NOI18N } - @Override - public SystemAction[] getActions() { - return new SystemAction[] {}; - } - - @Override public final SystemAction[] getActions(final Set foSet) { SystemAction[] some = status.getActions (foSet); if (some != null) { diff --git a/nbbuild/build.xml b/nbbuild/build.xml --- a/nbbuild/build.xml +++ b/nbbuild/build.xml @@ -1898,6 +1898,10 @@ + + + + diff --git a/nbbuild/cluster.properties b/nbbuild/cluster.properties --- a/nbbuild/cluster.properties +++ b/nbbuild/cluster.properties @@ -228,7 +228,10 @@ openide.compat,\ openide.dialogs,\ openide.execution,\ + openide.execution.compat8,\ openide.explorer,\ + openide.filesystems.compat8,\ + openide.filesystems.nb,\ openide.io,\ openide.loaders,\ openide.modules,\ diff --git a/nbbuild/javadoctools/links.xml b/nbbuild/javadoctools/links.xml --- a/nbbuild/javadoctools/links.xml +++ b/nbbuild/javadoctools/links.xml @@ -224,3 +224,4 @@ + diff --git a/nbbuild/javadoctools/properties.xml b/nbbuild/javadoctools/properties.xml --- a/nbbuild/javadoctools/properties.xml +++ b/nbbuild/javadoctools/properties.xml @@ -222,3 +222,4 @@ + diff --git a/nbbuild/javadoctools/replaces.xml b/nbbuild/javadoctools/replaces.xml --- a/nbbuild/javadoctools/replaces.xml +++ b/nbbuild/javadoctools/replaces.xml @@ -222,3 +222,4 @@ + diff --git a/nbbuild/templates/common.xml b/nbbuild/templates/common.xml --- a/nbbuild/templates/common.xml +++ b/nbbuild/templates/common.xml @@ -1309,6 +1309,16 @@ + + + + + + + + + + diff --git a/openide.execution.compat8/build.xml b/openide.execution.compat8/build.xml new file mode 100644 --- /dev/null +++ b/openide.execution.compat8/build.xml @@ -0,0 +1,5 @@ + + + Builds, tests, and runs the project org.openide.execution.compat8 + + diff --git a/openide.execution.compat8/manifest.mf b/openide.execution.compat8/manifest.mf new file mode 100644 --- /dev/null +++ b/openide.execution.compat8/manifest.mf @@ -0,0 +1,6 @@ +Manifest-Version: 1.0 +OpenIDE-Module: org.openide.execution.compat8 +OpenIDE-Module-Localizing-Bundle: org/openide/execution/compat8/Bundle.properties +OpenIDE-Module-Specification-Version: 9.0 +OpenIDE-Module-Fragment-Host: org.openide.execution + diff --git a/openide.execution.compat8/nbproject/project.properties b/openide.execution.compat8/nbproject/project.properties new file mode 100644 --- /dev/null +++ b/openide.execution.compat8/nbproject/project.properties @@ -0,0 +1,2 @@ +javac.source=1.6 +javac.compilerargs=-Xlint -Xlint:-serial diff --git a/openide.execution.compat8/nbproject/project.xml b/openide.execution.compat8/nbproject/project.xml new file mode 100644 --- /dev/null +++ b/openide.execution.compat8/nbproject/project.xml @@ -0,0 +1,38 @@ + + + org.netbeans.modules.apisupport.project + + + org.openide.execution.compat8 + + + org.openide.execution + + + + 9.0 + + + + org.openide.filesystems + + + + 9.0 + + + + org.openide.filesystems.compat8 + + + + 9.0 + + + + + org.openide.execution + + + + diff --git a/openide.execution.compat8/src/org/openide/execution/NbClassPathCompat.java b/openide.execution.compat8/src/org/openide/execution/NbClassPathCompat.java new file mode 100644 --- /dev/null +++ b/openide.execution.compat8/src/org/openide/execution/NbClassPathCompat.java @@ -0,0 +1,115 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2014 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2014 Sun Microsystems, Inc. + */ + +package org.openide.execution; + +import java.util.Enumeration; +import java.util.LinkedList; +import org.openide.filesystems.EnvironmentNotSupportedException; +import org.openide.filesystems.FileSystem; +import org.openide.filesystems.FileSystem$Environment; +import org.openide.filesystems.FileSystemCapability; +import org.openide.filesystems.FileSystemCompat; + +/** + * Backward binary compatibility support for deprecated/obsolete features + * @author sdedic + */ +public class NbClassPathCompat { + + /** Method to obtain class path for the current state of the repository. + * The classpath should be scanned for all occured exception caused + * by file systems that cannot be converted to class path by a call to + * method getExceptions(). + * + * + * @return class path for all reachable systems in the repository + * @deprecated Please use the ClassPath API instead. + */ + @Deprecated + public static NbClassPath createRepositoryPath () { + Thread.dumpStack(); + return createRepositoryPath (FileSystemCapability.ALL); + } + + /** Method to obtain class path for the current state of the repository. + * The classpath should be scanned for all occured exception caused + * by file systems that cannot be converted to class path by a call to + * method getExceptions(). + * + * + * @param cap the capability that must be satisfied by the file system + * added to the class path + * @return class path for all reachable systems in the repository + * @deprecated Please use the ClassPath API instead. + */ + @Deprecated + public static NbClassPath createRepositoryPath (FileSystemCapability cap) { + Thread.dumpStack(); + final LinkedList res = new LinkedList (); + + + final class Env extends FileSystem$Environment { + /* method of interface Environment */ + public void addClassPath(String element) { + res.add (element); + } + } + + + Env env = new Env (); + Enumeration en = cap.fileSystems (); + while (en.hasMoreElements ()) { + try { + FileSystem fs = (FileSystem)en.nextElement (); + FileSystemCompat.compat(fs).prepareEnvironment((FileSystem$Environment)env); + } catch (EnvironmentNotSupportedException ex) { + // store the exception + res.add (ex); + } + } + + // return it + return new NbClassPath (res.toArray ()); + } + +} diff --git a/openide.execution.compat8/src/org/openide/execution/compat8/Bundle.properties b/openide.execution.compat8/src/org/openide/execution/compat8/Bundle.properties new file mode 100644 --- /dev/null +++ b/openide.execution.compat8/src/org/openide/execution/compat8/Bundle.properties @@ -0,0 +1,8 @@ +OpenIDE-Module-Name=Execution API 8.0 Compatibility +OpenIDE-Module-Display-Category=Infrastructure +OpenIDE-Module-Short-Description=Compatibility support for clients compiled against Execution API \ + ver. 8.0 and earlier. +OpenIDE-Module-Long-Description=\ + The module provides deprecated and obsolete classes/methods removed from the \ + official APIs for binary compatibility of old Execution API clients. + diff --git a/openide.execution/manifest.mf b/openide.execution/manifest.mf --- a/openide.execution/manifest.mf +++ b/openide.execution/manifest.mf @@ -1,6 +1,6 @@ Manifest-Version: 1.0 OpenIDE-Module: org.openide.execution -OpenIDE-Module-Specification-Version: 1.36 +OpenIDE-Module-Specification-Version: 9.0 OpenIDE-Module-Localizing-Bundle: org/openide/execution/Bundle.properties OpenIDE-Module-Recommends: org.openide.execution.ExecutionEngine AutoUpdate-Essential-Module: true diff --git a/openide.execution/module-auto-deps.xml b/openide.execution/module-auto-deps.xml --- a/openide.execution/module-auto-deps.xml +++ b/openide.execution/module-auto-deps.xml @@ -62,5 +62,18 @@ + + Removal of FileSystemCapability + + + + + + + + + + + diff --git a/openide.execution/nbproject/project.xml b/openide.execution/nbproject/project.xml --- a/openide.execution/nbproject/project.xml +++ b/openide.execution/nbproject/project.xml @@ -54,7 +54,7 @@ - 7.57 + 9.0 diff --git a/openide.execution/src/org/openide/execution/NbClassLoader.java b/openide.execution/src/org/openide/execution/NbClassLoader.java --- a/openide.execution/src/org/openide/execution/NbClassLoader.java +++ b/openide.execution/src/org/openide/execution/NbClassLoader.java @@ -59,7 +59,6 @@ import java.util.logging.Logger; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileSystem; -import org.openide.filesystems.FileSystemCapability; import org.openide.filesystems.FileUtil; import org.openide.filesystems.URLMapper; import org.openide.util.Exceptions; diff --git a/openide.execution/src/org/openide/execution/NbClassPath.java b/openide.execution/src/org/openide/execution/NbClassPath.java --- a/openide.execution/src/org/openide/execution/NbClassPath.java +++ b/openide.execution/src/org/openide/execution/NbClassPath.java @@ -85,7 +85,7 @@ /** Private constructor * @param arr array of String and Exceptions */ - private NbClassPath (Object[] arr) { + NbClassPath (Object[] arr) { this.items = arr; } @@ -109,60 +109,6 @@ } } - /** Method to obtain class path for the current state of the repository. - * The classpath should be scanned for all occured exception caused - * by file systems that cannot be converted to class path by a call to - * method getExceptions(). - * - * - * @return class path for all reachable systems in the repository - * @deprecated Please use the ClassPath API instead. - */ - public static NbClassPath createRepositoryPath () { - Thread.dumpStack(); - return createRepositoryPath (FileSystemCapability.ALL); - } - - /** Method to obtain class path for the current state of the repository. - * The classpath should be scanned for all occured exception caused - * by file systems that cannot be converted to class path by a call to - * method getExceptions(). - * - * - * @param cap the capability that must be satisfied by the file system - * added to the class path - * @return class path for all reachable systems in the repository - * @deprecated Please use the ClassPath API instead. - */ - public static NbClassPath createRepositoryPath (FileSystemCapability cap) { - Thread.dumpStack(); - final LinkedList res = new LinkedList (); - - - final class Env extends FileSystem.Environment { - /* method of interface Environment */ - public void addClassPath(String element) { - res.add (element); - } - } - - - Env env = new Env (); - Enumeration en = cap.fileSystems (); - while (en.hasMoreElements ()) { - try { - FileSystem fs = (FileSystem)en.nextElement (); - fs.prepareEnvironment(env); - } catch (EnvironmentNotSupportedException ex) { - // store the exception - res.add (ex); - } - } - - // return it - return new NbClassPath (res.toArray ()); - } - /** Creates class path describing additional libraries needed by the system. * Never use this class path as part of a user project! * For more information consult the Module Class Path document. diff --git a/openide.filesystems.compat8/arch.xml b/openide.filesystems.compat8/arch.xml new file mode 100644 --- /dev/null +++ b/openide.filesystems.compat8/arch.xml @@ -0,0 +1,337 @@ + + +]> + + + + &api-questions; + + +

+ This module contains no public API. It only serves to provide binary backward compatibility + for modules compiled against FileSystems API 8.x and earlier. +

+
+ + +

+ Tests to ensure FileSystems 8.x features should be provided. +

+
+ + +

+ Already done. +

+
+ + +

+ Allows to run modules compiled against FileSystems 8.0 APIs +

+
+ + +

+ Preservation of compatibility +

+
+ + + + + + +

+ APIs that relate to FileSystemCapability and + FileSystem.Environment are removed from the main API + and provided here only for binary compatibility. +

+
+ + +

+ yes +

+
+ + +

+ no +

+
+ + + + +

+ yes +

+
+ + +

+ no dependency +

+
+ + +

+ JRE +

+
+ + + + + + +

+ None +

+
+ + +

+ All +

+
+ + +

+ None +

+
+ + +

+ No. +

+
+ + + +

+ Yes +

+
+ + +

+ Yes, packages are only available to strictly defined friends +

+
+ + +

+ Shared location +

+
+ + +

+ No +

+
+ + +

+ No. +

+
+ + +

+ No. +

+
+ + +

+ No. +

+
+ + +

+ None. +

+
+ + +

+ No. +

+
+ + +

+ No. +

+
+ + +

+ Not directly reflection. The code however relies on that it is deployed + to the same runtime package as FileSystems API and accessess its package + private parts. +

+
+ + +

+ See Filesystems API +

+
+ + +

+ See Filesystems API +

+
+ + +

+ See Filesystems API +

+
+ + +

+ None. +

+
+ + +

+ No. +

+
+ + +

+ None. +

+
+ + +

+ No. +

+
+ + +

+ No. +

+
+ + +

+ None. +

+
+ + +

+ N/A +

+
+ + +

+ N/A +

+
+ + +

+ No menus +

+
+ + +

+ No. +

+
+ + +

+ See Filesystems API +

+
+ + +

+ N/A +

+
+ + +

+ No. +

+
+ + +

+ No. +

+
+ + +

+ Yes, for initialization of LocalFileSystem + and JarFileSystem +

+
+ + +

+ No layer +

+
+ + +

+ No. +

+
+ + +

+ No. +

+
+ + +

+ No. +

+
+ + +

+ No. +

+
+ + +

+ No. +

+
+ +
diff --git a/openide.filesystems.compat8/build.xml b/openide.filesystems.compat8/build.xml new file mode 100644 --- /dev/null +++ b/openide.filesystems.compat8/build.xml @@ -0,0 +1,5 @@ + + + Builds, tests, and runs the project org.openide.filesystems.compat8 + + diff --git a/openide.filesystems.compat8/manifest.mf b/openide.filesystems.compat8/manifest.mf new file mode 100644 --- /dev/null +++ b/openide.filesystems.compat8/manifest.mf @@ -0,0 +1,6 @@ +Manifest-Version: 1.0 +OpenIDE-Module: org.openide.filesystems.compat8 +OpenIDE-Module-Localizing-Bundle: org/openide/filesystems/compat8/Bundle.properties +OpenIDE-Module-Specification-Version: 9.0 +OpenIDE-Module-Fragment-Host: org.openide.filesystems + diff --git a/openide.filesystems.compat8/nbproject/project.properties b/openide.filesystems.compat8/nbproject/project.properties new file mode 100644 --- /dev/null +++ b/openide.filesystems.compat8/nbproject/project.properties @@ -0,0 +1,4 @@ +javac.source=1.6 +javac.compilerargs=-Xlint -Xlint:-serial +module.jar.dir=core +javadoc.arch=${basedir}/arch.xml diff --git a/openide.filesystems.compat8/nbproject/project.xml b/openide.filesystems.compat8/nbproject/project.xml new file mode 100644 --- /dev/null +++ b/openide.filesystems.compat8/nbproject/project.xml @@ -0,0 +1,54 @@ + + + org.netbeans.modules.apisupport.project + + + org.openide.filesystems.compat8 + + + org.openide.filesystems + + + + 9.0 + + + + org.openide.modules + + + + 7.44 + + + + org.openide.util + + + + 9.0 + + + + org.openide.util.base + + + + 9.0 + + + + org.openide.util.lookup + + + + 8.17 + + + + + org.openide.filesystems + + + + diff --git a/openide.filesystems.compat8/src/org/openide/filesystems/AbstractFileSystemCompat.java b/openide.filesystems.compat8/src/org/openide/filesystems/AbstractFileSystemCompat.java new file mode 100644 --- /dev/null +++ b/openide.filesystems.compat8/src/org/openide/filesystems/AbstractFileSystemCompat.java @@ -0,0 +1,135 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2014 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2014 Sun Microsystems, Inc. + */ + +package org.openide.filesystems; + +import java.util.Enumeration; +import java.util.StringTokenizer; +import org.openide.modules.PatchFor; +import org.openide.util.Enumerations; +import org.openide.util.Lookup; +import org.openide.util.NbCollections; +import org.openide.util.SharedClassObject; +import org.openide.util.actions.SystemAction; + +/** + * 8.0 compatibility patch for AbstractFileSystem. + * @author sdedic + */ +@PatchFor(AbstractFileSystem.class) +public abstract class AbstractFileSystemCompat extends FileSystem { + /** system actions for this FS if it has refreshTime != 0 */ + private static SystemAction[] SYSTEM_ACTIONS; + + /** system actions for this FS */ + private static final SystemAction[] NO_SYSTEM_ACTIONS = new SystemAction[] { }; + + + /* Finds file when its name is provided. + * + * @param aPackage package name where each package is separated by a dot + * @param name name of the file (without dots) or null if + * one want to obtain name of package and not file in it + * @param ext extension of the file or null if one needs + * package and not file name + * + * @warning when one of name or ext is null then name and + * ext should be ignored and scan should look only for a package + * + * @return FileObject that represents file with given name or + * null if the file does not exist + */ + @Deprecated + public FileObject find(String aPackage, String name, String ext) { + // create enumeration of name to look for + Enumeration st = NbCollections.checkedEnumerationByFilter(new StringTokenizer(aPackage, "."), String.class, true); // NOI18N + + if ((name == null) || (ext == null)) { + // search for folder, return the object only if it is folder + FileObject fo = getAbstractRoot().find(st); + + return ((fo != null) && fo.isFolder()) ? fo : null; + } else { + Enumeration en = Enumerations.concat(st, Enumerations.singleton(name + '.' + ext)); + + // tries to find it (can return null) + return getAbstractRoot().find(en); + } + } + + abstract AbstractFileObject getAbstractRoot(); + + abstract boolean isEnabledRefreshFolder(); + + /* Action for this filesystem. + * + * @return refresh action + */ + public SystemAction[] getActions() { + if (!isEnabledRefreshFolder()) { + return NO_SYSTEM_ACTIONS; + } else { + if (SYSTEM_ACTIONS == null) { + try { + ClassLoader l = Lookup.getDefault().lookup(ClassLoader.class); + + if (l == null) { + l = getClass().getClassLoader(); + } + + Class c = Class.forName("org.openide.actions.FileSystemRefreshAction", true, l); // NOI18N + SystemAction ra = SharedClassObject.findObject(c.asSubclass(SystemAction.class), true); + + // initialize the SYSTEM_ACTIONS + SYSTEM_ACTIONS = new SystemAction[] { ra }; + } catch (Exception ex) { + // ok, we are probably running in standalone mode and + // classes needed to initialize the RefreshAction are + // not available + SYSTEM_ACTIONS = NO_SYSTEM_ACTIONS; + } + } + + return SYSTEM_ACTIONS; + } + } +} diff --git a/openide.filesystems.compat8/src/org/openide/filesystems/EnvironmentNotSupportedException.java b/openide.filesystems.compat8/src/org/openide/filesystems/EnvironmentNotSupportedException.java new file mode 100644 --- /dev/null +++ b/openide.filesystems.compat8/src/org/openide/filesystems/EnvironmentNotSupportedException.java @@ -0,0 +1,86 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * Contributor(s): + * + * The Original Software is NetBeans. The Initial Developer of the Original + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun + * Microsystems, Inc. All Rights Reserved. + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + */ + +package org.openide.filesystems; + +import java.io.IOException; + +/** Exception thrown to signal that external +* execution and compilation is not supported on a given filesystem. +* +* @author Jaroslav Tulach +* @deprecated Please use the ClassPath API instead. +*/ +@Deprecated +public class EnvironmentNotSupportedException extends IOException { + /** generated Serialized Version UID */ + static final long serialVersionUID = -1138390681913514558L; + + /** the throwing exception */ + private FileSystem fs; + + /** + * @param fs filesystem that caused the error + */ + public EnvironmentNotSupportedException(FileSystem fs) { + this.fs = fs; + assert false : "Deprecated."; + } + + /** + * @param fs filesystem that caused the error + * @param reason text description for the error + */ + public EnvironmentNotSupportedException(FileSystem fs, String reason) { + super(reason); + this.fs = fs; + assert false : "Deprecated."; + } + + /** Getter for the filesystem that does not support environment operations. + */ + public FileSystem getFileSystem() { + return fs; + } +} diff --git a/openide.filesystems.compat8/src/org/openide/filesystems/FileSystem$Environment.java b/openide.filesystems.compat8/src/org/openide/filesystems/FileSystem$Environment.java new file mode 100644 --- /dev/null +++ b/openide.filesystems.compat8/src/org/openide/filesystems/FileSystem$Environment.java @@ -0,0 +1,65 @@ +package org.openide.filesystems; + +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2014 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2014 Sun Microsystems, Inc. + */ + +/** Interface that allows filesystems to set up the Java environment +* for external execution and compilation. +* Currently just used to append entries to the external class path. +* @deprecated Please use the ClassPath API instead. +*/ +@Deprecated +public abstract class FileSystem$Environment { + /** Deprecated. */ + public FileSystem$Environment() { + assert false : "Deprecated."; + } + + /** Adds one element to the class path environment variable. + * @param classPathElement string representing the one element + * @deprecated Please use the ClassPath API instead. + */ + @Deprecated + public void addClassPath(String classPathElement) { + } +} + diff --git a/openide.filesystems.compat8/src/org/openide/filesystems/FileSystemCapability.java b/openide.filesystems.compat8/src/org/openide/filesystems/FileSystemCapability.java new file mode 100644 --- /dev/null +++ b/openide.filesystems.compat8/src/org/openide/filesystems/FileSystemCapability.java @@ -0,0 +1,436 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * Contributor(s): + * + * The Original Software is NetBeans. The Initial Developer of the Original + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun + * Microsystems, Inc. All Rights Reserved. + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + */ + +package org.openide.filesystems; + +import java.beans.PropertyChangeListener; +import java.beans.PropertyChangeSupport; +import java.util.Collection; +import java.util.Enumeration; +import java.util.Vector; + +/** This class defines the capabilities of a filesystem to +* take part in different operations. Some filesystems are +* not designed to allow compilation on them, some do not want +* to be present in class path when executing or debugging +* a program. +*

+* Moreover there can be additional capabilities to check +* and this class defines ways how one can communicated with +* a filesystem to find out whether the system is "capable" +* enough to be used in the operation. +* +* @author Jaroslav Tulach + * @deprecated Now useless. +*/ +@Deprecated +public class FileSystemCapability extends Object { + /** Object that is capable of every thing. + */ + public static final FileSystemCapability ALL = new FileSystemCapability() { + public boolean capableOf(FileSystemCapability c) { + return true; + } + }; + + /** Well known capability of being compiled. + * @deprecated Please use the ClassPath API instead. + */ + @Deprecated + public static final FileSystemCapability COMPILE = new FileSystemCapability(); + + /** Well known ability to be executed. + * @deprecated Please use the ClassPath API instead. + */ + @Deprecated + public static final FileSystemCapability EXECUTE = new FileSystemCapability(); + + /** Well known ability to be debugged. + * @deprecated Please use the ClassPath API instead. + */ + @Deprecated + public static final FileSystemCapability DEBUG = new FileSystemCapability(); + + /** Well known ability to contain documentation files + * @deprecated Please use JavadocForBinaryQuery instead. + */ + @Deprecated + public static final FileSystemCapability DOC = new FileSystemCapability(); + + public FileSystemCapability() { + if (DOC == null) { + // do not report static initializers + return; + } + + assert false : "Deprecated."; + } + + /** Basic operation that tests whether this object + * is capable to do different capability. + *

+ * The default implementation claims that it is + * capable to handle only identical capability (==). + * + * @param c capability to test + * @return true if yes + */ + public boolean capableOf(FileSystemCapability c) { + return c == this; + } + + /** All filesystems that are capable of this capability. + * @return enumeration of FileSystems that satifies this capability + * @deprecated Please use the ClassPath API instead. + */ + @Deprecated + public Enumeration fileSystems() { + class FFS implements org.openide.util.Enumerations.Processor { + @Deprecated + public FileSystem process(FileSystem fs, Collection ignore) { + return FileSystemCompat.compat(fs).getCapability(). + capableOf(FileSystemCapability.this) ? fs : null; + } + } + + return org.openide.util.Enumerations.filter(Repository.getDefault().fileSystems(), new FFS()); + } + + /** Find a resource in repository, ignoring not capable filesystems. + * @param resName name of the resource + * @deprecated Please use the ClassPath API instead. + */ + @Deprecated + public FileObject findResource(String resName) { + Enumeration en = fileSystems(); + + while (en.hasMoreElements()) { + FileSystem fs = en.nextElement(); + FileObject fo = fs.findResource(resName); + + if (fo != null) { + // object found + return fo; + } + } + + return null; + } + + /** Searches for the given resource among all filesystems + * that satifies this capability, returning all matches. + * @param name name of the resource + * @return enumeration of {@link FileObject}s + * @deprecated Please use the ClassPath API instead. + */ + @Deprecated + public Enumeration findAllResources(String name) { + Vector v = new Vector(8); + Enumeration en = fileSystems(); + + while (en.hasMoreElements()) { + FileSystem fs = en.nextElement(); + FileObject fo = fs.findResource(name); + + if (fo != null) { + v.addElement(fo); + } + } + + return v.elements(); + } + + /** Finds file when its name is provided. It scans in the list of + * filesystems and asks them for the specified file by a call to + * {@link FileSystem#find find}. The first object that is found is returned or null + * if none of the filesystems contain such a file. + * + * @param aPackage package name where each package is separated by a dot + * @param name name of the file (without dots) or null if + * one wants to obtain the name of a package and not a file in it + * @param ext extension of the file or null if one needs + * a package and not a file name + * + * @return {@link FileObject} that represents file with given name or + * null if the file does not exist + * @deprecated Please use the ClassPath API instead. + */ + @Deprecated + public final FileObject find(String aPackage, String name, String ext) { + Enumeration en = fileSystems(); + + while (en.hasMoreElements()) { + FileSystem fs = en.nextElement(); + FileObject fo = fs.find(aPackage, name, ext); + + if (fo != null) { + // object found + return fo; + } + } + + return null; + } + + /** Finds all files among all filesystems with this capability + * that match a given name, returning all matches. + * All filesystems are queried with {@link FileSystem#find}. + * + * @param aPackage package name where each package is separated by a dot + * @param name name of the file (without dots) or null if + * one wants to obtain the name of a package and not a file in it + * @param ext extension of the file or null if one needs + * a package and not a file name + * + * @return enumeration of {@link FileObject}s + * @deprecated Please use the ClassPath API instead. + */ + @Deprecated + public final Enumeration findAll(String aPackage, String name, String ext) { + Enumeration en = fileSystems(); + Vector ret = new Vector(); + + while (en.hasMoreElements()) { + FileSystem fs = (FileSystem) en.nextElement(); + FileObject fo = fs.find(aPackage, name, ext); + + if (fo != null) { + ret.addElement(fo); + } + } + + return ret.elements(); + } + + /** Adds PropertyChange listener. Every class which implements changes of capabilities + * has to implement it's property change support. + * @param l the listener to be added. + */ + public synchronized void addPropertyChangeListener(PropertyChangeListener l) { + } + + /** Removes PropertyChange listener. Every class which implements changes of capabilities + * has to implement it's property change support. + * @param l the listener to be removed. + */ + public void removePropertyChangeListener(PropertyChangeListener l) { + } + + /** Default implementation of capabilities, that behaves like + * JavaBean and allows to set whether the well known + * capabilities (like compile, execute) should be enabled + * or not. + * @deprecated For the same reason the whole class is. + */ + @Deprecated + public static class Bean extends FileSystemCapability implements java.io.Serializable { + static final long serialVersionUID = 627905674809532736L; + + /** change listeners */ + private transient PropertyChangeSupport supp; + + /** compilation */ + private boolean compilation = true; + + /** execution */ + private boolean execution = true; + + /** debugging */ + private boolean debug = true; + + /** doc */ + private boolean doc = false; + + /** Checks for well known capabilities and if they are allowed. + * + * @param c capability to test + * @return true if yes + */ + public boolean capableOf(FileSystemCapability c) { + if (c == COMPILE) { + return compilation; + } + + if (c == EXECUTE) { + return execution; + } + + if (c == DEBUG) { + return debug; + } + + if (c == DOC) { + return doc; + } + + if (c == ALL) { + return true; + } + + if (!(c instanceof Bean)) { + return false; + } + + // try match of values + Bean b = (Bean) c; + + return (compilation == b.compilation) && (execution == b.execution) && (debug == b.debug) && + (doc == b.doc); + } + + /** Getter for value of compiling capability. + * @deprecated Please use the ClassPath API instead. + */ + @Deprecated + public boolean getCompile() { + return compilation; + } + + /** Setter for allowing compiling capability. + * @deprecated Please use the ClassPath API instead. + */ + @Deprecated + public void setCompile(boolean val) { + if (val != compilation) { + compilation = val; + + if (supp != null) { + supp.firePropertyChange( + "compile", // NOI18N + (!val) ? Boolean.TRUE : Boolean.FALSE, val ? Boolean.TRUE : Boolean.FALSE + ); + } + } + } + + /** Getter for value of executiong capability. + * @deprecated Please use the ClassPath API instead. + */ + @Deprecated + public boolean getExecute() { + return execution; + } + + /** Setter for allowing executing capability. + * @deprecated Please use the ClassPath API instead. + */ + @Deprecated + public void setExecute(boolean val) { + if (val != execution) { + execution = val; + + if (supp != null) { + supp.firePropertyChange( + "execute", // NOI18N + (!val) ? Boolean.TRUE : Boolean.FALSE, val ? Boolean.TRUE : Boolean.FALSE + ); + } + } + } + + /** Getter for value of debugging capability. + * @deprecated Please use the ClassPath API instead. + */ + @Deprecated + public boolean getDebug() { + return debug; + } + + /** Setter for allowing debugging capability. + * @deprecated Please use the ClassPath API instead. + */ + @Deprecated + public void setDebug(boolean val) { + if (val != debug) { + debug = val; + + if (supp != null) { + supp.firePropertyChange( + "debug", // NOI18N + (!val) ? Boolean.TRUE : Boolean.FALSE, val ? Boolean.TRUE : Boolean.FALSE + ); + } + } + } + + /** Getter for value of doc capability. + * @deprecated Please use JavadocForBinaryQuery instead. + */ + @Deprecated + public boolean getDoc() { + return doc; + } + + /** Setter for allowing debugging capability. + * @deprecated Please use JavadocForBinaryQuery instead. + */ + @Deprecated + public void setDoc(boolean val) { + if (val != doc) { + doc = val; + + if (supp != null) { + supp.firePropertyChange( + "doc", // NOI18N + (!val) ? Boolean.TRUE : Boolean.FALSE, val ? Boolean.TRUE : Boolean.FALSE + ); + } + } + } + + public synchronized void addPropertyChangeListener(PropertyChangeListener l) { + if (supp == null) { + supp = new PropertyChangeSupport(this); + } + + supp.addPropertyChangeListener(l); + } + + public void removePropertyChangeListener(PropertyChangeListener l) { + if (supp != null) { + supp.removePropertyChangeListener(l); + } + } + } +} diff --git a/openide.filesystems.compat8/src/org/openide/filesystems/FileSystemCompat.java b/openide.filesystems.compat8/src/org/openide/filesystems/FileSystemCompat.java new file mode 100644 --- /dev/null +++ b/openide.filesystems.compat8/src/org/openide/filesystems/FileSystemCompat.java @@ -0,0 +1,237 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2014 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2014 Sun Microsystems, Inc. + */ + +package org.openide.filesystems; + +import java.beans.PropertyChangeListener; +import java.io.IOException; +import java.util.Set; +import org.openide.modules.PatchFor; +import org.openide.util.actions.SystemAction; + +/** + * The class provides an API compatibility bridge to support implementations + * compiled against org.openide.filesystems<8.0 and earlier + * + * @author sdedic + */ +@PatchFor(FileSystem.class) +public abstract class FileSystemCompat { + /** Property name giving capabilities state. @deprecated No more capabilities. */ + static final String PROP_CAPABILITIES = "capabilities"; // NOI18N + + /** hidden flag */ + private boolean hidden = false; + + /** Describes capabilities of the filesystem. + */ + @Deprecated // have to store it for compat + private /* XXX JDK #6460147: javac still reports it even though @Deprecated, + and @SuppressWarnings("deprecation") does not help either: FileSystemCapability*/Object capability; + + /** property listener on FileSystemCapability. */ + private transient PropertyChangeListener capabilityListener; + + /** Returns an array of actions that can be invoked on any file in + * this filesystem. + * These actions should preferably + * support the {@link org.openide.util.actions.Presenter.Menu Menu}, + * {@link org.openide.util.actions.Presenter.Popup Popup}, + * and {@link org.openide.util.actions.Presenter.Toolbar Toolbar} presenters. + * + * @return array of available actions + */ + public abstract SystemAction[] getActions(); + + /** + * Get actions appropriate to a certain file selection. + * By default, returns the same list as {@link #getActions()}. + * @param foSet one or more files which may be selected + * @return zero or more actions appropriate to those files + */ + public SystemAction[] getActions(Set foSet) { + return this.getActions(); + } + + /** Allows filesystems to set up the environment for external execution + * and compilation. + * Each filesystem can add its own values that + * influence the environment. The set of operations that can modify + * environment is described by the {@link Environment} interface. + *

+ * The default implementation throws an exception to signal that it does not + * support external compilation or execution. + * + * @param env the environment to setup + * @exception EnvironmentNotSupportedException if external execution + * and compilation cannot be supported + * @deprecated Please use the ClassPath API instead. + */ + @Deprecated + public void prepareEnvironment(FileSystem$Environment env) throws EnvironmentNotSupportedException { + Object o = this; + throw new EnvironmentNotSupportedException((FileSystem)o); + } + + /** + * Provides access to deprecated methods at runtime. + * + * @param fs The FileSystem + * @return the FileSystemCompat instanceo for the FileSystem. + */ + public static FileSystemCompat compat(FileSystem fs) { + Object o = fs; + return (FileSystemCompat)o; + } + + private FileSystem fs() { + Object o = this; + return (FileSystem)o; + } + + /** The object describing capabilities of this filesystem. + * Subclasses cannot override it. + * @return object describing capabilities of this filesystem. + * @deprecated Capabilities are no longer used. + */ + @Deprecated + public final FileSystemCapability getCapability() { + if (capability == null) { + capability = new FileSystemCapability.Bean(); + ((FileSystemCapability) capability).addPropertyChangeListener(getCapabilityChangeListener()); + } + + return (FileSystemCapability) capability; + } + + /** Allows subclasses to change a set of capabilities of the + * filesystem. + * @param capability the capability to use + * @deprecated Capabilities are no longer used. + */ + @Deprecated + protected final void setCapability(FileSystemCapability capability) { + if (this.capability != null) { + ((FileSystemCapability) this.capability).removePropertyChangeListener(getCapabilityChangeListener()); + } + + this.capability = capability; + + if (this.capability != null) { + ((FileSystemCapability) this.capability).addPropertyChangeListener(getCapabilityChangeListener()); + } + } + + /** returns property listener on FileSystemCapability. */ + private synchronized PropertyChangeListener getCapabilityChangeListener() { + if (capabilityListener == null) { + capabilityListener = new PropertyChangeListener() { + public void propertyChange(java.beans.PropertyChangeEvent propertyChangeEvent) { + firePropertyChange( + PROP_CAPABILITIES, propertyChangeEvent.getOldValue(), propertyChangeEvent.getNewValue() + ); + } + }; + } + + return capabilityListener; + } + + abstract void firePropertyChange(String s, Object o, Object n); + + /** Reads object from stream and creates listeners. + * @param in the input stream to read from + * @exception IOException error during read + * @exception ClassNotFoundException when class not found + */ + @SuppressWarnings("deprecation") + private void readObject(java.io.ObjectInputStream in) + throws java.io.IOException, java.lang.ClassNotFoundException { + in.defaultReadObject(); + + if (capability != null) { + ((FileSystemCapability) capability).addPropertyChangeListener(getCapabilityChangeListener()); + } + } + + /** Set hidden state of the object. + * A hidden filesystem is not presented to the user in the Repository list (though it may be present in the Repository Settings list). + * + * @param hide true if the filesystem should be hidden + * @deprecated This property is now useless. + */ + @Deprecated + public final void setHidden(boolean hide) { + if (hide != hidden) { + hidden = hide; + firePropertyChange(FileSystem.PROP_HIDDEN, (!hide) ? Boolean.TRUE : Boolean.FALSE, hide ? Boolean.TRUE : Boolean.FALSE); + } + } + + /** Getter for the hidden property. + * @return the hidden property. + * @deprecated This property is now useless. + */ + @Deprecated + public final boolean isHidden() { + return hidden; + } + + /** Tests whether filesystem will survive reloading of system pool. + * If true then when + * {@link Repository} is reloading its content, it preserves this + * filesystem in the pool. + *

+ * This can be used when the pool contains system level and user level + * filesystems. The system ones should be preserved when the user changes + * the content (for example when he is loading a new project). + *

The default implementation returns false. + * + * @return true if the filesystem should be persistent + * @deprecated This property is long since useless. + */ + @Deprecated + protected boolean isPersistent() { + return false; + } + +} diff --git a/openide.filesystems.compat8/src/org/openide/filesystems/JarFileSystemCompat.java b/openide.filesystems.compat8/src/org/openide/filesystems/JarFileSystemCompat.java new file mode 100644 --- /dev/null +++ b/openide.filesystems.compat8/src/org/openide/filesystems/JarFileSystemCompat.java @@ -0,0 +1,79 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2014 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2014 Sun Microsystems, Inc. + */ + +package org.openide.filesystems; + +import java.io.File; +import java.io.IOException; +import org.openide.modules.ConstructorDelegate; +import org.openide.modules.PatchFor; + +/** + * Support for compatibility with NB 8.0 and earlier. + * + * @author sdedic + */ +@PatchFor(JarFileSystem.class) +public abstract class JarFileSystemCompat extends AbstractFileSystem { + public JarFileSystemCompat() { + super(); + } + + @ConstructorDelegate + public static void createJarFileSystemCompat(JarFileSystemCompat jfs, FileSystemCapability cap) throws IOException { + FileSystemCompat.compat(jfs).setCapability(cap); + } + + /** Prepare environment for external compilation or execution. + *

+ * Adds name of the ZIP/JAR file, if it has been set, to the class path. + * @deprecated Useless. + */ + @Deprecated + public void prepareEnvironment(FileSystem$Environment env) { + if (getJarFile() != null) { + env.addClassPath(getJarFile().getAbsolutePath()); + } + } + + public abstract File getJarFile(); +} diff --git a/openide.filesystems.compat8/src/org/openide/filesystems/LocalFileSystemCompat.java b/openide.filesystems.compat8/src/org/openide/filesystems/LocalFileSystemCompat.java new file mode 100644 --- /dev/null +++ b/openide.filesystems.compat8/src/org/openide/filesystems/LocalFileSystemCompat.java @@ -0,0 +1,74 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2014 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2014 Sun Microsystems, Inc. + */ + +package org.openide.filesystems; + +import java.io.File; +import org.openide.modules.ConstructorDelegate; +import org.openide.modules.PatchFor; + +/** + * + * @author sdedic + */ +@PatchFor(LocalFileSystem.class) +public abstract class LocalFileSystemCompat extends AbstractFileSystem { + public LocalFileSystemCompat() { + + } + + @ConstructorDelegate + public static void createLocalFileSystemCompat(LocalFileSystemCompat self, FileSystemCapability cap) { + FileSystemCompat.compat(self).setCapability(cap); + } + + /** Prepare environment by adding the root directory of the filesystem to the class path. + * @param environment the environment to add to + * @deprecated Useless. + */ + @Deprecated + public void prepareEnvironment(FileSystem$Environment environment) { + environment.addClassPath(getRootDirectory().getAbsolutePath()); + } + + public abstract File getRootDirectory(); +} diff --git a/openide.filesystems.compat8/src/org/openide/filesystems/MultiFileSystemCompat.java b/openide.filesystems.compat8/src/org/openide/filesystems/MultiFileSystemCompat.java new file mode 100644 --- /dev/null +++ b/openide.filesystems.compat8/src/org/openide/filesystems/MultiFileSystemCompat.java @@ -0,0 +1,132 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2014 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2014 Sun Microsystems, Inc. + */ + +package org.openide.filesystems; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.openide.modules.PatchFor; +import org.openide.util.actions.SystemAction; + +/** + * + * @author sdedic + */ +@PatchFor(MultiFileSystem.class) +public abstract class MultiFileSystemCompat extends FileSystem { + /** Merge actions from all delegates. + */ + public SystemAction[] getActions() { + List al = new ArrayList(101); // randomly choosen constant + Set uniq = new HashSet(101); // not that randommly choosen + + FileSystem[] del = this.getDelegates(); + + for (int i = 0; i < del.length; i++) { + if (del[i] == null) { + continue; + } + + SystemAction[] acts = compat(del[i]).getActions(); + + for (int j = 0; j < acts.length; j++) { + if (uniq.add(acts[j])) { + al.add(acts[j]); + } + } + } + + return al.toArray(new SystemAction[al.size()]); + } + + public SystemAction[] getActions(final Set foSet) { + List al = new ArrayList(101); // randomly choosen constant + Set uniq = new HashSet(101); // not that randommly choosen + + final FileSystem[] del = this.getDelegates(); + + for (int i = 0; i < del.length; i++) { + if (del[i] == null) { + continue; + } + + final SystemAction[] acts = compat(del[i]).getActions(foSet); + + for (int j = 0; j < acts.length; j++) { + if (uniq.add(acts[j])) { + al.add(acts[j]); + } + } + } + + return al.toArray(new SystemAction[al.size()]); + } + + static FileSystemCompat compat(FileSystem fs) { + Object o = fs; + return (FileSystemCompat)o; + } + + /** Lets any sub filesystems prepare the environment. + * If they do not support it, it does not care. + * @deprecated Useless. + */ + @Deprecated + public void prepareEnvironment(FileSystem$Environment env) + throws EnvironmentNotSupportedException { + FileSystem[] layers = getDelegates(); + + for (int i = 0; i < layers.length; i++) { + if (layers[i] != null) { + try { + compat(layers[i]).prepareEnvironment(env); + } catch (EnvironmentNotSupportedException ense) { + // Fine. + } + } + } + } + + protected abstract FileSystem[] getDelegates(); +} diff --git a/openide.filesystems.compat8/src/org/openide/filesystems/compat8/Bundle.properties b/openide.filesystems.compat8/src/org/openide/filesystems/compat8/Bundle.properties new file mode 100644 --- /dev/null +++ b/openide.filesystems.compat8/src/org/openide/filesystems/compat8/Bundle.properties @@ -0,0 +1,6 @@ +OpenIDE-Module-Display-Category=Infrastructure +OpenIDE-Module-Long-Description=\ + After NetBeans 8.0 release, deprecated and obsolete features were removed from the FileSystem API mainline. \ + To preserve binary compatibility, implementations from this module are injected at runtime into Filesystem API classes to allow modules compiled against older version of FileSystem API to run +OpenIDE-Module-Name=Filesystems API 8.0 Compatibility +OpenIDE-Module-Short-Description=Support for FileSystem backward compatibility with NetBeans 8.0 diff --git a/openide.filesystems.nb/build.xml b/openide.filesystems.nb/build.xml new file mode 100644 --- /dev/null +++ b/openide.filesystems.nb/build.xml @@ -0,0 +1,5 @@ + + + Builds, tests, and runs the project openide.filesystems.nb + + diff --git a/openide.filesystems.nb/manifest.mf b/openide.filesystems.nb/manifest.mf new file mode 100644 --- /dev/null +++ b/openide.filesystems.nb/manifest.mf @@ -0,0 +1,5 @@ +Manifest-Version: 1.0 +OpenIDE-Module: org.openide.filesystems.nb +OpenIDE-Module-Localizing-Bundle: org/openide/filesystems/nb/Bundle.properties +OpenIDE-Module-Specification-Version: 9.0 + diff --git a/openide.filesystems.nb/nbproject/project.properties b/openide.filesystems.nb/nbproject/project.properties new file mode 100644 --- /dev/null +++ b/openide.filesystems.nb/nbproject/project.properties @@ -0,0 +1,2 @@ +javac.source=1.6 +javac.compilerargs=-Xlint -Xlint:-serial diff --git a/openide.filesystems.nb/nbproject/project.xml b/openide.filesystems.nb/nbproject/project.xml new file mode 100644 --- /dev/null +++ b/openide.filesystems.nb/nbproject/project.xml @@ -0,0 +1,71 @@ + + + org.netbeans.modules.apisupport.project + + + org.openide.filesystems.nb + + + org.openide.filesystems + + + + 9.0 + + + + org.openide.util + + + + 9.0 + + + + org.openide.util.base + + + + 9.0 + + + + org.openide.util.lookup + + + + 8.0 + + + + + + unit + + org.netbeans.libs.junit4 + + + + org.netbeans.modules.nbjunit + + + + + org.openide.filesystems + + + + + + org.openide.util.lookup + + + + + + + org.openide.filesystems + + + + diff --git a/openide.filesystems.nb/src/org/netbeans/modules/openide/filesystems/FileFilterSupport.java b/openide.filesystems.nb/src/org/netbeans/modules/openide/filesystems/FileFilterSupport.java new file mode 100644 --- /dev/null +++ b/openide.filesystems.nb/src/org/netbeans/modules/openide/filesystems/FileFilterSupport.java @@ -0,0 +1,470 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2012 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2012 Sun Microsystems, Inc. + */ +package org.netbeans.modules.openide.filesystems; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.swing.filechooser.FileFilter; +import org.openide.filesystems.FileObject; +import org.openide.filesystems.FileUtil; + +/** + * Support methods for creation of registered {@link FileFilter file filters}. + */ +public final class FileFilterSupport { + + /** + * The logger. + */ + private static final Logger LOG = Logger.getLogger( + FileFilterSupport.class.getName()); + + /** + * Hide the default constructor. + */ + private FileFilterSupport() { + } + + /** + * Construct description for {@link FileFilter} that accepts files with + * specified extension. + * + * @param displayName Human readable display name (e.g. "HTML files") + * @param elements List of accepted filter elements. + * + * @return Display name (description) for the filter. + */ + private static String constructFilterDisplayName(String displayName, + List elements) { + StringBuilder sb = new StringBuilder(displayName); + boolean first = true; + sb.append(" ["); //NOI18N + for (FilterElement el : elements) { + if (first) { + first = false; + } else { + sb.append(", "); //NOI18N + } + sb.append(el.getName()); + } + sb.append("]"); //NOI18N + return sb.toString(); + } + + /** + * Check whether passed file is accepted by filter for specified list of + * extensions. + * + * @param file File to be accepted or rejected. + * @param elements List of accepted filter elements. + * + * @return True if the file is accepted, false if it is rejected. + * + * @see FileFilterSupport + */ + private static boolean accept(File file, List elements) { + if (file != null) { + if (file.isDirectory()) { + return true; + } + for (FilterElement elm : elements) { + if (elm.accept(file)) { + return true; + } + } + } + return false; + } + + public static List findRegisteredFileFilters() { + List filters = new LinkedList(); + FileObject root = FileUtil.getConfigFile( + "Services/MIMEResolver"); //NOI18N + Map> filterNameToResolversMap = + new HashMap>(); + for (FileObject child : root.getChildren()) { + if (child.isFolder()) { + continue; + } + int i = 0; + String f; + while ((f = (String) child.getAttribute("fileChooser." + i))//NOI18N + != null) { + Set set = filterNameToResolversMap.get(f); + if (set == null) { + set = new HashSet(); + filterNameToResolversMap.put(f, set); + } + set.add(child); + i++; + } + } + for (Map.Entry> e : + filterNameToResolversMap.entrySet()) { + filters.add(createFilter(e.getKey(), e.getValue())); + } + return sortFiltersByDescription(filters); + } + + private static FileFilter createFilter(final String name, + final Set resolvers) { + ArrayList elems = new ArrayList(3); + String lastAtt; + for (FileObject fo : resolvers) { + int i = 0; + while ((lastAtt = (String) fo.getAttribute( + "ext." + i)) != null) { //NOI18N + addExtensionToList(elems, lastAtt); + i++; + } + int n = 0; + while ((lastAtt = (String) fo.getAttribute("fileName." //NOI18N + + (n++))) != null) { + addNameToList(elems, lastAtt); + } + String type; + if ((type = (String) fo.getAttribute("mimeType")) != null) {//NOI18N + addMimeTypeExts(elems, type); + } + int t = 0; + while ((type = (String) fo.getAttribute( + "mimeType." + (t++))) != null) { //NOI18N + addMimeTypeExts(elems, type); + } + } + sortFilterElements(elems); + return new FileFilterImpl(name, elems); + } + + /** + * Add all extensions assigned to a MIME Type to the extension list. + */ + private static void addMimeTypeExts(List exts, String type) { + addAllExtensionsToList(exts, FileUtil.getMIMETypeExtensions(type)); + } + + /** + * Add new items to list of extensions, prevent duplicates. + * + * @param list List of extensions to alter. + * @param toAdd List of extensions (without starting dot) to add. + */ + private static void addAllExtensionsToList(List list, + List toAdd) { + for (String s : toAdd) { + addExtensionToList(list, s); + } + } + + /** + * Add new item to list of extensions, prevent duplacates. + * + * @param list List of extensions to alter. + * @param s Extensions without starting dot. + */ + private static void addExtensionToList(List list, + String ext) { + addFilterElementToList(list, FilterElement.createForExtension(ext)); + } + + private static void addNameToList(List list, String name) { + Pattern p = Pattern.compile( + "\\[([^,]+), (true|false), (true|false)\\](\\S*)"); //NOI18N + Matcher m = p.matcher(name); + if (m.find()) { + String fileName = m.group(1); + boolean substring = m.group(2).equals("true"); //NOI18N + boolean ignoreCase = m.group(3).equals("true"); //NOI18N + String extension = m.group(4); + addFilterElementToList(list, FilterElement.createForFileName( + fileName, extension, substring, ignoreCase)); + } else { + LOG.log(Level.INFO, "Incorrect name pattern {0}", name); //NOI18N + } + } + + private static void addFilterElementToList(List list, + FilterElement newItem) { + + for (int i = 0; i < list.size(); i++) { + FilterElement el = list.get(i); + FilterElement.ComparisonResult result = newItem.compare(el); + switch (result) { + case DIFFERENT: + continue; + case THE_SAME: + case WORSE: + return; + case BETTER: + list.set(i, newItem); + return; + } + } + list.add(newItem); + } + + private static List sortFiltersByDescription( + List list) { + + Collections.sort(list, new Comparator() { + @Override + public int compare(FileFilter o1, FileFilter o2) { + return o1.getDescription().compareTo(o2.getDescription()); + } + }); + return list; + } + + private static List sortFilterElements( + List elements) { + Collections.sort(elements, new Comparator() { + @Override + public int compare(FilterElement o1, FilterElement o2) { + return o1.getName().compareTo(o2.getName()); + } + }); + return elements; + } + + private static class FileFilterImpl extends FileFilter { + + private final String name; + List filterElements; + + public FileFilterImpl(String name, List elements) { + this.name = name; + this.filterElements = elements; + } + + @Override + public boolean accept(File pathname) { + return FileFilterSupport.accept(pathname, filterElements); + } + + @Override + public String getDescription() { + return FileFilterSupport.constructFilterDisplayName( + name, filterElements); + } + } + + /** + * Element of File Filter. One accepted extension or file name pattern. + */ + private static abstract class FilterElement { + + public abstract String getName(); + + public abstract boolean accept(File f); + + /** + * Compare two filter elements. Correct implementation of this method + * prevents adding duplicite elements to the filter. + */ + public abstract ComparisonResult compare(FilterElement e); + + public static FilterElement createForExtension(String ext) { + return new ExtensionBasedFilterElement(ext); + } + + public static FilterElement createForFileName(String name, + String extension, boolean substring, boolean ignoreCase) { + return new NameBasedFilterElement(name, extension, + substring, ignoreCase); + } + + public static enum ComparisonResult { + + THE_SAME, BETTER, WORSE, DIFFERENT + } + + private static class ExtensionBasedFilterElement extends FilterElement { + + private final String extension; + + public ExtensionBasedFilterElement(String extension) { + if (extension != null) { + this.extension = extension; + } else { + throw new NullPointerException(); + } + } + + @Override + public String getName() { + return "." + extension; //NOI18N + } + + @Override + public boolean accept(File f) { + return f.getName().toLowerCase().endsWith( + "." + extension.toLowerCase()); //NOI18N + } + + @Override + public ComparisonResult compare(FilterElement e) { + if (!(e instanceof ExtensionBasedFilterElement)) { + return ComparisonResult.DIFFERENT; + } + ExtensionBasedFilterElement x = (ExtensionBasedFilterElement) e; + if (x == null) { + throw new NullPointerException(); + } + if (this.extension.equals(x.extension)) { + return ComparisonResult.THE_SAME; + } else if (this.extension.equalsIgnoreCase(x.extension) + && this.extension.length() > 1) { + if (Character.isUpperCase(x.extension.charAt(0))) { + return ComparisonResult.BETTER; //this better, x worse + } else { + return ComparisonResult.WORSE; // this worse, x better + } + } else { + return ComparisonResult.DIFFERENT; + } + } + } + + private static class NameBasedFilterElement extends FilterElement { + + String name; + String ext; + boolean substring; + boolean ignoreCase; + Pattern p; + + public NameBasedFilterElement(String name, String ext, + boolean substring, boolean ignoreCase) { + this.name = name; + this.ext = ext; + this.substring = substring; + this.ignoreCase = ignoreCase; + StringBuilder sb = new StringBuilder(); + if (ignoreCase) { + sb.append("(?i)"); //NOI18N + } + if (substring) { + sb.append(".*"); //NOI18N + } + sb.append(name); //NOI18N + if (substring) { + sb.append(".*"); //NOI18N + } + if (!ext.isEmpty()) { + sb.append("\\."); //NOI18N + sb.append(ext); + } + p = Pattern.compile(sb.toString()); + } + + @Override + public String getName() { + return name + (ext.isEmpty() ? "" : "." + ext); //NOI18N + } + + @Override + public boolean accept(File f) { + return p.matcher(f.getName()).matches(); + } + + @Override + public ComparisonResult compare(FilterElement e) { + if (e == null) { + throw new NullPointerException(); + } else if (!(e instanceof NameBasedFilterElement)) { + return ComparisonResult.DIFFERENT; + } + NameBasedFilterElement x = (NameBasedFilterElement) e; + if (this.name.equals(x.name) && this.ext.equals(x.ext)) { + if (this.substring == x.substring + && this.ignoreCase == x.ignoreCase) { + return ComparisonResult.THE_SAME; + } else { + return compareFlags(x); + } + } else if (this.ext.equalsIgnoreCase(x.ext) + && this.name.equalsIgnoreCase(x.name) + && (this.ignoreCase || x.ignoreCase)) { + if (this.substring == x.substring + && this.ignoreCase == x.ignoreCase) { + if (Character.isLowerCase(this.name.charAt(0))) { + return ComparisonResult.BETTER; + } else { + return ComparisonResult.WORSE; + } + } else { + return compareFlags(x); + } + } else { + return ComparisonResult.DIFFERENT; + } + } + + private ComparisonResult compareFlags(NameBasedFilterElement x) { + if (this.substring == x.substring + && this.ignoreCase) { + return ComparisonResult.BETTER; + } else if (this.ignoreCase == x.ignoreCase + && this.substring) { + return ComparisonResult.BETTER; + } else if (this.substring != x.substring + && this.ignoreCase != x.ignoreCase) { + return ComparisonResult.DIFFERENT; + } else { + return ComparisonResult.WORSE; + } + } + } + } +} diff --git a/openide.filesystems.nb/src/org/netbeans/modules/openide/filesystems/FileSystemStatus.java b/openide.filesystems.nb/src/org/netbeans/modules/openide/filesystems/FileSystemStatus.java new file mode 100644 --- /dev/null +++ b/openide.filesystems.nb/src/org/netbeans/modules/openide/filesystems/FileSystemStatus.java @@ -0,0 +1,163 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2014 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2014 Sun Microsystems, Inc. + */ + +package org.netbeans.modules.openide.filesystems; + +import java.awt.Image; +import java.awt.Toolkit; +import java.beans.BeanInfo; +import java.net.URL; +import java.util.Arrays; +import java.util.MissingResourceException; +import java.util.ResourceBundle; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.openide.filesystems.FileObject; +import org.openide.filesystems.FileSystem; +import org.openide.util.BaseUtilities; +import org.openide.util.Exceptions; +import org.openide.util.ImageUtilities; +import org.openide.util.NbBundle; +import org.openide.util.lookup.ServiceProvider; + +/** + * + * @author sdedic + */ +@ServiceProvider(service = FileSystem.Status.class) +public final class FileSystemStatus implements FileSystem.Status{ + private static final Logger LOG = Logger.getLogger(FileSystemStatus.class.getName()); + + public String annotateName(String s, Set files) { + // Look for a localized file name. + // Note: all files in the set are checked. But please only place the attribute + // on the primary file, and use this primary file name as the bundle key. + for (FileObject fo : files) { + // annotate a name + String displayName = annotateName(fo); + if (displayName != null) { + return displayName; + } + } + return s; + } + + private final String annotateName(FileObject fo) { + String bundleName = (String) fo.getAttribute("SystemFileSystem.localizingBundle"); // NOI18N + if (bundleName != null) { + try { + bundleName = BaseUtilities.translate(bundleName); + ResourceBundle b = NbBundle.getBundle(bundleName); + try { + return b.getString(fo.getPath()); + } catch (MissingResourceException ex) { + // ignore--normal + } + } catch (MissingResourceException ex) { + Exceptions.attachMessage(ex, warningMessage(bundleName, fo)); + LOG.log(Level.INFO, null, ex); + // ignore + } + } + return (String) fo.getAttribute("displayName"); // NOI18N + } + + private String warningMessage(String name, FileObject fo) { + Object by = fo.getAttribute("layers"); // NOI18N + if (by instanceof Object[]) { + by = Arrays.toString((Object[]) by); + } + return "Cannot load " + name + " for " + fo + " defined by " + by; // NOI18N + } + + public Image annotateIcon(Image im, int type, Set files) { + for (FileObject fo : files) { + Image img = annotateIcon(fo, type); + if (img != null) { + return img; + } + } + return im; + } + + private Image annotateIcon(FileObject fo, int type) { + String attr = null; + if (type == BeanInfo.ICON_COLOR_16x16) { + attr = "SystemFileSystem.icon"; // NOI18N + } else if (type == BeanInfo.ICON_COLOR_32x32) { + attr = "SystemFileSystem.icon32"; // NOI18N + } + if (attr != null) { + Object value = fo.getAttribute(attr); + if (value != null) { + if (value instanceof URL) { + return Toolkit.getDefaultToolkit().getImage((URL) value); + } else if (value instanceof Image) { + // #18832 + return (Image) value; + } else { + LOG.warning("Attribute " + attr + " on " + fo + " expected to be a URL or Image; was: " + value); + } + } + } + String base = (String) fo.getAttribute("iconBase"); // NOI18N + if (base != null) { + if (type == BeanInfo.ICON_COLOR_16x16) { + return ImageUtilities.loadImage(base, true); + } else if (type == BeanInfo.ICON_COLOR_32x32) { + return ImageUtilities.loadImage(insertBeforeSuffix(base, "_32"), true); // NOI18N + } + } + return null; + } + + private String insertBeforeSuffix(String path, String toInsert) { + String withoutSuffix = path; + String suffix = ""; // NOI18N + if (path.lastIndexOf('.') >= 0) { + withoutSuffix = path.substring(0, path.lastIndexOf('.')); + suffix = path.substring(path.lastIndexOf('.'), path.length()); + } + return withoutSuffix + toInsert + suffix; + } +} diff --git a/openide.filesystems.nb/src/org/netbeans/modules/openide/filesystems/SharedClassObjectFactory.java b/openide.filesystems.nb/src/org/netbeans/modules/openide/filesystems/SharedClassObjectFactory.java new file mode 100644 --- /dev/null +++ b/openide.filesystems.nb/src/org/netbeans/modules/openide/filesystems/SharedClassObjectFactory.java @@ -0,0 +1,66 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2014 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2014 Sun Microsystems, Inc. + */ + +package org.netbeans.modules.openide.filesystems; + +import org.openide.filesystems.spi.CustomInstanceFactory; +import org.openide.util.SharedClassObject; +import org.openide.util.lookup.ServiceProvider; + +/** + * Handles creation of SharedClassObjects for Filesystems API. + * + * @author sdedic + */ +@ServiceProvider(service = CustomInstanceFactory.class) +public final class SharedClassObjectFactory implements CustomInstanceFactory { + + @Override + public T createInstance(Class clazz) { + if (SharedClassObject.class.isAssignableFrom(clazz)) { + return (T)SharedClassObject.findObject(clazz.asSubclass(SharedClassObject.class), true); + } else { + return null; + } + } + +} diff --git a/openide.filesystems.nb/src/org/openide/filesystems/FileChooserBuilder.java b/openide.filesystems.nb/src/org/openide/filesystems/FileChooserBuilder.java new file mode 100644 --- /dev/null +++ b/openide.filesystems.nb/src/org/openide/filesystems/FileChooserBuilder.java @@ -0,0 +1,688 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * Contributor(s): + * + * The Original Software is NetBeans. The Initial Developer of the Original + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun + * Microsystems, Inc. All Rights Reserved. + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + */ +package org.openide.filesystems; + +import java.awt.Component; +import java.awt.FileDialog; +import java.awt.Frame; +import java.awt.HeadlessException; +import java.awt.KeyboardFocusManager; +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import javax.swing.Icon; +import javax.swing.JFileChooser; +import javax.swing.SwingUtilities; +import javax.swing.filechooser.FileFilter; +import javax.swing.filechooser.FileSystemView; +import javax.swing.filechooser.FileView; +import org.netbeans.modules.openide.filesystems.FileFilterSupport; +import org.openide.filesystems.FileUtil; +import org.openide.util.*; + +/** + * Utility class for working with JFileChoosers. In particular, remembering + * the last-used directory for a given file is made transparent. You pass an + * ad-hoc string key to the constructor (the fully qualified name of the + * calling class is good for uniqueness, and there is a constructor that takes + * a Class object as an argument for this purpose). That key is + * used to look up the most recently-used directory from any previous invocations + * with the same key. This makes it easy to have your user interface + * “remember” where the user keeps particular types of files, and + * saves the user from having to navigate through the same set of directories + * every time they need to locate a file from a particular place. + *

+ * FileChooserBuilder's methods each return this, so + * it is possible to chain invocations to simplify setting up a file chooser. + * Example usage: + *

+ *      //The default dir to use if no value is stored
+ *      File home = new File (System.getProperty("user.home") + File.separator + "lib");
+ *      //Now build a file chooser and invoke the dialog in one line of code
+ *      //"libraries-dir" is our unique key
+ *      File toAdd = new FileChooserBuilder ("libraries-dir").setTitle("Add Library").
+ *              setDefaultWorkingDirectory(home).setApproveText("Add").showOpenDialog();
+ *      //Result will be null if the user clicked cancel or closed the dialog w/o OK
+ *      if (toAdd != null) {
+ *          //do something
+ *      }
+ *
+ *

+ * Instances of this class are intended to be thrown away after use. Typically + * you create a builder, set it to create file choosers as you wish, then + * use it to show a dialog or create a file chooser you then do something + * with. + *

+ * Supports the most common subset of JFileChooser functionality; if you + * need to do something exotic with a file chooser, you are probably better + * off creating your own. + *

+ * Note: If you use the constructor that takes a Class object, + * please use new FileChooserBuilder(MyClass.class), not + * new FileChooserBuilder(getClass()). This avoids unexpected + * behavior in the case of subclassing. + * + * @author Tim Boudreau + */ +public class FileChooserBuilder { + private boolean dirsOnly; + private BadgeProvider badger; + private String title; + private String approveText; + //Just in case... + private static boolean PREVENT_SYMLINK_TRAVERSAL = + !Boolean.getBoolean("allow.filechooser.symlink.traversal"); //NOI18N + private final String dirKey; + private File failoverDir; + private FileFilter filter; + private boolean fileHiding; + private boolean controlButtonsShown = true; + private String aDescription; + private boolean filesOnly; + private static final boolean DONT_STORE_DIRECTORIES = + Boolean.getBoolean("forget.recent.dirs"); + private SelectionApprover approver; + private final List filters = new ArrayList(3); + private boolean useAcceptAllFileFilter = true; + /** + * Create a new FileChooserBuilder using the name of the passed class + * as the metadata for looking up a starting directory from previous + * application sessions or invocations. + * @param type A non-null class object, typically the calling class + */ + public FileChooserBuilder(Class type) { + this(type.getName()); + } + + /** + * Create a new FileChooserBuilder. The passed key is used as a key + * into NbPreferences to look up the directory the file chooser should + * initially be rooted on. + * + * @param dirKey A non-null ad-hoc string. If a FileChooser was previously + * used with the same string as is passed, then the initial directory + */ + public FileChooserBuilder(String dirKey) { + Parameters.notNull("dirKey", dirKey); + this.dirKey = dirKey; + } + + /** + * Set whether or not any file choosers created by this builder will show + * only directories. + * @param val true if files should not be shown + * @return this + */ + public FileChooserBuilder setDirectoriesOnly(boolean val) { + dirsOnly = val; + assert !filesOnly : "FilesOnly and DirsOnly are mutually exclusive"; + return this; + } + + public FileChooserBuilder setFilesOnly(boolean val) { + filesOnly = val; + assert !dirsOnly : "FilesOnly and DirsOnly are mutually exclusive"; + return this; + } + + /** + * Provide an implementation of BadgeProvider which will "badge" the + * icons of some files. + * + * @param provider A badge provider which will alter the icon of files + * or folders that may be of particular interest to the user + * @return this + */ + public FileChooserBuilder setBadgeProvider(BadgeProvider provider) { + this.badger = provider; + return this; + } + + /** + * Set the dialog title for any JFileChoosers created by this builder. + * @param val A localized, human-readable title + * @return this + */ + public FileChooserBuilder setTitle(String val) { + title = val; + return this; + } + + /** + * Set the text on the OK button for any file chooser dialogs produced + * by this builder. + * @param val A short, localized, human-readable string + * @return this + */ + public FileChooserBuilder setApproveText(String val) { + approveText = val; + return this; + } + + /** + * Set a file filter which filters the list of selectable files. + * @param filter + * @return this + */ + public FileChooserBuilder setFileFilter (FileFilter filter) { + this.filter = filter; + return this; + } + + /** + * Determines whether the AcceptAll FileFilter is used + * as an available choice in the choosable filter list. + * If false, the AcceptAll file filter is removed from + * the list of available file filters. + * If true, the AcceptAll file filter will become the + * the actively used file filter. + * @param accept whether the AcceptAll FileFilter is used + * @return this + * @since 8.3 + */ + public FileChooserBuilder setAcceptAllFileFilterUsed(boolean accept) { + useAcceptAllFileFilter = accept; + return this; + } + + /** + * Set the current directory which should be used only if + * a last-used directory cannot be found for the key string passed + * into this builder's constructor. + * @param dir A directory to root any created file choosers on if + * there is no stored path for this builder's key + * @return this + */ + public FileChooserBuilder setDefaultWorkingDirectory (File dir) { + failoverDir = dir; + return this; + } + + /** + * Enable file hiding in any created file choosers + * @param fileHiding Whether or not to hide files. Default is no. + * @return this + */ + public FileChooserBuilder setFileHiding(boolean fileHiding) { + this.fileHiding = fileHiding; + return this; + } + + /** + * Show/hide control buttons + * @param val Whether or not to hide files. Default is no. + * @return this + */ + public FileChooserBuilder setControlButtonsAreShown(boolean val) { + this.controlButtonsShown = val; + return this; + } + + /** + * Set the accessible description for any file choosers created by this + * builder + * @param aDescription The description + * @return this + */ + public FileChooserBuilder setAccessibleDescription(String aDescription) { + this.aDescription = aDescription; + return this; + } + + /** + * Create a JFileChooser that conforms to the parameters set in this + * builder. + * @return A file chooser + */ + public JFileChooser createFileChooser() { + JFileChooser result = new SavedDirFileChooser(dirKey, failoverDir, + force, approver); + prepareFileChooser(result); + return result; + } + + private boolean force = false; + /** + * Force use of the failover directory - i.e. ignore the directory key + * passed in. + * @param val + * @return this + */ + public FileChooserBuilder forceUseOfDefaultWorkingDirectory(boolean val) { + this.force = val; + return this; + } + + /** + * Tries to find an appropriate component to parent the file chooser to + * when showing a dialog. + * @return this + */ + private Component findDialogParent() { + Component parent = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); + if (parent == null) { + parent = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow(); + } + if (parent == null) { + Frame[] f = Frame.getFrames(); + parent = f.length == 0 ? null : f[f.length - 1]; + } + return parent; + } + + /** + * Show an open dialog that allows multiple selection. + * @return An array of files, or null if the user cancelled the dialog + */ + public File[] showMultiOpenDialog() { + JFileChooser chooser = createFileChooser(); + chooser.setMultiSelectionEnabled(true); + int result = chooser.showOpenDialog(findDialogParent()); + if (JFileChooser.APPROVE_OPTION == result) { + File[] files = chooser.getSelectedFiles(); + return files == null ? new File[0] : files; + } else { + return null; + } + } + + /** + * Show an open dialog with a file chooser set up according to the + * parameters of this builder. + * @return A file if the user clicks the accept button and a file or + * folder was selected at the time the user clicked cancel. + */ + public File showOpenDialog() { + JFileChooser chooser = createFileChooser(); + if( Boolean.getBoolean("nb.native.filechooser") ) { //NOI18N + FileDialog fileDialog = createFileDialog( chooser.getCurrentDirectory() ); + if( null != fileDialog ) { + return showFileDialog(fileDialog, FileDialog.LOAD ); + } + } + chooser.setMultiSelectionEnabled(false); + int dlgResult = chooser.showOpenDialog(findDialogParent()); + if (JFileChooser.APPROVE_OPTION == dlgResult) { + File result = chooser.getSelectedFile(); + if (result != null && !result.exists()) { + result = null; + } + return result; + } else { + return null; + } + + } + + /** + * Show a save dialog with the file chooser set up according to the + * parameters of this builder. + * @return A file if the user clicks the accept button and a file or + * folder was selected at the time the user clicked cancel. + */ + public File showSaveDialog() { + JFileChooser chooser = createFileChooser(); + if( Boolean.getBoolean("nb.native.filechooser") ) { //NOI18N + FileDialog fileDialog = createFileDialog( chooser.getCurrentDirectory() ); + if( null != fileDialog ) { + return showFileDialog( fileDialog, FileDialog.SAVE ); + } + } + int result = chooser.showSaveDialog(findDialogParent()); + if (JFileChooser.APPROVE_OPTION == result) { + return chooser.getSelectedFile(); + } else { + return null; + } + } + + private File showFileDialog( FileDialog fileDialog, int mode ) { + String oldFileDialogProp = System.getProperty("apple.awt.fileDialogForDirectories"); //NOI18N + if( dirsOnly ) { + System.setProperty("apple.awt.fileDialogForDirectories", "true"); //NOI18N + } + fileDialog.setMode( mode ); + fileDialog.setVisible(true); + if( dirsOnly ) { + if( null != oldFileDialogProp ) { + System.setProperty("apple.awt.fileDialogForDirectories", oldFileDialogProp); //NOI18N + } else { + System.clearProperty("apple.awt.fileDialogForDirectories"); //NOI18N + } + } + if( fileDialog.getDirectory() != null && fileDialog.getFile() != null ) { + String selFile = fileDialog.getFile(); + File dir = new File( fileDialog.getDirectory() ); + return new File( dir, selFile ); + } + return null; + } + + private void prepareFileChooser(JFileChooser chooser) { + chooser.setFileSelectionMode(dirsOnly ? JFileChooser.DIRECTORIES_ONLY + : filesOnly ? JFileChooser.FILES_ONLY : + JFileChooser.FILES_AND_DIRECTORIES); + chooser.setFileHidingEnabled(fileHiding); + chooser.setControlButtonsAreShown(controlButtonsShown); + chooser.setAcceptAllFileFilterUsed(useAcceptAllFileFilter); + if (title != null) { + chooser.setDialogTitle(title); + } + if (approveText != null) { + chooser.setApproveButtonText(approveText); + } + if (badger != null) { + chooser.setFileView(new CustomFileView(new BadgeIconProvider(badger), + chooser.getFileSystemView())); + } + if (PREVENT_SYMLINK_TRAVERSAL) { + FileUtil.preventFileChooserSymlinkTraversal(chooser, + chooser.getCurrentDirectory()); + } + if (filter != null) { + chooser.setFileFilter(filter); + } + if (aDescription != null) { + chooser.getAccessibleContext().setAccessibleDescription(aDescription); + } + if (!filters.isEmpty()) { + for (FileFilter f : filters) { + chooser.addChoosableFileFilter(f); + } + } + } + + private FileDialog createFileDialog( File currentDirectory ) { + if( badger != null ) + return null; + if( !Boolean.getBoolean("nb.native.filechooser") ) + return null; + if( dirsOnly && !BaseUtilities.isMac() ) + return null; + Component parentComponent = findDialogParent(); + Frame parentFrame = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parentComponent); + FileDialog fileDialog = new FileDialog(parentFrame); + if (title != null) { + fileDialog.setTitle(title); + } + if( null != currentDirectory ) + fileDialog.setDirectory(currentDirectory.getAbsolutePath()); + return fileDialog; + } + + /** + * Equivalent to calling JFileChooser.addChoosableFileFilter(filter). + * Adds another file filter that can be displayed in the file filters combo + * box in the file chooser. + * + * @param filter The file filter to add + * @return this + * @since 7.26.0 + */ + public FileChooserBuilder addFileFilter (FileFilter filter) { + filters.add (filter); + return this; + } + + /** + * Add all default file filters to the file chooser. + * + * @see MIMEResolver.Registration#showInFileChooser() + * @see MIMEResolver.ExtensionRegistration#showInFileChooser() + * @return this + * @since 8.1 + */ + public FileChooserBuilder addDefaultFileFilters() { + filters.addAll(FileFilterSupport.findRegisteredFileFilters()); + return this; + } + + /** + * Set a selection approver which can display an "Overwrite file?" + * or similar dialog if necessary, when the user presses the accept button + * in the file chooser dialog. + * + * @param approver A SelectionApprover which will determine if the selection + * is valid + * @return this + * @since 7.26.0 + */ + public FileChooserBuilder setSelectionApprover (SelectionApprover approver) { + this.approver = approver; + return this; + } + + /** + * Object which can approve the selection (enabling the OK button or + * equivalent) in a JFileChooser. Equivalent to overriding + * JFileChooser.approveSelection() + * @since 7.26.0 + */ + public interface SelectionApprover { + /** + * Approve the selection, enabling the dialog to be closed. Called by + * the JFileChooser's approveSelection() method. Use this + * interface if you want to, for example, show a dialog asking + * "Overwrite File X?" or similar. + * + * @param selection The selected file(s) at the time the user presses + * the Open, Save or OK button + * @return true if the selection is accepted, false if it is not and + * the dialog should not be closed + */ + public boolean approve (File[] selection); + } + + private static final class SavedDirFileChooser extends JFileChooser { + private final String dirKey; + private final SelectionApprover approver; + SavedDirFileChooser(String dirKey, File failoverDir, boolean force, SelectionApprover approver) { + this.dirKey = dirKey; + this.approver = approver; + if (force && failoverDir != null && failoverDir.exists() && failoverDir.isDirectory()) { + setCurrentDirectory(failoverDir); + } else { + String path = DONT_STORE_DIRECTORIES ? null : + NbPreferences.forModule(FileChooserBuilder.class).get(dirKey, null); + if (path != null) { + File f = new File(path); + if (f.exists() && f.isDirectory()) { + setCurrentDirectory(f); + } else if (failoverDir != null) { + setCurrentDirectory(failoverDir); + } + } else if (failoverDir != null) { + setCurrentDirectory(failoverDir); + } + } + } + + @Override + public void approveSelection() { + if (approver != null) { + File[] selected = getSelectedFiles(); + final File sf = getSelectedFile(); + if ((selected == null || selected.length == 0) && sf != null) { + selected = new File[] { sf }; + } + boolean approved = approver.approve(selected); + if (approved) { + super.approveSelection(); + } + } else { + super.approveSelection(); + } + } + + @Override + public int showDialog(Component parent, String approveButtonText) throws HeadlessException { + int result = super.showDialog(parent, approveButtonText); + if (result == APPROVE_OPTION) { + saveCurrentDir(); + } + return result; + } + + private void saveCurrentDir() { + File dir = super.getCurrentDirectory(); + if (!DONT_STORE_DIRECTORIES && dir != null && dir.exists() && dir.isDirectory()) { + NbPreferences.forModule(FileChooserBuilder.class).put(dirKey, dir.getPath()); + } + } + } + + //Can open this API later if there is a use-case + interface IconProvider { + public Icon getIcon(File file, Icon orig); + } + + /** + * Provides "badges" for icons that indicate files or folders of particular + * interest to the user. + * @see FileChooserBuilder#setBadgeProvider + */ + public interface BadgeProvider { + /** + * Get the badge the passed file should use. Note: this method + * is called for every visible file. The negative test (deciding + * not to badge a file) should be very, very fast and immediately + * return null. + * @param file The file in question + * @return an icon or null if no change to the appearance of the file + * is needed + */ + public Icon getBadge(File file); + + /** + * Get the x offset for badges produced by this provider. This is + * the location of the badge icon relative to the real icon for the + * file. + * @return a rightward pixel offset + */ + public int getXOffset(); + + /** + * Get the y offset for badges produced by this provider. This is + * the location of the badge icon relative to the real icon for the + * file. + * @return a downward pixel offset + */ + public int getYOffset(); + } + + private static final class BadgeIconProvider implements IconProvider { + + private final BadgeProvider badger; + + public BadgeIconProvider(BadgeProvider badger) { + this.badger = badger; + } + + public Icon getIcon(File file, Icon orig) { + Icon badge = badger.getBadge(file); + if (badge != null && orig != null) { + return new MergedIcon(orig, badge, badger.getXOffset(), + badger.getYOffset()); + } + return orig; + } + } + + private static final class CustomFileView extends FileView { + + private final IconProvider provider; + private final FileSystemView view; + + CustomFileView(IconProvider provider, FileSystemView view) { + this.provider = provider; + this.view = view; + } + + @Override + public Icon getIcon(File f) { + Icon result = view.getSystemIcon(f); + result = provider.getIcon(f, result); + return result; + } + } + + private static class MergedIcon implements Icon { + + private Icon icon1; + private Icon icon2; + private int xMerge; + private int yMerge; + + MergedIcon(Icon icon1, Icon icon2, int xMerge, int yMerge) { + assert icon1 != null; + assert icon2 != null; + this.icon1 = icon1; + this.icon2 = icon2; + + if (xMerge == -1) { + xMerge = icon1.getIconWidth() - icon2.getIconWidth(); + } + + if (yMerge == -1) { + yMerge = icon1.getIconHeight() - icon2.getIconHeight(); + } + + this.xMerge = xMerge; + this.yMerge = yMerge; + } + + public int getIconHeight() { + return Math.max(icon1.getIconHeight(), yMerge + icon2.getIconHeight()); + } + + public int getIconWidth() { + return Math.max(icon1.getIconWidth(), yMerge + icon2.getIconWidth()); + } + + public void paintIcon(java.awt.Component c, java.awt.Graphics g, int x, int y) { + icon1.paintIcon(c, g, x, y); + icon2.paintIcon(c, g, x + xMerge, y + yMerge); + } + } +} diff --git a/openide.filesystems.nb/src/org/openide/filesystems/nb/Bundle.properties b/openide.filesystems.nb/src/org/openide/filesystems/nb/Bundle.properties new file mode 100644 --- /dev/null +++ b/openide.filesystems.nb/src/org/openide/filesystems/nb/Bundle.properties @@ -0,0 +1,6 @@ +OpenIDE-Module-Display-Category=RCP Platform +OpenIDE-Module-Long-Description=\ + The FileSystems API should remain independent of desktop (most notably javax.swing) dependencies in order to be used as a support library in arbitrary deployment. \ + Classes that use Swing UI library were factored out into this module. +OpenIDE-Module-Name=Filesystems NetBeans Client +OpenIDE-Module-Short-Description=Swing specific classes for Filesystems API diff --git a/openide.filesystems.nb/test/unit/src/org/netbeans/modules/openide/filesystems/FileFilterSupportTest.java b/openide.filesystems.nb/test/unit/src/org/netbeans/modules/openide/filesystems/FileFilterSupportTest.java new file mode 100644 --- /dev/null +++ b/openide.filesystems.nb/test/unit/src/org/netbeans/modules/openide/filesystems/FileFilterSupportTest.java @@ -0,0 +1,113 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2012 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2012 Sun Microsystems, Inc. + */ +package org.netbeans.modules.openide.filesystems; + +import java.io.File; +import java.util.List; +import javax.swing.filechooser.FileFilter; +import org.netbeans.junit.NbTestCase; +import org.openide.filesystems.MIMEResolver; +import org.openide.util.NbBundle; + +/** + * Test registered FileFilters. + * + * @author jhavlin + */ +@NbBundle.Messages({ + "RESOLVER=Resolver", + "FILECHOOSER=BNM Files" +}) +@MIMEResolver.Registration( + displayName = "#RESOLVER", + resource = "mime-resolver-filechooser.xml", + showInFileChooser = "#FILECHOOSER", position=543543) +public class FileFilterSupportTest extends NbTestCase { + + public FileFilterSupportTest(String name) { + super(name); + } + + /** + * This test, although it is quite short, tests a lot of ascpects of default + * file filters. The resolver definition XML file contains several + * duplicities, which are detected and ignored. If this detection fails, + * filter description and {@code accept} method is changed, and it is cought + * by this test. + */ + public void testRegisteredFilters() { + List list = FileFilterSupport.findRegisteredFileFilters(); + assertNotNull(list); + assertFalse(list.isEmpty()); + + boolean found = false; + for (FileFilter filter : list) { + + if (filter.getDescription().startsWith("BNM Files")) { + found = true; + checkBnmFilesFilter(filter); + } + } + assertTrue("Registered File Filter was not found.", found); + } + + private void checkBnmFilesFilter(FileFilter f) { + assertEquals("BNM Files [.bnm, bnmHelp, bnmProject, bnminfo, bnmsettings]", + f.getDescription()); + assertTrue(f.accept(new File("first.bnm"))); + assertTrue(f.accept(new File("second.BNM"))); + assertTrue(f.accept(new File("third.bNm"))); + assertTrue(f.accept(new File("bnmProject"))); + assertTrue(f.accept(new File("PREFIXbnmProjectAndSuFfIx"))); + assertFalse(f.accept(new File("bnmproject"))); + assertTrue(f.accept(new File("bnmSettings"))); + assertTrue(f.accept(new File("BNMSETTINGS"))); + assertFalse(f.accept(new File("bnmSettingsX"))); + assertTrue(f.accept(new File("bnmInfo"))); + assertTrue(f.accept(new File("AbnmInfoB"))); + assertTrue(f.accept(new File("aBNMINFOb"))); + assertTrue(f.accept(new File("bnmHelp"))); + assertFalse(f.accept(new File("bnmhelp"))); + assertFalse(f.accept(new File("bnmHelpX"))); + assertFalse(f.accept(new File("foo.txt"))); + } +} diff --git a/openide.filesystems.nb/test/unit/src/org/netbeans/modules/openide/filesystems/SharedClassObjectFactoryTest.java b/openide.filesystems.nb/test/unit/src/org/netbeans/modules/openide/filesystems/SharedClassObjectFactoryTest.java new file mode 100644 --- /dev/null +++ b/openide.filesystems.nb/test/unit/src/org/netbeans/modules/openide/filesystems/SharedClassObjectFactoryTest.java @@ -0,0 +1,101 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2014 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2014 Sun Microsystems, Inc. + */ + +package org.netbeans.modules.openide.filesystems; + +import java.io.File; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.openide.filesystems.FileObject; +import org.openide.filesystems.FileUtil; +import org.openide.util.Lookup; +import org.openide.util.SharedClassObject; +import org.openide.util.lookup.Lookups; +import org.openide.util.lookup.NamedServicesLookupTest; + +/** + * + * @author sdedic + */ +public class SharedClassObjectFactoryTest extends NamedServicesLookupTest { + private FileObject root; + private Logger LOG; + + + public SharedClassObjectFactoryTest(String name) { + super(name); + } + + @Override + protected Level logLevel() { + return Level.FINEST; + } + + @Override + protected void setUp() throws Exception { + if (System.getProperty("netbeans.user") == null) { + System.setProperty("netbeans.user", new File(getWorkDir(), "ud").getPath()); + } + + LOG = Logger.getLogger("Test." + getName()); + + root = FileUtil.getConfigRoot(); + for (FileObject fo : root.getChildren()) { + fo.delete(); + } + + super.setUp(); + } + + public void testSharedClassObject() throws Exception { + Shared instance = SharedClassObject.findObject(Shared.class, true); + FileObject data = FileUtil.createData(root, "dir/" + Shared.class.getName().replace('.', '-') + ".instance"); + Lookup l = Lookups.forPath("dir"); + assertSame(instance, l.lookup(Shared.class)); + + Shared created = FileUtil.getConfigObject(data.getPath(), Shared.class); + assertSame("Config file found", instance, created); + } + + public static final class Shared extends SharedClassObject {} + +} diff --git a/openide.filesystems.nb/test/unit/src/org/netbeans/modules/openide/filesystems/mime-resolver-filechooser.xml b/openide.filesystems.nb/test/unit/src/org/netbeans/modules/openide/filesystems/mime-resolver-filechooser.xml new file mode 100644 --- /dev/null +++ b/openide.filesystems.nb/test/unit/src/org/netbeans/modules/openide/filesystems/mime-resolver-filechooser.xml @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/openide.filesystems.nb/test/unit/src/org/openide/filesystems/FileChooserBuilderTest.java b/openide.filesystems.nb/test/unit/src/org/openide/filesystems/FileChooserBuilderTest.java new file mode 100644 --- /dev/null +++ b/openide.filesystems.nb/test/unit/src/org/openide/filesystems/FileChooserBuilderTest.java @@ -0,0 +1,417 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2010 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2008 Sun Microsystems, Inc. + */ + +package org.openide.filesystems; + +import java.awt.Component; +import java.awt.Dialog; +import javax.swing.UIManager; +import javax.swing.JRootPane; +import java.util.concurrent.atomic.AtomicReference; +import java.lang.reflect.InvocationTargetException; +import java.util.concurrent.CountDownLatch; +import java.awt.Container; +import java.awt.EventQueue; +import java.io.File; +import java.io.IOException; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; +import javax.swing.AbstractButton; +import javax.swing.JFileChooser; +import javax.swing.RootPaneContainer; +import javax.swing.UnsupportedLookAndFeelException; +import javax.swing.event.AncestorEvent; +import javax.swing.event.AncestorListener; +import javax.swing.filechooser.FileFilter; +import javax.swing.plaf.metal.MetalLookAndFeel; +import org.netbeans.junit.NbTestCase; +import org.openide.util.RequestProcessor; +import static org.junit.Assert.*; +import org.netbeans.junit.RandomlyFails; + +/** + * @author tim + */ +public class FileChooserBuilderTest extends NbTestCase { + + public FileChooserBuilderTest(String name) { + super(name); + } + + /** + * Test of setDirectoriesOnly method, of class FileChooserBuilder. + */ + public void testSetDirectoriesOnly() { + FileChooserBuilder instance = new FileChooserBuilder("x"); + boolean dirsOnly = instance.createFileChooser().getFileSelectionMode() == JFileChooser.DIRECTORIES_ONLY; + assertFalse(dirsOnly); + instance.setDirectoriesOnly(true); + dirsOnly = instance.createFileChooser().getFileSelectionMode() == JFileChooser.DIRECTORIES_ONLY; + assertTrue(dirsOnly); + } + + /** + * Test of setFilesOnly method, of class FileChooserBuilder. + */ + public void testSetFilesOnly() { + FileChooserBuilder instance = new FileChooserBuilder("y"); + boolean filesOnly = instance.createFileChooser().getFileSelectionMode() == JFileChooser.FILES_ONLY; + assertFalse(filesOnly); + instance.setFilesOnly(true); + filesOnly = instance.createFileChooser().getFileSelectionMode() == JFileChooser.FILES_ONLY; + assertTrue(filesOnly); + } + + /** + * Test of setTitle method, of class FileChooserBuilder. + */ + public void testSetTitle() { + FileChooserBuilder instance = new FileChooserBuilder("a"); + assertNull(instance.createFileChooser().getDialogTitle()); + instance.setTitle("foo"); + assertEquals("foo", instance.createFileChooser().getDialogTitle()); + } + + /** + * Test of setApproveText method, of class FileChooserBuilder. + */ + public void testSetApproveText() { + FileChooserBuilder instance = new FileChooserBuilder("b"); + assertNull(instance.createFileChooser().getDialogTitle()); + instance.setApproveText("bar"); + assertEquals("bar", instance.createFileChooser().getApproveButtonText()); + } + + /** + * Test of setFileFilter method, of class FileChooserBuilder. + */ + public void testSetFileFilter() { + FileFilter filter = new FileFilter() { + + @Override + public boolean accept(File f) { + return true; + } + + @Override + public String getDescription() { + return "X"; + } + }; + FileChooserBuilder instance = new FileChooserBuilder("c"); + instance.setFileFilter(filter); + assertEquals(filter, instance.createFileChooser().getFileFilter()); + } + + /** + * Test of setDefaultWorkingDirectory method, of class FileChooserBuilder. + */ + public void testSetDefaultWorkingDirectory() throws IOException { + FileChooserBuilder instance = new FileChooserBuilder("d"); + File dir = getWorkDir(); + assertTrue("tmpdir is not sane", dir.exists() && dir.isDirectory()); + instance.setDefaultWorkingDirectory(dir); + assertEquals(dir, instance.createFileChooser().getCurrentDirectory()); + } + + /** + * Test of setFileHiding method, of class FileChooserBuilder. + */ + public void testSetFileHiding() { + FileChooserBuilder instance = new FileChooserBuilder("e"); + assertFalse(instance.createFileChooser().isFileHidingEnabled()); + instance.setFileHiding(true); + assertTrue(instance.createFileChooser().isFileHidingEnabled()); + } + + /** + * Test of setControlButtonsAreShown method, of class FileChooserBuilder. + */ + public void testSetControlButtonsAreShown() { + FileChooserBuilder instance = new FileChooserBuilder("f"); + assertTrue(instance.createFileChooser().getControlButtonsAreShown()); + instance.setControlButtonsAreShown(false); + assertFalse(instance.createFileChooser().getControlButtonsAreShown()); + } + + /** + * Test of setAccessibleDescription method, of class FileChooserBuilder. + */ + public void testSetAccessibleDescription() { + FileChooserBuilder instance = new FileChooserBuilder("g"); + String desc = "desc"; + instance.setAccessibleDescription(desc); + assertEquals(desc, instance.createFileChooser().getAccessibleContext().getAccessibleDescription()); + } + + /** + * Test of createFileChooser method, of class FileChooserBuilder. + */ + public void testCreateFileChooser() { + FileChooserBuilder instance = new FileChooserBuilder("h"); + assertNotNull(instance.createFileChooser()); + } + + public void testSetSelectionApprover() throws Exception { + FileChooserBuilder instance = new FileChooserBuilder("i"); + File tmp = new File(System.getProperty("java.io.tmpdir")); + assertTrue ("Environment is insane", tmp.exists() && tmp.isDirectory()); + File sel = new File("tmp" + System.currentTimeMillis()); + if (!sel.exists()) { + assertTrue (sel.createNewFile()); + } + instance.setDefaultWorkingDirectory(tmp); + SA sa = new SA(); + instance.setSelectionApprover(sa); + JFileChooser ch = instance.createFileChooser(); + ch.setSelectedFile(sel); + ch.approveSelection(); + sa.assertApproveInvoked(sel); + } + + public void testAddFileFilter() { + FileChooserBuilder instance = new FileChooserBuilder("j"); + FF one = new FF ("a"); + FF two = new FF ("b"); + instance.addFileFilter(one); + instance.addFileFilter(two); + JFileChooser ch = instance.createFileChooser(); + Set ff = new HashSet(Arrays.asList(one, two)); + Set actual = new HashSet(Arrays.asList(ch.getChoosableFileFilters())); + assertTrue (actual.containsAll(ff)); + //actual should also contain JFileChooser.getAcceptAllFileFilter() + assertEquals (ff.size() + 1, actual.size()); + } + + public void testSetAcceptAllFileFilterUsed() { + FileChooserBuilder instance = new FileChooserBuilder("k"); + assertTrue(instance.createFileChooser().isAcceptAllFileFilterUsed()); + instance.setAcceptAllFileFilterUsed(false); + assertFalse(instance.createFileChooser().isAcceptAllFileFilterUsed()); + } + + private static final class FF extends FileFilter { + private String x; + FF(String x) { + this.x = x; + } + + @Override + public boolean accept(File f) { + return f.getName().endsWith(x); + } + + @Override + public String getDescription() { + return x; + } + + } + + private static final class SA implements FileChooserBuilder.SelectionApprover { + private File[] selection; + @Override + public boolean approve(File[] selection) { + this.selection = selection; + return true; + } + + void assertApproveInvoked(File selected) { + assertNotNull ("approve method called", selection); + assertEquals("One selected file", 1, selection.length); + assertEquals("It is the one", selected, selection[0]); + } + } + + private static AbstractButton findDefaultButton(Container c, String txt) { + if (c instanceof RootPaneContainer) { + JRootPane root = ((RootPaneContainer) c).getRootPane(); + if (root == null) { + return null; + } + AbstractButton btn = root.getDefaultButton(); + if (btn == null) { + //Metal L&F does not set default button for JFileChooser + Container parent = c; + while (parent.getParent() != null && !(parent instanceof Dialog)) { + parent = parent.getParent(); + } + if (parent instanceof Dialog) { + return findFileChooserAcceptButton ((Dialog) parent, txt); + } + } else { + return btn; + } + } + return null; + } + + private static AbstractButton findFileChooserAcceptButton(Dialog dlg, String txt) { + for (Component c : dlg.getComponents()) { + if (c instanceof Container) { + AbstractButton result = scanForButton((Container) c, txt); + if (result != null) { + return result; + } + } + } + return null; + } + + private static AbstractButton scanForButton(Container container, String txt) { + assertNotNull (container); + assertNotNull (txt); + if (container instanceof AbstractButton) { + if (txt.equals(((AbstractButton) container).getText())) { + return ((AbstractButton) container); + } + } else { + for (Component c : container.getComponents()) { + if (c instanceof Container) { + AbstractButton b = scanForButton ((Container) c, txt); + if (b != null) { + return b; + } + } + } + } + return null; + } + + @RandomlyFails // NB-Core-Build #8038: Button is visible + public void testForceUseOfDefaultWorkingDirectory() throws InterruptedException, IOException, InvocationTargetException, UnsupportedLookAndFeelException { + UIManager.setLookAndFeel(new MetalLookAndFeel()); + FileChooserBuilder instance = new FileChooserBuilder("i").setApproveText("__OK"); + instance.setDirectoriesOnly(true); + final File toDir = getWorkDir(); + final File selDir = new File(toDir, "sel" + System.currentTimeMillis()); + if (!selDir.exists()) { + assertTrue(selDir.mkdirs()); + } + + final JFileChooser ch = instance.createFileChooser(); + assertEquals ("__OK", ch.getApproveButtonText()); + final CountDownLatch showLatch = new CountDownLatch(1); + ch.addAncestorListener (new AncestorListener() { + + @Override + public void ancestorAdded(AncestorEvent event) { + if (ch.isShowing()) { + ch.removeAncestorListener(this); + showLatch.countDown(); + } + } + + @Override + public void ancestorRemoved(AncestorEvent event) { + + } + + @Override + public void ancestorMoved(AncestorEvent event) { + + } + + }); + + final AtomicReference chooserRes = new AtomicReference(); + RequestProcessor.Task task = RequestProcessor.getDefault().post(new Runnable() { + + @Override + public void run() { + Object r = ch.showOpenDialog(null); + chooserRes.set(r); + } + + }); + + + showLatch.await(); + EventQueue.invokeAndWait (new Runnable() { + @Override + public void run() { + ch.setCurrentDirectory(toDir); + } + }); + EventQueue.invokeAndWait (new Runnable() { + @Override + public void run() { + ch.setSelectedFile (selDir); + } + }); + assertTrue ("Button is visible: " + ch, ch.isShowing()); + final AtomicReference btn = new AtomicReference(); + EventQueue.invokeAndWait(new Runnable() { + + @Override + public void run() { + AbstractButton defButton = findDefaultButton(ch.getTopLevelAncestor(), ch.getApproveButtonText()); + btn.set(defButton); + } + + }); + assertNotNull("have a button", btn.get()); + assertTrue(btn.get().isEnabled()); + EventQueue.invokeAndWait(new Runnable() { + @Override + public void run() { + AbstractButton defButton = btn.get(); + defButton.doClick(); + } + }); + + task.waitFinished(); + assertEquals(JFileChooser.APPROVE_OPTION, chooserRes.get()); + + assertEquals(toDir, ch.getCurrentDirectory()); + + instance = new FileChooserBuilder("i"); + assertEquals("Directory not retained", toDir, instance.createFileChooser().getCurrentDirectory()); + + File userHome = new File(System.getProperty("user.home")); + assertTrue("Environment not sane", userHome.exists() && userHome.isDirectory()); + instance.forceUseOfDefaultWorkingDirectory(true).setDefaultWorkingDirectory(userHome); + + assertEquals(userHome, instance.createFileChooser().getCurrentDirectory()); + } +} diff --git a/openide.filesystems/apichanges.xml b/openide.filesystems/apichanges.xml --- a/openide.filesystems/apichanges.xml +++ b/openide.filesystems/apichanges.xml @@ -49,6 +49,81 @@ Filesystems API + + + FileSystem.Status icon annotation moved + + + + + +

+ The default implementation of FileSystem.Status annotated file's icon using ImageUtilities + which uses AWT graphics etc. Such dependency is not desirable in a standalone FileSystem API + library. +

+

+ The builtin implementation now does not work with the icon at all and returns null. A proper + implementation for FileSystem.Status is looked up in default Lookup and is implemented + properly (with Icon annotations) in openide.filesystems.nb module. +

+
+ +
+ + + Removed dependency on SharedClassObject + + + + + +

+ If the FileSystems API encounters a SharedClassObject subclass in the instanceClass attribute, + or derives the subclass from FileObject's name, it does not create the instance using the default + constructor, but rather using SharedClassObject.find + method. + The SharedClassObject is long deprecated and adds unwanted dependency on desktop + utilities to FileSystems API. +

+

+ A new SPI, CustomInstanceFactory is created + to create instances based on the type. The instance is searched for in the default Lookup. + The NetBeans Platform will provide an implementation that handles SharedClassObjects, + but FileSystems API library no longer implements that behaviour. A compatible implementation + of CustomInstanceFactory is provided by the openide.filesystems.nb + module. +

+
+ +
+ + + Remove dependency on Swing (SystemAction) and obsolete APIs + + + + + +

+ The primary goal of the change is to remove dependencies on Swing APIs - FileSystems should not depend + or directly use SystemAction extends javax.swing.Action. At the same time, + methods or classes which are long @deprecated and have no semantic value are removed from the APIs. +

+

+ The changes are binary-compatible; a compatibility module is created as org.openide.filesystems.compat8. + Live code (FileChooserBuilder + is moved to a new module org.openide.filesystems.nb with automatic dependency in place for client which + use filesystems in their old API version. +

+

+ It's strongly discouraged to compile against the compat8 module. Its contents will be maintained only to + ensure binary compatibility with FileSystems API 8.x, API users should not rely on any contract exposed directly by the compat8 + module. +

+
+ +
Allowed to reveal deleted files, or original files overriden by writable layer diff --git a/openide.filesystems/arch.xml b/openide.filesystems/arch.xml --- a/openide.filesystems/arch.xml +++ b/openide.filesystems/arch.xml @@ -544,7 +544,14 @@ --> -Implementations of MIMEResolver and URLMapper are looked up . + The following services are looked up: +
    +
  • Implementations of MIMEResolver and URLMapper are looked up
  • +
  • instance of FileSystem.Status which is + used as the Status of the default FileSystem
  • +
  • instance of CustomInstanceFactory + which is used to create instances for FileSystem files without instanceCreate attribute
  • +
@@ -560,7 +567,8 @@ --> -No + URLStreamHandlerFactory implementations for nbfs: and + memory: protocols are registered as named services. diff --git a/openide.filesystems/manifest.mf b/openide.filesystems/manifest.mf --- a/openide.filesystems/manifest.mf +++ b/openide.filesystems/manifest.mf @@ -2,5 +2,5 @@ OpenIDE-Module: org.openide.filesystems OpenIDE-Module-Localizing-Bundle: org/openide/filesystems/Bundle.properties OpenIDE-Module-Layer: org/openide/filesystems/resources/layer.xml -OpenIDE-Module-Specification-Version: 8.11 +OpenIDE-Module-Specification-Version: 9.0 diff --git a/openide.filesystems/module-auto-deps.xml b/openide.filesystems/module-auto-deps.xml --- a/openide.filesystems/module-auto-deps.xml +++ b/openide.filesystems/module-auto-deps.xml @@ -61,4 +61,19 @@ + + Separation of desktop and cleanup + + + + + + + + + + + + + diff --git a/openide.filesystems/nbproject/project.xml b/openide.filesystems/nbproject/project.xml --- a/openide.filesystems/nbproject/project.xml +++ b/openide.filesystems/nbproject/project.xml @@ -50,14 +50,6 @@ org.openide.filesystems - org.openide.util - - - - 9.0 - - - org.openide.util.base @@ -91,8 +83,13 @@ + - org.openide.util + org.openide.util.base @@ -106,6 +103,7 @@ org.openide.filesystems org.openide.filesystems.annotations + org.openide.filesystems.spi diff --git a/openide.filesystems/src/org/netbeans/modules/openide/filesystems/FileFilterSupport.java b/openide.filesystems/src/org/netbeans/modules/openide/filesystems/FileFilterSupport.java deleted file mode 100644 --- a/openide.filesystems/src/org/netbeans/modules/openide/filesystems/FileFilterSupport.java +++ /dev/null @@ -1,470 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright 2012 Oracle and/or its affiliates. All rights reserved. - * - * Oracle and Java are registered trademarks of Oracle and/or its affiliates. - * Other names may be trademarks of their respective owners. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common - * Development and Distribution License("CDDL") (collectively, the - * "License"). You may not use this file except in compliance with the - * License. You can obtain a copy of the License at - * http://www.netbeans.org/cddl-gplv2.html - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the - * specific language governing permissions and limitations under the - * License. When distributing the software, include this License Header - * Notice in each file and include the License file at - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the GPL Version 2 section of the License file that - * accompanied this code. If applicable, add the following below the - * License Header, with the fields enclosed by brackets [] replaced by - * your own identifying information: - * "Portions Copyrighted [year] [name of copyright owner]" - * - * If you wish your version of this file to be governed by only the CDDL - * or only the GPL Version 2, indicate your decision by adding - * "[Contributor] elects to include this software in this distribution - * under the [CDDL or GPL Version 2] license." If you do not indicate a - * single choice of license, a recipient has the option to distribute - * your version of this file under either the CDDL, the GPL Version 2 or - * to extend the choice of license to its licensees as provided above. - * However, if you add GPL Version 2 code and therefore, elected the GPL - * Version 2 license, then the option applies only if the new code is - * made subject to such option by the copyright holder. - * - * Contributor(s): - * - * Portions Copyrighted 2012 Sun Microsystems, Inc. - */ -package org.netbeans.modules.openide.filesystems; - -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import javax.swing.filechooser.FileFilter; -import org.openide.filesystems.FileObject; -import org.openide.filesystems.FileUtil; - -/** - * Support methods for creation of registered {@link FileFilter file filters}. - */ -public final class FileFilterSupport { - - /** - * The logger. - */ - private static final Logger LOG = Logger.getLogger( - FileFilterSupport.class.getName()); - - /** - * Hide the default constructor. - */ - private FileFilterSupport() { - } - - /** - * Construct description for {@link FileFilter} that accepts files with - * specified extension. - * - * @param displayName Human readable display name (e.g. "HTML files") - * @param elements List of accepted filter elements. - * - * @return Display name (description) for the filter. - */ - private static String constructFilterDisplayName(String displayName, - List elements) { - StringBuilder sb = new StringBuilder(displayName); - boolean first = true; - sb.append(" ["); //NOI18N - for (FilterElement el : elements) { - if (first) { - first = false; - } else { - sb.append(", "); //NOI18N - } - sb.append(el.getName()); - } - sb.append("]"); //NOI18N - return sb.toString(); - } - - /** - * Check whether passed file is accepted by filter for specified list of - * extensions. - * - * @param file File to be accepted or rejected. - * @param elements List of accepted filter elements. - * - * @return True if the file is accepted, false if it is rejected. - * - * @see FileFilterSupport - */ - private static boolean accept(File file, List elements) { - if (file != null) { - if (file.isDirectory()) { - return true; - } - for (FilterElement elm : elements) { - if (elm.accept(file)) { - return true; - } - } - } - return false; - } - - public static List findRegisteredFileFilters() { - List filters = new LinkedList(); - FileObject root = FileUtil.getConfigFile( - "Services/MIMEResolver"); //NOI18N - Map> filterNameToResolversMap = - new HashMap>(); - for (FileObject child : root.getChildren()) { - if (child.isFolder()) { - continue; - } - int i = 0; - String f; - while ((f = (String) child.getAttribute("fileChooser." + i))//NOI18N - != null) { - Set set = filterNameToResolversMap.get(f); - if (set == null) { - set = new HashSet(); - filterNameToResolversMap.put(f, set); - } - set.add(child); - i++; - } - } - for (Map.Entry> e : - filterNameToResolversMap.entrySet()) { - filters.add(createFilter(e.getKey(), e.getValue())); - } - return sortFiltersByDescription(filters); - } - - private static FileFilter createFilter(final String name, - final Set resolvers) { - ArrayList elems = new ArrayList(3); - String lastAtt; - for (FileObject fo : resolvers) { - int i = 0; - while ((lastAtt = (String) fo.getAttribute( - "ext." + i)) != null) { //NOI18N - addExtensionToList(elems, lastAtt); - i++; - } - int n = 0; - while ((lastAtt = (String) fo.getAttribute("fileName." //NOI18N - + (n++))) != null) { - addNameToList(elems, lastAtt); - } - String type; - if ((type = (String) fo.getAttribute("mimeType")) != null) {//NOI18N - addMimeTypeExts(elems, type); - } - int t = 0; - while ((type = (String) fo.getAttribute( - "mimeType." + (t++))) != null) { //NOI18N - addMimeTypeExts(elems, type); - } - } - sortFilterElements(elems); - return new FileFilterImpl(name, elems); - } - - /** - * Add all extensions assigned to a MIME Type to the extension list. - */ - private static void addMimeTypeExts(List exts, String type) { - addAllExtensionsToList(exts, FileUtil.getMIMETypeExtensions(type)); - } - - /** - * Add new items to list of extensions, prevent duplicates. - * - * @param list List of extensions to alter. - * @param toAdd List of extensions (without starting dot) to add. - */ - private static void addAllExtensionsToList(List list, - List toAdd) { - for (String s : toAdd) { - addExtensionToList(list, s); - } - } - - /** - * Add new item to list of extensions, prevent duplacates. - * - * @param list List of extensions to alter. - * @param s Extensions without starting dot. - */ - private static void addExtensionToList(List list, - String ext) { - addFilterElementToList(list, FilterElement.createForExtension(ext)); - } - - private static void addNameToList(List list, String name) { - Pattern p = Pattern.compile( - "\\[([^,]+), (true|false), (true|false)\\](\\S*)"); //NOI18N - Matcher m = p.matcher(name); - if (m.find()) { - String fileName = m.group(1); - boolean substring = m.group(2).equals("true"); //NOI18N - boolean ignoreCase = m.group(3).equals("true"); //NOI18N - String extension = m.group(4); - addFilterElementToList(list, FilterElement.createForFileName( - fileName, extension, substring, ignoreCase)); - } else { - LOG.log(Level.INFO, "Incorrect name pattern {0}", name); //NOI18N - } - } - - private static void addFilterElementToList(List list, - FilterElement newItem) { - - for (int i = 0; i < list.size(); i++) { - FilterElement el = list.get(i); - FilterElement.ComparisonResult result = newItem.compare(el); - switch (result) { - case DIFFERENT: - continue; - case THE_SAME: - case WORSE: - return; - case BETTER: - list.set(i, newItem); - return; - } - } - list.add(newItem); - } - - private static List sortFiltersByDescription( - List list) { - - Collections.sort(list, new Comparator() { - @Override - public int compare(FileFilter o1, FileFilter o2) { - return o1.getDescription().compareTo(o2.getDescription()); - } - }); - return list; - } - - private static List sortFilterElements( - List elements) { - Collections.sort(elements, new Comparator() { - @Override - public int compare(FilterElement o1, FilterElement o2) { - return o1.getName().compareTo(o2.getName()); - } - }); - return elements; - } - - private static class FileFilterImpl extends FileFilter { - - private final String name; - List filterElements; - - public FileFilterImpl(String name, List elements) { - this.name = name; - this.filterElements = elements; - } - - @Override - public boolean accept(File pathname) { - return FileFilterSupport.accept(pathname, filterElements); - } - - @Override - public String getDescription() { - return FileFilterSupport.constructFilterDisplayName( - name, filterElements); - } - } - - /** - * Element of File Filter. One accepted extension or file name pattern. - */ - private static abstract class FilterElement { - - public abstract String getName(); - - public abstract boolean accept(File f); - - /** - * Compare two filter elements. Correct implementation of this method - * prevents adding duplicite elements to the filter. - */ - public abstract ComparisonResult compare(FilterElement e); - - public static FilterElement createForExtension(String ext) { - return new ExtensionBasedFilterElement(ext); - } - - public static FilterElement createForFileName(String name, - String extension, boolean substring, boolean ignoreCase) { - return new NameBasedFilterElement(name, extension, - substring, ignoreCase); - } - - public static enum ComparisonResult { - - THE_SAME, BETTER, WORSE, DIFFERENT - } - - private static class ExtensionBasedFilterElement extends FilterElement { - - private final String extension; - - public ExtensionBasedFilterElement(String extension) { - if (extension != null) { - this.extension = extension; - } else { - throw new NullPointerException(); - } - } - - @Override - public String getName() { - return "." + extension; //NOI18N - } - - @Override - public boolean accept(File f) { - return f.getName().toLowerCase().endsWith( - "." + extension.toLowerCase()); //NOI18N - } - - @Override - public ComparisonResult compare(FilterElement e) { - if (!(e instanceof ExtensionBasedFilterElement)) { - return ComparisonResult.DIFFERENT; - } - ExtensionBasedFilterElement x = (ExtensionBasedFilterElement) e; - if (x == null) { - throw new NullPointerException(); - } - if (this.extension.equals(x.extension)) { - return ComparisonResult.THE_SAME; - } else if (this.extension.equalsIgnoreCase(x.extension) - && this.extension.length() > 1) { - if (Character.isUpperCase(x.extension.charAt(0))) { - return ComparisonResult.BETTER; //this better, x worse - } else { - return ComparisonResult.WORSE; // this worse, x better - } - } else { - return ComparisonResult.DIFFERENT; - } - } - } - - private static class NameBasedFilterElement extends FilterElement { - - String name; - String ext; - boolean substring; - boolean ignoreCase; - Pattern p; - - public NameBasedFilterElement(String name, String ext, - boolean substring, boolean ignoreCase) { - this.name = name; - this.ext = ext; - this.substring = substring; - this.ignoreCase = ignoreCase; - StringBuilder sb = new StringBuilder(); - if (ignoreCase) { - sb.append("(?i)"); //NOI18N - } - if (substring) { - sb.append(".*"); //NOI18N - } - sb.append(name); //NOI18N - if (substring) { - sb.append(".*"); //NOI18N - } - if (!ext.isEmpty()) { - sb.append("\\."); //NOI18N - sb.append(ext); - } - p = Pattern.compile(sb.toString()); - } - - @Override - public String getName() { - return name + (ext.isEmpty() ? "" : "." + ext); //NOI18N - } - - @Override - public boolean accept(File f) { - return p.matcher(f.getName()).matches(); - } - - @Override - public ComparisonResult compare(FilterElement e) { - if (e == null) { - throw new NullPointerException(); - } else if (!(e instanceof NameBasedFilterElement)) { - return ComparisonResult.DIFFERENT; - } - NameBasedFilterElement x = (NameBasedFilterElement) e; - if (this.name.equals(x.name) && this.ext.equals(x.ext)) { - if (this.substring == x.substring - && this.ignoreCase == x.ignoreCase) { - return ComparisonResult.THE_SAME; - } else { - return compareFlags(x); - } - } else if (this.ext.equalsIgnoreCase(x.ext) - && this.name.equalsIgnoreCase(x.name) - && (this.ignoreCase || x.ignoreCase)) { - if (this.substring == x.substring - && this.ignoreCase == x.ignoreCase) { - if (Character.isLowerCase(this.name.charAt(0))) { - return ComparisonResult.BETTER; - } else { - return ComparisonResult.WORSE; - } - } else { - return compareFlags(x); - } - } else { - return ComparisonResult.DIFFERENT; - } - } - - private ComparisonResult compareFlags(NameBasedFilterElement x) { - if (this.substring == x.substring - && this.ignoreCase) { - return ComparisonResult.BETTER; - } else if (this.ignoreCase == x.ignoreCase - && this.substring) { - return ComparisonResult.BETTER; - } else if (this.substring != x.substring - && this.ignoreCase != x.ignoreCase) { - return ComparisonResult.DIFFERENT; - } else { - return ComparisonResult.WORSE; - } - } - } - } -} diff --git a/openide.filesystems/src/org/netbeans/modules/openide/filesystems/RecognizeInstanceFiles.java b/openide.filesystems/src/org/netbeans/modules/openide/filesystems/RecognizeInstanceFiles.java --- a/openide.filesystems/src/org/netbeans/modules/openide/filesystems/RecognizeInstanceFiles.java +++ b/openide.filesystems/src/org/netbeans/modules/openide/filesystems/RecognizeInstanceFiles.java @@ -30,13 +30,48 @@ * Software is Sun Microsystems, Inc. * * Portions Copyrighted 2007 Sun Microsystems, Inc. + *//* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * Contributor(s): + * + * The Original Software is NetBeans. The Initial Developer of the Original + * Software is Sun Microsystems, Inc. + * + * Portions Copyrighted 2007 Sun Microsystems, Inc. */ package org.netbeans.modules.openide.filesystems; import java.lang.ref.Reference; import java.lang.ref.WeakReference; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.LinkedHashMap; @@ -53,10 +88,10 @@ import org.openide.filesystems.FileStateInvalidException; import org.openide.filesystems.FileSystem; import org.openide.filesystems.FileUtil; +import org.openide.filesystems.spi.CustomInstanceFactory; +import org.openide.util.BaseUtilities; import org.openide.util.Exceptions; import org.openide.util.Lookup; -import org.openide.util.SharedClassObject; -import org.openide.util.Utilities; import org.openide.util.lookup.AbstractLookup; import org.openide.util.lookup.Lookups; import org.openide.util.lookup.ProxyLookup; @@ -200,6 +235,33 @@ } } // end of OverFiles + private static volatile Lookup.Result factories; + + private static Collection getInstanceFactories() { + Lookup.Result fr; + + if ((fr = factories) == null) { + factories = fr = Lookup.getDefault().lookupResult(CustomInstanceFactory.class); + } + return fr.allInstances(); + } + + public static final T createInstance(Class type) throws InstantiationException, + IllegalAccessException, InvocationTargetException, NoSuchMethodException { + T r = null; + for (CustomInstanceFactory fif : getInstanceFactories()) { + r = (T)fif.createInstance(type); + if (r != null) { + break; + } + } + if (r == null) { + Constructor init = type.getDeclaredConstructor(); + init.setAccessible(true); + r = init.newInstance(); + } + return r; + } private static final class FOItem extends AbstractLookup.Pair { private static Reference EMPTY = new WeakReference(null); @@ -257,15 +319,15 @@ if (type == null) { return null; } - if (SharedClassObject.class.isAssignableFrom(type)) { - r = SharedClassObject.findObject(type.asSubclass(SharedClassObject.class), true); - } else { - r = type.newInstance(); - } + r = createInstance(type); } catch (InstantiationException ex) { Exceptions.printStackTrace(ex); } catch (IllegalAccessException ex) { Exceptions.printStackTrace(ex); + } catch (InvocationTargetException ex) { + Exceptions.printStackTrace(ex); + } catch (NoSuchMethodException ex) { + Exceptions.printStackTrace(ex); } } return resultType.isInstance(r) ? resultType.cast(r) : null; @@ -312,7 +374,7 @@ // first of all try "instanceClass" property of the primary file Object attr = fo.getAttribute ("instanceClass"); if (attr instanceof String) { - return Utilities.translate((String) attr); + return BaseUtilities.translate((String) attr); } else if (attr != null) { LOG.warning( "instanceClass was a " + attr.getClass().getName()); // NOI18N @@ -350,7 +412,7 @@ } name = name.replace ('-', '.'); - name = Utilities.translate(name); + name = BaseUtilities.translate(name); //System.out.println ("Original: " + getPrimaryFile ().getName () + " new one: " + name); // NOI18N return name; diff --git a/openide.filesystems/src/org/netbeans/modules/openide/filesystems/declmime/FileElement.java b/openide.filesystems/src/org/netbeans/modules/openide/filesystems/declmime/FileElement.java --- a/openide.filesystems/src/org/netbeans/modules/openide/filesystems/declmime/FileElement.java +++ b/openide.filesystems/src/org/netbeans/modules/openide/filesystems/declmime/FileElement.java @@ -49,7 +49,7 @@ import java.util.logging.Logger; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; -import org.openide.util.Utilities; +import org.openide.util.BaseUtilities; import org.openide.xml.XMLUtil; /** @@ -529,7 +529,7 @@ /** #26521, 114976 - ignore not readable and windows' locked files. */ private static void handleIOException(FileObject fo, IOException ioe) throws IOException { if (fo.canRead()) { - if (!Utilities.isWindows() || !(ioe instanceof FileNotFoundException) || !fo.isValid() || !fo.getName().toLowerCase().contains("ntuser")) {//NOI18N + if (!BaseUtilities.isWindows() || !(ioe instanceof FileNotFoundException) || !fo.isValid() || !fo.getName().toLowerCase().contains("ntuser")) {//NOI18N throw ioe; } } diff --git a/openide.filesystems/src/org/netbeans/modules/openide/filesystems/declmime/MIMEResolverImpl.java b/openide.filesystems/src/org/netbeans/modules/openide/filesystems/declmime/MIMEResolverImpl.java --- a/openide.filesystems/src/org/netbeans/modules/openide/filesystems/declmime/MIMEResolverImpl.java +++ b/openide.filesystems/src/org/netbeans/modules/openide/filesystems/declmime/MIMEResolverImpl.java @@ -57,7 +57,7 @@ import org.openide.filesystems.MIMEResolver; import org.openide.util.Exceptions; import org.openide.util.Parameters; -import org.openide.util.Utilities; +import org.openide.util.BaseUtilities; import org.openide.xml.XMLUtil; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -75,7 +75,7 @@ // enable some tracing private static final Logger ERR = Logger.getLogger(MIMEResolverImpl.class.getName()); - static final boolean CASE_INSENSITIVE = Utilities.getOperatingSystem() == Utilities.OS_VMS; + static final boolean CASE_INSENSITIVE = BaseUtilities.getOperatingSystem() == BaseUtilities.OS_VMS; // notification limit in bytes for reading file content. It should not exceed 4192 (4kB) because it is read in one disk touch. private static final int READ_LIMIT = 4000; diff --git a/openide.filesystems/src/org/openide/filesystems/AbstractFileObject.java b/openide.filesystems/src/org/openide/filesystems/AbstractFileObject.java --- a/openide.filesystems/src/org/openide/filesystems/AbstractFileObject.java +++ b/openide.filesystems/src/org/openide/filesystems/AbstractFileObject.java @@ -1233,44 +1233,4 @@ } } // end of Invalid - - /** Replace that stores name of fs and file. - * @deprecated In favor of AbstractFolder.Replace. - */ - @Deprecated - static final class Replace extends Object implements Serializable { - /** generated Serialized Version UID */ - static final long serialVersionUID = -8543432135435542113L; - private String fsName; - private String fileName; - - /** Constructor - */ - public Replace(String fsName, String fileName) { - this.fsName = fsName; - this.fileName = fileName; - } - - /** Finds the right file. - */ - public Object readResolve() { - Repository rep = Repository.getDefault(); - @SuppressWarnings("deprecation") // FileSystem.systemName historical part of serial form - FileSystem fs = rep.findFileSystem(fsName); - FileObject fo = null; - - if (fs != null) { - // scan desired system - fo = fs.findResource(fileName); - } - - if (fo == null) { - // create invalid file instead - return new Invalid(fsName, fileName); - } - - return fo; - } - } - // end of Replace } diff --git a/openide.filesystems/src/org/openide/filesystems/AbstractFileSystem.java b/openide.filesystems/src/org/openide/filesystems/AbstractFileSystem.java --- a/openide.filesystems/src/org/openide/filesystems/AbstractFileSystem.java +++ b/openide.filesystems/src/org/openide/filesystems/AbstractFileSystem.java @@ -57,11 +57,7 @@ import java.util.Date; import java.util.Enumeration; import java.util.StringTokenizer; -import org.openide.util.Enumerations; -import org.openide.util.Lookup; import org.openide.util.NbCollections; -import org.openide.util.SharedClassObject; -import org.openide.util.actions.SystemAction; /** * This convenience implementation does much of the hard work of @@ -126,12 +122,6 @@ /** generated Serialized Version UID */ private static final long serialVersionUID = -3345098214331282438L; - /** system actions for this FS if it has refreshTime != 0 */ - private static SystemAction[] SYSTEM_ACTIONS; - - /** system actions for this FS */ - private static final SystemAction[] NO_SYSTEM_ACTIONS = new SystemAction[] { }; - /** cached last value of Enumeration which holds resource name (enumeration like StringTokenizer)*/ static transient private PathElements lastEnum; @@ -181,38 +171,6 @@ return getAbstractRoot(); } - /* Finds file when its name is provided. - * - * @param aPackage package name where each package is separated by a dot - * @param name name of the file (without dots) or null if - * one want to obtain name of package and not file in it - * @param ext extension of the file or null if one needs - * package and not file name - * - * @warning when one of name or ext is null then name and - * ext should be ignored and scan should look only for a package - * - * @return FileObject that represents file with given name or - * null if the file does not exist - */ - @Deprecated - public FileObject find(String aPackage, String name, String ext) { - // create enumeration of name to look for - Enumeration st = NbCollections.checkedEnumerationByFilter(new StringTokenizer(aPackage, "."), String.class, true); // NOI18N - - if ((name == null) || (ext == null)) { - // search for folder, return the object only if it is folder - FileObject fo = getAbstractRoot().find(st); - - return ((fo != null) && fo.isFolder()) ? fo : null; - } else { - Enumeration en = Enumerations.concat(st, Enumerations.singleton(name + '.' + ext)); - - // tries to find it (can return null) - return getAbstractRoot().find(en); - } - } - /* Finds file when its resource name is given. * The name has the usual format for the {@link ClassLoader#getResource(String)} * method. So it may consist of "package1/package2/filename.ext". @@ -270,39 +228,6 @@ return (refresher != null); } - /* Action for this filesystem. - * - * @return refresh action - */ - public SystemAction[] getActions() { - if (!isEnabledRefreshFolder()) { - return NO_SYSTEM_ACTIONS; - } else { - if (SYSTEM_ACTIONS == null) { - try { - ClassLoader l = Lookup.getDefault().lookup(ClassLoader.class); - - if (l == null) { - l = getClass().getClassLoader(); - } - - Class c = Class.forName("org.openide.actions.FileSystemRefreshAction", true, l); // NOI18N - SystemAction ra = SharedClassObject.findObject(c.asSubclass(SystemAction.class), true); - - // initialize the SYSTEM_ACTIONS - SYSTEM_ACTIONS = new SystemAction[] { ra }; - } catch (Exception ex) { - // ok, we are probably running in standalone mode and - // classes needed to initialize the RefreshAction are - // not available - SYSTEM_ACTIONS = NO_SYSTEM_ACTIONS; - } - } - - return SYSTEM_ACTIONS; - } - } - /** Set the number of milliseconds between automatic * refreshes of the directory structure. * diff --git a/openide.filesystems/src/org/openide/filesystems/AbstractFolder.java b/openide.filesystems/src/org/openide/filesystems/AbstractFolder.java --- a/openide.filesystems/src/org/openide/filesystems/AbstractFolder.java +++ b/openide.filesystems/src/org/openide/filesystems/AbstractFolder.java @@ -64,7 +64,7 @@ import java.util.Set; import org.openide.util.Enumerations; import org.openide.util.NbBundle; -import org.openide.util.Utilities; +import org.openide.util.BaseUtilities; /** Implementation of the file object that simplyfies common * tasks with hierarchy of objects for AbstractFileObject and MultiFileObject. @@ -348,7 +348,7 @@ //On OpenVMS, see if the name is stored in a different case //to work around a JVM bug. // - if (Utilities.getOperatingSystem() == Utilities.OS_VMS) { + if (BaseUtilities.getOperatingSystem() == BaseUtilities.OS_VMS) { if (Character.isLowerCase(name.charAt(0))) { r = map.get(name.toUpperCase()); } else { diff --git a/openide.filesystems/src/org/openide/filesystems/DeepListener.java b/openide.filesystems/src/org/openide/filesystems/DeepListener.java --- a/openide.filesystems/src/org/openide/filesystems/DeepListener.java +++ b/openide.filesystems/src/org/openide/filesystems/DeepListener.java @@ -52,7 +52,7 @@ import java.util.concurrent.Callable; import java.util.logging.Level; import java.util.logging.Logger; -import org.openide.util.Utilities; +import org.openide.util.BaseUtilities; import org.openide.util.WeakSet; /** @@ -71,7 +71,7 @@ private final int hash; DeepListener(FileChangeListener listener, File path, FileFilter ff, Callable stop) { - super(listener, Utilities.activeReferenceQueue()); + super(listener, BaseUtilities.activeReferenceQueue()); this.path = path; this.stop = stop; this.filter = ff; diff --git a/openide.filesystems/src/org/openide/filesystems/DefaultAttributes.java b/openide.filesystems/src/org/openide/filesystems/DefaultAttributes.java --- a/openide.filesystems/src/org/openide/filesystems/DefaultAttributes.java +++ b/openide.filesystems/src/org/openide/filesystems/DefaultAttributes.java @@ -73,7 +73,7 @@ import javax.xml.parsers.ParserConfigurationException; import org.openide.util.Enumerations; import org.openide.util.NbBundle; -import org.openide.util.Utilities; +import org.openide.util.BaseUtilities; import org.openide.util.io.NbMarshalledObject; import org.openide.xml.XMLUtil; import org.xml.sax.Attributes; @@ -238,7 +238,7 @@ // However, OpenVMS now supports a file name beginning with "." // So we now have to copy the existing "_nbattrs." file into ".nbattrs" // - if ((Utilities.getOperatingSystem() == Utilities.OS_VMS) && (arr[0] != null) && (f != null)) { + if ((BaseUtilities.getOperatingSystem() == BaseUtilities.OS_VMS) && (arr[0] != null) && (f != null)) { if (arr[0].equalsIgnoreCase("_nbattrs.")) { try { deleteFile(f + "/" + arr[0]); // NOI18N @@ -264,7 +264,7 @@ // However, OpenVMS now supports a file name beginning with "." // So we now have to copy the existing "_nbattrs." file into ".nbattrs" // - if ((Utilities.getOperatingSystem() == Utilities.OS_VMS) && (arr[i] != null) && (f != null)) { + if ((BaseUtilities.getOperatingSystem() == BaseUtilities.OS_VMS) && (arr[i] != null) && (f != null)) { if (arr[i].equalsIgnoreCase("_nbattrs.")) { try { File fp = new File(f + "/" + ".nbattrs"); diff --git a/openide.filesystems/src/org/openide/filesystems/EnvironmentNotSupportedException.java b/openide.filesystems/src/org/openide/filesystems/EnvironmentNotSupportedException.java deleted file mode 100644 --- a/openide.filesystems/src/org/openide/filesystems/EnvironmentNotSupportedException.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. - * - * Oracle and Java are registered trademarks of Oracle and/or its affiliates. - * Other names may be trademarks of their respective owners. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common - * Development and Distribution License("CDDL") (collectively, the - * "License"). You may not use this file except in compliance with the - * License. You can obtain a copy of the License at - * http://www.netbeans.org/cddl-gplv2.html - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the - * specific language governing permissions and limitations under the - * License. When distributing the software, include this License Header - * Notice in each file and include the License file at - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the GPL Version 2 section of the License file that - * accompanied this code. If applicable, add the following below the - * License Header, with the fields enclosed by brackets [] replaced by - * your own identifying information: - * "Portions Copyrighted [year] [name of copyright owner]" - * - * Contributor(s): - * - * The Original Software is NetBeans. The Initial Developer of the Original - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun - * Microsystems, Inc. All Rights Reserved. - * - * If you wish your version of this file to be governed by only the CDDL - * or only the GPL Version 2, indicate your decision by adding - * "[Contributor] elects to include this software in this distribution - * under the [CDDL or GPL Version 2] license." If you do not indicate a - * single choice of license, a recipient has the option to distribute - * your version of this file under either the CDDL, the GPL Version 2 or - * to extend the choice of license to its licensees as provided above. - * However, if you add GPL Version 2 code and therefore, elected the GPL - * Version 2 license, then the option applies only if the new code is - * made subject to such option by the copyright holder. - */ - -package org.openide.filesystems; - -import java.io.IOException; - -/** Exception thrown to signal that external -* execution and compilation is not supported on a given filesystem. -* -* @author Jaroslav Tulach -* @deprecated Please use the ClassPath API instead. -*/ -@Deprecated -public class EnvironmentNotSupportedException extends IOException { - /** generated Serialized Version UID */ - static final long serialVersionUID = -1138390681913514558L; - - /** the throwing exception */ - private FileSystem fs; - - /** - * @param fs filesystem that caused the error - */ - public EnvironmentNotSupportedException(FileSystem fs) { - this.fs = fs; - assert false : "Deprecated."; - } - - /** - * @param fs filesystem that caused the error - * @param reason text description for the error - */ - public EnvironmentNotSupportedException(FileSystem fs, String reason) { - super(reason); - this.fs = fs; - assert false : "Deprecated."; - } - - /** Getter for the filesystem that does not support environment operations. - */ - public FileSystem getFileSystem() { - return fs; - } -} diff --git a/openide.filesystems/src/org/openide/filesystems/FileChangeImpl.java b/openide.filesystems/src/org/openide/filesystems/FileChangeImpl.java --- a/openide.filesystems/src/org/openide/filesystems/FileChangeImpl.java +++ b/openide.filesystems/src/org/openide/filesystems/FileChangeImpl.java @@ -50,7 +50,7 @@ import java.util.concurrent.Callable; import java.util.logging.Level; import java.util.logging.Logger; -import org.openide.util.Utilities; +import org.openide.util.BaseUtilities; /** Holds FileChangeListener and File pair and handle movement of auxiliary * FileChangeListener to the first existing upper folder and firing appropriate events. @@ -66,7 +66,7 @@ private boolean isOnTarget = false; public FileChangeImpl(FileChangeListener listener, File path) { - super(listener, Utilities.activeReferenceQueue()); + super(listener, BaseUtilities.activeReferenceQueue()); assert path != null; this.path = path; } @@ -241,7 +241,7 @@ } static FileChangeListener removeFileChangeListenerImpl(Logger logger, FileChangeListener listener, File path) { - assert FileUtil.assertNormalized(path, Utilities.isMac()); + assert FileUtil.assertNormalized(path, BaseUtilities.isMac()); logger.log(Level.FINE, "removeFileChangeListener {0} @ {1}", new Object[]{listener, path}); synchronized (holders) { Map f2H = holders.get(listener); diff --git a/openide.filesystems/src/org/openide/filesystems/FileChooserBuilder.java b/openide.filesystems/src/org/openide/filesystems/FileChooserBuilder.java deleted file mode 100644 --- a/openide.filesystems/src/org/openide/filesystems/FileChooserBuilder.java +++ /dev/null @@ -1,687 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. - * - * Oracle and Java are registered trademarks of Oracle and/or its affiliates. - * Other names may be trademarks of their respective owners. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common - * Development and Distribution License("CDDL") (collectively, the - * "License"). You may not use this file except in compliance with the - * License. You can obtain a copy of the License at - * http://www.netbeans.org/cddl-gplv2.html - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the - * specific language governing permissions and limitations under the - * License. When distributing the software, include this License Header - * Notice in each file and include the License file at - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the GPL Version 2 section of the License file that - * accompanied this code. If applicable, add the following below the - * License Header, with the fields enclosed by brackets [] replaced by - * your own identifying information: - * "Portions Copyrighted [year] [name of copyright owner]" - * - * Contributor(s): - * - * The Original Software is NetBeans. The Initial Developer of the Original - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun - * Microsystems, Inc. All Rights Reserved. - * - * If you wish your version of this file to be governed by only the CDDL - * or only the GPL Version 2, indicate your decision by adding - * "[Contributor] elects to include this software in this distribution - * under the [CDDL or GPL Version 2] license." If you do not indicate a - * single choice of license, a recipient has the option to distribute - * your version of this file under either the CDDL, the GPL Version 2 or - * to extend the choice of license to its licensees as provided above. - * However, if you add GPL Version 2 code and therefore, elected the GPL - * Version 2 license, then the option applies only if the new code is - * made subject to such option by the copyright holder. - */ -package org.openide.filesystems; - -import java.awt.Component; -import java.awt.FileDialog; -import java.awt.Frame; -import java.awt.HeadlessException; -import java.awt.KeyboardFocusManager; -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import javax.swing.Icon; -import javax.swing.JFileChooser; -import javax.swing.SwingUtilities; -import javax.swing.filechooser.FileFilter; -import javax.swing.filechooser.FileSystemView; -import javax.swing.filechooser.FileView; -import org.netbeans.modules.openide.filesystems.FileFilterSupport; -import org.openide.util.*; - -/** - * Utility class for working with JFileChoosers. In particular, remembering - * the last-used directory for a given file is made transparent. You pass an - * ad-hoc string key to the constructor (the fully qualified name of the - * calling class is good for uniqueness, and there is a constructor that takes - * a Class object as an argument for this purpose). That key is - * used to look up the most recently-used directory from any previous invocations - * with the same key. This makes it easy to have your user interface - * “remember” where the user keeps particular types of files, and - * saves the user from having to navigate through the same set of directories - * every time they need to locate a file from a particular place. - *

- * FileChooserBuilder's methods each return this, so - * it is possible to chain invocations to simplify setting up a file chooser. - * Example usage: - *

- *      //The default dir to use if no value is stored
- *      File home = new File (System.getProperty("user.home") + File.separator + "lib");
- *      //Now build a file chooser and invoke the dialog in one line of code
- *      //"libraries-dir" is our unique key
- *      File toAdd = new FileChooserBuilder ("libraries-dir").setTitle("Add Library").
- *              setDefaultWorkingDirectory(home).setApproveText("Add").showOpenDialog();
- *      //Result will be null if the user clicked cancel or closed the dialog w/o OK
- *      if (toAdd != null) {
- *          //do something
- *      }
- *
- *

- * Instances of this class are intended to be thrown away after use. Typically - * you create a builder, set it to create file choosers as you wish, then - * use it to show a dialog or create a file chooser you then do something - * with. - *

- * Supports the most common subset of JFileChooser functionality; if you - * need to do something exotic with a file chooser, you are probably better - * off creating your own. - *

- * Note: If you use the constructor that takes a Class object, - * please use new FileChooserBuilder(MyClass.class), not - * new FileChooserBuilder(getClass()). This avoids unexpected - * behavior in the case of subclassing. - * - * @author Tim Boudreau - */ -public class FileChooserBuilder { - private boolean dirsOnly; - private BadgeProvider badger; - private String title; - private String approveText; - //Just in case... - private static boolean PREVENT_SYMLINK_TRAVERSAL = - !Boolean.getBoolean("allow.filechooser.symlink.traversal"); //NOI18N - private final String dirKey; - private File failoverDir; - private FileFilter filter; - private boolean fileHiding; - private boolean controlButtonsShown = true; - private String aDescription; - private boolean filesOnly; - private static final boolean DONT_STORE_DIRECTORIES = - Boolean.getBoolean("forget.recent.dirs"); - private SelectionApprover approver; - private final List filters = new ArrayList(3); - private boolean useAcceptAllFileFilter = true; - /** - * Create a new FileChooserBuilder using the name of the passed class - * as the metadata for looking up a starting directory from previous - * application sessions or invocations. - * @param type A non-null class object, typically the calling class - */ - public FileChooserBuilder(Class type) { - this(type.getName()); - } - - /** - * Create a new FileChooserBuilder. The passed key is used as a key - * into NbPreferences to look up the directory the file chooser should - * initially be rooted on. - * - * @param dirKey A non-null ad-hoc string. If a FileChooser was previously - * used with the same string as is passed, then the initial directory - */ - public FileChooserBuilder(String dirKey) { - Parameters.notNull("dirKey", dirKey); - this.dirKey = dirKey; - } - - /** - * Set whether or not any file choosers created by this builder will show - * only directories. - * @param val true if files should not be shown - * @return this - */ - public FileChooserBuilder setDirectoriesOnly(boolean val) { - dirsOnly = val; - assert !filesOnly : "FilesOnly and DirsOnly are mutually exclusive"; - return this; - } - - public FileChooserBuilder setFilesOnly(boolean val) { - filesOnly = val; - assert !dirsOnly : "FilesOnly and DirsOnly are mutually exclusive"; - return this; - } - - /** - * Provide an implementation of BadgeProvider which will "badge" the - * icons of some files. - * - * @param provider A badge provider which will alter the icon of files - * or folders that may be of particular interest to the user - * @return this - */ - public FileChooserBuilder setBadgeProvider(BadgeProvider provider) { - this.badger = provider; - return this; - } - - /** - * Set the dialog title for any JFileChoosers created by this builder. - * @param val A localized, human-readable title - * @return this - */ - public FileChooserBuilder setTitle(String val) { - title = val; - return this; - } - - /** - * Set the text on the OK button for any file chooser dialogs produced - * by this builder. - * @param val A short, localized, human-readable string - * @return this - */ - public FileChooserBuilder setApproveText(String val) { - approveText = val; - return this; - } - - /** - * Set a file filter which filters the list of selectable files. - * @param filter - * @return this - */ - public FileChooserBuilder setFileFilter (FileFilter filter) { - this.filter = filter; - return this; - } - - /** - * Determines whether the AcceptAll FileFilter is used - * as an available choice in the choosable filter list. - * If false, the AcceptAll file filter is removed from - * the list of available file filters. - * If true, the AcceptAll file filter will become the - * the actively used file filter. - * @param accept whether the AcceptAll FileFilter is used - * @return this - * @since 8.3 - */ - public FileChooserBuilder setAcceptAllFileFilterUsed(boolean accept) { - useAcceptAllFileFilter = accept; - return this; - } - - /** - * Set the current directory which should be used only if - * a last-used directory cannot be found for the key string passed - * into this builder's constructor. - * @param dir A directory to root any created file choosers on if - * there is no stored path for this builder's key - * @return this - */ - public FileChooserBuilder setDefaultWorkingDirectory (File dir) { - failoverDir = dir; - return this; - } - - /** - * Enable file hiding in any created file choosers - * @param fileHiding Whether or not to hide files. Default is no. - * @return this - */ - public FileChooserBuilder setFileHiding(boolean fileHiding) { - this.fileHiding = fileHiding; - return this; - } - - /** - * Show/hide control buttons - * @param val Whether or not to hide files. Default is no. - * @return this - */ - public FileChooserBuilder setControlButtonsAreShown(boolean val) { - this.controlButtonsShown = val; - return this; - } - - /** - * Set the accessible description for any file choosers created by this - * builder - * @param aDescription The description - * @return this - */ - public FileChooserBuilder setAccessibleDescription(String aDescription) { - this.aDescription = aDescription; - return this; - } - - /** - * Create a JFileChooser that conforms to the parameters set in this - * builder. - * @return A file chooser - */ - public JFileChooser createFileChooser() { - JFileChooser result = new SavedDirFileChooser(dirKey, failoverDir, - force, approver); - prepareFileChooser(result); - return result; - } - - private boolean force = false; - /** - * Force use of the failover directory - i.e. ignore the directory key - * passed in. - * @param val - * @return this - */ - public FileChooserBuilder forceUseOfDefaultWorkingDirectory(boolean val) { - this.force = val; - return this; - } - - /** - * Tries to find an appropriate component to parent the file chooser to - * when showing a dialog. - * @return this - */ - private Component findDialogParent() { - Component parent = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); - if (parent == null) { - parent = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow(); - } - if (parent == null) { - Frame[] f = Frame.getFrames(); - parent = f.length == 0 ? null : f[f.length - 1]; - } - return parent; - } - - /** - * Show an open dialog that allows multiple selection. - * @return An array of files, or null if the user cancelled the dialog - */ - public File[] showMultiOpenDialog() { - JFileChooser chooser = createFileChooser(); - chooser.setMultiSelectionEnabled(true); - int result = chooser.showOpenDialog(findDialogParent()); - if (JFileChooser.APPROVE_OPTION == result) { - File[] files = chooser.getSelectedFiles(); - return files == null ? new File[0] : files; - } else { - return null; - } - } - - /** - * Show an open dialog with a file chooser set up according to the - * parameters of this builder. - * @return A file if the user clicks the accept button and a file or - * folder was selected at the time the user clicked cancel. - */ - public File showOpenDialog() { - JFileChooser chooser = createFileChooser(); - if( Boolean.getBoolean("nb.native.filechooser") ) { //NOI18N - FileDialog fileDialog = createFileDialog( chooser.getCurrentDirectory() ); - if( null != fileDialog ) { - return showFileDialog(fileDialog, FileDialog.LOAD ); - } - } - chooser.setMultiSelectionEnabled(false); - int dlgResult = chooser.showOpenDialog(findDialogParent()); - if (JFileChooser.APPROVE_OPTION == dlgResult) { - File result = chooser.getSelectedFile(); - if (result != null && !result.exists()) { - result = null; - } - return result; - } else { - return null; - } - - } - - /** - * Show a save dialog with the file chooser set up according to the - * parameters of this builder. - * @return A file if the user clicks the accept button and a file or - * folder was selected at the time the user clicked cancel. - */ - public File showSaveDialog() { - JFileChooser chooser = createFileChooser(); - if( Boolean.getBoolean("nb.native.filechooser") ) { //NOI18N - FileDialog fileDialog = createFileDialog( chooser.getCurrentDirectory() ); - if( null != fileDialog ) { - return showFileDialog( fileDialog, FileDialog.SAVE ); - } - } - int result = chooser.showSaveDialog(findDialogParent()); - if (JFileChooser.APPROVE_OPTION == result) { - return chooser.getSelectedFile(); - } else { - return null; - } - } - - private File showFileDialog( FileDialog fileDialog, int mode ) { - String oldFileDialogProp = System.getProperty("apple.awt.fileDialogForDirectories"); //NOI18N - if( dirsOnly ) { - System.setProperty("apple.awt.fileDialogForDirectories", "true"); //NOI18N - } - fileDialog.setMode( mode ); - fileDialog.setVisible(true); - if( dirsOnly ) { - if( null != oldFileDialogProp ) { - System.setProperty("apple.awt.fileDialogForDirectories", oldFileDialogProp); //NOI18N - } else { - System.clearProperty("apple.awt.fileDialogForDirectories"); //NOI18N - } - } - if( fileDialog.getDirectory() != null && fileDialog.getFile() != null ) { - String selFile = fileDialog.getFile(); - File dir = new File( fileDialog.getDirectory() ); - return new File( dir, selFile ); - } - return null; - } - - private void prepareFileChooser(JFileChooser chooser) { - chooser.setFileSelectionMode(dirsOnly ? JFileChooser.DIRECTORIES_ONLY - : filesOnly ? JFileChooser.FILES_ONLY : - JFileChooser.FILES_AND_DIRECTORIES); - chooser.setFileHidingEnabled(fileHiding); - chooser.setControlButtonsAreShown(controlButtonsShown); - chooser.setAcceptAllFileFilterUsed(useAcceptAllFileFilter); - if (title != null) { - chooser.setDialogTitle(title); - } - if (approveText != null) { - chooser.setApproveButtonText(approveText); - } - if (badger != null) { - chooser.setFileView(new CustomFileView(new BadgeIconProvider(badger), - chooser.getFileSystemView())); - } - if (PREVENT_SYMLINK_TRAVERSAL) { - FileUtil.preventFileChooserSymlinkTraversal(chooser, - chooser.getCurrentDirectory()); - } - if (filter != null) { - chooser.setFileFilter(filter); - } - if (aDescription != null) { - chooser.getAccessibleContext().setAccessibleDescription(aDescription); - } - if (!filters.isEmpty()) { - for (FileFilter f : filters) { - chooser.addChoosableFileFilter(f); - } - } - } - - private FileDialog createFileDialog( File currentDirectory ) { - if( badger != null ) - return null; - if( !Boolean.getBoolean("nb.native.filechooser") ) - return null; - if( dirsOnly && !Utilities.isMac() ) - return null; - Component parentComponent = findDialogParent(); - Frame parentFrame = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parentComponent); - FileDialog fileDialog = new FileDialog(parentFrame); - if (title != null) { - fileDialog.setTitle(title); - } - if( null != currentDirectory ) - fileDialog.setDirectory(currentDirectory.getAbsolutePath()); - return fileDialog; - } - - /** - * Equivalent to calling JFileChooser.addChoosableFileFilter(filter). - * Adds another file filter that can be displayed in the file filters combo - * box in the file chooser. - * - * @param filter The file filter to add - * @return this - * @since 7.26.0 - */ - public FileChooserBuilder addFileFilter (FileFilter filter) { - filters.add (filter); - return this; - } - - /** - * Add all default file filters to the file chooser. - * - * @see MIMEResolver.Registration#showInFileChooser() - * @see MIMEResolver.ExtensionRegistration#showInFileChooser() - * @return this - * @since 8.1 - */ - public FileChooserBuilder addDefaultFileFilters() { - filters.addAll(FileFilterSupport.findRegisteredFileFilters()); - return this; - } - - /** - * Set a selection approver which can display an "Overwrite file?" - * or similar dialog if necessary, when the user presses the accept button - * in the file chooser dialog. - * - * @param approver A SelectionApprover which will determine if the selection - * is valid - * @return this - * @since 7.26.0 - */ - public FileChooserBuilder setSelectionApprover (SelectionApprover approver) { - this.approver = approver; - return this; - } - - /** - * Object which can approve the selection (enabling the OK button or - * equivalent) in a JFileChooser. Equivalent to overriding - * JFileChooser.approveSelection() - * @since 7.26.0 - */ - public interface SelectionApprover { - /** - * Approve the selection, enabling the dialog to be closed. Called by - * the JFileChooser's approveSelection() method. Use this - * interface if you want to, for example, show a dialog asking - * "Overwrite File X?" or similar. - * - * @param selection The selected file(s) at the time the user presses - * the Open, Save or OK button - * @return true if the selection is accepted, false if it is not and - * the dialog should not be closed - */ - public boolean approve (File[] selection); - } - - private static final class SavedDirFileChooser extends JFileChooser { - private final String dirKey; - private final SelectionApprover approver; - SavedDirFileChooser(String dirKey, File failoverDir, boolean force, SelectionApprover approver) { - this.dirKey = dirKey; - this.approver = approver; - if (force && failoverDir != null && failoverDir.exists() && failoverDir.isDirectory()) { - setCurrentDirectory(failoverDir); - } else { - String path = DONT_STORE_DIRECTORIES ? null : - NbPreferences.forModule(FileChooserBuilder.class).get(dirKey, null); - if (path != null) { - File f = new File(path); - if (f.exists() && f.isDirectory()) { - setCurrentDirectory(f); - } else if (failoverDir != null) { - setCurrentDirectory(failoverDir); - } - } else if (failoverDir != null) { - setCurrentDirectory(failoverDir); - } - } - } - - @Override - public void approveSelection() { - if (approver != null) { - File[] selected = getSelectedFiles(); - final File sf = getSelectedFile(); - if ((selected == null || selected.length == 0) && sf != null) { - selected = new File[] { sf }; - } - boolean approved = approver.approve(selected); - if (approved) { - super.approveSelection(); - } - } else { - super.approveSelection(); - } - } - - @Override - public int showDialog(Component parent, String approveButtonText) throws HeadlessException { - int result = super.showDialog(parent, approveButtonText); - if (result == APPROVE_OPTION) { - saveCurrentDir(); - } - return result; - } - - private void saveCurrentDir() { - File dir = super.getCurrentDirectory(); - if (!DONT_STORE_DIRECTORIES && dir != null && dir.exists() && dir.isDirectory()) { - NbPreferences.forModule(FileChooserBuilder.class).put(dirKey, dir.getPath()); - } - } - } - - //Can open this API later if there is a use-case - interface IconProvider { - public Icon getIcon(File file, Icon orig); - } - - /** - * Provides "badges" for icons that indicate files or folders of particular - * interest to the user. - * @see FileChooserBuilder#setBadgeProvider - */ - public interface BadgeProvider { - /** - * Get the badge the passed file should use. Note: this method - * is called for every visible file. The negative test (deciding - * not to badge a file) should be very, very fast and immediately - * return null. - * @param file The file in question - * @return an icon or null if no change to the appearance of the file - * is needed - */ - public Icon getBadge(File file); - - /** - * Get the x offset for badges produced by this provider. This is - * the location of the badge icon relative to the real icon for the - * file. - * @return a rightward pixel offset - */ - public int getXOffset(); - - /** - * Get the y offset for badges produced by this provider. This is - * the location of the badge icon relative to the real icon for the - * file. - * @return a downward pixel offset - */ - public int getYOffset(); - } - - private static final class BadgeIconProvider implements IconProvider { - - private final BadgeProvider badger; - - public BadgeIconProvider(BadgeProvider badger) { - this.badger = badger; - } - - public Icon getIcon(File file, Icon orig) { - Icon badge = badger.getBadge(file); - if (badge != null && orig != null) { - return new MergedIcon(orig, badge, badger.getXOffset(), - badger.getYOffset()); - } - return orig; - } - } - - private static final class CustomFileView extends FileView { - - private final IconProvider provider; - private final FileSystemView view; - - CustomFileView(IconProvider provider, FileSystemView view) { - this.provider = provider; - this.view = view; - } - - @Override - public Icon getIcon(File f) { - Icon result = view.getSystemIcon(f); - result = provider.getIcon(f, result); - return result; - } - } - - private static class MergedIcon implements Icon { - - private Icon icon1; - private Icon icon2; - private int xMerge; - private int yMerge; - - MergedIcon(Icon icon1, Icon icon2, int xMerge, int yMerge) { - assert icon1 != null; - assert icon2 != null; - this.icon1 = icon1; - this.icon2 = icon2; - - if (xMerge == -1) { - xMerge = icon1.getIconWidth() - icon2.getIconWidth(); - } - - if (yMerge == -1) { - yMerge = icon1.getIconHeight() - icon2.getIconHeight(); - } - - this.xMerge = xMerge; - this.yMerge = yMerge; - } - - public int getIconHeight() { - return Math.max(icon1.getIconHeight(), yMerge + icon2.getIconHeight()); - } - - public int getIconWidth() { - return Math.max(icon1.getIconWidth(), yMerge + icon2.getIconWidth()); - } - - public void paintIcon(java.awt.Component c, java.awt.Graphics g, int x, int y) { - icon1.paintIcon(c, g, x, y); - icon2.paintIcon(c, g, x + xMerge, y + yMerge); - } - } -} diff --git a/openide.filesystems/src/org/openide/filesystems/FileObject.java b/openide.filesystems/src/org/openide/filesystems/FileObject.java --- a/openide.filesystems/src/org/openide/filesystems/FileObject.java +++ b/openide.filesystems/src/org/openide/filesystems/FileObject.java @@ -68,7 +68,6 @@ import org.openide.util.NbBundle; import org.openide.util.Lookup; import org.openide.util.Lookup.Result; -import org.openide.util.UserQuestionException; /** This is the base for all implementations of file objects on a filesystem. * Provides basic information about the object (its name, parent, @@ -838,7 +837,7 @@ /** Lock this file. * @return lock that can be used to perform various modifications on the file * @throws FileAlreadyLockedException if the file is already locked - * @throws UserQuestionException in case when the lock cannot be obtained now, + * @throws IOException (UserQuestionException) in case when the lock cannot be obtained now, * but the underlaying implementation is able to do it after some * complex/dangerous/long-lasting operation and request confirmation * from the user @@ -1093,7 +1092,7 @@ *

  • Then: *
      *
    • If no exception is thrown, proceed with the operation. - *
    • If a {@link UserQuestionException} is thrown, + *
    • If a UserQuestionException is thrown, * call {@link UserQuestionException#confirmed} on it * (asynchronously - do not block any important threads). If true, * proceed with the operation. If false, exit. diff --git a/openide.filesystems/src/org/openide/filesystems/FileSystem.java b/openide.filesystems/src/org/openide/filesystems/FileSystem.java --- a/openide.filesystems/src/org/openide/filesystems/FileSystem.java +++ b/openide.filesystems/src/org/openide/filesystems/FileSystem.java @@ -45,8 +45,6 @@ package org.openide.filesystems; import java.awt.Image; -import java.awt.Toolkit; -import java.beans.BeanInfo; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; @@ -57,6 +55,7 @@ import java.net.URL; import java.util.Arrays; import java.util.Collection; +import java.util.Iterator; import java.util.List; import java.util.MissingResourceException; import java.util.ResourceBundle; @@ -64,7 +63,6 @@ import java.util.logging.Level; import java.util.logging.Logger; import org.openide.util.*; -import org.openide.util.actions.SystemAction; import org.openide.util.lookup.ServiceProvider; import org.openide.util.lookup.ServiceProviders; @@ -159,9 +157,6 @@ /** Property name giving read-only state. */ public static final String PROP_READ_ONLY = "readOnly"; // NOI18N - /** Property name giving capabilities state. @deprecated No more capabilities. */ - static final String PROP_CAPABILITIES = "capabilities"; // NOI18N - /** Used for synchronization purpose*/ private static final Object internLock = new Object(); private transient static ThreadLocal thrLocal = new ThreadLocal(); @@ -192,18 +187,6 @@ private transient Repository repository = null; private transient FCLSupport fclSupport; - /** Describes capabilities of the filesystem. - */ - @Deprecated // have to store it for compat - private /* XXX JDK #6460147: javac still reports it even though @Deprecated, - and @SuppressWarnings("deprecation") does not help either: FileSystemCapability*/Object capability; - - /** property listener on FileSystemCapability. */ - private transient PropertyChangeListener capabilityListener; - - /** hidden flag */ - private boolean hidden = false; - /** system name */ private String systemName = ""; // NOI18N @@ -250,47 +233,6 @@ } } - /** Set hidden state of the object. - * A hidden filesystem is not presented to the user in the Repository list (though it may be present in the Repository Settings list). - * - * @param hide true if the filesystem should be hidden - * @deprecated This property is now useless. - */ - @Deprecated - public final void setHidden(boolean hide) { - if (hide != hidden) { - hidden = hide; - firePropertyChange(PROP_HIDDEN, (!hide) ? Boolean.TRUE : Boolean.FALSE, hide ? Boolean.TRUE : Boolean.FALSE); - } - } - - /** Getter for the hidden property. - * @return the hidden property. - * @deprecated This property is now useless. - */ - @Deprecated - public final boolean isHidden() { - return hidden; - } - - /** Tests whether filesystem will survive reloading of system pool. - * If true then when - * {@link Repository} is reloading its content, it preserves this - * filesystem in the pool. - *

      - * This can be used when the pool contains system level and user level - * filesystems. The system ones should be preserved when the user changes - * the content (for example when he is loading a new project). - *

      The default implementation returns false. - * - * @return true if the filesystem should be persistent - * @deprecated This property is long since useless. - */ - @Deprecated - protected boolean isPersistent() { - return false; - } - /** Provides a name for the system that can be presented to the user. *

      * This call should never be used to attempt to identify the file root @@ -468,27 +410,6 @@ throw new IOException("Unsupported operation"); // NOI18N } - /** Returns an array of actions that can be invoked on any file in - * this filesystem. - * These actions should preferably - * support the {@link org.openide.util.actions.Presenter.Menu Menu}, - * {@link org.openide.util.actions.Presenter.Popup Popup}, - * and {@link org.openide.util.actions.Presenter.Toolbar Toolbar} presenters. - * - * @return array of available actions - */ - public abstract SystemAction[] getActions(); - - /** - * Get actions appropriate to a certain file selection. - * By default, returns the same list as {@link #getActions()}. - * @param foSet one or more files which may be selected - * @return zero or more actions appropriate to those files - */ - public SystemAction[] getActions(Set foSet) { - return this.getActions(); - } - /** Reads object from stream and creates listeners. * @param in the input stream to read from * @exception IOException error during read @@ -498,34 +419,21 @@ private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { in.defaultReadObject(); - - if (capability != null) { - ((FileSystemCapability) capability).addPropertyChangeListener(getCapabilityChangeListener()); - } } @Override public String toString() { return getSystemName() + "[" + super.toString() + "]"; // NOI18N } - - /** Allows filesystems to set up the environment for external execution - * and compilation. - * Each filesystem can add its own values that - * influence the environment. The set of operations that can modify - * environment is described by the {@link Environment} interface. - *

      - * The default implementation throws an exception to signal that it does not - * support external compilation or execution. - * - * @param env the environment to setup - * @exception EnvironmentNotSupportedException if external execution - * and compilation cannot be supported - * @deprecated Please use the ClassPath API instead. - */ - @Deprecated - public void prepareEnvironment(Environment env) throws EnvironmentNotSupportedException { - throw new EnvironmentNotSupportedException(this); + + private static volatile Lookup.Result statusResult; + + private static FileSystem.Status defaultStatus() { + if (statusResult == null) { + statusResult = Lookup.getDefault().lookupResult(FileSystem.Status.class); + } + Iterator it = statusResult.allInstances().iterator(); + return it.hasNext() ? it.next() : SFS_STATUS; } /** @@ -552,40 +460,7 @@ * @return the status object for this filesystem */ public Status getStatus() { - return isDefault() ? SFS_STATUS : STATUS_NONE; - } - - /** The object describing capabilities of this filesystem. - * Subclasses cannot override it. - * @return object describing capabilities of this filesystem. - * @deprecated Capabilities are no longer used. - */ - @Deprecated - public final FileSystemCapability getCapability() { - if (capability == null) { - capability = new FileSystemCapability.Bean(); - ((FileSystemCapability) capability).addPropertyChangeListener(getCapabilityChangeListener()); - } - - return (FileSystemCapability) capability; - } - - /** Allows subclasses to change a set of capabilities of the - * filesystem. - * @param capability the capability to use - * @deprecated Capabilities are no longer used. - */ - @Deprecated - protected final void setCapability(FileSystemCapability capability) { - if (this.capability != null) { - ((FileSystemCapability) this.capability).removePropertyChangeListener(getCapabilityChangeListener()); - } - - this.capability = capability; - - if (this.capability != null) { - ((FileSystemCapability) this.capability).addPropertyChangeListener(getCapabilityChangeListener()); - } + return isDefault() ? defaultStatus() : STATUS_NONE; } /** Executes atomic action. The atomic action represents a set of @@ -644,21 +519,6 @@ getEventControl().dispatchEvent(run); } - /** returns property listener on FileSystemCapability. */ - private synchronized PropertyChangeListener getCapabilityChangeListener() { - if (capabilityListener == null) { - capabilityListener = new PropertyChangeListener() { - public void propertyChange(java.beans.PropertyChangeEvent propertyChangeEvent) { - firePropertyChange( - PROP_CAPABILITIES, propertyChangeEvent.getOldValue(), propertyChangeEvent.getNewValue() - ); - } - }; - } - - return capabilityListener; - } - private final EventControl getEventControl() { EventControl evnCtrl = thrLocal.get(); @@ -971,27 +831,6 @@ public String annotateNameHtml(String name, Set files); } - /** Interface that allows filesystems to set up the Java environment - * for external execution and compilation. - * Currently just used to append entries to the external class path. - * @deprecated Please use the ClassPath API instead. - */ - @Deprecated - public static abstract class Environment extends Object { - /** Deprecated. */ - public Environment() { - assert false : "Deprecated."; - } - - /** Adds one element to the class path environment variable. - * @param classPathElement string representing the one element - * @deprecated Please use the ClassPath API instead. - */ - @Deprecated - public void addClassPath(String classPathElement) { - } - } - /** Class used to notify events for the filesystem. */ static abstract class EventDispatcher extends Object implements Runnable { @@ -1052,7 +891,7 @@ String bundleName = (String) fo.getAttribute("SystemFileSystem.localizingBundle"); // NOI18N if (bundleName != null) { try { - bundleName = Utilities.translate(bundleName); + bundleName = BaseUtilities.translate(bundleName); ResourceBundle b = NbBundle.getBundle(bundleName); try { return b.getString(fo.getPath()); @@ -1087,33 +926,6 @@ } private Image annotateIcon(FileObject fo, int type) { - String attr = null; - if (type == BeanInfo.ICON_COLOR_16x16) { - attr = "SystemFileSystem.icon"; // NOI18N - } else if (type == BeanInfo.ICON_COLOR_32x32) { - attr = "SystemFileSystem.icon32"; // NOI18N - } - if (attr != null) { - Object value = fo.getAttribute(attr); - if (value != null) { - if (value instanceof URL) { - return Toolkit.getDefaultToolkit().getImage((URL) value); - } else if (value instanceof Image) { - // #18832 - return (Image) value; - } else { - LOG.warning("Attribute " + attr + " on " + fo + " expected to be a URL or Image; was: " + value); - } - } - } - String base = (String) fo.getAttribute("iconBase"); // NOI18N - if (base != null) { - if (type == BeanInfo.ICON_COLOR_16x16) { - return ImageUtilities.loadImage(base, true); - } else if (type == BeanInfo.ICON_COLOR_32x32) { - return ImageUtilities.loadImage(insertBeforeSuffix(base, "_32"), true); // NOI18N - } - } return null; } diff --git a/openide.filesystems/src/org/openide/filesystems/FileSystemCapability.java b/openide.filesystems/src/org/openide/filesystems/FileSystemCapability.java deleted file mode 100644 --- a/openide.filesystems/src/org/openide/filesystems/FileSystemCapability.java +++ /dev/null @@ -1,435 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. - * - * Oracle and Java are registered trademarks of Oracle and/or its affiliates. - * Other names may be trademarks of their respective owners. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common - * Development and Distribution License("CDDL") (collectively, the - * "License"). You may not use this file except in compliance with the - * License. You can obtain a copy of the License at - * http://www.netbeans.org/cddl-gplv2.html - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the - * specific language governing permissions and limitations under the - * License. When distributing the software, include this License Header - * Notice in each file and include the License file at - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the GPL Version 2 section of the License file that - * accompanied this code. If applicable, add the following below the - * License Header, with the fields enclosed by brackets [] replaced by - * your own identifying information: - * "Portions Copyrighted [year] [name of copyright owner]" - * - * Contributor(s): - * - * The Original Software is NetBeans. The Initial Developer of the Original - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun - * Microsystems, Inc. All Rights Reserved. - * - * If you wish your version of this file to be governed by only the CDDL - * or only the GPL Version 2, indicate your decision by adding - * "[Contributor] elects to include this software in this distribution - * under the [CDDL or GPL Version 2] license." If you do not indicate a - * single choice of license, a recipient has the option to distribute - * your version of this file under either the CDDL, the GPL Version 2 or - * to extend the choice of license to its licensees as provided above. - * However, if you add GPL Version 2 code and therefore, elected the GPL - * Version 2 license, then the option applies only if the new code is - * made subject to such option by the copyright holder. - */ - -package org.openide.filesystems; - -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.util.Collection; -import java.util.Enumeration; -import java.util.Vector; - -/** This class defines the capabilities of a filesystem to -* take part in different operations. Some filesystems are -* not designed to allow compilation on them, some do not want -* to be present in class path when executing or debugging -* a program. -*

      -* Moreover there can be additional capabilities to check -* and this class defines ways how one can communicated with -* a filesystem to find out whether the system is "capable" -* enough to be used in the operation. -* -* @author Jaroslav Tulach - * @deprecated Now useless. -*/ -@Deprecated -public class FileSystemCapability extends Object { - /** Object that is capable of every thing. - */ - public static final FileSystemCapability ALL = new FileSystemCapability() { - public boolean capableOf(FileSystemCapability c) { - return true; - } - }; - - /** Well known capability of being compiled. - * @deprecated Please use the ClassPath API instead. - */ - @Deprecated - public static final FileSystemCapability COMPILE = new FileSystemCapability(); - - /** Well known ability to be executed. - * @deprecated Please use the ClassPath API instead. - */ - @Deprecated - public static final FileSystemCapability EXECUTE = new FileSystemCapability(); - - /** Well known ability to be debugged. - * @deprecated Please use the ClassPath API instead. - */ - @Deprecated - public static final FileSystemCapability DEBUG = new FileSystemCapability(); - - /** Well known ability to contain documentation files - * @deprecated Please use JavadocForBinaryQuery instead. - */ - @Deprecated - public static final FileSystemCapability DOC = new FileSystemCapability(); - - public FileSystemCapability() { - if (DOC == null) { - // do not report static initializers - return; - } - - assert false : "Deprecated."; - } - - /** Basic operation that tests whether this object - * is capable to do different capability. - *

      - * The default implementation claims that it is - * capable to handle only identical capability (==). - * - * @param c capability to test - * @return true if yes - */ - public boolean capableOf(FileSystemCapability c) { - return c == this; - } - - /** All filesystems that are capable of this capability. - * @return enumeration of FileSystems that satifies this capability - * @deprecated Please use the ClassPath API instead. - */ - @Deprecated - public Enumeration fileSystems() { - class FFS implements org.openide.util.Enumerations.Processor { - @Deprecated - public FileSystem process(FileSystem fs, Collection ignore) { - return fs.getCapability().capableOf(FileSystemCapability.this) ? fs : null; - } - } - - return org.openide.util.Enumerations.filter(Repository.getDefault().fileSystems(), new FFS()); - } - - /** Find a resource in repository, ignoring not capable filesystems. - * @param resName name of the resource - * @deprecated Please use the ClassPath API instead. - */ - @Deprecated - public FileObject findResource(String resName) { - Enumeration en = fileSystems(); - - while (en.hasMoreElements()) { - FileSystem fs = en.nextElement(); - FileObject fo = fs.findResource(resName); - - if (fo != null) { - // object found - return fo; - } - } - - return null; - } - - /** Searches for the given resource among all filesystems - * that satifies this capability, returning all matches. - * @param name name of the resource - * @return enumeration of {@link FileObject}s - * @deprecated Please use the ClassPath API instead. - */ - @Deprecated - public Enumeration findAllResources(String name) { - Vector v = new Vector(8); - Enumeration en = fileSystems(); - - while (en.hasMoreElements()) { - FileSystem fs = en.nextElement(); - FileObject fo = fs.findResource(name); - - if (fo != null) { - v.addElement(fo); - } - } - - return v.elements(); - } - - /** Finds file when its name is provided. It scans in the list of - * filesystems and asks them for the specified file by a call to - * {@link FileSystem#find find}. The first object that is found is returned or null - * if none of the filesystems contain such a file. - * - * @param aPackage package name where each package is separated by a dot - * @param name name of the file (without dots) or null if - * one wants to obtain the name of a package and not a file in it - * @param ext extension of the file or null if one needs - * a package and not a file name - * - * @return {@link FileObject} that represents file with given name or - * null if the file does not exist - * @deprecated Please use the ClassPath API instead. - */ - @Deprecated - public final FileObject find(String aPackage, String name, String ext) { - Enumeration en = fileSystems(); - - while (en.hasMoreElements()) { - FileSystem fs = en.nextElement(); - FileObject fo = fs.find(aPackage, name, ext); - - if (fo != null) { - // object found - return fo; - } - } - - return null; - } - - /** Finds all files among all filesystems with this capability - * that match a given name, returning all matches. - * All filesystems are queried with {@link FileSystem#find}. - * - * @param aPackage package name where each package is separated by a dot - * @param name name of the file (without dots) or null if - * one wants to obtain the name of a package and not a file in it - * @param ext extension of the file or null if one needs - * a package and not a file name - * - * @return enumeration of {@link FileObject}s - * @deprecated Please use the ClassPath API instead. - */ - @Deprecated - public final Enumeration findAll(String aPackage, String name, String ext) { - Enumeration en = fileSystems(); - Vector ret = new Vector(); - - while (en.hasMoreElements()) { - FileSystem fs = (FileSystem) en.nextElement(); - FileObject fo = fs.find(aPackage, name, ext); - - if (fo != null) { - ret.addElement(fo); - } - } - - return ret.elements(); - } - - /** Adds PropertyChange listener. Every class which implements changes of capabilities - * has to implement it's property change support. - * @param l the listener to be added. - */ - public synchronized void addPropertyChangeListener(PropertyChangeListener l) { - } - - /** Removes PropertyChange listener. Every class which implements changes of capabilities - * has to implement it's property change support. - * @param l the listener to be removed. - */ - public void removePropertyChangeListener(PropertyChangeListener l) { - } - - /** Default implementation of capabilities, that behaves like - * JavaBean and allows to set whether the well known - * capabilities (like compile, execute) should be enabled - * or not. - * @deprecated For the same reason the whole class is. - */ - @Deprecated - public static class Bean extends FileSystemCapability implements java.io.Serializable { - static final long serialVersionUID = 627905674809532736L; - - /** change listeners */ - private transient PropertyChangeSupport supp; - - /** compilation */ - private boolean compilation = true; - - /** execution */ - private boolean execution = true; - - /** debugging */ - private boolean debug = true; - - /** doc */ - private boolean doc = false; - - /** Checks for well known capabilities and if they are allowed. - * - * @param c capability to test - * @return true if yes - */ - public boolean capableOf(FileSystemCapability c) { - if (c == COMPILE) { - return compilation; - } - - if (c == EXECUTE) { - return execution; - } - - if (c == DEBUG) { - return debug; - } - - if (c == DOC) { - return doc; - } - - if (c == ALL) { - return true; - } - - if (!(c instanceof Bean)) { - return false; - } - - // try match of values - Bean b = (Bean) c; - - return (compilation == b.compilation) && (execution == b.execution) && (debug == b.debug) && - (doc == b.doc); - } - - /** Getter for value of compiling capability. - * @deprecated Please use the ClassPath API instead. - */ - @Deprecated - public boolean getCompile() { - return compilation; - } - - /** Setter for allowing compiling capability. - * @deprecated Please use the ClassPath API instead. - */ - @Deprecated - public void setCompile(boolean val) { - if (val != compilation) { - compilation = val; - - if (supp != null) { - supp.firePropertyChange( - "compile", // NOI18N - (!val) ? Boolean.TRUE : Boolean.FALSE, val ? Boolean.TRUE : Boolean.FALSE - ); - } - } - } - - /** Getter for value of executiong capability. - * @deprecated Please use the ClassPath API instead. - */ - @Deprecated - public boolean getExecute() { - return execution; - } - - /** Setter for allowing executing capability. - * @deprecated Please use the ClassPath API instead. - */ - @Deprecated - public void setExecute(boolean val) { - if (val != execution) { - execution = val; - - if (supp != null) { - supp.firePropertyChange( - "execute", // NOI18N - (!val) ? Boolean.TRUE : Boolean.FALSE, val ? Boolean.TRUE : Boolean.FALSE - ); - } - } - } - - /** Getter for value of debugging capability. - * @deprecated Please use the ClassPath API instead. - */ - @Deprecated - public boolean getDebug() { - return debug; - } - - /** Setter for allowing debugging capability. - * @deprecated Please use the ClassPath API instead. - */ - @Deprecated - public void setDebug(boolean val) { - if (val != debug) { - debug = val; - - if (supp != null) { - supp.firePropertyChange( - "debug", // NOI18N - (!val) ? Boolean.TRUE : Boolean.FALSE, val ? Boolean.TRUE : Boolean.FALSE - ); - } - } - } - - /** Getter for value of doc capability. - * @deprecated Please use JavadocForBinaryQuery instead. - */ - @Deprecated - public boolean getDoc() { - return doc; - } - - /** Setter for allowing debugging capability. - * @deprecated Please use JavadocForBinaryQuery instead. - */ - @Deprecated - public void setDoc(boolean val) { - if (val != doc) { - doc = val; - - if (supp != null) { - supp.firePropertyChange( - "doc", // NOI18N - (!val) ? Boolean.TRUE : Boolean.FALSE, val ? Boolean.TRUE : Boolean.FALSE - ); - } - } - } - - public synchronized void addPropertyChangeListener(PropertyChangeListener l) { - if (supp == null) { - supp = new PropertyChangeSupport(this); - } - - supp.addPropertyChangeListener(l); - } - - public void removePropertyChangeListener(PropertyChangeListener l) { - if (supp != null) { - supp.removePropertyChangeListener(l); - } - } - } -} diff --git a/openide.filesystems/src/org/openide/filesystems/FileUtil.java b/openide.filesystems/src/org/openide/filesystems/FileUtil.java --- a/openide.filesystems/src/org/openide/filesystems/FileUtil.java +++ b/openide.filesystems/src/org/openide/filesystems/FileUtil.java @@ -84,16 +84,13 @@ import java.util.jar.JarInputStream; import java.util.logging.Level; import java.util.logging.Logger; -import javax.swing.Icon; -import javax.swing.JFileChooser; -import javax.swing.filechooser.FileSystemView; import org.netbeans.modules.openide.filesystems.declmime.MIMEResolverImpl; import org.openide.filesystems.FileSystem.AtomicAction; import org.openide.util.Exceptions; import org.openide.util.NbBundle; import org.openide.util.Parameters; import org.openide.util.RequestProcessor; -import org.openide.util.Utilities; +import org.openide.util.BaseUtilities; import org.openide.util.WeakListeners; import org.openide.util.lookup.implspi.NamedServicesProvider; @@ -835,10 +832,10 @@ } if ((fileURL != null) && "file".equals(fileURL.getProtocol())) { - retVal = Utilities.toFile(URI.create(fileURL.toExternalForm())); + retVal = BaseUtilities.toFile(URI.create(fileURL.toExternalForm())); } } - assert assertNormalized(retVal, Utilities.isMac()); // #240180 + assert assertNormalized(retVal, BaseUtilities.isMac()); // #240180 return retVal; } @@ -885,7 +882,7 @@ FileObject retVal = null; try { - URL url = Utilities.toURI(file).toURL(); + URL url = BaseUtilities.toURI(file).toURL(); retVal = URLMapper.findFileObject(url); /*probably temporary piece of code to catch the cause of #46630*/ @@ -928,7 +925,7 @@ } try { - URL url = (Utilities.toURI(file).toURL()); + URL url = (BaseUtilities.toURI(file).toURL()); retVal = URLMapper.findFileObjects(url); } catch (MalformedURLException e) { retVal = null; @@ -1212,7 +1209,7 @@ * @return true, if such name does not exists */ private static boolean checkFreeName(FileObject fo, String name, String ext) { - if ((Utilities.isWindows() || (Utilities.getOperatingSystem() == Utilities.OS_OS2)) || Utilities.isMac()) { + if ((BaseUtilities.isWindows() || (BaseUtilities.getOperatingSystem() == BaseUtilities.OS_OS2)) || BaseUtilities.isMac()) { // case-insensitive, do some special check Enumeration en = fo.getChildren(false); @@ -1607,9 +1604,9 @@ LOG.log(Level.FINE, "FileUtil.normalizeFile for {0}", file); // NOI18N long now = System.currentTimeMillis(); - if ((Utilities.isWindows() || (Utilities.getOperatingSystem() == Utilities.OS_OS2))) { + if ((BaseUtilities.isWindows() || (BaseUtilities.getOperatingSystem() == BaseUtilities.OS_OS2))) { retFile = normalizeFileOnWindows(file); - } else if (Utilities.isMac()) { + } else if (BaseUtilities.isMac()) { retFile = normalizeFileOnMac(file); } else { retFile = normalizeFileOnUnixAlike(file); @@ -1625,7 +1622,7 @@ private static File normalizeFileOnUnixAlike(File file) { // On Unix, do not want to traverse symlinks. // URI.normalize removes ../ and ./ sequences nicely. - file = Utilities.toFile(Utilities.toURI(file).normalize()).getAbsoluteFile(); + file = BaseUtilities.toFile(BaseUtilities.toURI(file).normalize()).getAbsoluteFile(); while (file.getAbsolutePath().startsWith("/../")) { // NOI18N file = new File(file.getAbsolutePath().substring(3)); } @@ -1641,7 +1638,7 @@ try { // URI.normalize removes ../ and ./ sequences nicely. - File absoluteFile = Utilities.toFile(Utilities.toURI(file).normalize()); + File absoluteFile = BaseUtilities.toFile(BaseUtilities.toURI(file).normalize()); File canonicalFile = file.getCanonicalFile(); String absolutePath = absoluteFile.getAbsolutePath(); if (absolutePath.equals("/..")) { // NOI18N @@ -1738,7 +1735,7 @@ } } // #135547 - on Windows Vista map "Documents and Settings\\My Documents" to "Users\\Documents" - if((Utilities.getOperatingSystem() & Utilities.OS_WINVISTA) != 0) { + if((BaseUtilities.getOperatingSystem() & BaseUtilities.OS_WINVISTA) != 0) { if(retVal == null) { retVal = file.getAbsoluteFile(); } @@ -1987,7 +1984,7 @@ do { wasDir = entry.isDirectory(); LOG.finest("urlForArchiveOrDir:toURI:entry"); //NOI18N - u = Utilities.toURI(entry).toURL(); + u = BaseUtilities.toURI(entry).toURL(); isDir = entry.isDirectory(); } while (wasDir ^ isDir); if (isArchiveFile(u) || entry.isFile() && entry.length() < 4) { @@ -2022,9 +2019,9 @@ public static File archiveOrDirForURL(URL entry) { String u = entry.toString(); if (u.startsWith("jar:file:") && u.endsWith("!/")) { // NOI18N - return Utilities.toFile(URI.create(u.substring(4, u.length() - 2))); + return BaseUtilities.toFile(URI.create(u.substring(4, u.length() - 2))); } else if (u.startsWith("file:")) { // NOI18N - return Utilities.toFile(URI.create(u)); + return BaseUtilities.toFile(URI.create(u)); } else { return null; } @@ -2034,14 +2031,14 @@ * Make sure that a JFileChooser does not traverse symlinks on Unix. * @param chooser a file chooser * @param currentDirectory if not null, a file to set as the current directory - * using {@link JFileChooser#setCurrentDirectory} without canonicalizing + * using {@link javax.swing.JFileChooser#setCurrentDirectory} without canonicalizing * @see Issue #46459 * @see JRE bug #4906607 * @since org.openide/1 4.42 - * @deprecated Just use {@link JFileChooser#setCurrentDirectory}. JDK 6 does not have this bug. + * @deprecated Just use {@link javax.swing.JFileChooser#setCurrentDirectory}. JDK 6 does not have this bug. */ @Deprecated - public static void preventFileChooserSymlinkTraversal(JFileChooser chooser, File currentDirectory) { + public static void preventFileChooserSymlinkTraversal(javax.swing.JFileChooser chooser, File currentDirectory) { chooser.setCurrentDirectory(currentDirectory); } @@ -2211,123 +2208,6 @@ } } - private static final class NonCanonicalizingFileSystemView extends FileSystemView { - private final FileSystemView delegate = FileSystemView.getFileSystemView(); - - public NonCanonicalizingFileSystemView() { - } - - @Override - public boolean isFloppyDrive(File dir) { - return delegate.isFloppyDrive(dir); - } - - @Override - public boolean isComputerNode(File dir) { - return delegate.isComputerNode(dir); - } - - public File createNewFolder(File containingDir) - throws IOException { - return wrapFileNoCanonicalize(delegate.createNewFolder(containingDir)); - } - - @Override - public boolean isDrive(File dir) { - return delegate.isDrive(dir); - } - - @Override - public boolean isFileSystemRoot(File dir) { - return delegate.isFileSystemRoot(dir); - } - - @Override - public File getHomeDirectory() { - return wrapFileNoCanonicalize(delegate.getHomeDirectory()); - } - - @Override - public File createFileObject(File dir, String filename) { - return wrapFileNoCanonicalize(delegate.createFileObject(dir, filename)); - } - - @Override - public Boolean isTraversable(File f) { - return delegate.isTraversable(f); - } - - @Override - public boolean isFileSystem(File f) { - return delegate.isFileSystem(f); - } - - /* - protected File createFileSystemRoot(File f) { - return translate(delegate.createFileSystemRoot(f)); - } - */ - @Override - public File getChild(File parent, String fileName) { - return wrapFileNoCanonicalize(delegate.getChild(parent, fileName)); - } - - @Override - public File getParentDirectory(File dir) { - return wrapFileNoCanonicalize(delegate.getParentDirectory(dir)); - } - - @Override - public Icon getSystemIcon(File f) { - return delegate.getSystemIcon(f); - } - - @Override - public boolean isParent(File folder, File file) { - return delegate.isParent(folder, file); - } - - @Override - public String getSystemTypeDescription(File f) { - return delegate.getSystemTypeDescription(f); - } - - @Override - public File getDefaultDirectory() { - return wrapFileNoCanonicalize(delegate.getDefaultDirectory()); - } - - @Override - public String getSystemDisplayName(File f) { - return delegate.getSystemDisplayName(f); - } - - @Override - public File[] getRoots() { - return wrapFilesNoCanonicalize(delegate.getRoots()); - } - - @Override - public boolean isHiddenFile(File f) { - return delegate.isHiddenFile(f); - } - - @Override - public File[] getFiles(File dir, boolean useFileHiding) { - return wrapFilesNoCanonicalize(delegate.getFiles(dir, useFileHiding)); - } - - @Override - public boolean isRoot(File f) { - return delegate.isRoot(f); - } - - @Override - public File createFileObject(String path) { - return wrapFileNoCanonicalize(delegate.createFileObject(path)); - } - } - private static FileSystem getDiskFileSystem() { synchronized (FileUtil.class) { return diskFileSystem; diff --git a/openide.filesystems/src/org/openide/filesystems/JarFileSystem.java b/openide.filesystems/src/org/openide/filesystems/JarFileSystem.java --- a/openide.filesystems/src/org/openide/filesystems/JarFileSystem.java +++ b/openide.filesystems/src/org/openide/filesystems/JarFileSystem.java @@ -80,7 +80,7 @@ import org.openide.util.NbBundle; import org.openide.util.RequestProcessor; import org.openide.util.RequestProcessor.Task; -import org.openide.util.Utilities; +import org.openide.util.BaseUtilities; /** A virtual filesystem based on a JAR archive. *

      For historical reasons many AbstractFileSystem.* methods are implemented @@ -167,18 +167,7 @@ this.attr = impl; } - /** - * Constructor that can provide own capability for the filesystem. - * @param cap the capability - * @deprecated Useless. - */ - @Deprecated - public JarFileSystem(FileSystemCapability cap) { - this(); - setCapability(cap); - } - - /** Creates new JAR for a given JAR file. This constructor + /** Creates new JAR for a given JAR file. This constructor * behaves basically like: *

            * JarFileSystem fs = new JarFileSystem();
      @@ -427,18 +416,6 @@
           //        super.addNotify ();
           //    }
       
      -    /** Prepare environment for external compilation or execution.
      -    * 

      - * Adds name of the ZIP/JAR file, if it has been set, to the class path. - * @deprecated Useless. - */ - @Deprecated - @Override - public void prepareEnvironment(Environment env) { - if (root != null) { - env.addClassPath(root.getAbsolutePath()); - } - } // // List @@ -985,7 +962,7 @@ } private static void dumpFDs() { - if (Utilities.isUnix()) { + if (BaseUtilities.isUnix()) { String selfName = ManagementFactory.getRuntimeMXBean().getName().replaceAll("@.*", ""); // NOI18N LOGGER.log(Level.INFO, "Dumping file descriptors for pid {0}", selfName); // NOI18N int pid; @@ -1017,7 +994,7 @@ */ private class Ref extends WeakReference implements Runnable { public Ref(T fo) { - super(fo, Utilities.activeReferenceQueue()); + super(fo, BaseUtilities.activeReferenceQueue()); } // do the cleanup diff --git a/openide.filesystems/src/org/openide/filesystems/LocalFileSystem.java b/openide.filesystems/src/org/openide/filesystems/LocalFileSystem.java --- a/openide.filesystems/src/org/openide/filesystems/LocalFileSystem.java +++ b/openide.filesystems/src/org/openide/filesystems/LocalFileSystem.java @@ -61,7 +61,7 @@ import java.util.logging.Level; import org.openide.util.Exceptions; import org.openide.util.NbBundle; -import org.openide.util.Utilities; +import org.openide.util.BaseUtilities; /** Local filesystem. Provides access to files on local disk. *

      For historical reasons many AbstractFileSystem.* methods are implemented @@ -103,17 +103,6 @@ setRefreshTime(REFRESH_TIME); } - /** Constructor. Allows user to provide own capabilities - * for this filesystem. - * @param cap capabilities for this filesystem - * @deprecated Useless. - */ - @Deprecated - public LocalFileSystem(FileSystemCapability cap) { - this(); - setCapability(cap); - } - /* Human presentable name */ public String getDisplayName() { return rootFile.getAbsolutePath(); @@ -170,16 +159,6 @@ return readOnly; } - /** Prepare environment by adding the root directory of the filesystem to the class path. - * @param environment the environment to add to - * @deprecated Useless. - */ - @Deprecated - @Override - public void prepareEnvironment(FileSystem.Environment environment) { - environment.addClassPath(rootFile.getAbsolutePath()); - } - /** Compute the system name of this filesystem for a given root directory. *

      * The default implementation simply returns the filename separated by slashes. @@ -190,7 +169,7 @@ protected String computeSystemName(File rootFile) { String retVal = rootFile.getAbsolutePath().replace(File.separatorChar, '/'); - return ((Utilities.isWindows() || (Utilities.getOperatingSystem() == Utilities.OS_OS2))) ? retVal.toLowerCase() + return ((BaseUtilities.isWindows() || (BaseUtilities.getOperatingSystem() == BaseUtilities.OS_OS2))) ? retVal.toLowerCase() : retVal; } @@ -301,7 +280,7 @@ // #7086 - (nf.exists() && !nf.equals(of)) instead of nf.exists() - fix for Win32 boolean existsNF = nf.exists(); boolean equalsOF = nf.equals(of); - if (Utilities.isMac()) { + if (BaseUtilities.isMac()) { // File.equal on mac is not case insensitive (which it should be), // so try harder equalsOF = of.getCanonicalFile().equals(nf.getCanonicalFile()); @@ -465,7 +444,7 @@ OutputStream retVal = new BufferedOutputStream(new FileOutputStream(f)); // workaround for #42624 - if (Utilities.isMac()) { + if (BaseUtilities.isMac()) { retVal = getOutputStreamForMac42624(retVal, name); } diff --git a/openide.filesystems/src/org/openide/filesystems/MultiFileSystem.java b/openide.filesystems/src/org/openide/filesystems/MultiFileSystem.java --- a/openide.filesystems/src/org/openide/filesystems/MultiFileSystem.java +++ b/openide.filesystems/src/org/openide/filesystems/MultiFileSystem.java @@ -45,7 +45,6 @@ package org.openide.filesystems; import java.io.IOException; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @@ -57,7 +56,6 @@ import org.openide.util.Enumerations; import org.openide.util.NbBundle; import org.openide.util.NbCollections; -import org.openide.util.actions.SystemAction; /** * General base class for filesystems which proxy to others. @@ -287,54 +285,6 @@ return root; } - /** Merge actions from all delegates. - */ - public @Override SystemAction[] getActions() { - List al = new ArrayList(101); // randomly choosen constant - Set uniq = new HashSet(101); // not that randommly choosen - - FileSystem[] del = this.getDelegates(); - - for (int i = 0; i < del.length; i++) { - if (del[i] == null) { - continue; - } - - SystemAction[] acts = del[i].getActions(); - - for (int j = 0; j < acts.length; j++) { - if (uniq.add(acts[j])) { - al.add(acts[j]); - } - } - } - - return al.toArray(new SystemAction[al.size()]); - } - - public @Override SystemAction[] getActions(final Set foSet) { - List al = new ArrayList(101); // randomly choosen constant - Set uniq = new HashSet(101); // not that randommly choosen - - final FileSystem[] del = this.getDelegates(); - - for (int i = 0; i < del.length; i++) { - if (del[i] == null) { - continue; - } - - final SystemAction[] acts = del[i].getActions(foSet); - - for (int j = 0; j < acts.length; j++) { - if (uniq.add(acts[j])) { - al.add(acts[j]); - } - } - } - - return al.toArray(new SystemAction[al.size()]); - } - @Deprecated // have to override for compat public @Override FileObject find(String aPackage, String name, String ext) { // create enumeration of name to look for @@ -544,26 +494,6 @@ protected void markUnimportant(FileObject fo) { } - /** Lets any sub filesystems prepare the environment. - * If they do not support it, it does not care. - * @deprecated Useless. - */ - @Deprecated - public @Override void prepareEnvironment(FileSystem.Environment env) - throws EnvironmentNotSupportedException { - FileSystem[] layers = getDelegates(); - - for (int i = 0; i < layers.length; i++) { - if (layers[i] != null) { - try { - layers[i].prepareEnvironment(env); - } catch (EnvironmentNotSupportedException ense) { - // Fine. - } - } - } - } - /** Notifies all encapsulated filesystems in advance * to superclass behaviour. */ public @Override void addNotify() { diff --git a/openide.filesystems/src/org/openide/filesystems/Ordering.java b/openide.filesystems/src/org/openide/filesystems/Ordering.java --- a/openide.filesystems/src/org/openide/filesystems/Ordering.java +++ b/openide.filesystems/src/org/openide/filesystems/Ordering.java @@ -47,7 +47,7 @@ import java.util.logging.Logger; import org.openide.util.NbCollections; import org.openide.util.TopologicalSortException; -import org.openide.util.Utilities; +import org.openide.util.BaseUtilities; /** * Implements folder ordering logic in {@link FileUtil}. @@ -209,7 +209,7 @@ return new ArrayList(children); } else { try { - return Utilities.topologicalSort(children, edges); + return BaseUtilities.topologicalSort(children, edges); } catch (TopologicalSortException x) { if (logWarnings) { LOG.log(Level.WARNING, "Contradictory partial ordering in " + parent.getPath(), x); diff --git a/openide.filesystems/src/org/openide/filesystems/Repository.java b/openide.filesystems/src/org/openide/filesystems/Repository.java --- a/openide.filesystems/src/org/openide/filesystems/Repository.java +++ b/openide.filesystems/src/org/openide/filesystems/Repository.java @@ -631,7 +631,7 @@ while (iter.hasNext()) { FileSystem fs = (FileSystem) iter.next(); - if (!fs.isDefault() && !fs.isPersistent()) { + if (!fs.isDefault()) { oos.writeObject(new NbMarshalledObject(fs)); } } @@ -688,7 +688,7 @@ while (ee.hasMoreElements()) { fs = ee.nextElement(); - if (!fs.isPersistent()) { + if (!fs.isDefault()) { removeFileSystem(fs); } } diff --git a/openide.filesystems/src/org/openide/filesystems/URLMapper.java b/openide.filesystems/src/org/openide/filesystems/URLMapper.java --- a/openide.filesystems/src/org/openide/filesystems/URLMapper.java +++ b/openide.filesystems/src/org/openide/filesystems/URLMapper.java @@ -64,7 +64,7 @@ import org.openide.util.Lookup; import org.openide.util.LookupEvent; import org.openide.util.LookupListener; -import org.openide.util.Utilities; +import org.openide.util.BaseUtilities; /** Mapper from FileObject -> URL. * Should be registered in default lookup. For details see {@link Lookup#getDefault()}. @@ -422,7 +422,7 @@ // XXX clumsy; see ArchiveURLMapper for possible cleaner style String toReplace = "__EXCLAMATION_REPLACEMENT__";//NOI18N retURL = new URL( - "jar:" + Utilities.toURI(new File(f,toReplace + fo.getPath())).toString().replaceFirst("/"+toReplace,"!/") + // NOI18N + "jar:" + BaseUtilities.toURI(new File(f,toReplace + fo.getPath())).toString().replaceFirst("/"+toReplace,"!/") + // NOI18N ((fo.isFolder() && !fo.isRoot()) ? "/" : "") ); // NOI18N } catch (MalformedURLException mfx) { @@ -460,7 +460,7 @@ } private static URL toURL(File fFile, FileObject fo) throws MalformedURLException { - URL retVal = Utilities.toURI(fFile).toURL(); + URL retVal = BaseUtilities.toURI(fFile).toURL(); if (retVal != null && fo.isFolder()) { // #155742,160333 - URL for folder must always end with slash final String urlDef = retVal.toExternalForm(); @@ -529,7 +529,7 @@ try { URI uri = new URI(u.toExternalForm()); - return FileUtil.normalizeFile(Utilities.toFile(uri)); + return FileUtil.normalizeFile(BaseUtilities.toFile(uri)); } catch (URISyntaxException use) { // malformed URL return null; diff --git a/openide.filesystems/src/org/openide/filesystems/XMLFileSystem.java b/openide.filesystems/src/org/openide/filesystems/XMLFileSystem.java --- a/openide.filesystems/src/org/openide/filesystems/XMLFileSystem.java +++ b/openide.filesystems/src/org/openide/filesystems/XMLFileSystem.java @@ -74,7 +74,7 @@ import org.openide.util.Enumerations; import org.openide.util.Exceptions; import org.openide.util.NbBundle; -import org.openide.util.Utilities; +import org.openide.util.BaseUtilities; import org.openide.xml.XMLUtil; import org.xml.sax.Attributes; import org.xml.sax.InputSource; @@ -240,12 +240,12 @@ * for this filesystem. * @param cap capabilities for this filesystem * @deprecated Useless. - */ @Deprecated public XMLFileSystem(FileSystemCapability cap) { this(); setCapability(cap); } + */ /** Getter of url field. * @return URL associated with XMLFileSystem or null if no URL was set. @@ -1113,7 +1113,7 @@ if ("file".equals(protocol)) { //NOI18N try { - File f = Utilities.toFile(URI.create(url.toExternalForm())); + File f = BaseUtilities.toFile(URI.create(url.toExternalForm())); if (!f.equals(lastFile)) { lastFile = f; lastFileDate = new Date(f.lastModified()); diff --git a/openide.filesystems/src/org/openide/filesystems/XMLMapAttr.java b/openide.filesystems/src/org/openide/filesystems/XMLMapAttr.java --- a/openide.filesystems/src/org/openide/filesystems/XMLMapAttr.java +++ b/openide.filesystems/src/org/openide/filesystems/XMLMapAttr.java @@ -65,9 +65,9 @@ import java.util.TreeSet; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; +import org.netbeans.modules.openide.filesystems.RecognizeInstanceFiles; import org.openide.util.NbBundle; -import org.openide.util.SharedClassObject; -import org.openide.util.Utilities; +import org.openide.util.BaseUtilities; import org.openide.util.io.NbMarshalledObject; import org.openide.util.io.NbObjectInputStream; @@ -824,7 +824,7 @@ case 11: return URL.class; case 12: - return ExternalUtil.findClass(Utilities.translate(value)); + return ExternalUtil.findClass(BaseUtilities.translate(value)); case 13: return String.class; } @@ -967,15 +967,8 @@ return new URL(value); case 12: // special support for singletons - Class cls = ExternalUtil.findClass(Utilities.translate(value)); - - if (SharedClassObject.class.isAssignableFrom(cls)) { - return SharedClassObject.findObject(cls, true); - } else { - Constructor init = cls.getDeclaredConstructor(); - init.setAccessible(true); - return init.newInstance((Object[]) null); - } + Class cls = ExternalUtil.findClass(BaseUtilities.translate(value)); + return RecognizeInstanceFiles.createInstance(cls); case 13: String[] arr = value.split("#", 2); // NOI18N return NbBundle.getBundle(arr[0]).getObject(arr[1]); diff --git a/openide.filesystems/src/org/openide/filesystems/spi/CustomInstanceFactory.java b/openide.filesystems/src/org/openide/filesystems/spi/CustomInstanceFactory.java new file mode 100644 --- /dev/null +++ b/openide.filesystems/src/org/openide/filesystems/spi/CustomInstanceFactory.java @@ -0,0 +1,71 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2014 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2014 Sun Microsystems, Inc. + */ + +package org.openide.filesystems.spi; + +/** + * Creates instance of the desired class based on the file. + * Module providers may register factories to control creation of instances + * from files that use only file name or {@code instanceClass} attribute. + *

      + * Registered factories are called in the registration order, until one provides + * a non-null result, which become the file's created instance. If all factories + * return {@code null}, the FileSystems API will create the instance using the default + * constructor. + * + *

      + * Module implementors are encouraged to use the instanceCreate attribute + * instead. + * + * @author sdedic + * @since 9.0 + */ +public interface CustomInstanceFactory { + /** + * Creates an instance of the class. + * + * @param the desired type + * @param clazz the desired type + * @return an instance of the `clazz' or null + */ + public T createInstance(Class clazz); +} diff --git a/openide.filesystems/test/unit/src/org/netbeans/modules/openide/filesystems/FSFoldersInLookupTest.java b/openide.filesystems/test/unit/src/org/netbeans/modules/openide/filesystems/FSFoldersInLookupTest.java --- a/openide.filesystems/test/unit/src/org/netbeans/modules/openide/filesystems/FSFoldersInLookupTest.java +++ b/openide.filesystems/test/unit/src/org/netbeans/modules/openide/filesystems/FSFoldersInLookupTest.java @@ -51,7 +51,6 @@ import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.util.Lookup; -import org.openide.util.SharedClassObject; /** * @author Jaroslav Tulach @@ -104,6 +103,6 @@ assertNull("not found again", Lookup.getDefault().lookup(Shared.class)); } - public static final class Shared extends SharedClassObject {} + public static final class Shared {} } diff --git a/openide.filesystems/test/unit/src/org/netbeans/modules/openide/filesystems/FileFilterSupportTest.java b/openide.filesystems/test/unit/src/org/netbeans/modules/openide/filesystems/FileFilterSupportTest.java deleted file mode 100644 --- a/openide.filesystems/test/unit/src/org/netbeans/modules/openide/filesystems/FileFilterSupportTest.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright 2012 Oracle and/or its affiliates. All rights reserved. - * - * Oracle and Java are registered trademarks of Oracle and/or its affiliates. - * Other names may be trademarks of their respective owners. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common - * Development and Distribution License("CDDL") (collectively, the - * "License"). You may not use this file except in compliance with the - * License. You can obtain a copy of the License at - * http://www.netbeans.org/cddl-gplv2.html - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the - * specific language governing permissions and limitations under the - * License. When distributing the software, include this License Header - * Notice in each file and include the License file at - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the GPL Version 2 section of the License file that - * accompanied this code. If applicable, add the following below the - * License Header, with the fields enclosed by brackets [] replaced by - * your own identifying information: - * "Portions Copyrighted [year] [name of copyright owner]" - * - * If you wish your version of this file to be governed by only the CDDL - * or only the GPL Version 2, indicate your decision by adding - * "[Contributor] elects to include this software in this distribution - * under the [CDDL or GPL Version 2] license." If you do not indicate a - * single choice of license, a recipient has the option to distribute - * your version of this file under either the CDDL, the GPL Version 2 or - * to extend the choice of license to its licensees as provided above. - * However, if you add GPL Version 2 code and therefore, elected the GPL - * Version 2 license, then the option applies only if the new code is - * made subject to such option by the copyright holder. - * - * Contributor(s): - * - * Portions Copyrighted 2012 Sun Microsystems, Inc. - */ -package org.netbeans.modules.openide.filesystems; - -import java.io.File; -import java.util.List; -import javax.swing.filechooser.FileFilter; -import org.netbeans.junit.NbTestCase; -import org.openide.filesystems.MIMEResolver; -import org.openide.util.NbBundle; - -/** - * Test registered FileFilters. - * - * @author jhavlin - */ -@NbBundle.Messages({ - "RESOLVER=Resolver", - "FILECHOOSER=BNM Files" -}) -@MIMEResolver.Registration( - displayName = "#RESOLVER", -resource = "mime-resolver-filechooser.xml", -showInFileChooser = "#FILECHOOSER", position=543543) -public class FileFilterSupportTest extends NbTestCase { - - public FileFilterSupportTest(String name) { - super(name); - } - - /** - * This test, although it is quite short, tests a lot of ascpects of default - * file filters. The resolver definition XML file contains several - * duplicities, which are detected and ignored. If this detection fails, - * filter description and {@code accept} method is changed, and it is cought - * by this test. - */ - public void testRegisteredFilters() { - List list = FileFilterSupport.findRegisteredFileFilters(); - assertNotNull(list); - assertFalse(list.isEmpty()); - - boolean found = false; - for (FileFilter filter : list) { - - if (filter.getDescription().startsWith("BNM Files")) { - found = true; - checkBnmFilesFilter(filter); - } - } - assertTrue("Registered File Filter was not found.", found); - } - - private void checkBnmFilesFilter(FileFilter f) { - assertEquals("BNM Files [.bnm, bnmHelp, bnmProject, bnminfo, bnmsettings]", - f.getDescription()); - assertTrue(f.accept(new File("first.bnm"))); - assertTrue(f.accept(new File("second.BNM"))); - assertTrue(f.accept(new File("third.bNm"))); - assertTrue(f.accept(new File("bnmProject"))); - assertTrue(f.accept(new File("PREFIXbnmProjectAndSuFfIx"))); - assertFalse(f.accept(new File("bnmproject"))); - assertTrue(f.accept(new File("bnmSettings"))); - assertTrue(f.accept(new File("BNMSETTINGS"))); - assertFalse(f.accept(new File("bnmSettingsX"))); - assertTrue(f.accept(new File("bnmInfo"))); - assertTrue(f.accept(new File("AbnmInfoB"))); - assertTrue(f.accept(new File("aBNMINFOb"))); - assertTrue(f.accept(new File("bnmHelp"))); - assertFalse(f.accept(new File("bnmhelp"))); - assertFalse(f.accept(new File("bnmHelpX"))); - assertFalse(f.accept(new File("foo.txt"))); - } -} diff --git a/openide.filesystems/test/unit/src/org/netbeans/modules/openide/filesystems/RecognizeInstanceFilesTest.java b/openide.filesystems/test/unit/src/org/netbeans/modules/openide/filesystems/RecognizeInstanceFilesTest.java --- a/openide.filesystems/test/unit/src/org/netbeans/modules/openide/filesystems/RecognizeInstanceFilesTest.java +++ b/openide.filesystems/test/unit/src/org/netbeans/modules/openide/filesystems/RecognizeInstanceFilesTest.java @@ -55,7 +55,6 @@ import org.openide.filesystems.FileSystem; import org.openide.filesystems.FileUtil; import org.openide.util.Lookup; -import org.openide.util.SharedClassObject; import org.openide.util.lookup.Lookups; import org.openide.util.lookup.NamedServicesLookupTest; @@ -228,22 +227,13 @@ public static final class Inst extends Object { } - public void testSharedClassObject() throws Exception { - Shared instance = SharedClassObject.findObject(Shared.class, true); - FileObject data = FileUtil.createData(root, "dir/" + Shared.class.getName().replace('.', '-') + ".instance"); - Lookup l = Lookups.forPath("dir"); - assertSame(instance, l.lookup(Shared.class)); - - Shared created = FileUtil.getConfigObject(data.getPath(), Shared.class); - assertSame("Config file found", instance, created); - } public void testNullForFolders() throws Exception { FileObject data = FileUtil.createFolder(root, "dir/" + Shared.class.getName().replace('.', '-') + ".instance"); Shared nul = FileUtil.getConfigObject(data.getPath(), Shared.class); assertNull("No object for folders", nul); } - public static final class Shared extends SharedClassObject {} + public static final class Shared {} public void testDoNotCreateFoldersJustBecauseILookedThemUp() throws Exception { assertEquals(0, Lookups.forPath("nonexistent").lookupAll(Object.class).size()); diff --git a/openide.filesystems/test/unit/src/org/netbeans/modules/openide/filesystems/mime-resolver-filechooser.xml b/openide.filesystems/test/unit/src/org/netbeans/modules/openide/filesystems/mime-resolver-filechooser.xml deleted file mode 100644 --- a/openide.filesystems/test/unit/src/org/netbeans/modules/openide/filesystems/mime-resolver-filechooser.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/openide.filesystems/test/unit/src/org/openide/filesystems/AttributesTestHidden.java b/openide.filesystems/test/unit/src/org/openide/filesystems/AttributesTestHidden.java --- a/openide.filesystems/test/unit/src/org/openide/filesystems/AttributesTestHidden.java +++ b/openide.filesystems/test/unit/src/org/openide/filesystems/AttributesTestHidden.java @@ -48,7 +48,7 @@ import java.util.*; import java.io.*; import java.lang.reflect.Method; -import org.openide.util.Utilities; +import org.openide.util.BaseUtilities; /** * @@ -306,7 +306,7 @@ ).getBytes()); fos.close(); - XMLFileSystem xfs = new XMLFileSystem(Utilities.toURI(f).toURL()); + XMLFileSystem xfs = new XMLFileSystem(BaseUtilities.toURI(f).toURL()); FileObject template = xfs.findResource("Templates/Other/special"); assertNotNull("template found", template); FileObject foTested = testedFS.getRoot().createData("copiedTemplate"); diff --git a/openide.filesystems/test/unit/src/org/openide/filesystems/FileChooserBuilderTest.java b/openide.filesystems/test/unit/src/org/openide/filesystems/FileChooserBuilderTest.java deleted file mode 100644 --- a/openide.filesystems/test/unit/src/org/openide/filesystems/FileChooserBuilderTest.java +++ /dev/null @@ -1,417 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright 2010 Oracle and/or its affiliates. All rights reserved. - * - * Oracle and Java are registered trademarks of Oracle and/or its affiliates. - * Other names may be trademarks of their respective owners. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common - * Development and Distribution License("CDDL") (collectively, the - * "License"). You may not use this file except in compliance with the - * License. You can obtain a copy of the License at - * http://www.netbeans.org/cddl-gplv2.html - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the - * specific language governing permissions and limitations under the - * License. When distributing the software, include this License Header - * Notice in each file and include the License file at - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the GPL Version 2 section of the License file that - * accompanied this code. If applicable, add the following below the - * License Header, with the fields enclosed by brackets [] replaced by - * your own identifying information: - * "Portions Copyrighted [year] [name of copyright owner]" - * - * If you wish your version of this file to be governed by only the CDDL - * or only the GPL Version 2, indicate your decision by adding - * "[Contributor] elects to include this software in this distribution - * under the [CDDL or GPL Version 2] license." If you do not indicate a - * single choice of license, a recipient has the option to distribute - * your version of this file under either the CDDL, the GPL Version 2 or - * to extend the choice of license to its licensees as provided above. - * However, if you add GPL Version 2 code and therefore, elected the GPL - * Version 2 license, then the option applies only if the new code is - * made subject to such option by the copyright holder. - * - * Contributor(s): - * - * Portions Copyrighted 2008 Sun Microsystems, Inc. - */ - -package org.openide.filesystems; - -import java.awt.Component; -import java.awt.Dialog; -import javax.swing.UIManager; -import javax.swing.JRootPane; -import java.util.concurrent.atomic.AtomicReference; -import java.lang.reflect.InvocationTargetException; -import java.util.concurrent.CountDownLatch; -import java.awt.Container; -import java.awt.EventQueue; -import java.io.File; -import java.io.IOException; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; -import javax.swing.AbstractButton; -import javax.swing.JFileChooser; -import javax.swing.RootPaneContainer; -import javax.swing.UnsupportedLookAndFeelException; -import javax.swing.event.AncestorEvent; -import javax.swing.event.AncestorListener; -import javax.swing.filechooser.FileFilter; -import javax.swing.plaf.metal.MetalLookAndFeel; -import org.netbeans.junit.NbTestCase; -import org.openide.util.RequestProcessor; -import static org.junit.Assert.*; -import org.netbeans.junit.RandomlyFails; - -/** - * @author tim - */ -public class FileChooserBuilderTest extends NbTestCase { - - public FileChooserBuilderTest(String name) { - super(name); - } - - /** - * Test of setDirectoriesOnly method, of class FileChooserBuilder. - */ - public void testSetDirectoriesOnly() { - FileChooserBuilder instance = new FileChooserBuilder("x"); - boolean dirsOnly = instance.createFileChooser().getFileSelectionMode() == JFileChooser.DIRECTORIES_ONLY; - assertFalse(dirsOnly); - instance.setDirectoriesOnly(true); - dirsOnly = instance.createFileChooser().getFileSelectionMode() == JFileChooser.DIRECTORIES_ONLY; - assertTrue(dirsOnly); - } - - /** - * Test of setFilesOnly method, of class FileChooserBuilder. - */ - public void testSetFilesOnly() { - FileChooserBuilder instance = new FileChooserBuilder("y"); - boolean filesOnly = instance.createFileChooser().getFileSelectionMode() == JFileChooser.FILES_ONLY; - assertFalse(filesOnly); - instance.setFilesOnly(true); - filesOnly = instance.createFileChooser().getFileSelectionMode() == JFileChooser.FILES_ONLY; - assertTrue(filesOnly); - } - - /** - * Test of setTitle method, of class FileChooserBuilder. - */ - public void testSetTitle() { - FileChooserBuilder instance = new FileChooserBuilder("a"); - assertNull(instance.createFileChooser().getDialogTitle()); - instance.setTitle("foo"); - assertEquals("foo", instance.createFileChooser().getDialogTitle()); - } - - /** - * Test of setApproveText method, of class FileChooserBuilder. - */ - public void testSetApproveText() { - FileChooserBuilder instance = new FileChooserBuilder("b"); - assertNull(instance.createFileChooser().getDialogTitle()); - instance.setApproveText("bar"); - assertEquals("bar", instance.createFileChooser().getApproveButtonText()); - } - - /** - * Test of setFileFilter method, of class FileChooserBuilder. - */ - public void testSetFileFilter() { - FileFilter filter = new FileFilter() { - - @Override - public boolean accept(File f) { - return true; - } - - @Override - public String getDescription() { - return "X"; - } - }; - FileChooserBuilder instance = new FileChooserBuilder("c"); - instance.setFileFilter(filter); - assertEquals(filter, instance.createFileChooser().getFileFilter()); - } - - /** - * Test of setDefaultWorkingDirectory method, of class FileChooserBuilder. - */ - public void testSetDefaultWorkingDirectory() throws IOException { - FileChooserBuilder instance = new FileChooserBuilder("d"); - File dir = getWorkDir(); - assertTrue("tmpdir is not sane", dir.exists() && dir.isDirectory()); - instance.setDefaultWorkingDirectory(dir); - assertEquals(dir, instance.createFileChooser().getCurrentDirectory()); - } - - /** - * Test of setFileHiding method, of class FileChooserBuilder. - */ - public void testSetFileHiding() { - FileChooserBuilder instance = new FileChooserBuilder("e"); - assertFalse(instance.createFileChooser().isFileHidingEnabled()); - instance.setFileHiding(true); - assertTrue(instance.createFileChooser().isFileHidingEnabled()); - } - - /** - * Test of setControlButtonsAreShown method, of class FileChooserBuilder. - */ - public void testSetControlButtonsAreShown() { - FileChooserBuilder instance = new FileChooserBuilder("f"); - assertTrue(instance.createFileChooser().getControlButtonsAreShown()); - instance.setControlButtonsAreShown(false); - assertFalse(instance.createFileChooser().getControlButtonsAreShown()); - } - - /** - * Test of setAccessibleDescription method, of class FileChooserBuilder. - */ - public void testSetAccessibleDescription() { - FileChooserBuilder instance = new FileChooserBuilder("g"); - String desc = "desc"; - instance.setAccessibleDescription(desc); - assertEquals(desc, instance.createFileChooser().getAccessibleContext().getAccessibleDescription()); - } - - /** - * Test of createFileChooser method, of class FileChooserBuilder. - */ - public void testCreateFileChooser() { - FileChooserBuilder instance = new FileChooserBuilder("h"); - assertNotNull(instance.createFileChooser()); - } - - public void testSetSelectionApprover() throws Exception { - FileChooserBuilder instance = new FileChooserBuilder("i"); - File tmp = new File(System.getProperty("java.io.tmpdir")); - assertTrue ("Environment is insane", tmp.exists() && tmp.isDirectory()); - File sel = new File("tmp" + System.currentTimeMillis()); - if (!sel.exists()) { - assertTrue (sel.createNewFile()); - } - instance.setDefaultWorkingDirectory(tmp); - SA sa = new SA(); - instance.setSelectionApprover(sa); - JFileChooser ch = instance.createFileChooser(); - ch.setSelectedFile(sel); - ch.approveSelection(); - sa.assertApproveInvoked(sel); - } - - public void testAddFileFilter() { - FileChooserBuilder instance = new FileChooserBuilder("j"); - FF one = new FF ("a"); - FF two = new FF ("b"); - instance.addFileFilter(one); - instance.addFileFilter(two); - JFileChooser ch = instance.createFileChooser(); - Set ff = new HashSet(Arrays.asList(one, two)); - Set actual = new HashSet(Arrays.asList(ch.getChoosableFileFilters())); - assertTrue (actual.containsAll(ff)); - //actual should also contain JFileChooser.getAcceptAllFileFilter() - assertEquals (ff.size() + 1, actual.size()); - } - - public void testSetAcceptAllFileFilterUsed() { - FileChooserBuilder instance = new FileChooserBuilder("k"); - assertTrue(instance.createFileChooser().isAcceptAllFileFilterUsed()); - instance.setAcceptAllFileFilterUsed(false); - assertFalse(instance.createFileChooser().isAcceptAllFileFilterUsed()); - } - - private static final class FF extends FileFilter { - private String x; - FF(String x) { - this.x = x; - } - - @Override - public boolean accept(File f) { - return f.getName().endsWith(x); - } - - @Override - public String getDescription() { - return x; - } - - } - - private static final class SA implements FileChooserBuilder.SelectionApprover { - private File[] selection; - @Override - public boolean approve(File[] selection) { - this.selection = selection; - return true; - } - - void assertApproveInvoked(File selected) { - assertNotNull ("approve method called", selection); - assertEquals("One selected file", 1, selection.length); - assertEquals("It is the one", selected, selection[0]); - } - } - - private static AbstractButton findDefaultButton(Container c, String txt) { - if (c instanceof RootPaneContainer) { - JRootPane root = ((RootPaneContainer) c).getRootPane(); - if (root == null) { - return null; - } - AbstractButton btn = root.getDefaultButton(); - if (btn == null) { - //Metal L&F does not set default button for JFileChooser - Container parent = c; - while (parent.getParent() != null && !(parent instanceof Dialog)) { - parent = parent.getParent(); - } - if (parent instanceof Dialog) { - return findFileChooserAcceptButton ((Dialog) parent, txt); - } - } else { - return btn; - } - } - return null; - } - - private static AbstractButton findFileChooserAcceptButton(Dialog dlg, String txt) { - for (Component c : dlg.getComponents()) { - if (c instanceof Container) { - AbstractButton result = scanForButton((Container) c, txt); - if (result != null) { - return result; - } - } - } - return null; - } - - private static AbstractButton scanForButton(Container container, String txt) { - assertNotNull (container); - assertNotNull (txt); - if (container instanceof AbstractButton) { - if (txt.equals(((AbstractButton) container).getText())) { - return ((AbstractButton) container); - } - } else { - for (Component c : container.getComponents()) { - if (c instanceof Container) { - AbstractButton b = scanForButton ((Container) c, txt); - if (b != null) { - return b; - } - } - } - } - return null; - } - - @RandomlyFails // NB-Core-Build #8038: Button is visible - public void testForceUseOfDefaultWorkingDirectory() throws InterruptedException, IOException, InvocationTargetException, UnsupportedLookAndFeelException { - UIManager.setLookAndFeel(new MetalLookAndFeel()); - FileChooserBuilder instance = new FileChooserBuilder("i").setApproveText("__OK"); - instance.setDirectoriesOnly(true); - final File toDir = getWorkDir(); - final File selDir = new File(toDir, "sel" + System.currentTimeMillis()); - if (!selDir.exists()) { - assertTrue(selDir.mkdirs()); - } - - final JFileChooser ch = instance.createFileChooser(); - assertEquals ("__OK", ch.getApproveButtonText()); - final CountDownLatch showLatch = new CountDownLatch(1); - ch.addAncestorListener (new AncestorListener() { - - @Override - public void ancestorAdded(AncestorEvent event) { - if (ch.isShowing()) { - ch.removeAncestorListener(this); - showLatch.countDown(); - } - } - - @Override - public void ancestorRemoved(AncestorEvent event) { - - } - - @Override - public void ancestorMoved(AncestorEvent event) { - - } - - }); - - final AtomicReference chooserRes = new AtomicReference(); - RequestProcessor.Task task = RequestProcessor.getDefault().post(new Runnable() { - - @Override - public void run() { - Object r = ch.showOpenDialog(null); - chooserRes.set(r); - } - - }); - - - showLatch.await(); - EventQueue.invokeAndWait (new Runnable() { - @Override - public void run() { - ch.setCurrentDirectory(toDir); - } - }); - EventQueue.invokeAndWait (new Runnable() { - @Override - public void run() { - ch.setSelectedFile (selDir); - } - }); - assertTrue ("Button is visible: " + ch, ch.isShowing()); - final AtomicReference btn = new AtomicReference(); - EventQueue.invokeAndWait(new Runnable() { - - @Override - public void run() { - AbstractButton defButton = findDefaultButton(ch.getTopLevelAncestor(), ch.getApproveButtonText()); - btn.set(defButton); - } - - }); - assertNotNull("have a button", btn.get()); - assertTrue(btn.get().isEnabled()); - EventQueue.invokeAndWait(new Runnable() { - @Override - public void run() { - AbstractButton defButton = btn.get(); - defButton.doClick(); - } - }); - - task.waitFinished(); - assertEquals(JFileChooser.APPROVE_OPTION, chooserRes.get()); - - assertEquals(toDir, ch.getCurrentDirectory()); - - instance = new FileChooserBuilder("i"); - assertEquals("Directory not retained", toDir, instance.createFileChooser().getCurrentDirectory()); - - File userHome = new File(System.getProperty("user.home")); - assertTrue("Environment not sane", userHome.exists() && userHome.isDirectory()); - instance.forceUseOfDefaultWorkingDirectory(true).setDefaultWorkingDirectory(userHome); - - assertEquals(userHome, instance.createFileChooser().getCurrentDirectory()); - } -} diff --git a/openide.filesystems/test/unit/src/org/openide/filesystems/FileObjectTestHid.java b/openide.filesystems/test/unit/src/org/openide/filesystems/FileObjectTestHid.java --- a/openide.filesystems/test/unit/src/org/openide/filesystems/FileObjectTestHid.java +++ b/openide.filesystems/test/unit/src/org/openide/filesystems/FileObjectTestHid.java @@ -1101,8 +1101,8 @@ public void testGetPath3() throws IOException{ /** There is no possible to create filenames ending in dots on Win platforms*/ - if ((org.openide.util.Utilities.isWindows () || - (org.openide.util.Utilities.getOperatingSystem () == org.openide.util.Utilities.OS_OS2))) { + if ((org.openide.util.BaseUtilities.isWindows () || + (org.openide.util.BaseUtilities.getOperatingSystem () == BaseUtilities.OS_OS2))) { return; } checkSetUp(); diff --git a/openide.filesystems/test/unit/src/org/openide/filesystems/FileUtilTest.java b/openide.filesystems/test/unit/src/org/openide/filesystems/FileUtilTest.java --- a/openide.filesystems/test/unit/src/org/openide/filesystems/FileUtilTest.java +++ b/openide.filesystems/test/unit/src/org/openide/filesystems/FileUtilTest.java @@ -68,7 +68,7 @@ import org.openide.util.Exceptions; import org.openide.util.Lookup; import org.openide.util.RequestProcessor; -import org.openide.util.Utilities; +import org.openide.util.BaseUtilities; import org.openide.util.test.MockLookup; /** @@ -113,7 +113,7 @@ } public void testLowerAndCapitalNormalization() throws IOException { - if (!Utilities.isWindows()) { + if (!BaseUtilities.isWindows()) { return; } clearWorkDir(); @@ -148,7 +148,7 @@ } public void testToFileObjectSlash() throws Exception { // #98388 - if (!Utilities.isUnix()) { + if (!BaseUtilities.isUnix()) { return; } File root = new File("/"); @@ -225,12 +225,12 @@ } private void assertCorrectURL(String filename, String expectedURLPrefix, String expectedURLSuffix) throws Exception { File d = getWorkDir(); - assertEquals(expectedURLSuffix == null ? null : new URL(expectedURLPrefix + Utilities.toURI(d) + expectedURLSuffix), + assertEquals(expectedURLSuffix == null ? null : new URL(expectedURLPrefix + BaseUtilities.toURI(d) + expectedURLSuffix), FileUtil.urlForArchiveOrDir(new File(d, filename))); } private void assertCorrectFile(String expectedFilename, String urlPrefix, String urlSuffix) throws Exception { assertEquals(expectedFilename == null ? null : new File(getWorkDir(), expectedFilename), - FileUtil.archiveOrDirForURL(new URL(urlPrefix + Utilities.toURI(getWorkDir()) + urlSuffix))); + FileUtil.archiveOrDirForURL(new URL(urlPrefix + BaseUtilities.toURI(getWorkDir()) + urlSuffix))); } /** Tests translation from jar resource url to jar archive url. */ @@ -299,7 +299,7 @@ }; log.addHandler(handler); try { - final boolean result = FileUtil.isArchiveFile(Utilities.toURI(testFile).toURL()); + final boolean result = FileUtil.isArchiveFile(BaseUtilities.toURI(testFile).toURL()); assertTrue("The test.jar should be archive.",result); //NOI18N } finally { log.removeHandler(handler); @@ -319,7 +319,7 @@ } public void testNormalizeNonExistingButNotAccessibleRootOnWindows() throws IOException { - if (!Utilities.isWindows()) { + if (!BaseUtilities.isWindows()) { return; } for (File r : File.listRoots()) { @@ -362,7 +362,7 @@ private Map createNormalizedPaths() throws IOException { // pairs of path before and after normalization Map paths = new HashMap(); - if (Utilities.isWindows()) { + if (BaseUtilities.isWindows()) { paths.put("A:\\", "A:\\"); paths.put("A:\\dummy", "A:\\dummy"); paths.put("a:\\", "A:\\"); @@ -403,7 +403,7 @@ } public void testNormalizePathChangeCase() throws Exception { - if (!Utilities.isWindows()) { + if (!BaseUtilities.isWindows()) { return; } clearWorkDir(); diff --git a/openide.filesystems/test/unit/src/org/openide/filesystems/FileUtilTestHidden.java b/openide.filesystems/test/unit/src/org/openide/filesystems/FileUtilTestHidden.java --- a/openide.filesystems/test/unit/src/org/openide/filesystems/FileUtilTestHidden.java +++ b/openide.filesystems/test/unit/src/org/openide/filesystems/FileUtilTestHidden.java @@ -48,7 +48,7 @@ import java.net.URL; import java.util.List; import java.util.ArrayList; -import org.openide.util.Utilities; +import org.openide.util.BaseUtilities; public class FileUtilTestHidden extends TestBaseHid { @@ -144,7 +144,7 @@ file2 = FileUtil.normalizeFile(file); assertEquals(file2, file); - if (Utilities.isUnix()) { + if (BaseUtilities.isUnix()) { assertEquals(new File("/"), FileUtil.normalizeFile(new File("/.."))); assertEquals(new File("/"), FileUtil.normalizeFile(new File("/../."))); assertEquals(new File("/tmp"), FileUtil.normalizeFile(new File("/../../tmp"))); @@ -152,7 +152,7 @@ } public void testNormalizeFile2() throws Exception { - if (!Utilities.isWindows()) { + if (!BaseUtilities.isWindows()) { return; } File rootFile = FileUtil.toFile(root); @@ -182,7 +182,7 @@ } public void testIsArchiveFile() throws Exception { - final String base = Utilities.toURI(getWorkDir()).toURL().toExternalForm(); + final String base = BaseUtilities.toURI(getWorkDir()).toURL().toExternalForm(); URL url = new URL(base + "test.jar"); //NOI18N assertTrue("test.jar has to be an archive", FileUtil.isArchiveFile(url)); //NOI18N url = new URL(base + ".hidden.jar"); //NOI18N diff --git a/openide.filesystems/test/unit/src/org/openide/filesystems/MIMESupport68318Test.java b/openide.filesystems/test/unit/src/org/openide/filesystems/MIMESupport68318Test.java --- a/openide.filesystems/test/unit/src/org/openide/filesystems/MIMESupport68318Test.java +++ b/openide.filesystems/test/unit/src/org/openide/filesystems/MIMESupport68318Test.java @@ -44,7 +44,6 @@ package org.openide.filesystems; import java.io.IOException; import org.netbeans.junit.NbTestCase; -import org.openide.ErrorManager; import org.openide.util.Lookup; import org.openide.util.lookup.InstanceContent; @@ -62,7 +61,7 @@ } protected void setUp() throws Exception { - ErrorManager.getDefault().log("Just initialize the ErrorManager"); +// ErrorManager.getDefault().log("Just initialize the ErrorManager"); } public void testQueryMIMEFromInsideTheLookup() throws IOException { diff --git a/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileObjectTestHid.java b/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileObjectTestHid.java --- a/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileObjectTestHid.java +++ b/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileObjectTestHid.java @@ -49,7 +49,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.openide.util.Utilities; +import org.openide.util.BaseUtilities; public class MultiFileObjectTestHid extends TestBaseHid { private static String[] resources = new String [] { @@ -236,7 +236,7 @@ + " \n" + " \n" + ""); - XMLFileSystem xml = new XMLFileSystem(Utilities.toURI(f).toURL()); + XMLFileSystem xml = new XMLFileSystem(BaseUtilities.toURI(f).toURL()); all.add(xml); mfs.setDelegates(all.toArray(new FileSystem[0])); diff --git a/openide.filesystems/test/unit/src/org/openide/filesystems/TestUtilHid.java b/openide.filesystems/test/unit/src/org/openide/filesystems/TestUtilHid.java --- a/openide.filesystems/test/unit/src/org/openide/filesystems/TestUtilHid.java +++ b/openide.filesystems/test/unit/src/org/openide/filesystems/TestUtilHid.java @@ -58,7 +58,7 @@ import java.util.Iterator; import java.util.Map; import java.util.StringTokenizer; -import org.openide.util.Utilities; +import org.openide.util.BaseUtilities; /** * @author rm111737 @@ -178,7 +178,7 @@ XMLFileSystem xfs = new XMLFileSystem (); try { - xfs.setXmlUrl(Utilities.toURI(xmlFile).toURL()); + xfs.setXmlUrl(BaseUtilities.toURI(xmlFile).toURL()); } catch (Exception ex) {} return xfs; @@ -189,7 +189,7 @@ XMLFileSystem xfs = new XMLFileSystem (); try { - xfs.setXmlUrl(Utilities.toURI(xmlFile).toURL()); + xfs.setXmlUrl(BaseUtilities.toURI(xmlFile).toURL()); } catch (Exception ex) {} return xfs; diff --git a/openide.filesystems/test/unit/src/org/openide/filesystems/URLMapper50852Test.java b/openide.filesystems/test/unit/src/org/openide/filesystems/URLMapper50852Test.java --- a/openide.filesystems/test/unit/src/org/openide/filesystems/URLMapper50852Test.java +++ b/openide.filesystems/test/unit/src/org/openide/filesystems/URLMapper50852Test.java @@ -46,11 +46,10 @@ import org.netbeans.junit.*; -import org.openide.util.Lookup; import java.net.URL; import java.io.File; -import org.openide.util.Utilities; +import org.openide.util.BaseUtilities; /** * Simulates issue 50852. @@ -77,7 +76,7 @@ */ protected void setUp() throws Exception { File workdir = getWorkDir(); - testURL = Utilities.toURI(workdir).toURL(); + testURL = BaseUtilities.toURI(workdir).toURL(); System.setProperty("org.openide.util.Lookup", "org.openide.filesystems.URLMapper50852Test$Lkp"); MAPPER_INSTANCE = new MyURLMapper (); Lkp lkp = (Lkp)org.openide.util.Lookup.getDefault(); diff --git a/openide.filesystems/test/unit/src/org/openide/filesystems/URLMapperTest.java b/openide.filesystems/test/unit/src/org/openide/filesystems/URLMapperTest.java --- a/openide.filesystems/test/unit/src/org/openide/filesystems/URLMapperTest.java +++ b/openide.filesystems/test/unit/src/org/openide/filesystems/URLMapperTest.java @@ -51,13 +51,12 @@ import java.io.OutputStream; import java.net.URL; import java.util.Arrays; -import java.util.Collections; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.zip.CRC32; import java.util.zip.ZipEntry; import org.netbeans.junit.NbTestCase; -import org.openide.util.Utilities; +import org.openide.util.BaseUtilities; /** * Test functionality of URLMapper. @@ -77,7 +76,7 @@ lfs.setRootDirectory(getWorkDir()); Repository.getDefault().addFileSystem(lfs); - URL uPlus = Utilities.toURI(plus).toURL(); + URL uPlus = BaseUtilities.toURI(plus).toURL(); FileObject fo = URLMapper.findFileObject(uPlus); assertNotNull("File object found", fo); assertEquals("plus+plus", fo.getNameExt()); @@ -117,7 +116,7 @@ FileObject rootFO = jfs.getRoot(); FileObject textFO = jfs.findResource(textPath); assertNotNull("JAR contains a/b.txt", textFO); - String rootS = "jar:" + Utilities.toURI(jar) + "!/"; + String rootS = "jar:" + BaseUtilities.toURI(jar) + "!/"; URL rootU = new URL(rootS); URL textU = new URL(rootS + textPath); assertEquals("correct FO -> URL for root", rootU, URLMapper.findURL(rootFO, URLMapper.EXTERNAL)); diff --git a/openide.filesystems/test/unit/src/org/openide/filesystems/XMLFileSystemTestHid.java b/openide.filesystems/test/unit/src/org/openide/filesystems/XMLFileSystemTestHid.java --- a/openide.filesystems/test/unit/src/org/openide/filesystems/XMLFileSystemTestHid.java +++ b/openide.filesystems/test/unit/src/org/openide/filesystems/XMLFileSystemTestHid.java @@ -62,7 +62,7 @@ import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import org.openide.util.Enumerations; -import org.openide.util.Utilities; +import org.openide.util.BaseUtilities; public class XMLFileSystemTestHid extends TestBaseHid { /** Factory for all filesystems that want to use TCK in this class. @@ -107,7 +107,7 @@ resources = new String[] {"a/b/c","a/b1/c"}; - if (!FileSystemFactoryHid.switchXMLSystem(xfs, this, Utilities.toURI(createXMLLayer()).toURL())) { + if (!FileSystemFactoryHid.switchXMLSystem(xfs, this, BaseUtilities.toURI(createXMLLayer()).toURL())) { // OK, unsupported return; } @@ -120,7 +120,7 @@ @Override protected void setUp() throws Exception { File f = createXMLLayer(); - xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL()); + xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL()); this.testedFS = xfs; this.allTestedFS = new FileSystem[] { xfs }; super.setUp(); @@ -152,13 +152,13 @@ - xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL()); + xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL()); FileObject fo = xfs.findResource ("TestModule/sample.txt"); assertEquals ("Four bytes there", 4, fo.getSize ()); registerDefaultListener (fo); - if (!FileSystemFactoryHid.switchXMLSystem(xfs, this, Utilities.toURI(f2).toURL())) { + if (!FileSystemFactoryHid.switchXMLSystem(xfs, this, BaseUtilities.toURI(f2).toURL())) { // OK, unsupported return; } @@ -191,13 +191,13 @@ - xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL()); + xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL()); FileObject fo = xfs.findResource ("TestModule/sample.txt"); assertEquals ("Four bytes there", 4, fo.getSize ()); registerDefaultListener (fo); - if (!FileSystemFactoryHid.switchXMLSystem(xfs, this, Utilities.toURI(f2).toURL())) { + if (!FileSystemFactoryHid.switchXMLSystem(xfs, this, BaseUtilities.toURI(f2).toURL())) { // OK, unsupported return; } @@ -231,13 +231,13 @@ - xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL()); + xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL()); FileObject fo = xfs.findResource ("TestModule/sample.txt"); assertEquals("Old value is in the attribute", "old", fo.getAttribute("value")); registerDefaultListener (fo); - if (!FileSystemFactoryHid.switchXMLSystem(xfs, this, Utilities.toURI(f2).toURL())) { + if (!FileSystemFactoryHid.switchXMLSystem(xfs, this, BaseUtilities.toURI(f2).toURL())) { // OK, unsupported return; } @@ -265,13 +265,13 @@ - xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL()); + xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL()); FileObject fo = xfs.findResource("TestModule/sample.txt"); assertEquals("Four bytes there", 4, fo.getSize()); registerDefaultListener(fo); - if (!FileSystemFactoryHid.switchXMLSystem(xfs, this, Utilities.toURI(f2).toURL())) { + if (!FileSystemFactoryHid.switchXMLSystem(xfs, this, BaseUtilities.toURI(f2).toURL())) { // OK, unsupported return; } @@ -301,7 +301,7 @@ f.lastModified() < f2.lastModified() ); } - xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL()); + xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL()); FileObject fo = xfs.findResource ("TestModule/sample.txt"); assertNotNull(fo); assertEquals(fo.lastModified().getTime(), f.lastModified()); @@ -326,7 +326,7 @@ "\n" ); - xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL()); + xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL()); FileObject fo = xfs.findResource ("TestModule/sample.txt"); assertNotNull(fo); @@ -350,7 +350,7 @@ + " \n" + ""); - xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL()); + xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL()); final LocalFileSystem lfs = new LocalFileSystem(); lfs.setRootDirectory(getWorkDir()); MultiFileSystem mfs = new MultiFileSystem(lfs, xfs); @@ -377,7 +377,7 @@ ); Count.cnt = 0; - xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL()); + xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL()); /** the following is a fake implementation of filesystem that * allows us to prevent calls to fileObject.getAttributes() */ @@ -500,7 +500,7 @@ "\n" ); - xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL()); + xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL()); FileObject fo = xfs.findResource ("TestModule/sample.txt"); assertNotNull(fo); @@ -525,7 +525,7 @@ "\n" ); - xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL()); + xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL()); FileObject fo = xfs.findResource ("TestModule/sample.txt"); assertNotNull(fo); @@ -550,7 +550,7 @@ "\n" ); - xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL()); + xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL()); FileObject fo = xfs.findResource ("TestModule/sample.txt"); assertNotNull(fo); @@ -580,11 +580,11 @@ "\n" ); - xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL()); + xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL()); FileObject fo = xfs.findResource ("TestModule/sample.txt"); assertNotNull(fo); - XMLFileSystem realXMLFS = new XMLFileSystem(Utilities.toURI(f).toURL()); + XMLFileSystem realXMLFS = new XMLFileSystem(BaseUtilities.toURI(f).toURL()); FileObject realfo = realXMLFS.findResource("TestModule/sample.txt"); assertNotNull(realfo); @@ -621,7 +621,7 @@ "\n" ); - xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL()); + xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL()); FileObject fo = xfs.findResource ("TestModule/sample.txt"); FileObject snd = xfs.findResource ("TestModule/snd.txt"); assertNotNull(fo); @@ -722,7 +722,7 @@ "\n" ); - xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL()); + xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL()); FileObject fo = xfs.findResource ("TestModule/sample.txt"); assertNotNull(fo); @@ -771,8 +771,8 @@ ) ); - URL url1 = new URL("jar:" + Utilities.toURI(jar1) + "!/layer.xml"); - URL url2 = new URL("jar:" + Utilities.toURI(jar2) + "!/layer.xml"); + URL url1 = new URL("jar:" + BaseUtilities.toURI(jar1) + "!/layer.xml"); + URL url2 = new URL("jar:" + BaseUtilities.toURI(jar2) + "!/layer.xml"); FileSystem xfs1 = FileSystemFactoryHid.createXMLSystem(getName(), this, url1); FileObject fo1 = xfs1.findResource("dir/file"); @@ -902,7 +902,7 @@ File f2 = changeOfAnAttributeInLayerIsFiredgenerateLayer("Folder", "java.awt.Button"); File f3 = changeOfAnAttributeInLayerIsFiredgenerateLayer("NoChange", "nochange"); - fs.setXmlUrls (new URL[] { Utilities.toURI(f1).toURL(), Utilities.toURI(f3).toURL() } ); + fs.setXmlUrls (new URL[] { BaseUtilities.toURI(f1).toURL(), BaseUtilities.toURI(f3).toURL() } ); FileObject file = fs.findResource("Folder/empty.xml"); assertNotNull("File found in layer", file); @@ -918,7 +918,7 @@ assertAttr("The first value is list", file, "value", "java.awt.List"); assertAttr("Imutable value is nochange", nochange, "value", "nochange"); - fs.setXmlUrls (new URL[] { Utilities.toURI(f2).toURL(), Utilities.toURI(f3).toURL() } ); + fs.setXmlUrls (new URL[] { BaseUtilities.toURI(f2).toURL(), BaseUtilities.toURI(f3).toURL() } ); String v2 = (String) file.getAttribute("value"); assertEquals("The second value is button", "java.awt.Button", v2); @@ -953,7 +953,7 @@ LocalFileSystem target = new LocalFileSystem(); target.setRootDirectory(r); - FileSystem source = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL()); + FileSystem source = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL()); FileObject template = source.findResource("Templates/Other/special"); assertNotNull("template found", template); FileObject foTested = target.getRoot().createData("copiedTemplate"); @@ -1078,7 +1078,7 @@ w.close(); } - xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f1).toURL(), Utilities.toURI(f2).toURL()); + xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f1).toURL(), BaseUtilities.toURI(f2).toURL()); FileObject just1 = xfs.findResource("just1/empty.xml"); @@ -1090,19 +1090,19 @@ String layers2 = layers(just2); String layersB = layers(both); - if (!layersR.contains(Utilities.toURI(f1).toString())) { - fail("Missing " + Utilities.toURI(f1).toString() + "\ninside: " + layersR); + if (!layersR.contains(BaseUtilities.toURI(f1).toString())) { + fail("Missing " + BaseUtilities.toURI(f1).toString() + "\ninside: " + layersR); } - if (!layersR.contains(Utilities.toURI(f2).toString())) { - fail("Missing " + Utilities.toURI(f2).toString() + "\ninside: " + layersR); + if (!layersR.contains(BaseUtilities.toURI(f2).toString())) { + fail("Missing " + BaseUtilities.toURI(f2).toString() + "\ninside: " + layersR); } - assertEquals(Utilities.toURI(f1).toString(), layers1); - assertEquals(Utilities.toURI(f2).toString(), layers2); - if (!layersB.contains(Utilities.toURI(f1).toString())) { + assertEquals(BaseUtilities.toURI(f1).toString(), layers1); + assertEquals(BaseUtilities.toURI(f2).toString(), layers2); + if (!layersB.contains(BaseUtilities.toURI(f1).toString())) { fail("Missing " + f1 + "\ninside: " + layersB); } - if (!layersB.contains(Utilities.toURI(f2).toString())) { + if (!layersB.contains(BaseUtilities.toURI(f2).toString())) { fail("Missing " + f2 + "\ninside: " + layersB); } } @@ -1120,7 +1120,7 @@ + ""); w.close(); - xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(layer).toURL()); + xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(layer).toURL()); FileObject fo = xfs.findResource("f/empty.xml"); assertNotNull("File found", fo); @@ -1143,25 +1143,25 @@ File f1 = writeFile("layer1.xml", "\n" + "\n" + - "" + + "" + "\n" + "\n" ); File f2 = writeFile("layer2.xml", "\n" + "\n" + - "" + + "" + " " + "\n" + "\n" + "\n" ); - xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f2).toURL(), Utilities.toURI(f1).toURL()); + xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f2).toURL(), BaseUtilities.toURI(f1).toURL()); FileObject fo = xfs.findResource("d/f"); assertNotNull(fo); assertEquals(6, fo.getSize()); - xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f1).toURL(), Utilities.toURI(f2).toURL()); + xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f1).toURL(), BaseUtilities.toURI(f2).toURL()); fo = xfs.findResource("d/f"); assertNotNull(fo); assertEquals(6, fo.getSize()); diff --git a/openide.filesystems/test/unit/src/org/openide/filesystems/annotations/LayerBuilderTest.java b/openide.filesystems/test/unit/src/org/openide/filesystems/annotations/LayerBuilderTest.java --- a/openide.filesystems/test/unit/src/org/openide/filesystems/annotations/LayerBuilderTest.java +++ b/openide.filesystems/test/unit/src/org/openide/filesystems/annotations/LayerBuilderTest.java @@ -67,7 +67,7 @@ import org.netbeans.junit.NbTestCase; import org.openide.filesystems.FileObject; import org.openide.filesystems.XMLFileSystem; -import org.openide.util.Utilities; +import org.openide.util.BaseUtilities; import org.openide.util.lookup.ServiceProvider; import org.openide.util.test.AnnotationProcessorTestUtils; import org.openide.util.test.TestFileUtils; @@ -304,12 +304,12 @@ File j = TestFileUtils.writeZipFile(new File(getWorkDir(), "cp.jar"), "other/x1:x1"); TestFileUtils.writeFile(new File(src, "p/resources/x2"), "x2"); ByteArrayOutputStream err = new ByteArrayOutputStream(); - boolean status = AnnotationProcessorTestUtils.runJavac(src, null, dest, new File[] {j, Utilities.toFile(LayerBuilderTest.class.getProtectionDomain().getCodeSource().getLocation().toURI())}, err); + boolean status = AnnotationProcessorTestUtils.runJavac(src, null, dest, new File[] {j, BaseUtilities.toFile(LayerBuilderTest.class.getProtectionDomain().getCodeSource().getLocation().toURI())}, err); String msgs = err.toString(); assertTrue(msgs, status); assertTrue(msgs, msgs.contains("r1=x1") ^ AnnotationProcessorTestUtils.searchClasspathBroken()); assertTrue(msgs, msgs.contains("r2=x2")); - FileObject f = new XMLFileSystem(Utilities.toURI(new File(dest, "META-INF/generated-layer.xml")).toURL()).findResource("f"); + FileObject f = new XMLFileSystem(BaseUtilities.toURI(new File(dest, "META-INF/generated-layer.xml")).toURL()).findResource("f"); assertNotNull(f); assertEquals("other/x1", f.getAttribute("r1")); assertEquals("p/resources/x2", f.getAttribute("r2")); @@ -320,14 +320,14 @@ File j = TestFileUtils.writeZipFile(new File(getWorkDir(), "cp.jar"), "other/x1:x1"); TestFileUtils.writeFile(new File(src, "p/resources/x2"), "x2"); ByteArrayOutputStream err = new ByteArrayOutputStream(); - boolean status = AnnotationProcessorTestUtils.runJavac(src, null, dest, new File[] {j, Utilities.toFile(LayerBuilderTest.class.getProtectionDomain().getCodeSource().getLocation().toURI())}, err); + boolean status = AnnotationProcessorTestUtils.runJavac(src, null, dest, new File[] {j, BaseUtilities.toFile(LayerBuilderTest.class.getProtectionDomain().getCodeSource().getLocation().toURI())}, err); String msgs = err.toString(); assertFalse(msgs, status); assertTrue(msgs, msgs.contains("resourcez")); assertTrue(msgs, msgs.contains("r1=x1") ^ AnnotationProcessorTestUtils.searchClasspathBroken()); AnnotationProcessorTestUtils.makeSource(src, "p.C", "@" + V.class.getCanonicalName() + "(r1=\"othr/x1\", r2=\"resources/x2\") public class C {}"); err = new ByteArrayOutputStream(); - status = AnnotationProcessorTestUtils.runJavac(src, null, dest, new File[] {j, Utilities.toFile(LayerBuilderTest.class.getProtectionDomain().getCodeSource().getLocation().toURI())}, err); + status = AnnotationProcessorTestUtils.runJavac(src, null, dest, new File[] {j, BaseUtilities.toFile(LayerBuilderTest.class.getProtectionDomain().getCodeSource().getLocation().toURI())}, err); msgs = err.toString(); assertFalse(msgs, status ^ AnnotationProcessorTestUtils.searchClasspathBroken()); assertTrue(msgs, msgs.contains("othr") ^ AnnotationProcessorTestUtils.searchClasspathBroken()); diff --git a/openide.util.base/src/org/netbeans/modules/openide/util/ProxyURLStreamHandlerFactory.java b/openide.util.base/src/org/netbeans/modules/openide/util/ProxyURLStreamHandlerFactory.java new file mode 100644 --- /dev/null +++ b/openide.util.base/src/org/netbeans/modules/openide/util/ProxyURLStreamHandlerFactory.java @@ -0,0 +1,91 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2010 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2009 Sun Microsystems, Inc. + */ + +package org.netbeans.modules.openide.util; + +import java.net.URLStreamHandler; +import java.net.URLStreamHandlerFactory; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import org.openide.util.Lookup; +import org.openide.util.LookupEvent; +import org.openide.util.LookupListener; +import org.openide.util.URLStreamHandlerRegistration; +import org.openide.util.lookup.Lookups; +import org.openide.util.lookup.ServiceProvider; + +/** + * @see URLStreamHandlerRegistration + */ +@ServiceProvider(service=URLStreamHandlerFactory.class) +public final class ProxyURLStreamHandlerFactory implements URLStreamHandlerFactory { + /** prevents GC only */ + private final Map> results = new HashMap>(); + private final Map handlers = new HashMap(); + private static final Set STANDARD_PROTOCOLS = new HashSet(Arrays.asList("jar", "file", "http", "https", "resource")); // NOI18N + + public @Override synchronized URLStreamHandler createURLStreamHandler(final String protocol) { + if (STANDARD_PROTOCOLS.contains(protocol)) { + // Well-known handlers in JRE. Do not try to initialize lookup. + return null; + } + if (!results.containsKey(protocol)) { + final Lookup.Result result = Lookups.forPath("URLStreamHandler/" + protocol).lookupResult(URLStreamHandler.class); + LookupListener listener = new LookupListener() { + public @Override void resultChanged(LookupEvent ev) { + synchronized (ProxyURLStreamHandlerFactory.this) { + Collection instances = result.allInstances(); + handlers.put(protocol, instances.isEmpty() ? null : instances.iterator().next()); + } + } + }; + result.addLookupListener(listener); + listener.resultChanged(null); + results.put(protocol, result); + } + return handlers.get(protocol); + } +} diff --git a/openide.util.base/src/org/openide/util/URLStreamHandlerRegistration.java b/openide.util.base/src/org/openide/util/URLStreamHandlerRegistration.java new file mode 100644 --- /dev/null +++ b/openide.util.base/src/org/openide/util/URLStreamHandlerRegistration.java @@ -0,0 +1,83 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2010 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2009 Sun Microsystems, Inc. + */ + +package org.openide.util; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.net.URL; +import java.net.URLStreamHandler; +import java.net.URLStreamHandlerFactory; +import org.openide.util.lookup.NamedServiceDefinition; + +/** + * Replacement for {@link URLStreamHandlerFactory} within the NetBeans platform. + * (The JVM only permits one global factory to be set at a time, + * whereas various independent modules may wish to register handlers.) + * May be placed on a {@link URLStreamHandler} implementation to register it. + * Your handler will be loaded and used if and when a URL of a matching protocol is created. + *

      A {@link URLStreamHandlerFactory} which uses these registrations may be found in {@link Lookup#getDefault}. + * This factory is active whenever the module system is loaded. + * You may also wish to call {@link URL#setURLStreamHandlerFactory} + * from a unit test or otherwise without the module system active. + * @since org.openide.util 7.31 + */ +@NamedServiceDefinition(path="URLStreamHandler/@protocol()", serviceType=URLStreamHandler.class) +@Retention(RetentionPolicy.SOURCE) +@Target(ElementType.TYPE) +public @interface URLStreamHandlerRegistration { + + /** + * URL protocol(s) which are handled. + * {@link URLStreamHandler#openConnection} will be called with a matching {@link URL#getProtocol}. + */ + String[] protocol(); + + /** + * An optional position in which to register this handler relative to others. + * The lowest-numbered handler is used in favor of any others, including unnumbered handlers. + */ + int position() default Integer.MAX_VALUE; + +} diff --git a/openide.util.base/test/unit/src/org/openide/util/test/JarBuilder.java b/openide.util.base/test/unit/src/org/openide/util/test/JarBuilder.java new file mode 100644 --- /dev/null +++ b/openide.util.base/test/unit/src/org/openide/util/test/JarBuilder.java @@ -0,0 +1,126 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2011 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2011 Sun Microsystems, Inc. + */ + +package org.openide.util.test; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import org.netbeans.junit.NbTestCase; + +// XXX could add methods to add a JAR manifest, include text or binary resources, ... + +/** + * Builder for compiling some source files and packing the result into a JAR. + */ +public final class JarBuilder { + + private final File src, dest, jar; + private List classpath; + + /** + * @param workdir as in {@link NbTestCase#getWorkDir} + */ + public JarBuilder(File workdir) throws Exception { + jar = File.createTempFile("test", ".jar", workdir); + String n = jar.getName().replaceAll("^test|[.]jar$", ""); + src = new File(workdir, "src" + n); + dest = new File(workdir, "classes" + n); + } + + /** + * Optional classpath for compiling sources. + * If unspecified, use Java classpath of test.) + */ + public JarBuilder classpath(File... cp) { + if (classpath == null) { + classpath = new ArrayList(); + } + classpath.addAll(Arrays.asList(cp)); + return this; + } + + /** + * Adds a source file to compile. + * @see AnnotationProcessorTestUtils#makeSource + */ + public JarBuilder source(String clazz, String... content) throws Exception { + AnnotationProcessorTestUtils.makeSource(src, clazz, content); + return this; + } + + /** + * Compiles sources and creates resulting JAR. + * @return the created JAR file + */ + public File build() throws Exception { + if (!AnnotationProcessorTestUtils.runJavac(src, null, dest, classpath != null ? classpath.toArray(new File[0]) : null, null)) { + throw new Exception("compilation failed"); + } + Map data = new TreeMap(); + scan(data, dest, ""); + OutputStream os = new FileOutputStream(jar); + try { + TestFileUtils.writeZipFile(os, data); + } finally { + os.close(); + } + return jar; + } + + private static void scan(Map data, File d, String prefix) throws Exception { + for (File kid : d.listFiles()) { + String prefixName = prefix + kid.getName(); + if (kid.isDirectory()) { + scan(data, kid, prefixName + '/'); + } else { + data.put(prefixName, TestFileUtils.readFileBin(kid)); + } + } + } + +} diff --git a/openide.util.base/test/unit/src/org/openide/util/test/MockChangeListenerTest.java b/openide.util.base/test/unit/src/org/openide/util/test/MockChangeListenerTest.java new file mode 100644 --- /dev/null +++ b/openide.util.base/test/unit/src/org/openide/util/test/MockChangeListenerTest.java @@ -0,0 +1,145 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * Contributor(s): + * + * The Original Software is NetBeans. The Initial Developer of the Original + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun + * Microsystems, Inc. All Rights Reserved. + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + */ + +package org.openide.util.test; + +import junit.framework.AssertionFailedError; +import org.netbeans.junit.NbTestCase; +import org.netbeans.junit.RandomlyFails; +import org.openide.util.ChangeSupport; + +public class MockChangeListenerTest extends NbTestCase { + + public MockChangeListenerTest(String n) { + super(n); + } + + Object source; + ChangeSupport cs; + MockChangeListener l; + + @Override + protected void setUp() throws Exception { + super.setUp(); + source = new Object(); + cs = new ChangeSupport(source); + l = new MockChangeListener(); + cs.addChangeListener(l); + } + + public void testBasicUsage() throws Exception { + l.assertNoEvents(); + l.assertEventCount(0); + try { + l.assertEvent(); + assert false; + } catch (AssertionFailedError e) {} + try { + l.assertEventCount(1); + assert false; + } catch (AssertionFailedError e) {} + cs.fireChange(); + l.assertEvent(); + l.assertNoEvents(); + l.assertEventCount(0); + cs.fireChange(); + cs.fireChange(); + l.assertEventCount(2); + cs.fireChange(); + l.assertEvent(); + l.assertNoEvents(); + l.assertNoEvents(); + cs.fireChange(); + l.reset(); + l.assertNoEvents(); + cs.fireChange(); + cs.fireChange(); + assertEquals(2, l.allEvents().size()); + } + + public void testMessages() throws Exception { + try { + l.assertEvent(); + assert false; + } catch (AssertionFailedError e) {} + try { + l.msg("stuff").assertEvent(); + assert false; + } catch (AssertionFailedError e) { + assertTrue(e.getMessage().contains("stuff")); + } + try { + l.assertEvent(); + assert false; + } catch (AssertionFailedError e) { + assertFalse(String.valueOf(e.getMessage()).contains("stuff")); + } + } + + @RandomlyFails // NB-Core-Build #8154 + public void testExpect() throws Exception { + l.expectNoEvents(1000); + cs.fireChange(); + l.expectEvent(1000); + l.assertNoEvents(); + new Thread() { + @Override public void run() { + try { + Thread.sleep(2000); + } catch (InterruptedException x) { + assert false; + } + cs.fireChange(); + } + }.start(); + try { + l.expectEvent(1000); + assert false; + } catch (AssertionFailedError e) {} + l.expectEvent(2000); + l.assertNoEvents(); + l.expectNoEvents(1000); + } + +} diff --git a/openide.util.base/test/unit/src/org/openide/util/test/MockPropertyChangeListener.java b/openide.util.base/test/unit/src/org/openide/util/test/MockPropertyChangeListener.java new file mode 100644 --- /dev/null +++ b/openide.util.base/test/unit/src/org/openide/util/test/MockPropertyChangeListener.java @@ -0,0 +1,227 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * Contributor(s): + * + * The Original Software is NetBeans. The Initial Developer of the Original + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun + * Microsystems, Inc. All Rights Reserved. + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + */ + +package org.openide.util.test; + +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import static junit.framework.Assert.*; +import junit.framework.AssertionFailedError; + +/** + * A scriptable property change listener. + */ +public class MockPropertyChangeListener implements PropertyChangeListener { + + private final List events = new ArrayList(); + private final Set whitelist; + private final Set blacklist = new HashSet(); + private final Set ignored = new HashSet(); + private String msg; + + /** + * Makes a fresh listener. + * @param whiteListedPropertyNames an optional list of property names; if any others are received, an assertion will be thrown + */ + public MockPropertyChangeListener(String... whitelistedPropertyNames) { + whitelist = whitelistedPropertyNames.length > 0 ? new HashSet(Arrays.asList(whitelistedPropertyNames)) : null; + } + + /** + * Marks certain property names as being definitely not expected. + * If any are received henceforth, an assertion will be thrown. + */ + public synchronized void blacklist(String... blacklistedPropertyNames) { + assertNull("Meaningless to blacklist some properties while there is an active whitelist", whitelist); + blacklist.addAll(Arrays.asList(blacklistedPropertyNames)); + } + + /** + * Marks certain property names as being ignored. + * If any are received henceforth, no action will be taken. + */ + public synchronized void ignore(String... ignoredPropertyNames) { + ignored.addAll(Arrays.asList(ignoredPropertyNames)); + } + + public synchronized void propertyChange(PropertyChangeEvent ev) { + String propname = ev.getPropertyName(); + if (ignored.contains(propname)) { + return; + } + assertTrue("Property name " + propname + " not expected", whitelist == null || whitelist.contains(propname)); + assertFalse("Property name " + propname + " not expected", blacklist.contains(propname)); + if (propname == null) { + assertNull("null prop name -> null old value", ev.getOldValue()); + assertNull("null prop name -> null new value", ev.getNewValue()); + } + events.add(ev); + notifyAll(); + } + + /** + * Specifies a failure message to use for the next assertion. + * @return this object, for convenient chaining + */ + public MockPropertyChangeListener msg(String msg) { + this.msg = msg; + return this; + } + + private String compose(String msg) { + return this.msg == null ? msg : msg + ": " + this.msg; + } + + /** + * Asserts that the set of property change event names fired matches an expected list. + * (Order and multiplicity of events is not considered.) + * After this call, the list of received events is reset, so each call checks events since the last call. + */ + public synchronized void assertEvents(String... expectedPropertyNames) throws AssertionFailedError { + try { + Set actualEvents = new TreeSet(); + for (PropertyChangeEvent ev : events) { + actualEvents.add(ev.getPropertyName()); + } + assertEquals(msg, new TreeSet(Arrays.asList(expectedPropertyNames)).toString(), actualEvents.toString()); + } finally { + reset(); + } + } + + /** + * Asserts that a certain number of events have been received. + * (Property name is not considered.) + * After this call, the list of received events is reset, so each call checks events since the last call. + */ + public synchronized void assertEventCount(int expectedCount) throws AssertionFailedError { + try { + assertEquals(msg, expectedCount, events.size()); + } finally { + reset(); + } + } + + /** + * Asserts that some events were received with particular old and new values. + * After this call, the list of received events is reset, so each call checks events since the last call. + * @param expectedOldValues mapping from expected property names to old values (may be left null to skip this check) + * @param expectedNewValues mapping from expected property names to new values + */ + public synchronized void assertEventsAndValues(Map expectedOldValues, Map expectedNewValues) throws AssertionFailedError { + try { + if (expectedOldValues != null) { + Map actualOldValues = new HashMap(); + for (PropertyChangeEvent ev : events) { + actualOldValues.put(ev.getPropertyName(), ev.getOldValue()); + } + assertEquals(msg, expectedOldValues, actualOldValues); + } + Map actualNewValues = new HashMap(); + for (PropertyChangeEvent ev : events) { + actualNewValues.put(ev.getPropertyName(), ev.getNewValue()); + } + assertEquals(msg, expectedNewValues, actualNewValues); + } finally { + reset(); + } + } + + /** + * Expects a single event to be fired. + * After this call, the list of received events is reset, so each call checks events since the last call. + * @param propertyName optional property name which is expected (or null for any) + * @param timeout a timeout in milliseconds (zero means no timeout) + */ + public synchronized void expectEvent(String expectedPropertyName, long timeout) throws AssertionFailedError { + try { + if (events.isEmpty()) { + try { + wait(timeout); + } catch (InterruptedException x) { + fail(compose("Timed out waiting for event")); + } + } + assertFalse(compose("Did not get event"), events.isEmpty()); + assertFalse(compose("Got too many events"), events.size() > 1); + PropertyChangeEvent received = events.iterator().next(); + if (expectedPropertyName != null) { + assertEquals(msg, expectedPropertyName, received.getPropertyName()); + } + } finally { + reset(); + } + } + + /** + * Gets a list of all received events, for special processing. + * (For example, checking of source, ...) + * After this call, the list of received events is reset, so each call checks events since the last call. + */ + public synchronized List allEvents() { + try { + return new ArrayList(events); + } finally { + reset(); + } + } + + /** + * Simply resets the list of events without checking anything. + * Also resets any failure message. + */ + public synchronized void reset() { + msg = null; + events.clear(); + } + +} diff --git a/openide.util.base/test/unit/src/org/openide/util/test/MockPropertyChangeListenerTest.java b/openide.util.base/test/unit/src/org/openide/util/test/MockPropertyChangeListenerTest.java new file mode 100644 --- /dev/null +++ b/openide.util.base/test/unit/src/org/openide/util/test/MockPropertyChangeListenerTest.java @@ -0,0 +1,169 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * Contributor(s): + * + * The Original Software is NetBeans. The Initial Developer of the Original + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun + * Microsystems, Inc. All Rights Reserved. + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + */ + +package org.openide.util.test; + +import java.beans.PropertyChangeSupport; +import java.util.Collections; +import junit.framework.AssertionFailedError; +import junit.framework.TestCase; + +public class MockPropertyChangeListenerTest extends TestCase { + + public MockPropertyChangeListenerTest(String n) { + super(n); + } + + Object source; + PropertyChangeSupport pcs; + MockPropertyChangeListener l; + + @Override + protected void setUp() throws Exception { + super.setUp(); + source = new Object(); + pcs = new PropertyChangeSupport(source); + l = new MockPropertyChangeListener(); + pcs.addPropertyChangeListener(l); + } + + // XXX test expect + + public void testBasicUsage() throws Exception { + l.assertEvents(); + try { + l.assertEvents("whatever"); + assert false; + } catch (AssertionFailedError e) {} + pcs.firePropertyChange("foo", null, null); + l.assertEvents("foo"); + try { + l.assertEvents("foo"); + assert false; + } catch (AssertionFailedError e) {} + l.assertEventCount(0); + pcs.firePropertyChange("bar", null, null); + pcs.firePropertyChange("baz", null, null); + l.assertEventCount(2); + try { + l.assertEventCount(2); + assert false; + } catch (AssertionFailedError e) {} + assertEquals(0, l.allEvents().size()); + pcs.firePropertyChange("bar", null, null); + pcs.firePropertyChange("baz", null, null); + assertEquals(2, l.allEvents().size()); + assertEquals(0, l.allEvents().size()); + pcs.firePropertyChange("foo", "old", "new"); + l.assertEventsAndValues(null, Collections.singletonMap("foo", "new")); + pcs.firePropertyChange("foo", "old2", "new2"); + l.assertEventsAndValues(Collections.singletonMap("foo", "old2"), Collections.singletonMap("foo", "new2")); + try { + l.assertEventsAndValues(null, Collections.singletonMap("foo", "new2")); + assert false; + } catch (AssertionFailedError e) {} + pcs.firePropertyChange("foo", null, null); + l.reset(); + l.assertEvents(); + pcs.firePropertyChange("x", null, null); + try { + l.assertEvents(); + assert false; + } catch (AssertionFailedError e) {} + l.assertEvents(); + } + + public void testMessages() throws Exception { + pcs.firePropertyChange("foo", null, null); + try { + l.assertEvents(); + assert false; + } catch (AssertionFailedError e) {} + pcs.firePropertyChange("foo", null, null); + try { + l.msg("stuff").assertEvents(); + assert false; + } catch (AssertionFailedError e) { + assertTrue(e.getMessage().contains("stuff")); + } + pcs.firePropertyChange("foo", null, null); + try { + l.assertEvents(); + assert false; + } catch (AssertionFailedError e) { + assertFalse(e.getMessage().contains("stuff")); + } + } + + public void testPropertyNameFiltering() throws Exception { + l.ignore("irrelevant"); + l.blacklist("bad", "worse"); + pcs.firePropertyChange("relevant", null, null); + l.assertEvents("relevant"); + pcs.firePropertyChange("irrelevant", null, null); + l.assertEvents(); + try { + pcs.firePropertyChange("bad", null, null); + assert false; + } catch (AssertionFailedError e) {} + try { + pcs.firePropertyChange("worse", null, null); + assert false; + } catch (AssertionFailedError e) {} + pcs.removePropertyChangeListener(l); + l = new MockPropertyChangeListener("expected1", "expected2"); + pcs.addPropertyChangeListener(l); + l.ignore("irrelevant"); + pcs.firePropertyChange("expected1", null, null); + pcs.firePropertyChange("expected2", null, null); + l.assertEvents("expected1", "expected2"); + pcs.firePropertyChange("irrelevant", null, null); + l.assertEvents(); + try { + pcs.firePropertyChange("other", null, null); + assert false; + } catch (AssertionFailedError e) {} + } + +} diff --git a/openide.util.base/test/unit/src/org/openide/util/test/RestrictThreadCreation.java b/openide.util.base/test/unit/src/org/openide/util/test/RestrictThreadCreation.java new file mode 100644 --- /dev/null +++ b/openide.util.base/test/unit/src/org/openide/util/test/RestrictThreadCreation.java @@ -0,0 +1,130 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * Contributor(s): + * + * Portions Copyrighted 2007 Sun Microsystems, Inc. + */ + +package org.openide.util.test; + +import java.security.Permission; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +/** + * Permits unit tests to limit creation of threads. + * Unexpected thread creation can make tests fail randomly, which makes debugging difficult. + *

      Start off calling {@link #permitStandard} and {@link #forbidNewThreads}. + * To determine which methods to permit, just try running the test; + * if you see any {@link SecurityException}s which look like harmless thread creation + * activities, just copy the appropriate part of the stack trace and pass to {@link #permit}. + *

      Use non-strict mode for {@link #forbidNewThreads} if you suspect some code + * might be catching and not reporting {@link SecurityException}s; or you may prefer + * to simply use non-strict mode while developing the test and then switch to strict + * mode once it begins passing. + *

      Place calls to this class early in your test's initialization, e.g. in a static block. + * (Not suitable for use from {@link junit.framework.TestCase#setUp}.) + */ +public class RestrictThreadCreation { + + private RestrictThreadCreation() {} + + private static Set currentlyPermitted = new HashSet(); + + /** + * Explicitly permits one or more thread creation idioms. + * Each entry is of the form fully.qualified.Clazz.methodName + * and if such a method can be found on the call stack the thread creation + * is permitted. + * @param permitted one or more fully qualified method names to accept + */ + public static void permit(String... permitted) { + currentlyPermitted.addAll(Arrays.asList(permitted)); + } + + /** + * Permits a standard set of thread creation idioms which are normally harmless to unit tests. + * Feel free to add to this list if it seems appropriate. + */ + public static void permitStandard() { + permit(// Found experimentally: + "org.netbeans.junit.NbTestCase.runBare", + "sun.java2d.Disposer.", + "java.awt.Toolkit.getDefaultToolkit", + "java.util.logging.LogManager$Cleaner.", + "org.netbeans.ModuleManager$1.", + "org.netbeans.Stamps$Worker.", + "org.netbeans.core.startup.Splash$SplashComponent.setText", + "org.netbeans.core.startup.preferences.NbPreferences.asyncInvocationOfFlushSpi", + "org.openide.loaders.FolderInstance.waitFinished", + "org.openide.loaders.FolderInstance.postCreationTask", + "org.netbeans.modules.masterfs.filebasedfs.fileobjects.LockForFile.", + "org.netbeans.api.java.source.JavaSource.", + "org.netbeans.api.java.source.JavaSourceTaskFactory.fileObjectsChanged", + "org.netbeans.modules.progress.spi.Controller.resetTimer", + "org.netbeans.modules.project.ui.problems.BrokenProjectAnnotator.annotateIcon", + "org.netbeans.modules.timers.InstanceWatcher$FinalizingToken.finalize", + "org.openide.util.NbBundle.getBundleFast", + "org.openide.util.RequestProcessor$TickTac.run", + "org.openide.util.Utilities$ActiveQueue.ping", + "javax.swing.JComponent.revalidate", + "javax.swing.ImageIcon."); + } + + /** + * Install a security manager which prevents new threads from being created + * unless they were explicitly permitted. + * @param strict if true, throw a security exception; if false, just print stack traces + */ + public static void forbidNewThreads(final boolean strict) { + System.setSecurityManager(new SecurityManager() { + public @Override void checkAccess(ThreadGroup g) { + boolean inThreadInit = false; + for (StackTraceElement line : Thread.currentThread().getStackTrace()) { + String id = line.getClassName() + "." + line.getMethodName(); + if (currentlyPermitted.contains(id)) { + return; + } else if (id.equals("java.lang.Thread.init") || id.equals("org.openide.util.RequestProcessor$Processor.checkAccess")) { + inThreadInit = true; + } + } + if (inThreadInit) { + SecurityException x = new SecurityException("Unauthorized thread creation"); + if (strict) { + throw x; + } else { + x.printStackTrace(); + } + } + } + public @Override void checkPermission(Permission perm) {} + public @Override void checkPermission(Permission perm, Object context) {} + }); + } + +} diff --git a/openide.util.base/test/unit/src/org/openide/util/test/TestFileUtils.java b/openide.util.base/test/unit/src/org/openide/util/test/TestFileUtils.java new file mode 100644 --- /dev/null +++ b/openide.util.base/test/unit/src/org/openide/util/test/TestFileUtils.java @@ -0,0 +1,271 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2010 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2008 Sun Microsystems, Inc. + */ + +package org.openide.util.test; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.zip.CRC32; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import java.util.zip.ZipOutputStream; +import junit.framework.Assert; + +/** + * Common utility methods for massaging and inspecting files from tests. + */ +public class TestFileUtils { + + private TestFileUtils() {} + + /** + * Create a new data file with specified initial contents. + * @param f a file to create (parents will be created automatically) + * @param body the complete contents of the new file (in UTF-8 encoding) + */ + public static File writeFile(File f, String body) throws IOException { + f.getParentFile().mkdirs(); + OutputStream os = new FileOutputStream(f); + PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, "UTF-8")); + pw.print(body); + pw.flush(); + os.close(); + return f; + } + + /** + * Read the contents of a file as a single string. + * @param a data file + * @return its contents (in UTF-8 encoding) + */ + public static String readFile(File file) throws IOException { + InputStream is = new FileInputStream(file); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] buf = new byte[4096]; + int read; + while ((read = is.read(buf)) != -1) { + baos.write(buf, 0, read); + } + is.close(); + return baos.toString("UTF-8"); + } + + /** + * Read the contents of a file as a byte array. + * @param a data file + * @return its raw binary contents + */ + public static byte[] readFileBin(File file) throws IOException { + InputStream is = new FileInputStream(file); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] buf = new byte[4096]; + int read; + while ((read = is.read(buf)) != -1) { + baos.write(buf, 0, read); + } + is.close(); + return baos.toByteArray(); + } + + /** + * Create a new ZIP file. + * @param jar the ZIP file to create + * @param entries a list of entries in the form of "filename:UTF8-contents"; parent dirs created automatically + * @return the {@code jar} parameter, for convenience + * @throws IOException for the usual reasons + */ + public static File writeZipFile(File jar, String... entries) throws IOException { + jar.getParentFile().mkdirs(); + writeZipFile(new FileOutputStream(jar), entries); + return jar; + } + + /** + * Create a new ZIP file. + * @param os a stream to which the ZIP will be written + * @param entries a list of entries in the form of "filename:UTF8-contents"; parent dirs created automatically + * @throws IOException for the usual reasons + */ + public static void writeZipFile(OutputStream os, String... entries) throws IOException { + Map binary = new LinkedHashMap(); + for (String entry : entries) { + int colon = entry.indexOf(':'); + assert colon != -1 : entry; + binary.put(entry.substring(0, colon), entry.substring(colon + 1).getBytes("UTF-8")); + } + writeZipFile(os, binary); + } + + /** + * Create a new ZIP file. + * @param os a stream to which the ZIP will be written + * @param entries entries as maps from filename to binary contents;; parent dirs created automatically + * @throws IOException for the usual reasons + */ + public static void writeZipFile(OutputStream os, Map entries) throws IOException { + ZipOutputStream zos = new ZipOutputStream(os); + Set parents = new HashSet(); + if (entries.isEmpty()) { + entries = Collections.singletonMap("PLACEHOLDER", new byte[0]); + } + for (Map.Entry entry : entries.entrySet()) { + String name = entry.getKey(); + assert name.length() > 0 && !name.endsWith("/") && !name.startsWith("/") && name.indexOf("//") == -1 : name; + for (int i = 0; i < name.length(); i++) { + if (name.charAt(i) == '/') { + String parent = name.substring(0, i + 1); + if (parents.add(parent)) { + ZipEntry ze = new ZipEntry(parent); + ze.setMethod(ZipEntry.STORED); + ze.setSize(0); + ze.setCrc(0); + ze.setTime(0); + zos.putNextEntry(ze); + zos.closeEntry(); + } + } + } + byte[] data = entry.getValue(); + ZipEntry ze = new ZipEntry(name); + ze.setMethod(ZipEntry.STORED); + ze.setSize(data.length); + CRC32 crc = new CRC32(); + crc.update(data); + ze.setCrc(crc.getValue()); + ze.setTime(0); + zos.putNextEntry(ze); + zos.write(data, 0, data.length); + zos.closeEntry(); + } + zos.finish(); + zos.close(); + os.close(); + } + + /** + * Unpacks a ZIP file to disk. + * All entries are unpacked, even {@code META-INF/MANIFEST.MF} if present. + * Parent directories are created as needed (even if not mentioned in the ZIP); + * empty ZIP directories are created too. + * Existing files are overwritten. + * @param zip a ZIP file + * @param dir the base directory in which to unpack (need not yet exist) + * @throws IOException in case of problems + */ + public static void unpackZipFile(File zip, File dir) throws IOException { + byte[] buf = new byte[8192]; + InputStream is = new FileInputStream(zip); + try { + ZipInputStream zis = new ZipInputStream(is); + ZipEntry entry; + while ((entry = zis.getNextEntry()) != null) { + String name = entry.getName(); + int slash = name.lastIndexOf('/'); + File d = new File(dir, name.substring(0, slash).replace('/', File.separatorChar)); + if (!d.isDirectory() && !d.mkdirs()) { + throw new IOException("could not make " + d); + } + if (slash != name.length() - 1) { + File f = new File(dir, name.replace('/', File.separatorChar)); + OutputStream os = new FileOutputStream(f); + try { + int read; + while ((read = zis.read(buf)) != -1) { + os.write(buf, 0, read); + } + } finally { + os.close(); + } + } + } + } finally { + is.close(); + } + } + + /** + * Make sure the timestamp on a file changes. + * @param f a file to touch (make newer) + * @param ref if not null, make f newer than this file; else make f newer than it was before + */ + @SuppressWarnings("SleepWhileInLoop") + public static void touch(File f, File ref) throws IOException, InterruptedException { + long older = f.lastModified(); + if (ref != null) { + older = Math.max(older, ref.lastModified()); + } else { + older = Math.max(older, System.currentTimeMillis()); + } + int maxPause = 9999; + /* XXX consider this (as yet untested): + long curr = System.currentTimeMillis(); + if (older > curr + maxPause) { + throw new IllegalArgumentException("reference too far into the future, by " + (older - curr) + "msec"); + } + */ + for (long pause = 1; pause < maxPause; pause *= 2) { + Thread.sleep(pause); + f.setLastModified(System.currentTimeMillis() + 1); // plus 1 needed for FileObject tests (initially FO lastModified is set to currentTimeMillis) + if (f.lastModified() > older) { + while (f.lastModified() >= System.currentTimeMillis()) { +// LOG.log(Level.INFO, "Modification time is in future {0}", System.currentTimeMillis()); + Thread.sleep(10); + } + return; + } + } + Assert.fail("Did not manage to touch " + f); + } + +} diff --git a/openide.util.base/test/unit/src/org/openide/util/test/package-info.java b/openide.util.base/test/unit/src/org/openide/util/test/package-info.java new file mode 100644 --- /dev/null +++ b/openide.util.base/test/unit/src/org/openide/util/test/package-info.java @@ -0,0 +1,48 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * Contributor(s): + * + * The Original Software is NetBeans. The Initial Developer of the Original + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun + * Microsystems, Inc. All Rights Reserved. + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + */ + +/** + * General utility classes useful for writing unit tests in various modules. + */ +package org.openide.util.test; diff --git a/openide.util/src/org/netbeans/modules/openide/util/ProxyURLStreamHandlerFactory.java b/openide.util/src/org/netbeans/modules/openide/util/ProxyURLStreamHandlerFactory.java deleted file mode 100644 --- a/openide.util/src/org/netbeans/modules/openide/util/ProxyURLStreamHandlerFactory.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright 2010 Oracle and/or its affiliates. All rights reserved. - * - * Oracle and Java are registered trademarks of Oracle and/or its affiliates. - * Other names may be trademarks of their respective owners. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common - * Development and Distribution License("CDDL") (collectively, the - * "License"). You may not use this file except in compliance with the - * License. You can obtain a copy of the License at - * http://www.netbeans.org/cddl-gplv2.html - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the - * specific language governing permissions and limitations under the - * License. When distributing the software, include this License Header - * Notice in each file and include the License file at - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the GPL Version 2 section of the License file that - * accompanied this code. If applicable, add the following below the - * License Header, with the fields enclosed by brackets [] replaced by - * your own identifying information: - * "Portions Copyrighted [year] [name of copyright owner]" - * - * If you wish your version of this file to be governed by only the CDDL - * or only the GPL Version 2, indicate your decision by adding - * "[Contributor] elects to include this software in this distribution - * under the [CDDL or GPL Version 2] license." If you do not indicate a - * single choice of license, a recipient has the option to distribute - * your version of this file under either the CDDL, the GPL Version 2 or - * to extend the choice of license to its licensees as provided above. - * However, if you add GPL Version 2 code and therefore, elected the GPL - * Version 2 license, then the option applies only if the new code is - * made subject to such option by the copyright holder. - * - * Contributor(s): - * - * Portions Copyrighted 2009 Sun Microsystems, Inc. - */ - -package org.netbeans.modules.openide.util; - -import java.net.URLStreamHandler; -import java.net.URLStreamHandlerFactory; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import org.openide.util.Lookup; -import org.openide.util.LookupEvent; -import org.openide.util.LookupListener; -import org.openide.util.URLStreamHandlerRegistration; -import org.openide.util.lookup.Lookups; -import org.openide.util.lookup.ServiceProvider; - -/** - * @see URLStreamHandlerRegistration - */ -@ServiceProvider(service=URLStreamHandlerFactory.class) -public final class ProxyURLStreamHandlerFactory implements URLStreamHandlerFactory { - /** prevents GC only */ - private final Map> results = new HashMap>(); - private final Map handlers = new HashMap(); - private static final Set STANDARD_PROTOCOLS = new HashSet(Arrays.asList("jar", "file", "http", "https", "resource")); // NOI18N - - public @Override synchronized URLStreamHandler createURLStreamHandler(final String protocol) { - if (STANDARD_PROTOCOLS.contains(protocol)) { - // Well-known handlers in JRE. Do not try to initialize lookup. - return null; - } - if (!results.containsKey(protocol)) { - final Lookup.Result result = Lookups.forPath("URLStreamHandler/" + protocol).lookupResult(URLStreamHandler.class); - LookupListener listener = new LookupListener() { - public @Override void resultChanged(LookupEvent ev) { - synchronized (ProxyURLStreamHandlerFactory.this) { - Collection instances = result.allInstances(); - handlers.put(protocol, instances.isEmpty() ? null : instances.iterator().next()); - } - } - }; - result.addLookupListener(listener); - listener.resultChanged(null); - results.put(protocol, result); - } - return handlers.get(protocol); - } -} diff --git a/openide.util/src/org/openide/util/URLStreamHandlerRegistration.java b/openide.util/src/org/openide/util/URLStreamHandlerRegistration.java deleted file mode 100644 --- a/openide.util/src/org/openide/util/URLStreamHandlerRegistration.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright 2010 Oracle and/or its affiliates. All rights reserved. - * - * Oracle and Java are registered trademarks of Oracle and/or its affiliates. - * Other names may be trademarks of their respective owners. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common - * Development and Distribution License("CDDL") (collectively, the - * "License"). You may not use this file except in compliance with the - * License. You can obtain a copy of the License at - * http://www.netbeans.org/cddl-gplv2.html - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the - * specific language governing permissions and limitations under the - * License. When distributing the software, include this License Header - * Notice in each file and include the License file at - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the GPL Version 2 section of the License file that - * accompanied this code. If applicable, add the following below the - * License Header, with the fields enclosed by brackets [] replaced by - * your own identifying information: - * "Portions Copyrighted [year] [name of copyright owner]" - * - * If you wish your version of this file to be governed by only the CDDL - * or only the GPL Version 2, indicate your decision by adding - * "[Contributor] elects to include this software in this distribution - * under the [CDDL or GPL Version 2] license." If you do not indicate a - * single choice of license, a recipient has the option to distribute - * your version of this file under either the CDDL, the GPL Version 2 or - * to extend the choice of license to its licensees as provided above. - * However, if you add GPL Version 2 code and therefore, elected the GPL - * Version 2 license, then the option applies only if the new code is - * made subject to such option by the copyright holder. - * - * Contributor(s): - * - * Portions Copyrighted 2009 Sun Microsystems, Inc. - */ - -package org.openide.util; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.net.URL; -import java.net.URLStreamHandler; -import java.net.URLStreamHandlerFactory; -import org.openide.util.lookup.NamedServiceDefinition; - -/** - * Replacement for {@link URLStreamHandlerFactory} within the NetBeans platform. - * (The JVM only permits one global factory to be set at a time, - * whereas various independent modules may wish to register handlers.) - * May be placed on a {@link URLStreamHandler} implementation to register it. - * Your handler will be loaded and used if and when a URL of a matching protocol is created. - *

      A {@link URLStreamHandlerFactory} which uses these registrations may be found in {@link Lookup#getDefault}. - * This factory is active whenever the module system is loaded. - * You may also wish to call {@link URL#setURLStreamHandlerFactory} - * from a unit test or otherwise without the module system active. - * @since org.openide.util 7.31 - */ -@NamedServiceDefinition(path="URLStreamHandler/@protocol()", serviceType=URLStreamHandler.class) -@Retention(RetentionPolicy.SOURCE) -@Target(ElementType.TYPE) -public @interface URLStreamHandlerRegistration { - - /** - * URL protocol(s) which are handled. - * {@link URLStreamHandler#openConnection} will be called with a matching {@link URL#getProtocol}. - */ - String[] protocol(); - - /** - * An optional position in which to register this handler relative to others. - * The lowest-numbered handler is used in favor of any others, including unnumbered handlers. - */ - int position() default Integer.MAX_VALUE; - -} diff --git a/web.inspect/src/org/netbeans/modules/web/inspect/webkit/RemoteStyleSheetCache.java b/web.inspect/src/org/netbeans/modules/web/inspect/webkit/RemoteStyleSheetCache.java --- a/web.inspect/src/org/netbeans/modules/web/inspect/webkit/RemoteStyleSheetCache.java +++ b/web.inspect/src/org/netbeans/modules/web/inspect/webkit/RemoteStyleSheetCache.java @@ -392,7 +392,6 @@ return null; } - @Override public SystemAction[] getActions() { return new SystemAction[0]; }