This Bugzilla instance is a read-only archive of historic NetBeans bug reports. To report a bug in NetBeans please follow the project's instructions for reporting issues.

View | Details | Raw Unified | Return to bug 243683
Collapse All | Expand All

(-)a/apisupport.project/src/org/netbeans/modules/apisupport/project/api/LayerHandle.java (-2 / +31 lines)
Lines 49-54 Link Here
49
import java.io.InputStream;
49
import java.io.InputStream;
50
import java.io.OutputStream;
50
import java.io.OutputStream;
51
import java.lang.ref.WeakReference;
51
import java.lang.ref.WeakReference;
52
import java.lang.reflect.InvocationTargetException;
53
import java.lang.reflect.Method;
52
import java.util.ArrayList;
54
import java.util.ArrayList;
53
import java.util.List;
55
import java.util.List;
54
import java.util.Map;
56
import java.util.Map;
Lines 71-76 Link Here
71
import org.openide.filesystems.FileUtil;
73
import org.openide.filesystems.FileUtil;
72
import org.openide.filesystems.MultiFileSystem;
74
import org.openide.filesystems.MultiFileSystem;
73
import org.openide.filesystems.XMLFileSystem;
75
import org.openide.filesystems.XMLFileSystem;
76
import org.openide.util.Exceptions;
74
import org.openide.util.Parameters;
77
import org.openide.util.Parameters;
75
import org.openide.util.Utilities;
78
import org.openide.util.Utilities;
76
import org.openide.util.actions.SystemAction;
79
import org.openide.util.actions.SystemAction;
Lines 301-306 Link Here
301
        public @Override void fileAttributeChanged(FileAttributeEvent fe) {}
304
        public @Override void fileAttributeChanged(FileAttributeEvent fe) {}
302
    }
305
    }
303
    
306
    
307
    private static final SystemAction[] NO_ACTIONS = new SystemAction[0];
308
    
309
    /**
310
     * Extracts actions from a FileSystem that implements the old contract.
311
     * 
312
     * @param fs the filesystem
313
     * @return FD actions, or an empty array.
314
     */
315
    private static SystemAction[] getFSActions(FileSystem fs) {
316
        try {
317
            Method m = fs.getClass().getMethod("getActions");
318
            return (SystemAction[])m.invoke(fs);
319
        } catch (NoSuchMethodException ex) {
320
            // OK, no such method exists
321
        } catch (SecurityException ex) {
322
            Exceptions.printStackTrace(ex);
323
        } catch (IllegalAccessException ex) {
324
            Exceptions.printStackTrace(ex);
325
        } catch (IllegalArgumentException ex) {
326
            Exceptions.printStackTrace(ex);
327
        } catch (InvocationTargetException ex) {
328
            Exceptions.printStackTrace(ex);
329
        }
330
        return NO_ACTIONS;
331
    }
332
    
304
    private final class SingleLayer extends FileSystem implements FileChangeListener {
333
    private final class SingleLayer extends FileSystem implements FileChangeListener {
305
        private final FileSystem explicit;
334
        private final FileSystem explicit;
306
        SingleLayer(FileSystem explicit) {
335
        SingleLayer(FileSystem explicit) {
Lines 348-356 Link Here
348
            return this.explicit!=null?this.explicit.findResource(name):null;
377
            return this.explicit!=null?this.explicit.findResource(name):null;
349
        }
378
        }
350
379
351
        @Override
380
//        @Override
352
        public SystemAction[] getActions() {
381
        public SystemAction[] getActions() {
353
            return this.explicit!=null?this.explicit.getActions():null;
382
            return this.explicit!=null?getFSActions(this.explicit):null;
354
        }
383
        }
355
    }
384
    }
356
385
(-)a/apisupport.project/src/org/netbeans/modules/apisupport/project/layers/LayerNode.java (-1 / +1 lines)
Lines 239-245 Link Here
239
            public String getDisplayName() {
239
            public String getDisplayName() {
240
                return FileUtil.getFileDisplayName(layer);
240
                return FileUtil.getFileDisplayName(layer);
241
            }
241
            }
242
            @Override
242
            
243
            public SystemAction[] getActions(Set<FileObject> foSet) {
243
            public SystemAction[] getActions(Set<FileObject> foSet) {
244
                return new SystemAction[] {
244
                return new SystemAction[] {
245
                    SystemAction.get(PickNameAction.class),
245
                    SystemAction.get(PickNameAction.class),
(-)a/cnd.apt/test/unit/src/org/netbeans/modules/cnd/apt/support/APTConditionResolverTest.java (-5 lines)
Lines 189-198 Link Here
189
        public FileObject findResource(String name) {
189
        public FileObject findResource(String name) {
190
            throw new UnsupportedOperationException();
190
            throw new UnsupportedOperationException();
191
        }
191
        }
192
193
        @Override
194
        public org.openide.util.actions.SystemAction[] getActions() {
195
            throw new UnsupportedOperationException();
196
        }
197
    }
192
    }
198
}
193
}
(-)a/cnd.apt/test/unit/src/org/netbeans/modules/cnd/apt/support/GuardDetectorTestCase.java (-4 lines)
Lines 263-271 Link Here
263
            throw new UnsupportedOperationException("Not supported yet.");
263
            throw new UnsupportedOperationException("Not supported yet.");
264
        }
264
        }
265
265
266
        @Override
267
        public SystemAction[] getActions() {
268
            throw new UnsupportedOperationException("Not supported yet.");
269
        }
270
    }
266
    }
271
}
267
}
(-)a/cnd.folding/test/unit/src/org/netbeans/modules/cnd/folding/APTFoldingProviderTestCase.java (-5 lines)
Lines 138-148 Link Here
138
        public FileObject findResource(String name) {
138
        public FileObject findResource(String name) {
139
            throw new UnsupportedOperationException();
139
            throw new UnsupportedOperationException();
140
        }
140
        }
141
142
        @Override
143
        public org.openide.util.actions.SystemAction[] getActions() {
144
            throw new UnsupportedOperationException();
145
        }
146
    }
141
    }
147
142
148
}
143
}
(-)a/core.osgi/nbproject/project.xml (-1 / +9 lines)
Lines 24-30 Link Here
24
                    <build-prerequisite/>
24
                    <build-prerequisite/>
25
                    <compile-dependency/>
25
                    <compile-dependency/>
26
                    <run-dependency>
26
                    <run-dependency>
27
                        <specification-version>7.36</specification-version>
27
                        <specification-version>9.0</specification-version>
28
                    </run-dependency>
29
                </dependency>
30
                <dependency>
31
                    <code-name-base>org.openide.filesystems.compat8</code-name-base>
32
                    <build-prerequisite/>
33
                    <compile-dependency/>
34
                    <run-dependency>
35
                        <specification-version>9.0</specification-version>
28
                    </run-dependency>
36
                    </run-dependency>
29
                </dependency>
37
                </dependency>
30
                <dependency>
38
                <dependency>
(-)a/core.osgi/src/org/netbeans/core/osgi/OSGiRepository.java (-1 / +2 lines)
Lines 54-59 Link Here
54
import java.util.logging.Level;
54
import java.util.logging.Level;
55
import java.util.logging.Logger;
55
import java.util.logging.Logger;
56
import org.openide.filesystems.FileStatusListener;
56
import org.openide.filesystems.FileStatusListener;
57
import org.openide.filesystems.FileSystem$Environment;
57
import org.openide.filesystems.FileSystem;
58
import org.openide.filesystems.FileSystem;
58
import org.openide.filesystems.FileUtil;
59
import org.openide.filesystems.FileUtil;
59
import org.openide.filesystems.LocalFileSystem;
60
import org.openide.filesystems.LocalFileSystem;
Lines 141-147 Link Here
141
    private static final class SFS extends MultiFileSystem implements LookupListener {
142
    private static final class SFS extends MultiFileSystem implements LookupListener {
142
143
143
        static {
144
        static {
144
            @SuppressWarnings("deprecation") Object _1 = FileSystem.Environment.class; // FELIX-2128
145
            @SuppressWarnings("deprecation") Object _1 = FileSystem$Environment.class; // FELIX-2128
145
            @SuppressWarnings("deprecation") Object _2 = org.openide.filesystems.FileSystemCapability.class;
146
            @SuppressWarnings("deprecation") Object _2 = org.openide.filesystems.FileSystemCapability.class;
146
            Object _3 = FileStatusListener.class;
147
            Object _3 = FileStatusListener.class;
147
            Object _4 = LookupEvent.class; // FELIX-3477
148
            Object _4 = LookupEvent.class; // FELIX-3477
(-)a/core.startup/src/org/netbeans/core/startup/layers/SystemFileSystem.java (-8 lines)
Lines 118-124 Link Here
118
        home = fss.length > 1 ? (ModuleLayeredFileSystem) fss[1] : null;
118
        home = fss.length > 1 ? (ModuleLayeredFileSystem) fss[1] : null;
119
        
119
        
120
        setSystemName(SYSTEM_NAME);
120
        setSystemName(SYSTEM_NAME);
121
        setHidden(true);
122
        addFileChangeListener(this);
121
        addFileChangeListener(this);
123
    }
122
    }
124
123
Lines 188-200 Link Here
188
        return super.createLocksOn (name);
187
        return super.createLocksOn (name);
189
    }
188
    }
190
    
189
    
191
    /** This filesystem cannot be removed from pool, it is persistent.
192
    */
193
    @Deprecated
194
    public @Override boolean isPersistent() {
195
        return true;
196
    }
197
198
    /** Initializes and creates new repository. This repository's system fs is
190
    /** Initializes and creates new repository. This repository's system fs is
199
    * based on the content of ${HOME_DIR}/system and ${USER_DIR}/system directories
191
    * based on the content of ${HOME_DIR}/system and ${USER_DIR}/system directories
200
    *
192
    *
(-)a/dlight.libs.common/src/org/netbeans/modules/dlight/libs/common/InvalidFileObjectSupport.java (-5 lines)
Lines 135-145 Link Here
135
        }
135
        }
136
136
137
        @Override
137
        @Override
138
        public SystemAction[] getActions() {
139
            return new SystemAction[0];
140
        }
141
142
        @Override
143
        public String getDisplayName() {
138
        public String getDisplayName() {
144
            return "Dummy"; //NOI18N
139
            return "Dummy"; //NOI18N
145
        }
140
        }
(-)a/dlight.remote.impl/src/org/netbeans/modules/remote/impl/fs/RemoteFileSystem.java (-6 / +1 lines)
Lines 358-368 Link Here
358
    }
358
    }
359
    
359
    
360
360
361
    @Override
362
    public SystemAction[] getActions() {
363
        return NO_SYSTEM_ACTIONS;
364
    }
365
366
    public void addPendingFile(RemoteFileObjectBase fo) {
361
    public void addPendingFile(RemoteFileObjectBase fo) {
367
        remoteFileSupport.addPendingFile(fo);
362
        remoteFileSupport.addPendingFile(fo);
368
        fireProblemListeners(fo.getPath());
363
        fireProblemListeners(fo.getPath());
Lines 665-671 Link Here
665
        }
660
        }
666
    }
661
    }
667
662
668
    @Override
663
//    @Override -- overrides at runtime
669
    public final SystemAction[] getActions(final Set<FileObject> foSet) {
664
    public final SystemAction[] getActions(final Set<FileObject> foSet) {
670
        SystemAction[] result = status.getActions (foSet);
665
        SystemAction[] result = status.getActions (foSet);
671
        SystemAction refreshAction = isManualRefresh() ? null :  FileSystemRefreshAction.get(FileSystemRefreshAction.class);                 
666
        SystemAction refreshAction = isManualRefresh() ? null :  FileSystemRefreshAction.get(FileSystemRefreshAction.class);                 
(-)a/masterfs/src/org/netbeans/modules/masterfs/filebasedfs/FileBasedFileSystem.java (-6 lines)
Lines 237-248 Link Here
237
        throw new IOException("Cannot create temporary file"); // NOI18N
237
        throw new IOException("Cannot create temporary file"); // NOI18N
238
    }
238
    }
239
239
240
    @Override
241
    public SystemAction[] getActions() {
242
        return new SystemAction[] {};
243
    }
244
245
    @Override
246
    public final SystemAction[] getActions(final Set<FileObject> foSet) {
240
    public final SystemAction[] getActions(final Set<FileObject> foSet) {
247
        SystemAction[] some = status.getActions (foSet);
241
        SystemAction[] some = status.getActions (foSet);
248
        if (some != null) {
242
        if (some != null) {
(-)a/nbbuild/build.xml (+4 lines)
Lines 1898-1903 Link Here
1898
            <equals arg1="${code.name.base.dashes}" arg2="org-netbeans-libs-asm" />
1898
            <equals arg1="${code.name.base.dashes}" arg2="org-netbeans-libs-asm" />
1899
        </condition>
1899
        </condition>
1900
1900
1901
        <condition property="module" value="tmp/netbeans/lib/org-netbeans-libs-asm.jar">
1902
            <equals arg1="${code.name.base.dashes}" arg2="org-netbeans-libs-asm" />
1903
        </condition>
1904
1901
        <condition property="module" value="tmp/netbeans/core/org-netbeans-upgrader.jar">
1905
        <condition property="module" value="tmp/netbeans/core/org-netbeans-upgrader.jar">
1902
            <equals arg1="${code.name.base.dashes}" arg2="org-netbeans-upgrader" />
1906
            <equals arg1="${code.name.base.dashes}" arg2="org-netbeans-upgrader" />
1903
        </condition>
1907
        </condition>
(-)a/nbbuild/cluster.properties (+3 lines)
Lines 228-234 Link Here
228
        openide.compat,\
228
        openide.compat,\
229
        openide.dialogs,\
229
        openide.dialogs,\
230
        openide.execution,\
230
        openide.execution,\
231
        openide.execution.compat8,\
231
        openide.explorer,\
232
        openide.explorer,\
233
        openide.filesystems.compat8,\
234
        openide.filesystems.nb,\
232
        openide.io,\
235
        openide.io,\
233
        openide.loaders,\
236
        openide.loaders,\
234
        openide.modules,\
237
        openide.modules,\
(-)a/nbbuild/javadoctools/links.xml (+1 lines)
Lines 224-226 Link Here
224
<link href="${javadoc.docs.org-netbeans-core-multitabs}" offline="true" packagelistloc="${netbeans.javadoc.dir}/org-netbeans-core-multitabs"/>
224
<link href="${javadoc.docs.org-netbeans-core-multitabs}" offline="true" packagelistloc="${netbeans.javadoc.dir}/org-netbeans-core-multitabs"/>
225
<link href="${javadoc.docs.org-openide-util-base}" offline="true" packagelistloc="${netbeans.javadoc.dir}/org-openide-util-base"/>
225
<link href="${javadoc.docs.org-openide-util-base}" offline="true" packagelistloc="${netbeans.javadoc.dir}/org-openide-util-base"/>
226
<link href="${javadoc.docs.org-openide-filesystems-compat8}" offline="true" packagelistloc="${netbeans.javadoc.dir}/org-openide-filesystems-compat8"/>
226
<link href="${javadoc.docs.org-openide-filesystems-compat8}" offline="true" packagelistloc="${netbeans.javadoc.dir}/org-openide-filesystems-compat8"/>
227
<link href="${javadoc.docs.org-openide-filesystems-compat8}" offline="true" packagelistloc="${netbeans.javadoc.dir}/org-openide-filesystems-compat8"/>
(-)a/nbbuild/javadoctools/properties.xml (+1 lines)
Lines 222-224 Link Here
222
<property name="javadoc.docs.org-netbeans-core-multitabs" value="${javadoc.web.root}/org-netbeans-core-multitabs"/>
222
<property name="javadoc.docs.org-netbeans-core-multitabs" value="${javadoc.web.root}/org-netbeans-core-multitabs"/>
223
<property name="javadoc.docs.org-openide-util-base" value="${javadoc.web.root}/org-openide-util-base"/>
223
<property name="javadoc.docs.org-openide-util-base" value="${javadoc.web.root}/org-openide-util-base"/>
224
<property name="javadoc.docs.org-openide-filesystems-compat8" value="${javadoc.web.root}/org-openide-filesystems-compat8"/>
224
<property name="javadoc.docs.org-openide-filesystems-compat8" value="${javadoc.web.root}/org-openide-filesystems-compat8"/>
225
<property name="javadoc.docs.org-openide-filesystems-compat8" value="${javadoc.web.root}/org-openide-filesystems-compat8"/>
(-)a/nbbuild/javadoctools/replaces.xml (+1 lines)
Lines 222-224 Link Here
222
<replacefilter token="@org-netbeans-core-multitabs@" value="${javadoc.docs.org-netbeans-core-multitabs}"/>
222
<replacefilter token="@org-netbeans-core-multitabs@" value="${javadoc.docs.org-netbeans-core-multitabs}"/>
223
<replacefilter token="@org-openide-util-base@" value="${javadoc.docs.org-openide-util-base}"/>
223
<replacefilter token="@org-openide-util-base@" value="${javadoc.docs.org-openide-util-base}"/>
224
<replacefilter token="@org-openide-filesystems-compat8@" value="${javadoc.docs.org-openide-filesystems-compat8}"/>
224
<replacefilter token="@org-openide-filesystems-compat8@" value="${javadoc.docs.org-openide-filesystems-compat8}"/>
225
<replacefilter token="@org-openide-filesystems-compat8@" value="${javadoc.docs.org-openide-filesystems-compat8}"/>
(-)a/nbbuild/templates/common.xml (+10 lines)
Lines 1309-1314 Link Here
1309
                <module codenamebase="org.openide.util" spec="9.0"/>
1309
                <module codenamebase="org.openide.util" spec="9.0"/>
1310
                <module codenamebase="org.openide.util.base" spec="9.0"/>
1310
                <module codenamebase="org.openide.util.base" spec="9.0"/>
1311
            </replace>
1311
            </replace>
1312
1313
            <replace codenamebase="org.openide.filesystems" addcompiletime="true">
1314
                <module codenamebase="org.openide.filesystems" spec="9.0"/>
1315
                <module codenamebase="org.openide.filesystems.nb" spec="9.0"/>
1316
                <module codenamebase="org.openide.filesystems.compat8" spec="9.0"/>
1317
            </replace>
1318
            <replace codenamebase="org.openide.execution" addcompiletime="true">
1319
                <module codenamebase="org.openide.execution" spec="9.0"/>
1320
                <module codenamebase="org.openide.execution.compat8" spec="9.0"/>
1321
            </replace>
1312
            <fileset dir="nbproject" >
1322
            <fileset dir="nbproject" >
1313
                <include name="project.xml" />
1323
                <include name="project.xml" />
1314
            </fileset>
1324
            </fileset>
(-)a/openide.execution.compat8/build.xml (+5 lines)
Line 0 Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
2
<project basedir="." default="netbeans" name="openide.execution.compat8">
3
    <description>Builds, tests, and runs the project org.openide.execution.compat8</description>
4
    <import file="../nbbuild/templates/projectized.xml"/>
5
</project>
(-)a/openide.execution.compat8/manifest.mf (+6 lines)
Line 0 Link Here
1
Manifest-Version: 1.0
2
OpenIDE-Module: org.openide.execution.compat8
3
OpenIDE-Module-Localizing-Bundle: org/openide/execution/compat8/Bundle.properties
4
OpenIDE-Module-Specification-Version: 9.0
5
OpenIDE-Module-Fragment-Host: org.openide.execution
6
(-)a/openide.execution.compat8/nbproject/project.properties (+2 lines)
Line 0 Link Here
1
javac.source=1.6
2
javac.compilerargs=-Xlint -Xlint:-serial
(-)a/openide.execution.compat8/nbproject/project.xml (+38 lines)
Line 0 Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
2
<project xmlns="http://www.netbeans.org/ns/project/1">
3
    <type>org.netbeans.modules.apisupport.project</type>
4
    <configuration>
5
        <data xmlns="http://www.netbeans.org/ns/nb-module-project/3">
6
            <code-name-base>org.openide.execution.compat8</code-name-base>
7
            <module-dependencies>
8
                <dependency>
9
                    <code-name-base>org.openide.execution</code-name-base>
10
                    <build-prerequisite/>
11
                    <compile-dependency/>
12
                    <run-dependency>
13
                        <specification-version>9.0</specification-version>
14
                    </run-dependency>
15
                </dependency>
16
                <dependency>
17
                    <code-name-base>org.openide.filesystems</code-name-base>
18
                    <build-prerequisite/>
19
                    <compile-dependency/>
20
                    <run-dependency>
21
                        <specification-version>9.0</specification-version>
22
                    </run-dependency>
23
                </dependency>
24
                <dependency>
25
                    <code-name-base>org.openide.filesystems.compat8</code-name-base>
26
                    <build-prerequisite/>
27
                    <compile-dependency/>
28
                    <run-dependency>
29
                        <specification-version>9.0</specification-version>
30
                    </run-dependency>
31
                </dependency>
32
            </module-dependencies>
33
            <public-packages>
34
                <package>org.openide.execution</package>
35
            </public-packages>
36
        </data>
37
    </configuration>
38
</project>
(-)a/openide.execution.compat8/src/org/openide/execution/NbClassPathCompat.java (+115 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2014 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2014 Sun Microsystems, Inc.
41
 */
42
43
package org.openide.execution;
44
45
import java.util.Enumeration;
46
import java.util.LinkedList;
47
import org.openide.filesystems.EnvironmentNotSupportedException;
48
import org.openide.filesystems.FileSystem;
49
import org.openide.filesystems.FileSystem$Environment;
50
import org.openide.filesystems.FileSystemCapability;
51
import org.openide.filesystems.FileSystemCompat;
52
53
/**
54
 * Backward binary compatibility support for deprecated/obsolete features
55
 * @author sdedic
56
 */
57
public class NbClassPathCompat {
58
    
59
    /** Method to obtain class path for the current state of the repository.
60
    * The classpath should be scanned for all occured exception caused
61
    * by file systems that cannot be converted to class path by a call to
62
    * method getExceptions().
63
    *
64
    *
65
    * @return class path for all reachable systems in the repository
66
    * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/api.html">ClassPath API</a> instead.
67
    */
68
    @Deprecated
69
    public static NbClassPath createRepositoryPath () {
70
        Thread.dumpStack();
71
        return createRepositoryPath (FileSystemCapability.ALL);
72
    }
73
74
    /** Method to obtain class path for the current state of the repository.
75
    * The classpath should be scanned for all occured exception caused
76
    * by file systems that cannot be converted to class path by a call to
77
    * method getExceptions().
78
    *
79
    *
80
    * @param cap the capability that must be satisfied by the file system
81
    *    added to the class path
82
    * @return class path for all reachable systems in the repository
83
    * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/api.html">ClassPath API</a> instead.
84
    */
85
    @Deprecated
86
    public static NbClassPath createRepositoryPath (FileSystemCapability cap) {
87
        Thread.dumpStack();
88
        final LinkedList res = new LinkedList ();
89
90
91
        final class Env extends FileSystem$Environment {
92
            /* method of interface Environment */
93
            public void addClassPath(String element) {
94
                res.add (element);
95
            }
96
        }
97
98
99
        Env env = new Env ();
100
        Enumeration en = cap.fileSystems ();
101
        while (en.hasMoreElements ()) {
102
            try {
103
                FileSystem fs = (FileSystem)en.nextElement ();
104
                FileSystemCompat.compat(fs).prepareEnvironment((FileSystem$Environment)env);
105
            } catch (EnvironmentNotSupportedException ex) {
106
                // store the exception
107
                res.add (ex);
108
            }
109
        }
110
111
        // return it
112
        return new NbClassPath (res.toArray ());
113
    }
114
115
}
(-)a/openide.execution.compat8/src/org/openide/execution/compat8/Bundle.properties (+8 lines)
Line 0 Link Here
1
OpenIDE-Module-Name=Execution API 8.0 Compatibility
2
OpenIDE-Module-Display-Category=Infrastructure
3
OpenIDE-Module-Short-Description=Compatibility support for clients compiled against Execution API \
4
    ver. 8.0 and earlier.
5
OpenIDE-Module-Long-Description=\
6
    The module provides deprecated and obsolete classes/methods removed from the \
7
    official APIs for binary compatibility of old Execution API clients.
8
(-)a/openide.execution/manifest.mf (-1 / +1 lines)
Lines 1-6 Link Here
1
Manifest-Version: 1.0
1
Manifest-Version: 1.0
2
OpenIDE-Module: org.openide.execution
2
OpenIDE-Module: org.openide.execution
3
OpenIDE-Module-Specification-Version: 1.36
3
OpenIDE-Module-Specification-Version: 9.0
4
OpenIDE-Module-Localizing-Bundle: org/openide/execution/Bundle.properties
4
OpenIDE-Module-Localizing-Bundle: org/openide/execution/Bundle.properties
5
OpenIDE-Module-Recommends: org.openide.execution.ExecutionEngine
5
OpenIDE-Module-Recommends: org.openide.execution.ExecutionEngine
6
AutoUpdate-Essential-Module: true
6
AutoUpdate-Essential-Module: true
(-)a/openide.execution/module-auto-deps.xml (+13 lines)
Lines 62-66 Link Here
62
            </implies>
62
            </implies>
63
        </transformation>
63
        </transformation>
64
    </transformationgroup>
64
    </transformationgroup>
65
    <transformationgroup>
66
        <description>Removal of FileSystemCapability</description>
67
        <transformation>
68
            <trigger-dependency type="older">
69
                <module-dependency codenamebase="org.openide.execution" spec="9.0"/>
70
            </trigger-dependency>
71
            <implies>
72
                <result>
73
                    <module-dependency codenamebase="org.openide.execution.compat8" spec="9.0"/>
74
                </result>
75
            </implies>
76
        </transformation>
77
    </transformationgroup>
65
78
66
</transformations>
79
</transformations>
(-)a/openide.execution/nbproject/project.xml (-1 / +1 lines)
Lines 54-60 Link Here
54
                    <build-prerequisite/>
54
                    <build-prerequisite/>
55
                    <compile-dependency/>
55
                    <compile-dependency/>
56
                    <run-dependency>
56
                    <run-dependency>
57
                        <specification-version>7.57</specification-version>
57
                        <specification-version>9.0</specification-version>
58
                    </run-dependency>
58
                    </run-dependency>
59
                </dependency>
59
                </dependency>
60
                <dependency>
60
                <dependency>
(-)a/openide.execution/src/org/openide/execution/NbClassLoader.java (-1 lines)
Lines 59-65 Link Here
59
import java.util.logging.Logger;
59
import java.util.logging.Logger;
60
import org.openide.filesystems.FileObject;
60
import org.openide.filesystems.FileObject;
61
import org.openide.filesystems.FileSystem;
61
import org.openide.filesystems.FileSystem;
62
import org.openide.filesystems.FileSystemCapability;
63
import org.openide.filesystems.FileUtil;
62
import org.openide.filesystems.FileUtil;
64
import org.openide.filesystems.URLMapper;
63
import org.openide.filesystems.URLMapper;
65
import org.openide.util.Exceptions;
64
import org.openide.util.Exceptions;
(-)a/openide.execution/src/org/openide/execution/NbClassPath.java (-55 / +1 lines)
Lines 85-91 Link Here
85
    /** Private constructor
85
    /** Private constructor
86
    * @param arr array of String and Exceptions
86
    * @param arr array of String and Exceptions
87
    */
87
    */
88
    private NbClassPath (Object[] arr) {
88
    NbClassPath (Object[] arr) {
89
        this.items = arr;
89
        this.items = arr;
90
    }
90
    }
91
91
Lines 109-168 Link Here
109
        }
109
        }
110
    }
110
    }
111
111
112
    /** Method to obtain class path for the current state of the repository.
113
    * The classpath should be scanned for all occured exception caused
114
    * by file systems that cannot be converted to class path by a call to
115
    * method getExceptions().
116
    *
117
    *
118
    * @return class path for all reachable systems in the repository
119
    * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/api.html">ClassPath API</a> instead.
120
    */
121
    public static NbClassPath createRepositoryPath () {
122
        Thread.dumpStack();
123
        return createRepositoryPath (FileSystemCapability.ALL);
124
    }
125
126
    /** Method to obtain class path for the current state of the repository.
127
    * The classpath should be scanned for all occured exception caused
128
    * by file systems that cannot be converted to class path by a call to
129
    * method getExceptions().
130
    *
131
    *
132
    * @param cap the capability that must be satisfied by the file system
133
    *    added to the class path
134
    * @return class path for all reachable systems in the repository
135
    * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/api.html">ClassPath API</a> instead.
136
    */
137
    public static NbClassPath createRepositoryPath (FileSystemCapability cap) {
138
        Thread.dumpStack();
139
        final LinkedList res = new LinkedList ();
140
141
142
        final class Env extends FileSystem.Environment {
143
            /* method of interface Environment */
144
            public void addClassPath(String element) {
145
                res.add (element);
146
            }
147
        }
148
149
150
        Env env = new Env ();
151
        Enumeration en = cap.fileSystems ();
152
        while (en.hasMoreElements ()) {
153
            try {
154
                FileSystem fs = (FileSystem)en.nextElement ();
155
                fs.prepareEnvironment(env);
156
            } catch (EnvironmentNotSupportedException ex) {
157
                // store the exception
158
                res.add (ex);
159
            }
160
        }
161
162
        // return it
163
        return new NbClassPath (res.toArray ());
164
    }
165
166
    /** Creates class path describing additional libraries needed by the system.
112
    /** Creates class path describing additional libraries needed by the system.
167
     * Never use this class path as part of a user project!
113
     * Never use this class path as part of a user project!
168
     * For more information consult the <a href="../doc-files/classpath.html">Module Class Path</a> document.
114
     * For more information consult the <a href="../doc-files/classpath.html">Module Class Path</a> document.
(-)a/openide.filesystems.compat8/arch.xml (+337 lines)
Line 0 Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
2
<!DOCTYPE api-answers PUBLIC "-//NetBeans//DTD Arch Answers//EN" "../nbbuild/antsrc/org/netbeans/nbbuild/Arch.dtd" [
3
  <!ENTITY api-questions SYSTEM "../nbbuild/antsrc/org/netbeans/nbbuild/Arch-api-questions.xml">
4
]>
5
6
<api-answers
7
  question-version="1.29"
8
  author="sdedic@netbeans.org"
9
>
10
11
  &api-questions;
12
13
 <answer id="arch-overall">
14
  <p>
15
   This module contains no public API. It only serves to provide binary backward compatibility
16
    for modules compiled against FileSystems API 8.x and earlier.
17
  </p>
18
 </answer>
19
20
 <answer id="arch-quality">
21
  <p>
22
    Tests to ensure FileSystems 8.x features should be provided.
23
  </p>
24
 </answer>
25
26
 <answer id="arch-time">
27
  <p>
28
   Already done.
29
  </p>
30
 </answer>
31
32
 <answer id="arch-usecases">
33
  <p>
34
   Allows to run modules compiled against FileSystems 8.0 APIs
35
  </p>
36
 </answer>
37
38
 <answer id="arch-what">
39
  <p>
40
   Preservation of compatibility
41
  </p>
42
 </answer>
43
44
 <answer id="arch-where">
45
  <defaultanswer generate='here' />
46
 </answer>
47
48
 <answer id="compat-deprecation">
49
  <p>
50
   APIs that relate to <a href="@TOP@/org/openide/filesystems/FileSystemCapability.html">FileSystemCapability</a> and 
51
   <a href="@TOP@/org/openide/filesystems/FileSystem$Environment.html">FileSystem.Environment</a> are removed from the main API
52
   and provided here only for binary compatibility.
53
  </p>
54
 </answer>
55
56
 <answer id="compat-i18n">
57
  <p>
58
   yes
59
  </p>
60
 </answer>
61
62
 <answer id="compat-standards">
63
  <p>
64
   no
65
  </p>
66
 </answer>
67
68
69
70
 <answer id="compat-version">
71
  <p>
72
   yes
73
  </p>
74
 </answer>
75
76
 <answer id="dep-jre">
77
  <p>
78
   no dependency
79
  </p>
80
 </answer>
81
82
 <answer id="dep-jrejdk">
83
  <p>
84
   JRE
85
  </p>
86
 </answer>
87
88
 <answer id="dep-nb">
89
  <defaultanswer generate='here' />
90
 </answer>
91
92
 <answer id="dep-non-nb">
93
  <p>
94
   None
95
  </p>
96
 </answer>
97
98
 <answer id="dep-platform">
99
  <p>
100
   All
101
  </p>
102
 </answer>
103
104
 <answer id="deploy-dependencies">
105
  <p>
106
   None
107
  </p>
108
 </answer>
109
110
 <answer id="deploy-jar">
111
  <p>
112
   No.
113
  </p>
114
 </answer>
115
116
<!--
117
        <question id="deploy-nbm" when="impl">
118
            Can you deploy an NBM via the Update Center?
119
            <hint>
120
            If not why?
121
            </hint>
122
        </question>
123
-->
124
 <answer id="deploy-nbm">
125
  <p>
126
   Yes
127
  </p>
128
 </answer>
129
130
 <answer id="deploy-packages">
131
  <p>
132
   Yes, packages are only available to strictly defined friends
133
  </p>
134
 </answer>
135
136
 <answer id="deploy-shared">
137
  <p>
138
   Shared location
139
  </p>
140
 </answer>
141
142
 <answer id="exec-ant-tasks">
143
  <p>
144
   No
145
  </p>
146
 </answer>
147
148
 <answer id="exec-classloader">
149
  <p>
150
   No.
151
  </p>
152
 </answer>
153
154
 <answer id="exec-component">
155
  <p>
156
   No.
157
  </p>
158
 </answer>
159
160
 <answer id="exec-introspection">
161
  <p>
162
   No.
163
  </p>
164
 </answer>
165
166
 <answer id="exec-privateaccess">
167
  <p>
168
   None.
169
  </p>
170
 </answer>
171
172
 <answer id="exec-process">
173
  <p>
174
   No.
175
  </p>
176
 </answer>
177
178
 <answer id="exec-property">
179
  <p>
180
   No.
181
  </p>
182
 </answer>
183
184
 <answer id="exec-reflection">
185
  <p>
186
   Not directly reflection. The code however relies on that it is deployed
187
   to the same runtime package as FileSystems API and accessess its package
188
   private parts.
189
  </p>
190
 </answer>
191
192
 <answer id="exec-threading">
193
  <p>
194
   See Filesystems API
195
  </p>
196
 </answer>
197
198
 <answer id="format-clipboard">
199
  <p>
200
   See Filesystems API
201
  </p>
202
 </answer>
203
204
 <answer id="format-dnd">
205
  <p>
206
   See Filesystems API
207
  </p>
208
 </answer>
209
210
 <answer id="format-types">
211
  <p>
212
   None.
213
  </p>
214
 </answer>
215
216
 <answer id="lookup-lookup">
217
  <p>
218
   No.
219
  </p>
220
 </answer>
221
222
 <answer id="lookup-register">
223
  <p>
224
   None.
225
  </p>
226
 </answer>
227
228
 <answer id="lookup-remove">
229
  <p>
230
   No.
231
  </p>
232
 </answer>
233
234
 <answer id="perf-exit">
235
  <p>
236
   No.
237
  </p>
238
 </answer>
239
240
 <answer id="perf-huge_dialogs">
241
  <p>
242
   None.
243
  </p>
244
 </answer>
245
246
 <answer id="perf-limit">
247
  <p>
248
   N/A
249
  </p>
250
 </answer>
251
252
 <answer id="perf-mem">
253
  <p>
254
   N/A
255
  </p>
256
 </answer>
257
258
 <answer id="perf-menus">
259
  <p>
260
   No menus
261
  </p>
262
 </answer>
263
264
 <answer id="perf-progress">
265
  <p>
266
   No.
267
  </p>
268
 </answer>
269
270
 <answer id="perf-scale">
271
  <p>
272
   See Filesystems API
273
  </p>
274
 </answer>
275
276
 <answer id="perf-spi">
277
  <p>
278
   N/A
279
  </p>
280
 </answer>
281
282
 <answer id="perf-startup">
283
  <p>
284
   No.
285
  </p>
286
 </answer>
287
288
 <answer id="perf-wakeup">
289
  <p>
290
   No.
291
  </p>
292
 </answer>
293
294
 <answer id="resources-file">
295
  <p>
296
      Yes, for initialization of <a href="@openide-filesystems@/org/openide/filesystems/LocalFileSystem.html">LocalFileSystem</a>
297
      and <a href="@openide-filesystems@/org/openide/filesystems/JarFileSystem.html">JarFileSystem</a>
298
  </p>
299
 </answer>
300
301
 <answer id="resources-layer">
302
  <p>
303
   No layer
304
  </p>
305
 </answer>
306
307
 <answer id="resources-mask">
308
  <p>
309
   No.
310
  </p>
311
 </answer>
312
313
 <answer id="resources-preferences">
314
  <p>
315
   No.
316
  </p>
317
 </answer>
318
319
 <answer id="resources-read">
320
  <p>
321
   No.
322
  </p>
323
 </answer>
324
325
 <answer id="security-grant">
326
  <p>
327
   No.
328
  </p>
329
 </answer>
330
331
 <answer id="security-policy">
332
  <p>
333
   No.
334
  </p>
335
 </answer>
336
337
</api-answers>
(-)a/openide.filesystems.compat8/build.xml (+5 lines)
Line 0 Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
2
<project basedir="." default="netbeans" name="openide.filesystems.compat8">
3
    <description>Builds, tests, and runs the project org.openide.filesystems.compat8</description>
4
    <import file="../nbbuild/templates/projectized.xml"/>
5
</project>
(-)a/openide.filesystems.compat8/manifest.mf (+6 lines)
Line 0 Link Here
1
Manifest-Version: 1.0
2
OpenIDE-Module: org.openide.filesystems.compat8
3
OpenIDE-Module-Localizing-Bundle: org/openide/filesystems/compat8/Bundle.properties
4
OpenIDE-Module-Specification-Version: 9.0
5
OpenIDE-Module-Fragment-Host: org.openide.filesystems
6
(-)a/openide.filesystems.compat8/nbproject/project.properties (+4 lines)
Line 0 Link Here
1
javac.source=1.6
2
javac.compilerargs=-Xlint -Xlint:-serial
3
module.jar.dir=core
4
javadoc.arch=${basedir}/arch.xml
(-)a/openide.filesystems.compat8/nbproject/project.xml (+54 lines)
Line 0 Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
2
<project xmlns="http://www.netbeans.org/ns/project/1">
3
    <type>org.netbeans.modules.apisupport.project</type>
4
    <configuration>
5
        <data xmlns="http://www.netbeans.org/ns/nb-module-project/3">
6
            <code-name-base>org.openide.filesystems.compat8</code-name-base>
7
            <module-dependencies>
8
                <dependency>
9
                    <code-name-base>org.openide.filesystems</code-name-base>
10
                    <build-prerequisite/>
11
                    <compile-dependency/>
12
                    <run-dependency>
13
                        <specification-version>9.0</specification-version>
14
                    </run-dependency>
15
                </dependency>
16
                <dependency>
17
                    <code-name-base>org.openide.modules</code-name-base>
18
                    <build-prerequisite/>
19
                    <compile-dependency/>
20
                    <run-dependency>
21
                        <specification-version>7.44</specification-version>
22
                    </run-dependency>
23
                </dependency>
24
                <dependency>
25
                    <code-name-base>org.openide.util</code-name-base>
26
                    <build-prerequisite/>
27
                    <compile-dependency/>
28
                    <run-dependency>
29
                        <specification-version>9.0</specification-version>
30
                    </run-dependency>
31
                </dependency>
32
                <dependency>
33
                    <code-name-base>org.openide.util.base</code-name-base>
34
                    <build-prerequisite/>
35
                    <compile-dependency/>
36
                    <run-dependency>
37
                        <specification-version>9.0</specification-version>
38
                    </run-dependency>
39
                </dependency>
40
                <dependency>
41
                    <code-name-base>org.openide.util.lookup</code-name-base>
42
                    <build-prerequisite/>
43
                    <compile-dependency/>
44
                    <run-dependency>
45
                        <specification-version>8.17</specification-version>
46
                    </run-dependency>
47
                </dependency>
48
            </module-dependencies>
49
            <public-packages>
50
                <package>org.openide.filesystems</package>
51
            </public-packages>
52
        </data>
53
    </configuration>
54
</project>
(-)a/openide.filesystems.compat8/src/org/openide/filesystems/AbstractFileSystemCompat.java (+135 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2014 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2014 Sun Microsystems, Inc.
41
 */
42
43
package org.openide.filesystems;
44
45
import java.util.Enumeration;
46
import java.util.StringTokenizer;
47
import org.openide.modules.PatchFor;
48
import org.openide.util.Enumerations;
49
import org.openide.util.Lookup;
50
import org.openide.util.NbCollections;
51
import org.openide.util.SharedClassObject;
52
import org.openide.util.actions.SystemAction;
53
54
/**
55
 * 8.0 compatibility patch for AbstractFileSystem.
56
 * @author sdedic
57
 */
58
@PatchFor(AbstractFileSystem.class)
59
public abstract class AbstractFileSystemCompat extends FileSystem {
60
    /** system actions for this FS if it has refreshTime != 0 */
61
    private static SystemAction[] SYSTEM_ACTIONS;
62
63
    /** system actions for this FS */
64
    private static final SystemAction[] NO_SYSTEM_ACTIONS = new SystemAction[] {  };
65
66
    
67
    /* Finds file when its name is provided.
68
    *
69
    * @param aPackage package name where each package is separated by a dot
70
    * @param name name of the file (without dots) or <CODE>null</CODE> if
71
    *    one want to obtain name of package and not file in it
72
    * @param ext extension of the file or <CODE>null</CODE> if one needs
73
    *    package and not file name
74
    *
75
    * @warning when one of name or ext is <CODE>null</CODE> then name and
76
    *    ext should be ignored and scan should look only for a package
77
    *
78
    * @return FileObject that represents file with given name or
79
    *   <CODE>null</CODE> if the file does not exist
80
    */
81
    @Deprecated
82
    public FileObject find(String aPackage, String name, String ext) {
83
        // create enumeration of name to look for
84
        Enumeration<String> st = NbCollections.checkedEnumerationByFilter(new StringTokenizer(aPackage, "."), String.class, true); // NOI18N
85
86
        if ((name == null) || (ext == null)) {
87
            // search for folder, return the object only if it is folder
88
            FileObject fo = getAbstractRoot().find(st);
89
90
            return ((fo != null) && fo.isFolder()) ? fo : null;
91
        } else {
92
            Enumeration<String> en = Enumerations.concat(st, Enumerations.singleton(name + '.' + ext));
93
94
            // tries to find it (can return null)
95
            return getAbstractRoot().find(en);
96
        }
97
    }
98
99
    abstract AbstractFileObject getAbstractRoot();
100
    
101
    abstract boolean isEnabledRefreshFolder();
102
103
    /* Action for this filesystem.
104
    *
105
    * @return refresh action
106
    */
107
    public SystemAction[] getActions() {
108
        if (!isEnabledRefreshFolder()) {
109
            return NO_SYSTEM_ACTIONS;
110
        } else {
111
            if (SYSTEM_ACTIONS == null) {
112
                try {
113
                    ClassLoader l = Lookup.getDefault().lookup(ClassLoader.class);
114
115
                    if (l == null) {
116
                        l = getClass().getClassLoader();
117
                    }
118
119
                    Class<?> c = Class.forName("org.openide.actions.FileSystemRefreshAction", true, l); // NOI18N
120
                    SystemAction ra = SharedClassObject.findObject(c.asSubclass(SystemAction.class), true);
121
122
                    // initialize the SYSTEM_ACTIONS
123
                    SYSTEM_ACTIONS = new SystemAction[] { ra };
124
                } catch (Exception ex) {
125
                    // ok, we are probably running in standalone mode and
126
                    // classes needed to initialize the RefreshAction are
127
                    // not available
128
                    SYSTEM_ACTIONS = NO_SYSTEM_ACTIONS;
129
                }
130
            }
131
132
            return SYSTEM_ACTIONS;
133
        }
134
    }
135
}
(-)a/openide.filesystems.compat8/src/org/openide/filesystems/EnvironmentNotSupportedException.java (+86 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * Contributor(s):
28
 *
29
 * The Original Software is NetBeans. The Initial Developer of the Original
30
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
31
 * Microsystems, Inc. All Rights Reserved.
32
 *
33
 * If you wish your version of this file to be governed by only the CDDL
34
 * or only the GPL Version 2, indicate your decision by adding
35
 * "[Contributor] elects to include this software in this distribution
36
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
37
 * single choice of license, a recipient has the option to distribute
38
 * your version of this file under either the CDDL, the GPL Version 2 or
39
 * to extend the choice of license to its licensees as provided above.
40
 * However, if you add GPL Version 2 code and therefore, elected the GPL
41
 * Version 2 license, then the option applies only if the new code is
42
 * made subject to such option by the copyright holder.
43
 */
44
45
package org.openide.filesystems;
46
47
import java.io.IOException;
48
49
/** Exception thrown to signal that external
50
* execution and compilation is not supported on a given filesystem.
51
*
52
* @author Jaroslav Tulach
53
* @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
54
*/
55
@Deprecated
56
public class EnvironmentNotSupportedException extends IOException {
57
    /** generated Serialized Version UID */
58
    static final long serialVersionUID = -1138390681913514558L;
59
60
    /** the throwing exception */
61
    private FileSystem fs;
62
63
    /**
64
    * @param fs filesystem that caused the error
65
    */
66
    public EnvironmentNotSupportedException(FileSystem fs) {
67
        this.fs = fs;
68
        assert false : "Deprecated.";
69
    }
70
71
    /**
72
    * @param fs filesystem that caused the error
73
    * @param reason text description for the error
74
    */
75
    public EnvironmentNotSupportedException(FileSystem fs, String reason) {
76
        super(reason);
77
        this.fs = fs;
78
        assert false : "Deprecated.";
79
    }
80
81
    /** Getter for the filesystem that does not support environment operations.
82
    */
83
    public FileSystem getFileSystem() {
84
        return fs;
85
    }
86
}
(-)a/openide.filesystems.compat8/src/org/openide/filesystems/FileSystem$Environment.java (+65 lines)
Line 0 Link Here
1
package org.openide.filesystems;
2
3
/*
4
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
5
 *
6
 * Copyright 2014 Oracle and/or its affiliates. All rights reserved.
7
 *
8
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
9
 * Other names may be trademarks of their respective owners.
10
 *
11
 * The contents of this file are subject to the terms of either the GNU
12
 * General Public License Version 2 only ("GPL") or the Common
13
 * Development and Distribution License("CDDL") (collectively, the
14
 * "License"). You may not use this file except in compliance with the
15
 * License. You can obtain a copy of the License at
16
 * http://www.netbeans.org/cddl-gplv2.html
17
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
18
 * specific language governing permissions and limitations under the
19
 * License.  When distributing the software, include this License Header
20
 * Notice in each file and include the License file at
21
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
22
 * particular file as subject to the "Classpath" exception as provided
23
 * by Oracle in the GPL Version 2 section of the License file that
24
 * accompanied this code. If applicable, add the following below the
25
 * License Header, with the fields enclosed by brackets [] replaced by
26
 * your own identifying information:
27
 * "Portions Copyrighted [year] [name of copyright owner]"
28
 *
29
 * If you wish your version of this file to be governed by only the CDDL
30
 * or only the GPL Version 2, indicate your decision by adding
31
 * "[Contributor] elects to include this software in this distribution
32
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
33
 * single choice of license, a recipient has the option to distribute
34
 * your version of this file under either the CDDL, the GPL Version 2 or
35
 * to extend the choice of license to its licensees as provided above.
36
 * However, if you add GPL Version 2 code and therefore, elected the GPL
37
 * Version 2 license, then the option applies only if the new code is
38
 * made subject to such option by the copyright holder.
39
 *
40
 * Contributor(s):
41
 *
42
 * Portions Copyrighted 2014 Sun Microsystems, Inc.
43
 */
44
45
/** Interface that allows filesystems to set up the Java environment
46
* for external execution and compilation.
47
* Currently just used to append entries to the external class path.
48
* @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
49
*/
50
@Deprecated
51
public abstract class FileSystem$Environment {
52
        /** Deprecated. */
53
        public FileSystem$Environment() {
54
            assert false : "Deprecated.";
55
        }
56
57
        /** Adds one element to the class path environment variable.
58
        * @param classPathElement string representing the one element
59
        * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
60
        */
61
        @Deprecated
62
        public void addClassPath(String classPathElement) {
63
        }
64
}
65
(-)a/openide.filesystems.compat8/src/org/openide/filesystems/FileSystemCapability.java (+436 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * Contributor(s):
28
 *
29
 * The Original Software is NetBeans. The Initial Developer of the Original
30
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
31
 * Microsystems, Inc. All Rights Reserved.
32
 *
33
 * If you wish your version of this file to be governed by only the CDDL
34
 * or only the GPL Version 2, indicate your decision by adding
35
 * "[Contributor] elects to include this software in this distribution
36
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
37
 * single choice of license, a recipient has the option to distribute
38
 * your version of this file under either the CDDL, the GPL Version 2 or
39
 * to extend the choice of license to its licensees as provided above.
40
 * However, if you add GPL Version 2 code and therefore, elected the GPL
41
 * Version 2 license, then the option applies only if the new code is
42
 * made subject to such option by the copyright holder.
43
 */
44
45
package org.openide.filesystems;
46
47
import java.beans.PropertyChangeListener;
48
import java.beans.PropertyChangeSupport;
49
import java.util.Collection;
50
import java.util.Enumeration;
51
import java.util.Vector;
52
53
/** This class defines the capabilities of a filesystem to
54
* take part in different operations. Some filesystems are
55
* not designed to allow compilation on them, some do not want
56
* to be present in class path when executing or debugging
57
* a program.
58
* <P>
59
* Moreover there can be additional capabilities to check
60
* and this class defines ways how one can communicated with
61
* a filesystem to find out whether the system is "capable"
62
* enough to be used in the operation.
63
*
64
* @author Jaroslav Tulach
65
 * @deprecated Now useless.
66
*/
67
@Deprecated
68
public class FileSystemCapability extends Object {
69
    /** Object that is capable of every thing.
70
    */
71
    public static final FileSystemCapability ALL = new FileSystemCapability() {
72
            public boolean capableOf(FileSystemCapability c) {
73
                return true;
74
            }
75
        };
76
77
    /** Well known capability of being compiled.
78
     * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
79
     */
80
    @Deprecated
81
    public static final FileSystemCapability COMPILE = new FileSystemCapability();
82
83
    /** Well known ability to be executed.
84
     * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
85
     */
86
    @Deprecated
87
    public static final FileSystemCapability EXECUTE = new FileSystemCapability();
88
89
    /** Well known ability to be debugged.
90
     * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
91
     */
92
    @Deprecated
93
    public static final FileSystemCapability DEBUG = new FileSystemCapability();
94
95
    /** Well known ability to contain documentation files
96
     * @deprecated Please use <a href="@org-netbeans-api-java@/org/netbeans/api/queries/JavadocForBinaryQuery.html"><code>JavadocForBinaryQuery</code></a> instead.
97
     */
98
    @Deprecated
99
    public static final FileSystemCapability DOC = new FileSystemCapability();
100
101
    public FileSystemCapability() {
102
        if (DOC == null) {
103
            // do not report static initializers
104
            return;
105
        }
106
107
        assert false : "Deprecated.";
108
    }
109
110
    /** Basic operation that tests whether this object
111
    * is capable to do different capability.
112
    * <P>
113
    * The default implementation claims that it is
114
    * capable to handle only identical capability (==).
115
    *
116
    * @param c capability to test
117
    * @return true if yes
118
    */
119
    public boolean capableOf(FileSystemCapability c) {
120
        return c == this;
121
    }
122
123
    /** All filesystems that are capable of this capability.
124
    * @return enumeration of FileSystems that satifies this capability
125
    * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
126
    */
127
    @Deprecated
128
    public Enumeration<? extends FileSystem> fileSystems() {
129
        class FFS implements org.openide.util.Enumerations.Processor<FileSystem, FileSystem> {
130
            @Deprecated
131
            public FileSystem process(FileSystem fs, Collection<FileSystem> ignore) {
132
                return FileSystemCompat.compat(fs).getCapability().
133
                        capableOf(FileSystemCapability.this) ? fs : null;
134
            }
135
        }
136
137
        return org.openide.util.Enumerations.filter(Repository.getDefault().fileSystems(), new FFS());
138
    }
139
140
    /** Find a resource in repository, ignoring not capable filesystems.
141
    * @param resName name of the resource
142
    * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
143
    */
144
    @Deprecated
145
    public FileObject findResource(String resName) {
146
        Enumeration<? extends FileSystem> en = fileSystems();
147
148
        while (en.hasMoreElements()) {
149
            FileSystem fs = en.nextElement();
150
            FileObject fo = fs.findResource(resName);
151
152
            if (fo != null) {
153
                // object found
154
                return fo;
155
            }
156
        }
157
158
        return null;
159
    }
160
161
    /** Searches for the given resource among all filesystems
162
    * that satifies this capability, returning all matches.
163
    * @param name name of the resource
164
    * @return enumeration of {@link FileObject}s
165
    * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
166
    */
167
    @Deprecated
168
    public Enumeration<? extends FileObject> findAllResources(String name) {
169
        Vector<FileObject> v = new Vector<FileObject>(8);
170
        Enumeration<? extends FileSystem> en = fileSystems();
171
172
        while (en.hasMoreElements()) {
173
            FileSystem fs = en.nextElement();
174
            FileObject fo = fs.findResource(name);
175
176
            if (fo != null) {
177
                v.addElement(fo);
178
            }
179
        }
180
181
        return v.elements();
182
    }
183
184
    /** Finds file when its name is provided. It scans in the list of
185
    * filesystems and asks them for the specified file by a call to
186
    * {@link FileSystem#find find}. The first object that is found is returned or <CODE>null</CODE>
187
    * if none of the filesystems contain such a file.
188
    *
189
    * @param aPackage package name where each package is separated by a dot
190
    * @param name name of the file (without dots) or <CODE>null</CODE> if
191
    *    one wants to obtain the name of a package and not a file in it
192
    * @param ext extension of the file or <CODE>null</CODE> if one needs
193
    *    a package and not a file name
194
    *
195
    * @return {@link FileObject} that represents file with given name or
196
    *   <CODE>null</CODE> if the file does not exist
197
    * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
198
    */
199
    @Deprecated
200
    public final FileObject find(String aPackage, String name, String ext) {
201
        Enumeration<? extends FileSystem> en = fileSystems();
202
203
        while (en.hasMoreElements()) {
204
            FileSystem fs = en.nextElement();
205
            FileObject fo = fs.find(aPackage, name, ext);
206
207
            if (fo != null) {
208
                // object found
209
                return fo;
210
            }
211
        }
212
213
        return null;
214
    }
215
216
    /** Finds all files among all filesystems with this capability
217
    * that match a given name, returning all matches.
218
    * All filesystems are queried with {@link FileSystem#find}.
219
    *
220
    * @param aPackage package name where each package is separated by a dot
221
    * @param name name of the file (without dots) or <CODE>null</CODE> if
222
    *    one wants to obtain the name of a package and not a file in it
223
    * @param ext extension of the file or <CODE>null</CODE> if one needs
224
    *    a package and not a file name
225
    *
226
    * @return enumeration of {@link FileObject}s
227
    * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
228
    */
229
    @Deprecated
230
    public final Enumeration<? extends FileObject> findAll(String aPackage, String name, String ext) {
231
        Enumeration<? extends FileSystem> en = fileSystems();
232
        Vector<FileObject> ret = new Vector<FileObject>();
233
234
        while (en.hasMoreElements()) {
235
            FileSystem fs = (FileSystem) en.nextElement();
236
            FileObject fo = fs.find(aPackage, name, ext);
237
238
            if (fo != null) {
239
                ret.addElement(fo);
240
            }
241
        }
242
243
        return ret.elements();
244
    }
245
246
    /** Adds PropertyChange listener. Every class which implements changes of capabilities
247
    * has to implement it's property change support.
248
    * @param l the listener to be added.
249
    */
250
    public synchronized void addPropertyChangeListener(PropertyChangeListener l) {
251
    }
252
253
    /** Removes PropertyChange listener. Every class which implements changes of capabilities
254
    * has to implement it's property change support.
255
    * @param l the listener to be removed.
256
    */
257
    public void removePropertyChangeListener(PropertyChangeListener l) {
258
    }
259
260
    /** Default implementation of capabilities, that behaves like
261
    * JavaBean and allows to set whether the well known
262
    * capabilities (like compile, execute) should be enabled
263
    * or not.
264
     * @deprecated For the same reason the whole class is.
265
    */
266
    @Deprecated
267
    public static class Bean extends FileSystemCapability implements java.io.Serializable {
268
        static final long serialVersionUID = 627905674809532736L;
269
270
        /** change listeners */
271
        private transient PropertyChangeSupport supp;
272
273
        /** compilation */
274
        private boolean compilation = true;
275
276
        /** execution */
277
        private boolean execution = true;
278
279
        /** debugging */
280
        private boolean debug = true;
281
282
        /** doc */
283
        private boolean doc = false;
284
285
        /** Checks for well known capabilities and if they are allowed.
286
        *
287
        * @param c capability to test
288
        * @return true if yes
289
        */
290
        public boolean capableOf(FileSystemCapability c) {
291
            if (c == COMPILE) {
292
                return compilation;
293
            }
294
295
            if (c == EXECUTE) {
296
                return execution;
297
            }
298
299
            if (c == DEBUG) {
300
                return debug;
301
            }
302
303
            if (c == DOC) {
304
                return doc;
305
            }
306
307
            if (c == ALL) {
308
                return true;
309
            }
310
311
            if (!(c instanceof Bean)) {
312
                return false;
313
            }
314
315
            // try match of values
316
            Bean b = (Bean) c;
317
318
            return (compilation == b.compilation) && (execution == b.execution) && (debug == b.debug) &&
319
            (doc == b.doc);
320
        }
321
322
        /** Getter for value of compiling capability.
323
         * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
324
        */
325
        @Deprecated
326
        public boolean getCompile() {
327
            return compilation;
328
        }
329
330
        /** Setter for allowing compiling capability.
331
         * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
332
        */
333
        @Deprecated
334
        public void setCompile(boolean val) {
335
            if (val != compilation) {
336
                compilation = val;
337
338
                if (supp != null) {
339
                    supp.firePropertyChange(
340
                        "compile", // NOI18N
341
                        (!val) ? Boolean.TRUE : Boolean.FALSE, val ? Boolean.TRUE : Boolean.FALSE
342
                    );
343
                }
344
            }
345
        }
346
347
        /** Getter for value of executiong capability.
348
         * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
349
        */
350
        @Deprecated
351
        public boolean getExecute() {
352
            return execution;
353
        }
354
355
        /** Setter for allowing executing capability.
356
         * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
357
        */
358
        @Deprecated
359
        public void setExecute(boolean val) {
360
            if (val != execution) {
361
                execution = val;
362
363
                if (supp != null) {
364
                    supp.firePropertyChange(
365
                        "execute", // NOI18N
366
                        (!val) ? Boolean.TRUE : Boolean.FALSE, val ? Boolean.TRUE : Boolean.FALSE
367
                    );
368
                }
369
            }
370
        }
371
372
        /** Getter for value of debugging capability.
373
         * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
374
        */
375
        @Deprecated
376
        public boolean getDebug() {
377
            return debug;
378
        }
379
380
        /** Setter for allowing debugging capability.
381
         * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
382
        */
383
        @Deprecated
384
        public void setDebug(boolean val) {
385
            if (val != debug) {
386
                debug = val;
387
388
                if (supp != null) {
389
                    supp.firePropertyChange(
390
                        "debug", // NOI18N
391
                        (!val) ? Boolean.TRUE : Boolean.FALSE, val ? Boolean.TRUE : Boolean.FALSE
392
                    );
393
                }
394
            }
395
        }
396
397
        /** Getter for value of doc capability.
398
         * @deprecated Please use <a href="@org-netbeans-api-java@/org/netbeans/api/queries/JavadocForBinaryQuery.html"><code>JavadocForBinaryQuery</code></a> instead.
399
        */
400
        @Deprecated
401
        public boolean getDoc() {
402
            return doc;
403
        }
404
405
        /** Setter for allowing debugging capability.
406
         * @deprecated Please use <a href="@org-netbeans-api-java@/org/netbeans/api/queries/JavadocForBinaryQuery.html"><code>JavadocForBinaryQuery</code></a> instead.
407
        */
408
        @Deprecated
409
        public void setDoc(boolean val) {
410
            if (val != doc) {
411
                doc = val;
412
413
                if (supp != null) {
414
                    supp.firePropertyChange(
415
                        "doc", // NOI18N
416
                        (!val) ? Boolean.TRUE : Boolean.FALSE, val ? Boolean.TRUE : Boolean.FALSE
417
                    );
418
                }
419
            }
420
        }
421
422
        public synchronized void addPropertyChangeListener(PropertyChangeListener l) {
423
            if (supp == null) {
424
                supp = new PropertyChangeSupport(this);
425
            }
426
427
            supp.addPropertyChangeListener(l);
428
        }
429
430
        public void removePropertyChangeListener(PropertyChangeListener l) {
431
            if (supp != null) {
432
                supp.removePropertyChangeListener(l);
433
            }
434
        }
435
    }
436
}
(-)a/openide.filesystems.compat8/src/org/openide/filesystems/FileSystemCompat.java (+237 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2014 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2014 Sun Microsystems, Inc.
41
 */
42
43
package org.openide.filesystems;
44
45
import java.beans.PropertyChangeListener;
46
import java.io.IOException;
47
import java.util.Set;
48
import org.openide.modules.PatchFor;
49
import org.openide.util.actions.SystemAction;
50
51
/**
52
 * The class provides an API compatibility bridge to support implementations
53
 * compiled against <code>org.openide.filesystems&lt;8.0</code> and earlier
54
 *
55
 * @author sdedic
56
 */
57
@PatchFor(FileSystem.class)
58
public abstract class FileSystemCompat {
59
    /** Property name giving capabilities state. @deprecated No more capabilities. */
60
    static final String PROP_CAPABILITIES = "capabilities"; // NOI18N    
61
62
    /** hidden flag */
63
    private boolean hidden = false;
64
65
    /** Describes capabilities of the filesystem.
66
    */
67
    @Deprecated // have to store it for compat
68
    private /* XXX JDK #6460147: javac still reports it even though @Deprecated,
69
               and @SuppressWarnings("deprecation") does not help either: FileSystemCapability*/Object capability;
70
71
    /** property listener on FileSystemCapability. */
72
    private transient PropertyChangeListener capabilityListener;
73
74
    /** Returns an array of actions that can be invoked on any file in
75
    * this filesystem.
76
    * These actions should preferably
77
    * support the {@link org.openide.util.actions.Presenter.Menu Menu},
78
    * {@link org.openide.util.actions.Presenter.Popup Popup},
79
    * and {@link org.openide.util.actions.Presenter.Toolbar Toolbar} presenters.
80
    *
81
    * @return array of available actions
82
    */
83
    public abstract SystemAction[] getActions();
84
85
    /**
86
     * Get actions appropriate to a certain file selection.
87
     * By default, returns the same list as {@link #getActions()}.
88
     * @param foSet one or more files which may be selected
89
     * @return zero or more actions appropriate to those files
90
     */
91
    public SystemAction[] getActions(Set<FileObject> foSet) {
92
        return this.getActions();
93
    }
94
95
    /** Allows filesystems to set up the environment for external execution
96
    * and compilation.
97
    * Each filesystem can add its own values that
98
    * influence the environment. The set of operations that can modify
99
    * environment is described by the {@link Environment} interface.
100
    * <P>
101
    * The default implementation throws an exception to signal that it does not
102
    * support external compilation or execution.
103
    *
104
    * @param env the environment to setup
105
    * @exception EnvironmentNotSupportedException if external execution
106
    *    and compilation cannot be supported
107
    * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
108
    */
109
    @Deprecated
110
    public void prepareEnvironment(FileSystem$Environment env) throws EnvironmentNotSupportedException {
111
        Object o = this;
112
        throw new EnvironmentNotSupportedException((FileSystem)o);
113
    }
114
    
115
    /**
116
     * Provides access to deprecated methods at runtime.
117
     * 
118
     * @param fs The FileSystem
119
     * @return the FileSystemCompat instanceo for the FileSystem.
120
     */
121
    public static FileSystemCompat compat(FileSystem fs) {
122
        Object o = fs;
123
        return (FileSystemCompat)o;
124
    }
125
    
126
    private FileSystem fs() {
127
        Object o = this;
128
        return (FileSystem)o;
129
    }
130
131
    /** The object describing capabilities of this filesystem.
132
     * Subclasses cannot override it.
133
     * @return object describing capabilities of this filesystem.
134
     * @deprecated Capabilities are no longer used.
135
     */
136
    @Deprecated
137
    public final FileSystemCapability getCapability() {
138
        if (capability == null) {
139
            capability = new FileSystemCapability.Bean();
140
            ((FileSystemCapability) capability).addPropertyChangeListener(getCapabilityChangeListener());
141
        }
142
143
        return (FileSystemCapability) capability;
144
    }
145
146
    /** Allows subclasses to change a set of capabilities of the
147
    * filesystem.
148
    * @param capability the capability to use
149
     * @deprecated Capabilities are no longer used.
150
    */
151
    @Deprecated
152
    protected final void setCapability(FileSystemCapability capability) {
153
        if (this.capability != null) {
154
            ((FileSystemCapability) this.capability).removePropertyChangeListener(getCapabilityChangeListener());
155
        }
156
157
        this.capability = capability;
158
159
        if (this.capability != null) {
160
            ((FileSystemCapability) this.capability).addPropertyChangeListener(getCapabilityChangeListener());
161
        }
162
    }
163
164
    /** returns property listener on FileSystemCapability. */
165
    private synchronized PropertyChangeListener getCapabilityChangeListener() {
166
        if (capabilityListener == null) {
167
            capabilityListener = new PropertyChangeListener() {
168
                        public void propertyChange(java.beans.PropertyChangeEvent propertyChangeEvent) {
169
                            firePropertyChange(
170
                                PROP_CAPABILITIES, propertyChangeEvent.getOldValue(), propertyChangeEvent.getNewValue()
171
                            );
172
                        }
173
                    };
174
        }
175
176
        return capabilityListener;
177
    }
178
    
179
    abstract void firePropertyChange(String s, Object o, Object n);
180
181
    /** Reads object from stream and creates listeners.
182
    * @param in the input stream to read from
183
    * @exception IOException error during read
184
    * @exception ClassNotFoundException when class not found
185
    */
186
    @SuppressWarnings("deprecation")
187
    private void readObject(java.io.ObjectInputStream in)
188
    throws java.io.IOException, java.lang.ClassNotFoundException {
189
        in.defaultReadObject();
190
191
        if (capability != null) {
192
            ((FileSystemCapability) capability).addPropertyChangeListener(getCapabilityChangeListener());
193
        }
194
    }
195
196
    /** Set hidden state of the object.
197
     * A hidden filesystem is not presented to the user in the Repository list (though it may be present in the Repository Settings list).
198
    *
199
    * @param hide <code>true</code> if the filesystem should be hidden
200
     * @deprecated This property is now useless.
201
    */
202
    @Deprecated
203
    public final void setHidden(boolean hide) {
204
        if (hide != hidden) {
205
            hidden = hide;
206
            firePropertyChange(FileSystem.PROP_HIDDEN, (!hide) ? Boolean.TRUE : Boolean.FALSE, hide ? Boolean.TRUE : Boolean.FALSE);
207
        }
208
    }
209
210
    /** Getter for the hidden property.
211
     * @return the hidden property.
212
     * @deprecated This property is now useless.
213
    */
214
    @Deprecated
215
    public final boolean isHidden() {
216
        return hidden;
217
    }
218
219
    /** Tests whether filesystem will survive reloading of system pool.
220
    * If true then when
221
    * {@link Repository} is reloading its content, it preserves this
222
    * filesystem in the pool.
223
    * <P>
224
    * This can be used when the pool contains system level and user level
225
    * filesystems. The system ones should be preserved when the user changes
226
    * the content (for example when he is loading a new project).
227
    * <p>The default implementation returns <code>false</code>.
228
    *
229
    * @return true if the filesystem should be persistent
230
     * @deprecated This property is long since useless.
231
    */
232
    @Deprecated
233
    protected boolean isPersistent() {
234
        return false;
235
    }
236
237
}
(-)a/openide.filesystems.compat8/src/org/openide/filesystems/JarFileSystemCompat.java (+79 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2014 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2014 Sun Microsystems, Inc.
41
 */
42
43
package org.openide.filesystems;
44
45
import java.io.File;
46
import java.io.IOException;
47
import org.openide.modules.ConstructorDelegate;
48
import org.openide.modules.PatchFor;
49
50
/**
51
 * Support for compatibility with NB 8.0 and earlier.
52
 * 
53
 * @author sdedic
54
 */
55
@PatchFor(JarFileSystem.class)
56
public abstract class JarFileSystemCompat extends AbstractFileSystem {
57
    public JarFileSystemCompat() {
58
        super();
59
    }
60
    
61
    @ConstructorDelegate
62
    public static void createJarFileSystemCompat(JarFileSystemCompat jfs, FileSystemCapability cap) throws IOException {
63
        FileSystemCompat.compat(jfs).setCapability(cap);
64
    }
65
    
66
    /** Prepare environment for external compilation or execution.
67
    * <P>
68
    * Adds name of the ZIP/JAR file, if it has been set, to the class path.
69
     * @deprecated Useless.
70
    */
71
    @Deprecated
72
    public void prepareEnvironment(FileSystem$Environment env) {
73
        if (getJarFile() != null) {
74
            env.addClassPath(getJarFile().getAbsolutePath());
75
        }
76
    }
77
    
78
    public abstract File getJarFile();
79
}
(-)a/openide.filesystems.compat8/src/org/openide/filesystems/LocalFileSystemCompat.java (+74 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2014 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2014 Sun Microsystems, Inc.
41
 */
42
43
package org.openide.filesystems;
44
45
import java.io.File;
46
import org.openide.modules.ConstructorDelegate;
47
import org.openide.modules.PatchFor;
48
49
/**
50
 *
51
 * @author sdedic
52
 */
53
@PatchFor(LocalFileSystem.class)
54
public abstract class LocalFileSystemCompat extends AbstractFileSystem {
55
    public LocalFileSystemCompat() {
56
        
57
    }
58
    
59
    @ConstructorDelegate
60
    public static void createLocalFileSystemCompat(LocalFileSystemCompat self, FileSystemCapability cap) {
61
        FileSystemCompat.compat(self).setCapability(cap);
62
    }
63
    
64
    /** Prepare environment by adding the root directory of the filesystem to the class path.
65
    * @param environment the environment to add to
66
     * @deprecated Useless.
67
    */
68
    @Deprecated
69
    public void prepareEnvironment(FileSystem$Environment environment) {
70
        environment.addClassPath(getRootDirectory().getAbsolutePath());
71
    }
72
    
73
    public abstract File getRootDirectory();
74
}
(-)a/openide.filesystems.compat8/src/org/openide/filesystems/MultiFileSystemCompat.java (+132 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2014 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2014 Sun Microsystems, Inc.
41
 */
42
43
package org.openide.filesystems;
44
45
import java.util.ArrayList;
46
import java.util.HashSet;
47
import java.util.List;
48
import java.util.Set;
49
import org.openide.modules.PatchFor;
50
import org.openide.util.actions.SystemAction;
51
52
/**
53
 *
54
 * @author sdedic
55
 */
56
@PatchFor(MultiFileSystem.class)
57
public abstract class MultiFileSystemCompat extends FileSystem {
58
    /** Merge actions from all delegates.
59
    */
60
    public SystemAction[] getActions() {
61
        List<SystemAction> al = new ArrayList<SystemAction>(101); // randomly choosen constant
62
        Set<SystemAction> uniq = new HashSet<SystemAction>(101); // not that randommly choosen
63
64
        FileSystem[] del = this.getDelegates();
65
66
        for (int i = 0; i < del.length; i++) {
67
            if (del[i] == null) {
68
                continue;
69
            }
70
71
            SystemAction[] acts = compat(del[i]).getActions();
72
73
            for (int j = 0; j < acts.length; j++) {
74
                if (uniq.add(acts[j])) {
75
                    al.add(acts[j]);
76
                }
77
            }
78
        }
79
80
        return al.toArray(new SystemAction[al.size()]);
81
    }
82
83
    public SystemAction[] getActions(final Set<FileObject> foSet) {
84
        List<SystemAction> al = new ArrayList<SystemAction>(101); // randomly choosen constant
85
        Set<SystemAction> uniq = new HashSet<SystemAction>(101); // not that randommly choosen
86
87
        final FileSystem[] del = this.getDelegates();
88
89
        for (int i = 0; i < del.length; i++) {
90
            if (del[i] == null) {
91
                continue;
92
            }
93
94
            final SystemAction[] acts = compat(del[i]).getActions(foSet);
95
96
            for (int j = 0; j < acts.length; j++) {
97
                if (uniq.add(acts[j])) {
98
                    al.add(acts[j]);
99
                }
100
            }
101
        }
102
103
        return al.toArray(new SystemAction[al.size()]);
104
    }
105
    
106
    static FileSystemCompat compat(FileSystem fs) {
107
        Object o = fs;
108
        return (FileSystemCompat)o;
109
    }
110
111
    /** Lets any sub filesystems prepare the environment.
112
     * If they do not support it, it does not care.
113
     * @deprecated Useless.
114
     */
115
    @Deprecated
116
    public void prepareEnvironment(FileSystem$Environment env)
117
    throws EnvironmentNotSupportedException {
118
        FileSystem[] layers = getDelegates();
119
120
        for (int i = 0; i < layers.length; i++) {
121
            if (layers[i] != null) {
122
                try {
123
                    compat(layers[i]).prepareEnvironment(env);
124
                } catch (EnvironmentNotSupportedException ense) {
125
                    // Fine.
126
                }
127
            }
128
        }
129
    }
130
131
    protected abstract FileSystem[] getDelegates();
132
}
(-)a/openide.filesystems.compat8/src/org/openide/filesystems/compat8/Bundle.properties (+6 lines)
Line 0 Link Here
1
OpenIDE-Module-Display-Category=Infrastructure
2
OpenIDE-Module-Long-Description=\
3
    After NetBeans 8.0 release, deprecated and obsolete features were removed from the FileSystem API mainline. \
4
    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
5
OpenIDE-Module-Name=Filesystems API 8.0 Compatibility
6
OpenIDE-Module-Short-Description=Support for FileSystem backward compatibility with NetBeans 8.0
(-)a/openide.filesystems.nb/build.xml (+5 lines)
Line 0 Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
2
<project basedir="." default="netbeans" name="openide.filesystems.nb">
3
    <description>Builds, tests, and runs the project openide.filesystems.nb</description>
4
    <import file="../nbbuild/templates/projectized.xml"/>
5
</project>
(-)a/openide.filesystems.nb/manifest.mf (+5 lines)
Line 0 Link Here
1
Manifest-Version: 1.0
2
OpenIDE-Module: org.openide.filesystems.nb
3
OpenIDE-Module-Localizing-Bundle: org/openide/filesystems/nb/Bundle.properties
4
OpenIDE-Module-Specification-Version: 9.0
5
(-)a/openide.filesystems.nb/nbproject/project.properties (+2 lines)
Line 0 Link Here
1
javac.source=1.6
2
javac.compilerargs=-Xlint -Xlint:-serial
(-)a/openide.filesystems.nb/nbproject/project.xml (+71 lines)
Line 0 Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
2
<project xmlns="http://www.netbeans.org/ns/project/1">
3
    <type>org.netbeans.modules.apisupport.project</type>
4
    <configuration>
5
        <data xmlns="http://www.netbeans.org/ns/nb-module-project/3">
6
            <code-name-base>org.openide.filesystems.nb</code-name-base>
7
            <module-dependencies>
8
                <dependency>
9
                    <code-name-base>org.openide.filesystems</code-name-base>
10
                    <build-prerequisite/>
11
                    <compile-dependency/>
12
                    <run-dependency>
13
                        <specification-version>9.0</specification-version>
14
                    </run-dependency>
15
                </dependency>
16
                <dependency>
17
                    <code-name-base>org.openide.util</code-name-base>
18
                    <build-prerequisite/>
19
                    <compile-dependency/>
20
                    <run-dependency>
21
                        <specification-version>9.0</specification-version>
22
                    </run-dependency>
23
                </dependency>
24
                <dependency>
25
                    <code-name-base>org.openide.util.base</code-name-base>
26
                    <build-prerequisite/>
27
                    <compile-dependency/>
28
                    <run-dependency>
29
                        <specification-version>9.0</specification-version>
30
                    </run-dependency>
31
                </dependency>
32
                <dependency>
33
                    <code-name-base>org.openide.util.lookup</code-name-base>
34
                    <build-prerequisite/>
35
                    <compile-dependency/>
36
                    <run-dependency>
37
                        <specification-version>8.0</specification-version>
38
                    </run-dependency>
39
                </dependency>
40
            </module-dependencies>
41
            <test-dependencies>
42
                <test-type>
43
                    <name>unit</name>
44
                    <test-dependency>
45
                        <code-name-base>org.netbeans.libs.junit4</code-name-base>
46
                        <compile-dependency/>
47
                    </test-dependency>
48
                    <test-dependency>
49
                        <code-name-base>org.netbeans.modules.nbjunit</code-name-base>
50
                        <recursive/>
51
                        <compile-dependency/>
52
                    </test-dependency>
53
                    <test-dependency>
54
                        <code-name-base>org.openide.filesystems</code-name-base>
55
                        <recursive/>
56
                        <compile-dependency/>
57
                        <test/>
58
                    </test-dependency>
59
                    <test-dependency>
60
                        <code-name-base>org.openide.util.lookup</code-name-base>
61
                        <compile-dependency/>
62
                        <test/>
63
                    </test-dependency>
64
                </test-type>
65
            </test-dependencies>
66
            <public-packages>
67
                <package>org.openide.filesystems</package>
68
            </public-packages>
69
        </data>
70
    </configuration>
71
</project>
(-)a/openide.filesystems.nb/src/org/netbeans/modules/openide/filesystems/FileFilterSupport.java (+470 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2012 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.modules.openide.filesystems;
43
44
import java.io.File;
45
import java.util.ArrayList;
46
import java.util.Collections;
47
import java.util.Comparator;
48
import java.util.HashMap;
49
import java.util.HashSet;
50
import java.util.LinkedList;
51
import java.util.List;
52
import java.util.Map;
53
import java.util.Set;
54
import java.util.logging.Level;
55
import java.util.logging.Logger;
56
import java.util.regex.Matcher;
57
import java.util.regex.Pattern;
58
import javax.swing.filechooser.FileFilter;
59
import org.openide.filesystems.FileObject;
60
import org.openide.filesystems.FileUtil;
61
62
/**
63
 * Support methods for creation of registered {@link FileFilter file filters}.
64
 */
65
public final class FileFilterSupport {
66
67
    /**
68
     * The logger.
69
     */
70
    private static final Logger LOG = Logger.getLogger(
71
            FileFilterSupport.class.getName());
72
73
    /**
74
     * Hide the default constructor.
75
     */
76
    private FileFilterSupport() {
77
    }
78
79
    /**
80
     * Construct description for {@link FileFilter} that accepts files with
81
     * specified extension.
82
     *
83
     * @param displayName Human readable display name (e.g. "HTML files")
84
     * @param elements List of accepted filter elements.
85
     *
86
     * @return Display name (description) for the filter.
87
     */
88
    private static String constructFilterDisplayName(String displayName,
89
            List<FilterElement> elements) {
90
        StringBuilder sb = new StringBuilder(displayName);
91
        boolean first = true;
92
        sb.append(" [");                                                //NOI18N
93
        for (FilterElement el : elements) {
94
            if (first) {
95
                first = false;
96
            } else {
97
                sb.append(", ");                                        //NOI18N
98
            }
99
            sb.append(el.getName());
100
        }
101
        sb.append("]");                                                 //NOI18N
102
        return sb.toString();
103
    }
104
105
    /**
106
     * Check whether passed file is accepted by filter for specified list of
107
     * extensions.
108
     *
109
     * @param file File to be accepted or rejected.
110
     * @param elements List of accepted filter elements.
111
     *
112
     * @return True if the file is accepted, false if it is rejected.
113
     *
114
     * @see FileFilterSupport
115
     */
116
    private static boolean accept(File file, List<FilterElement> elements) {
117
        if (file != null) {
118
            if (file.isDirectory()) {
119
                return true;
120
            }
121
            for (FilterElement elm : elements) {
122
                if (elm.accept(file)) {
123
                    return true;
124
                }
125
            }
126
        }
127
        return false;
128
    }
129
130
    public static List<FileFilter> findRegisteredFileFilters() {
131
        List<FileFilter> filters = new LinkedList<FileFilter>();
132
        FileObject root = FileUtil.getConfigFile(
133
                "Services/MIMEResolver");                               //NOI18N
134
        Map<String, Set<FileObject>> filterNameToResolversMap =
135
                new HashMap<String, Set<FileObject>>();
136
        for (FileObject child : root.getChildren()) {
137
            if (child.isFolder()) {
138
                continue;
139
            }
140
            int i = 0;
141
            String f;
142
            while ((f = (String) child.getAttribute("fileChooser." + i))//NOI18N
143
                    != null) {
144
                Set<FileObject> set = filterNameToResolversMap.get(f);
145
                if (set == null) {
146
                    set = new HashSet<FileObject>();
147
                    filterNameToResolversMap.put(f, set);
148
                }
149
                set.add(child);
150
                i++;
151
            }
152
        }
153
        for (Map.Entry<String, Set<FileObject>> e :
154
                filterNameToResolversMap.entrySet()) {
155
            filters.add(createFilter(e.getKey(), e.getValue()));
156
        }
157
        return sortFiltersByDescription(filters);
158
    }
159
160
    private static FileFilter createFilter(final String name,
161
            final Set<FileObject> resolvers) {
162
        ArrayList<FilterElement> elems = new ArrayList<FilterElement>(3);
163
        String lastAtt;
164
        for (FileObject fo : resolvers) {
165
            int i = 0;
166
            while ((lastAtt = (String) fo.getAttribute(
167
                    "ext." + i)) != null) { //NOI18N
168
                addExtensionToList(elems, lastAtt);
169
                i++;
170
            }
171
            int n = 0;
172
            while ((lastAtt = (String) fo.getAttribute("fileName." //NOI18N
173
                    + (n++))) != null) {
174
                addNameToList(elems, lastAtt);
175
            }
176
            String type;
177
            if ((type = (String) fo.getAttribute("mimeType")) != null) {//NOI18N
178
                addMimeTypeExts(elems, type);
179
            }
180
            int t = 0;
181
            while ((type = (String) fo.getAttribute(
182
                    "mimeType." + (t++))) != null) {     //NOI18N
183
                addMimeTypeExts(elems, type);
184
            }
185
        }
186
        sortFilterElements(elems);
187
        return new FileFilterImpl(name, elems);
188
    }
189
190
    /**
191
     * Add all extensions assigned to a MIME Type to the extension list.
192
     */
193
    private static void addMimeTypeExts(List<FilterElement> exts, String type) {
194
        addAllExtensionsToList(exts, FileUtil.getMIMETypeExtensions(type));
195
    }
196
197
    /**
198
     * Add new items to list of extensions, prevent duplicates.
199
     *
200
     * @param list List of extensions to alter.
201
     * @param toAdd List of extensions (without starting dot) to add.
202
     */
203
    private static void addAllExtensionsToList(List<FilterElement> list,
204
            List<String> toAdd) {
205
        for (String s : toAdd) {
206
            addExtensionToList(list, s);
207
        }
208
    }
209
210
    /**
211
     * Add new item to list of extensions, prevent duplacates.
212
     *
213
     * @param list List of extensions to alter.
214
     * @param s Extensions without starting dot.
215
     */
216
    private static void addExtensionToList(List<FilterElement> list,
217
            String ext) {
218
        addFilterElementToList(list, FilterElement.createForExtension(ext));
219
    }
220
221
    private static void addNameToList(List<FilterElement> list, String name) {
222
        Pattern p = Pattern.compile(
223
                "\\[([^,]+), (true|false), (true|false)\\](\\S*)");     //NOI18N
224
        Matcher m = p.matcher(name);
225
        if (m.find()) {
226
            String fileName = m.group(1);
227
            boolean substring = m.group(2).equals("true");              //NOI18N
228
            boolean ignoreCase = m.group(3).equals("true");             //NOI18N
229
            String extension = m.group(4);
230
            addFilterElementToList(list, FilterElement.createForFileName(
231
                    fileName, extension, substring, ignoreCase));
232
        } else {
233
            LOG.log(Level.INFO, "Incorrect name pattern {0}", name);    //NOI18N
234
        }
235
    }
236
237
    private static void addFilterElementToList(List<FilterElement> list,
238
            FilterElement newItem) {
239
240
        for (int i = 0; i < list.size(); i++) {
241
            FilterElement el = list.get(i);
242
            FilterElement.ComparisonResult result = newItem.compare(el);
243
            switch (result) {
244
                case DIFFERENT:
245
                    continue;
246
                case THE_SAME:
247
                case WORSE:
248
                    return;
249
                case BETTER:
250
                    list.set(i, newItem);
251
                    return;
252
            }
253
        }
254
        list.add(newItem);
255
    }
256
257
    private static List<FileFilter> sortFiltersByDescription(
258
            List<FileFilter> list) {
259
260
        Collections.sort(list, new Comparator<FileFilter>() {
261
            @Override
262
            public int compare(FileFilter o1, FileFilter o2) {
263
                return o1.getDescription().compareTo(o2.getDescription());
264
            }
265
        });
266
        return list;
267
    }
268
269
    private static List<FilterElement> sortFilterElements(
270
            List<FilterElement> elements) {
271
        Collections.sort(elements, new Comparator<FilterElement>() {
272
            @Override
273
            public int compare(FilterElement o1, FilterElement o2) {
274
                return o1.getName().compareTo(o2.getName());
275
            }
276
        });
277
        return elements;
278
    }
279
280
    private static class FileFilterImpl extends FileFilter {
281
282
        private final String name;
283
        List<FilterElement> filterElements;
284
285
        public FileFilterImpl(String name, List<FilterElement> elements) {
286
            this.name = name;
287
            this.filterElements = elements;
288
        }
289
290
        @Override
291
        public boolean accept(File pathname) {
292
            return FileFilterSupport.accept(pathname, filterElements);
293
        }
294
295
        @Override
296
        public String getDescription() {
297
            return FileFilterSupport.constructFilterDisplayName(
298
                    name, filterElements);
299
        }
300
    }
301
302
    /**
303
     * Element of File Filter. One accepted extension or file name pattern.
304
     */
305
    private static abstract class FilterElement {
306
307
        public abstract String getName();
308
309
        public abstract boolean accept(File f);
310
311
        /**
312
         * Compare two filter elements. Correct implementation of this method
313
         * prevents adding duplicite elements to the filter.
314
         */
315
        public abstract ComparisonResult compare(FilterElement e);
316
317
        public static FilterElement createForExtension(String ext) {
318
            return new ExtensionBasedFilterElement(ext);
319
        }
320
321
        public static FilterElement createForFileName(String name,
322
                String extension, boolean substring, boolean ignoreCase) {
323
            return new NameBasedFilterElement(name, extension,
324
                    substring, ignoreCase);
325
        }
326
327
        public static enum ComparisonResult {
328
329
            THE_SAME, BETTER, WORSE, DIFFERENT
330
        }
331
332
        private static class ExtensionBasedFilterElement extends FilterElement {
333
334
            private final String extension;
335
336
            public ExtensionBasedFilterElement(String extension) {
337
                if (extension != null) {
338
                    this.extension = extension;
339
                } else {
340
                    throw new NullPointerException();
341
                }
342
            }
343
344
            @Override
345
            public String getName() {
346
                return "." + extension;                                 //NOI18N
347
            }
348
349
            @Override
350
            public boolean accept(File f) {
351
                return f.getName().toLowerCase().endsWith(
352
                        "." + extension.toLowerCase());                 //NOI18N
353
            }
354
355
            @Override
356
            public ComparisonResult compare(FilterElement e) {
357
                if (!(e instanceof ExtensionBasedFilterElement)) {
358
                    return ComparisonResult.DIFFERENT;
359
                }
360
                ExtensionBasedFilterElement x = (ExtensionBasedFilterElement) e;
361
                if (x == null) {
362
                    throw new NullPointerException();
363
                }
364
                if (this.extension.equals(x.extension)) {
365
                    return ComparisonResult.THE_SAME;
366
                } else if (this.extension.equalsIgnoreCase(x.extension)
367
                        && this.extension.length() > 1) {
368
                    if (Character.isUpperCase(x.extension.charAt(0))) {
369
                        return ComparisonResult.BETTER; //this better, x worse
370
                    } else {
371
                        return ComparisonResult.WORSE; // this worse, x better
372
                    }
373
                } else {
374
                    return ComparisonResult.DIFFERENT;
375
                }
376
            }
377
        }
378
379
        private static class NameBasedFilterElement extends FilterElement {
380
381
            String name;
382
            String ext;
383
            boolean substring;
384
            boolean ignoreCase;
385
            Pattern p;
386
387
            public NameBasedFilterElement(String name, String ext,
388
                    boolean substring, boolean ignoreCase) {
389
                this.name = name;
390
                this.ext = ext;
391
                this.substring = substring;
392
                this.ignoreCase = ignoreCase;
393
                StringBuilder sb = new StringBuilder();
394
                if (ignoreCase) {
395
                    sb.append("(?i)");                                  //NOI18N
396
                }
397
                if (substring) {
398
                    sb.append(".*");                                    //NOI18N
399
                }
400
                sb.append(name);                                        //NOI18N
401
                if (substring) {
402
                    sb.append(".*");                                    //NOI18N
403
                }
404
                if (!ext.isEmpty()) {
405
                    sb.append("\\.");                                   //NOI18N
406
                    sb.append(ext);
407
                }
408
                p = Pattern.compile(sb.toString());
409
            }
410
411
            @Override
412
            public String getName() {
413
                return name + (ext.isEmpty() ? "" : "." + ext);         //NOI18N
414
            }
415
416
            @Override
417
            public boolean accept(File f) {
418
                return p.matcher(f.getName()).matches();
419
            }
420
421
            @Override
422
            public ComparisonResult compare(FilterElement e) {
423
                if (e == null) {
424
                    throw new NullPointerException();
425
                } else if (!(e instanceof NameBasedFilterElement)) {
426
                    return ComparisonResult.DIFFERENT;
427
                }
428
                NameBasedFilterElement x = (NameBasedFilterElement) e;
429
                if (this.name.equals(x.name) && this.ext.equals(x.ext)) {
430
                    if (this.substring == x.substring
431
                            && this.ignoreCase == x.ignoreCase) {
432
                        return ComparisonResult.THE_SAME;
433
                    } else {
434
                        return compareFlags(x);
435
                    }
436
                } else if (this.ext.equalsIgnoreCase(x.ext)
437
                        && this.name.equalsIgnoreCase(x.name)
438
                        && (this.ignoreCase || x.ignoreCase)) {
439
                    if (this.substring == x.substring
440
                            && this.ignoreCase == x.ignoreCase) {
441
                        if (Character.isLowerCase(this.name.charAt(0))) {
442
                            return ComparisonResult.BETTER;
443
                        } else {
444
                            return ComparisonResult.WORSE;
445
                        }
446
                    } else {
447
                        return compareFlags(x);
448
                    }
449
                } else {
450
                    return ComparisonResult.DIFFERENT;
451
                }
452
            }
453
454
            private ComparisonResult compareFlags(NameBasedFilterElement x) {
455
                if (this.substring == x.substring
456
                        && this.ignoreCase) {
457
                    return ComparisonResult.BETTER;
458
                } else if (this.ignoreCase == x.ignoreCase
459
                        && this.substring) {
460
                    return ComparisonResult.BETTER;
461
                } else if (this.substring != x.substring
462
                        && this.ignoreCase != x.ignoreCase) {
463
                    return ComparisonResult.DIFFERENT;
464
                } else {
465
                    return ComparisonResult.WORSE;
466
                }
467
            }
468
        }
469
    }
470
}
(-)a/openide.filesystems.nb/src/org/netbeans/modules/openide/filesystems/FileSystemStatus.java (+163 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2014 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2014 Sun Microsystems, Inc.
41
 */
42
43
package org.netbeans.modules.openide.filesystems;
44
45
import java.awt.Image;
46
import java.awt.Toolkit;
47
import java.beans.BeanInfo;
48
import java.net.URL;
49
import java.util.Arrays;
50
import java.util.MissingResourceException;
51
import java.util.ResourceBundle;
52
import java.util.Set;
53
import java.util.logging.Level;
54
import java.util.logging.Logger;
55
import org.openide.filesystems.FileObject;
56
import org.openide.filesystems.FileSystem;
57
import org.openide.util.BaseUtilities;
58
import org.openide.util.Exceptions;
59
import org.openide.util.ImageUtilities;
60
import org.openide.util.NbBundle;
61
import org.openide.util.lookup.ServiceProvider;
62
63
/**
64
 *
65
 * @author sdedic
66
 */
67
@ServiceProvider(service = FileSystem.Status.class)
68
public final class FileSystemStatus implements FileSystem.Status{
69
    private static final Logger LOG = Logger.getLogger(FileSystemStatus.class.getName());
70
    
71
    public String annotateName(String s, Set<? extends FileObject> files) {
72
        // Look for a localized file name.
73
        // Note: all files in the set are checked. But please only place the attribute
74
        // on the primary file, and use this primary file name as the bundle key.
75
        for (FileObject fo : files) {
76
            // annotate a name
77
            String displayName = annotateName(fo);
78
            if (displayName != null) {
79
                return displayName;
80
            }
81
        }
82
        return s;
83
    }
84
85
    private final String annotateName(FileObject fo) {
86
        String bundleName = (String) fo.getAttribute("SystemFileSystem.localizingBundle"); // NOI18N
87
        if (bundleName != null) {
88
            try {
89
                bundleName = BaseUtilities.translate(bundleName);
90
                ResourceBundle b = NbBundle.getBundle(bundleName);
91
                try {
92
                    return b.getString(fo.getPath());
93
                } catch (MissingResourceException ex) {
94
                    // ignore--normal
95
                }
96
            } catch (MissingResourceException ex) {
97
                Exceptions.attachMessage(ex, warningMessage(bundleName, fo));
98
                LOG.log(Level.INFO, null, ex);
99
                // ignore
100
            }
101
        }
102
        return (String) fo.getAttribute("displayName"); // NOI18N
103
    }
104
105
    private String warningMessage(String name, FileObject fo) {
106
        Object by = fo.getAttribute("layers"); // NOI18N
107
        if (by instanceof Object[]) {
108
            by = Arrays.toString((Object[]) by);
109
        }
110
        return "Cannot load " + name + " for " + fo + " defined by " + by; // NOI18N
111
    }
112
113
    public Image annotateIcon(Image im, int type, Set<? extends FileObject> files) {
114
        for (FileObject fo : files) {
115
            Image img = annotateIcon(fo, type);
116
            if (img != null) {
117
                return img;
118
            }
119
        }
120
        return im;
121
    }
122
123
    private Image annotateIcon(FileObject fo, int type) {
124
        String attr = null;
125
        if (type == BeanInfo.ICON_COLOR_16x16) {
126
            attr = "SystemFileSystem.icon"; // NOI18N
127
        } else if (type == BeanInfo.ICON_COLOR_32x32) {
128
            attr = "SystemFileSystem.icon32"; // NOI18N
129
        }
130
        if (attr != null) {
131
            Object value = fo.getAttribute(attr);
132
            if (value != null) {
133
                if (value instanceof URL) {
134
                    return Toolkit.getDefaultToolkit().getImage((URL) value);
135
                } else if (value instanceof Image) {
136
                    // #18832
137
                    return (Image) value;
138
                } else {
139
                    LOG.warning("Attribute " + attr + " on " + fo + " expected to be a URL or Image; was: " + value);
140
                }
141
            }
142
        }
143
        String base = (String) fo.getAttribute("iconBase"); // NOI18N
144
        if (base != null) {
145
            if (type == BeanInfo.ICON_COLOR_16x16) {
146
                return ImageUtilities.loadImage(base, true);
147
            } else if (type == BeanInfo.ICON_COLOR_32x32) {
148
                return ImageUtilities.loadImage(insertBeforeSuffix(base, "_32"), true); // NOI18N
149
            }
150
        }
151
        return null;
152
    }
153
154
    private String insertBeforeSuffix(String path, String toInsert) {
155
        String withoutSuffix = path;
156
        String suffix = ""; // NOI18N
157
        if (path.lastIndexOf('.') >= 0) {
158
            withoutSuffix = path.substring(0, path.lastIndexOf('.'));
159
            suffix = path.substring(path.lastIndexOf('.'), path.length());
160
        }
161
        return withoutSuffix + toInsert + suffix;
162
    }
163
}
(-)a/openide.filesystems.nb/src/org/netbeans/modules/openide/filesystems/SharedClassObjectFactory.java (+66 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2014 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2014 Sun Microsystems, Inc.
41
 */
42
43
package org.netbeans.modules.openide.filesystems;
44
45
import org.openide.filesystems.spi.CustomInstanceFactory;
46
import org.openide.util.SharedClassObject;
47
import org.openide.util.lookup.ServiceProvider;
48
49
/**
50
 * Handles creation of SharedClassObjects for Filesystems API.
51
 * 
52
 * @author sdedic
53
 */
54
@ServiceProvider(service = CustomInstanceFactory.class)
55
public final class SharedClassObjectFactory implements CustomInstanceFactory {
56
57
    @Override
58
    public <T> T createInstance(Class<T> clazz) {
59
        if (SharedClassObject.class.isAssignableFrom(clazz)) {
60
            return (T)SharedClassObject.findObject(clazz.asSubclass(SharedClassObject.class), true);
61
        } else {
62
            return null;
63
        }
64
    }
65
    
66
}
(-)a/openide.filesystems.nb/src/org/openide/filesystems/FileChooserBuilder.java (+688 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * Contributor(s):
28
 *
29
 * The Original Software is NetBeans. The Initial Developer of the Original
30
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
31
 * Microsystems, Inc. All Rights Reserved.
32
 *
33
 * If you wish your version of this file to be governed by only the CDDL
34
 * or only the GPL Version 2, indicate your decision by adding
35
 * "[Contributor] elects to include this software in this distribution
36
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
37
 * single choice of license, a recipient has the option to distribute
38
 * your version of this file under either the CDDL, the GPL Version 2 or
39
 * to extend the choice of license to its licensees as provided above.
40
 * However, if you add GPL Version 2 code and therefore, elected the GPL
41
 * Version 2 license, then the option applies only if the new code is
42
 * made subject to such option by the copyright holder.
43
 */
44
package org.openide.filesystems;
45
46
import java.awt.Component;
47
import java.awt.FileDialog;
48
import java.awt.Frame;
49
import java.awt.HeadlessException;
50
import java.awt.KeyboardFocusManager;
51
import java.io.File;
52
import java.util.ArrayList;
53
import java.util.List;
54
import javax.swing.Icon;
55
import javax.swing.JFileChooser;
56
import javax.swing.SwingUtilities;
57
import javax.swing.filechooser.FileFilter;
58
import javax.swing.filechooser.FileSystemView;
59
import javax.swing.filechooser.FileView;
60
import org.netbeans.modules.openide.filesystems.FileFilterSupport;
61
import org.openide.filesystems.FileUtil;
62
import org.openide.util.*;
63
64
/**
65
 * Utility class for working with JFileChoosers.  In particular, remembering
66
 * the last-used directory for a given file is made transparent.  You pass an
67
 * ad-hoc string key to the constructor (the fully qualified name of the
68
 * calling class is good for uniqueness, and there is a constructor that takes
69
 * a <code>Class</code> object as an argument for this purpose).  That key is
70
 * used to look up the most recently-used directory from any previous invocations
71
 * with the same key.  This makes it easy to have your user interface
72
 * &ldquo;remember&rdquo; where the user keeps particular types of files, and
73
 * saves the user from having to navigate through the same set of directories
74
 * every time they need to locate a file from a particular place.
75
 * <p/>
76
 * <code>FileChooserBuilder</code>'s methods each return <code>this</code>, so
77
 * it is possible to chain invocations to simplify setting up a file chooser.
78
 * Example usage:
79
 * <pre>
80
 *      <font color="gray">//The default dir to use if no value is stored</font>
81
 *      File home = new File (System.getProperty("user.home") + File.separator + "lib");
82
 *      <font color="gray">//Now build a file chooser and invoke the dialog in one line of code</font>
83
 *      <font color="gray">//&quot;libraries-dir&quot; is our unique key</font>
84
 *      File toAdd = new FileChooserBuilder ("libraries-dir").setTitle("Add Library").
85
 *              setDefaultWorkingDirectory(home).setApproveText("Add").showOpenDialog();
86
 *      <font color="gray">//Result will be null if the user clicked cancel or closed the dialog w/o OK</font>
87
 *      if (toAdd != null) {
88
 *          //do something
89
 *      }
90
 *</pre>
91
 * <p/>
92
 * Instances of this class are intended to be thrown away after use.  Typically
93
 * you create a builder, set it to create file choosers as you wish, then
94
 * use it to show a dialog or create a file chooser you then do something
95
 * with.
96
 * <p/>
97
 * Supports the most common subset of JFileChooser functionality;  if you
98
 * need to do something exotic with a file chooser, you are probably better
99
 * off creating your own.
100
 * <p/>
101
 * <b>Note:</b> If you use the constructor that takes a <code>Class</code> object,
102
 * please use <code>new FileChooserBuilder(MyClass.class)</code>, not
103
 * <code>new FileChooserBuilder(getClass())</code>.  This avoids unexpected
104
 * behavior in the case of subclassing.
105
 *
106
 * @author Tim Boudreau
107
 */
108
public class FileChooserBuilder {
109
    private boolean dirsOnly;
110
    private BadgeProvider badger;
111
    private String title;
112
    private String approveText;
113
    //Just in case...
114
    private static boolean PREVENT_SYMLINK_TRAVERSAL =
115
            !Boolean.getBoolean("allow.filechooser.symlink.traversal"); //NOI18N
116
    private final String dirKey;
117
    private File failoverDir;
118
    private FileFilter filter;
119
    private boolean fileHiding;
120
    private boolean controlButtonsShown = true;
121
    private String aDescription;
122
    private boolean filesOnly;
123
    private static final boolean DONT_STORE_DIRECTORIES =
124
            Boolean.getBoolean("forget.recent.dirs");
125
    private SelectionApprover approver;
126
    private final List<FileFilter> filters = new ArrayList<FileFilter>(3);
127
    private boolean useAcceptAllFileFilter = true;
128
    /**
129
     * Create a new FileChooserBuilder using the name of the passed class
130
     * as the metadata for looking up a starting directory from previous
131
     * application sessions or invocations.
132
     * @param type A non-null class object, typically the calling class
133
     */
134
    public FileChooserBuilder(Class type) {
135
        this(type.getName());
136
    }
137
138
    /**
139
     * Create a new FileChooserBuilder.  The passed key is used as a key
140
     * into NbPreferences to look up the directory the file chooser should
141
     * initially be rooted on.
142
     *
143
     * @param dirKey A non-null ad-hoc string.  If a FileChooser was previously
144
     * used with the same string as is passed, then the initial directory
145
     */
146
    public FileChooserBuilder(String dirKey) {
147
        Parameters.notNull("dirKey", dirKey);
148
        this.dirKey = dirKey;
149
    }
150
151
    /**
152
     * Set whether or not any file choosers created by this builder will show
153
     * only directories.
154
     * @param val true if files should not be shown
155
     * @return this
156
     */
157
    public FileChooserBuilder setDirectoriesOnly(boolean val) {
158
        dirsOnly = val;
159
        assert !filesOnly : "FilesOnly and DirsOnly are mutually exclusive";
160
        return this;
161
    }
162
163
    public FileChooserBuilder setFilesOnly(boolean val) {
164
        filesOnly = val;
165
        assert !dirsOnly : "FilesOnly and DirsOnly are mutually exclusive";
166
        return this;
167
    }
168
169
    /**
170
     * Provide an implementation of BadgeProvider which will "badge" the
171
     * icons of some files.
172
     *
173
     * @param provider A badge provider which will alter the icon of files
174
     * or folders that may be of particular interest to the user
175
     * @return this
176
     */
177
    public FileChooserBuilder setBadgeProvider(BadgeProvider provider) {
178
        this.badger = provider;
179
        return this;
180
    }
181
182
    /**
183
     * Set the dialog title for any JFileChoosers created by this builder.
184
     * @param val A localized, human-readable title
185
     * @return this
186
     */
187
    public FileChooserBuilder setTitle(String val) {
188
        title = val;
189
        return this;
190
    }
191
192
    /**
193
     * Set the text on the OK button for any file chooser dialogs produced
194
     * by this builder.
195
     * @param val A short, localized, human-readable string
196
     * @return this
197
     */
198
    public FileChooserBuilder setApproveText(String val) {
199
        approveText = val;
200
        return this;
201
    }
202
203
    /**
204
     * Set a file filter which filters the list of selectable files.
205
     * @param filter
206
     * @return this
207
     */
208
    public FileChooserBuilder setFileFilter (FileFilter filter) {
209
        this.filter = filter;
210
        return this;
211
    }
212
213
    /**
214
     * Determines whether the <code>AcceptAll FileFilter</code> is used
215
     * as an available choice in the choosable filter list.
216
     * If false, the <code>AcceptAll</code> file filter is removed from
217
     * the list of available file filters.
218
     * If true, the <code>AcceptAll</code> file filter will become the
219
     * the actively used file filter.
220
     * @param accept whether the <code>AcceptAll FileFilter</code> is used
221
     * @return this
222
     * @since 8.3
223
     */
224
    public FileChooserBuilder setAcceptAllFileFilterUsed(boolean accept) {
225
        useAcceptAllFileFilter = accept;
226
        return this;
227
    }
228
229
    /**
230
     * Set the current directory which should be used <b>only if</b>
231
     * a last-used directory cannot be found for the key string passed
232
     * into this builder's constructor.
233
     * @param dir A directory to root any created file choosers on if
234
     * there is no stored path for this builder's key
235
     * @return this
236
     */
237
    public FileChooserBuilder setDefaultWorkingDirectory (File dir) {
238
        failoverDir = dir;
239
        return this;
240
    }
241
242
    /**
243
     * Enable file hiding in any created file choosers
244
     * @param fileHiding Whether or not to hide files.  Default is no.
245
     * @return this
246
     */
247
    public FileChooserBuilder setFileHiding(boolean fileHiding) {
248
        this.fileHiding = fileHiding;
249
        return this;
250
    }
251
252
    /**
253
     * Show/hide control buttons
254
     * @param val Whether or not to hide files.  Default is no.
255
     * @return this
256
     */
257
    public FileChooserBuilder setControlButtonsAreShown(boolean val) {
258
        this.controlButtonsShown = val;
259
        return this;
260
    }
261
262
    /**
263
     * Set the accessible description for any file choosers created by this
264
     * builder
265
     * @param aDescription The description
266
     * @return this
267
     */
268
    public FileChooserBuilder setAccessibleDescription(String aDescription) {
269
        this.aDescription = aDescription;
270
        return this;
271
    }
272
273
    /**
274
     * Create a JFileChooser that conforms to the parameters set in this
275
     * builder.
276
     * @return A file chooser
277
     */
278
    public JFileChooser createFileChooser() {
279
        JFileChooser result = new SavedDirFileChooser(dirKey, failoverDir,
280
                force, approver);
281
        prepareFileChooser(result);
282
        return result;
283
    }
284
285
    private boolean force = false;
286
    /**
287
     * Force use of the failover directory - i.e. ignore the directory key
288
     * passed in.
289
     * @param val
290
     * @return this
291
     */
292
    public FileChooserBuilder forceUseOfDefaultWorkingDirectory(boolean val) {
293
        this.force = val;
294
        return this;
295
    }
296
297
    /**
298
     * Tries to find an appropriate component to parent the file chooser to
299
     * when showing a dialog.
300
     * @return this
301
     */
302
    private Component findDialogParent() {
303
        Component parent = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
304
        if (parent == null) {
305
            parent = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
306
        }
307
        if (parent == null) {
308
            Frame[] f = Frame.getFrames();
309
            parent = f.length == 0 ? null : f[f.length - 1];
310
        }
311
        return parent;
312
    }
313
314
    /**
315
     * Show an open dialog that allows multiple selection.
316
     * @return An array of files, or null if the user cancelled the dialog
317
     */
318
    public File[] showMultiOpenDialog() {
319
        JFileChooser chooser = createFileChooser();
320
        chooser.setMultiSelectionEnabled(true);
321
        int result = chooser.showOpenDialog(findDialogParent());
322
        if (JFileChooser.APPROVE_OPTION == result) {
323
            File[] files = chooser.getSelectedFiles();
324
            return files == null ? new File[0] : files;
325
        } else {
326
            return null;
327
        }
328
    }
329
330
    /**
331
     * Show an open dialog with a file chooser set up according to the
332
     * parameters of this builder.
333
     * @return A file if the user clicks the accept button and a file or
334
     * folder was selected at the time the user clicked cancel.
335
     */
336
    public File showOpenDialog() {
337
        JFileChooser chooser = createFileChooser();
338
        if( Boolean.getBoolean("nb.native.filechooser") ) { //NOI18N
339
            FileDialog fileDialog = createFileDialog( chooser.getCurrentDirectory() );
340
            if( null != fileDialog ) {
341
                return showFileDialog(fileDialog, FileDialog.LOAD );
342
            }
343
        }
344
        chooser.setMultiSelectionEnabled(false);
345
        int dlgResult = chooser.showOpenDialog(findDialogParent());
346
        if (JFileChooser.APPROVE_OPTION == dlgResult) {
347
            File result = chooser.getSelectedFile();
348
            if (result != null && !result.exists()) {
349
                result = null;
350
            }
351
            return result;
352
        } else {
353
            return null;
354
        }
355
356
    }
357
358
    /**
359
     * Show a save dialog with the file chooser set up according to the
360
     * parameters of this builder.
361
     * @return A file if the user clicks the accept button and a file or
362
     * folder was selected at the time the user clicked cancel.
363
     */
364
    public File showSaveDialog() {
365
        JFileChooser chooser = createFileChooser();
366
        if( Boolean.getBoolean("nb.native.filechooser") ) { //NOI18N
367
            FileDialog fileDialog = createFileDialog( chooser.getCurrentDirectory() );
368
            if( null != fileDialog ) {
369
                return showFileDialog( fileDialog, FileDialog.SAVE );
370
            }
371
        }
372
        int result = chooser.showSaveDialog(findDialogParent());
373
        if (JFileChooser.APPROVE_OPTION == result) {
374
            return chooser.getSelectedFile();
375
        } else {
376
            return null;
377
        }
378
    }
379
    
380
    private File showFileDialog( FileDialog fileDialog, int mode ) {
381
        String oldFileDialogProp = System.getProperty("apple.awt.fileDialogForDirectories"); //NOI18N
382
        if( dirsOnly ) {
383
            System.setProperty("apple.awt.fileDialogForDirectories", "true"); //NOI18N
384
        }
385
        fileDialog.setMode( mode );
386
        fileDialog.setVisible(true);
387
        if( dirsOnly ) {
388
            if( null != oldFileDialogProp ) {
389
                System.setProperty("apple.awt.fileDialogForDirectories", oldFileDialogProp); //NOI18N
390
            } else {
391
                System.clearProperty("apple.awt.fileDialogForDirectories"); //NOI18N
392
            }
393
        }
394
        if( fileDialog.getDirectory() != null && fileDialog.getFile() != null ) {
395
            String selFile = fileDialog.getFile();
396
            File dir = new File( fileDialog.getDirectory() );
397
            return new File( dir, selFile );
398
        }
399
        return null;
400
    }
401
    
402
    private void prepareFileChooser(JFileChooser chooser) {
403
        chooser.setFileSelectionMode(dirsOnly ? JFileChooser.DIRECTORIES_ONLY
404
                : filesOnly ? JFileChooser.FILES_ONLY :
405
                JFileChooser.FILES_AND_DIRECTORIES);
406
        chooser.setFileHidingEnabled(fileHiding);
407
        chooser.setControlButtonsAreShown(controlButtonsShown);
408
        chooser.setAcceptAllFileFilterUsed(useAcceptAllFileFilter);
409
        if (title != null) {
410
            chooser.setDialogTitle(title);
411
        }
412
        if (approveText != null) {
413
            chooser.setApproveButtonText(approveText);
414
        }
415
        if (badger != null) {
416
            chooser.setFileView(new CustomFileView(new BadgeIconProvider(badger),
417
                    chooser.getFileSystemView()));
418
        }
419
        if (PREVENT_SYMLINK_TRAVERSAL) {
420
            FileUtil.preventFileChooserSymlinkTraversal(chooser,
421
                    chooser.getCurrentDirectory());
422
        }
423
        if (filter != null) {
424
            chooser.setFileFilter(filter);
425
        }
426
        if (aDescription != null) {
427
            chooser.getAccessibleContext().setAccessibleDescription(aDescription);
428
        }
429
        if (!filters.isEmpty()) {
430
            for (FileFilter f : filters) {
431
                chooser.addChoosableFileFilter(f);
432
            }
433
        }
434
    }
435
436
    private FileDialog createFileDialog( File currentDirectory ) {
437
        if( badger != null )
438
            return null;
439
        if( !Boolean.getBoolean("nb.native.filechooser") )
440
            return null;
441
        if( dirsOnly && !BaseUtilities.isMac() )
442
            return null;
443
        Component parentComponent = findDialogParent();
444
        Frame parentFrame = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parentComponent);
445
        FileDialog fileDialog = new FileDialog(parentFrame);
446
        if (title != null) {
447
            fileDialog.setTitle(title);
448
        }
449
        if( null != currentDirectory )
450
            fileDialog.setDirectory(currentDirectory.getAbsolutePath());
451
        return fileDialog;
452
    }
453
    
454
    /**
455
     * Equivalent to calling <code>JFileChooser.addChoosableFileFilter(filter)</code>.
456
     * Adds another file filter that can be displayed in the file filters combo
457
     * box in the file chooser.
458
     *
459
     * @param filter The file filter to add
460
     * @return this
461
     * @since 7.26.0
462
     */
463
    public FileChooserBuilder addFileFilter (FileFilter filter) {
464
        filters.add (filter);
465
        return this;
466
    }
467
468
    /**
469
     * Add all default file filters to the file chooser.
470
     *
471
     * @see MIMEResolver.Registration#showInFileChooser()
472
     * @see MIMEResolver.ExtensionRegistration#showInFileChooser()
473
     * @return this
474
     * @since 8.1
475
     */
476
    public FileChooserBuilder addDefaultFileFilters() {
477
        filters.addAll(FileFilterSupport.findRegisteredFileFilters());
478
        return this;
479
    }
480
481
    /**
482
     * Set a selection approver which can display an &quot;Overwrite file?&quot;
483
     * or similar dialog if necessary, when the user presses the accept button
484
     * in the file chooser dialog.
485
     *
486
     * @param approver A SelectionApprover which will determine if the selection
487
     * is valid
488
     * @return this
489
     * @since 7.26.0
490
     */
491
    public FileChooserBuilder setSelectionApprover (SelectionApprover approver) {
492
        this.approver = approver;
493
        return this;
494
    }
495
496
    /**
497
     * Object which can approve the selection (enabling the OK button or
498
     * equivalent) in a JFileChooser.  Equivalent to overriding
499
     * <code>JFileChooser.approveSelection()</code>
500
     * @since 7.26.0
501
     */
502
    public interface SelectionApprover {
503
        /**
504
         * Approve the selection, enabling the dialog to be closed.  Called by
505
         * the JFileChooser's <code>approveSelection()</code> method.  Use this
506
         * interface if you want to, for example, show a dialog asking
507
         * &quot;Overwrite File X?&quot; or similar.
508
         *
509
         * @param selection The selected file(s) at the time the user presses
510
         * the Open, Save or OK button
511
         * @return true if the selection is accepted, false if it is not and
512
         * the dialog should not be closed
513
         */
514
        public boolean approve (File[] selection);
515
    }
516
517
    private static final class SavedDirFileChooser extends JFileChooser {
518
        private final String dirKey;
519
        private final SelectionApprover approver;
520
        SavedDirFileChooser(String dirKey, File failoverDir, boolean force, SelectionApprover approver) {
521
            this.dirKey = dirKey;
522
            this.approver = approver;
523
            if (force && failoverDir != null && failoverDir.exists() && failoverDir.isDirectory()) {
524
                setCurrentDirectory(failoverDir);
525
            } else {
526
                String path = DONT_STORE_DIRECTORIES ? null :
527
                    NbPreferences.forModule(FileChooserBuilder.class).get(dirKey, null);
528
                if (path != null) {
529
                    File f = new File(path);
530
                    if (f.exists() && f.isDirectory()) {
531
                        setCurrentDirectory(f);
532
                    } else if (failoverDir != null) {
533
                        setCurrentDirectory(failoverDir);
534
                    }
535
                } else if (failoverDir != null) {
536
                    setCurrentDirectory(failoverDir);
537
                }
538
            }
539
        }
540
541
        @Override
542
        public void approveSelection() {
543
            if (approver != null) {
544
                File[] selected = getSelectedFiles();
545
                final File sf = getSelectedFile();
546
                if ((selected == null || selected.length == 0) && sf != null) {
547
                    selected = new File[] { sf };
548
                }
549
                boolean approved = approver.approve(selected);
550
                if (approved) {
551
                    super.approveSelection();
552
                }
553
            } else {
554
                super.approveSelection();
555
            }
556
        }
557
558
        @Override
559
        public int showDialog(Component parent, String approveButtonText) throws HeadlessException {
560
            int result = super.showDialog(parent, approveButtonText);
561
            if (result == APPROVE_OPTION) {
562
                saveCurrentDir();
563
            }
564
            return result;
565
        }
566
567
        private void saveCurrentDir() {
568
            File dir = super.getCurrentDirectory();
569
            if (!DONT_STORE_DIRECTORIES && dir != null && dir.exists() && dir.isDirectory()) {
570
                NbPreferences.forModule(FileChooserBuilder.class).put(dirKey, dir.getPath());
571
            }
572
        }
573
    }
574
575
    //Can open this API later if there is a use-case
576
    interface IconProvider {
577
        public Icon getIcon(File file, Icon orig);
578
    }
579
580
    /**
581
     * Provides "badges" for icons that indicate files or folders of particular
582
     * interest to the user.
583
     * @see FileChooserBuilder#setBadgeProvider
584
     */
585
    public interface BadgeProvider {
586
        /**
587
         *  Get the badge the passed file should use.  <b>Note:</b> this method
588
         * is called for every visible file.  The negative test (deciding
589
         * <i>not</i> to badge a file) should be very, very fast and immediately
590
         * return null.
591
         * @param file The file in question
592
         * @return an icon or null if no change to the appearance of the file
593
         * is needed
594
         */
595
        public Icon getBadge(File file);
596
597
        /**
598
         * Get the x offset for badges produced by this provider.  This is
599
         * the location of the badge icon relative to the real icon for the
600
         * file.
601
         * @return  a rightward pixel offset
602
         */
603
        public int getXOffset();
604
605
        /**
606
         * Get the y offset for badges produced by this provider.  This is
607
         * the location of the badge icon relative to the real icon for the
608
         * file.
609
         * @return  a downward pixel offset
610
         */
611
        public int getYOffset();
612
    }
613
614
    private static final class BadgeIconProvider implements IconProvider {
615
616
        private final BadgeProvider badger;
617
618
        public BadgeIconProvider(BadgeProvider badger) {
619
            this.badger = badger;
620
        }
621
622
        public Icon getIcon(File file, Icon orig) {
623
            Icon badge = badger.getBadge(file);
624
            if (badge != null && orig != null) {
625
                return new MergedIcon(orig, badge, badger.getXOffset(),
626
                        badger.getYOffset());
627
            }
628
            return orig;
629
        }
630
    }
631
632
    private static final class CustomFileView extends FileView {
633
634
        private final IconProvider provider;
635
        private final FileSystemView view;
636
637
        CustomFileView(IconProvider provider, FileSystemView view) {
638
            this.provider = provider;
639
            this.view = view;
640
        }
641
642
        @Override
643
        public Icon getIcon(File f) {
644
            Icon result = view.getSystemIcon(f);
645
            result = provider.getIcon(f, result);
646
            return result;
647
        }
648
    }
649
650
    private static class MergedIcon implements Icon {
651
652
        private Icon icon1;
653
        private Icon icon2;
654
        private int xMerge;
655
        private int yMerge;
656
657
        MergedIcon(Icon icon1, Icon icon2, int xMerge, int yMerge) {
658
            assert icon1 != null;
659
            assert icon2 != null;
660
            this.icon1 = icon1;
661
            this.icon2 = icon2;
662
663
            if (xMerge == -1) {
664
                xMerge = icon1.getIconWidth() - icon2.getIconWidth();
665
            }
666
667
            if (yMerge == -1) {
668
                yMerge = icon1.getIconHeight() - icon2.getIconHeight();
669
            }
670
671
            this.xMerge = xMerge;
672
            this.yMerge = yMerge;
673
        }
674
675
        public int getIconHeight() {
676
            return Math.max(icon1.getIconHeight(), yMerge + icon2.getIconHeight());
677
        }
678
679
        public int getIconWidth() {
680
            return Math.max(icon1.getIconWidth(), yMerge + icon2.getIconWidth());
681
        }
682
683
        public void paintIcon(java.awt.Component c, java.awt.Graphics g, int x, int y) {
684
            icon1.paintIcon(c, g, x, y);
685
            icon2.paintIcon(c, g, x + xMerge, y + yMerge);
686
        }
687
    }
688
}
(-)a/openide.filesystems.nb/src/org/openide/filesystems/nb/Bundle.properties (+6 lines)
Line 0 Link Here
1
OpenIDE-Module-Display-Category=RCP Platform
2
OpenIDE-Module-Long-Description=\
3
    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. \
4
    Classes that use Swing UI library were factored out into this module.
5
OpenIDE-Module-Name=Filesystems NetBeans Client
6
OpenIDE-Module-Short-Description=Swing specific classes for Filesystems API
(-)a/openide.filesystems.nb/test/unit/src/org/netbeans/modules/openide/filesystems/FileFilterSupportTest.java (+113 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2012 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.modules.openide.filesystems;
43
44
import java.io.File;
45
import java.util.List;
46
import javax.swing.filechooser.FileFilter;
47
import org.netbeans.junit.NbTestCase;
48
import org.openide.filesystems.MIMEResolver;
49
import org.openide.util.NbBundle;
50
51
/**
52
 * Test registered FileFilters.
53
 *
54
 * @author jhavlin
55
 */
56
@NbBundle.Messages({
57
    "RESOLVER=Resolver",
58
    "FILECHOOSER=BNM Files"
59
})
60
@MIMEResolver.Registration(
61
    displayName = "#RESOLVER",
62
    resource = "mime-resolver-filechooser.xml",
63
    showInFileChooser = "#FILECHOOSER", position=543543)
64
public class FileFilterSupportTest extends NbTestCase {
65
66
    public FileFilterSupportTest(String name) {
67
        super(name);
68
    }
69
70
    /**
71
     * This test, although it is quite short, tests a lot of ascpects of default
72
     * file filters. The resolver definition XML file contains several
73
     * duplicities, which are detected and ignored. If this detection fails,
74
     * filter description and {@code accept} method is changed, and it is cought
75
     * by this test.
76
     */
77
    public void testRegisteredFilters() {
78
        List<FileFilter> list = FileFilterSupport.findRegisteredFileFilters();
79
        assertNotNull(list);
80
        assertFalse(list.isEmpty());
81
82
        boolean found = false;
83
        for (FileFilter filter : list) {
84
85
            if (filter.getDescription().startsWith("BNM Files")) {
86
                found = true;
87
                checkBnmFilesFilter(filter);
88
            }
89
        }
90
        assertTrue("Registered File Filter was not found.", found);
91
    }
92
93
    private void checkBnmFilesFilter(FileFilter f) {
94
        assertEquals("BNM Files [.bnm, bnmHelp, bnmProject, bnminfo, bnmsettings]",
95
                f.getDescription());
96
        assertTrue(f.accept(new File("first.bnm")));
97
        assertTrue(f.accept(new File("second.BNM")));
98
        assertTrue(f.accept(new File("third.bNm")));
99
        assertTrue(f.accept(new File("bnmProject")));
100
        assertTrue(f.accept(new File("PREFIXbnmProjectAndSuFfIx")));
101
        assertFalse(f.accept(new File("bnmproject")));
102
        assertTrue(f.accept(new File("bnmSettings")));
103
        assertTrue(f.accept(new File("BNMSETTINGS")));
104
        assertFalse(f.accept(new File("bnmSettingsX")));
105
        assertTrue(f.accept(new File("bnmInfo")));
106
        assertTrue(f.accept(new File("AbnmInfoB")));
107
        assertTrue(f.accept(new File("aBNMINFOb")));
108
        assertTrue(f.accept(new File("bnmHelp")));
109
        assertFalse(f.accept(new File("bnmhelp")));
110
        assertFalse(f.accept(new File("bnmHelpX")));
111
        assertFalse(f.accept(new File("foo.txt")));
112
    }
113
}
(-)a/openide.filesystems.nb/test/unit/src/org/netbeans/modules/openide/filesystems/SharedClassObjectFactoryTest.java (+101 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2014 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2014 Sun Microsystems, Inc.
41
 */
42
43
package org.netbeans.modules.openide.filesystems;
44
45
import java.io.File;
46
import java.util.logging.Level;
47
import java.util.logging.Logger;
48
import org.openide.filesystems.FileObject;
49
import org.openide.filesystems.FileUtil;
50
import org.openide.util.Lookup;
51
import org.openide.util.SharedClassObject;
52
import org.openide.util.lookup.Lookups;
53
import org.openide.util.lookup.NamedServicesLookupTest;
54
55
/**
56
 *
57
 * @author sdedic
58
 */
59
public class SharedClassObjectFactoryTest extends NamedServicesLookupTest {
60
    private FileObject root;
61
    private Logger LOG;
62
    
63
64
    public SharedClassObjectFactoryTest(String name) {
65
        super(name);
66
    }
67
    
68
    @Override
69
    protected Level logLevel() {
70
        return Level.FINEST;
71
    }
72
    
73
    @Override
74
    protected void setUp() throws Exception {
75
        if (System.getProperty("netbeans.user") == null) {
76
            System.setProperty("netbeans.user", new File(getWorkDir(), "ud").getPath());
77
        }
78
        
79
        LOG = Logger.getLogger("Test." + getName());
80
        
81
        root = FileUtil.getConfigRoot();
82
        for (FileObject fo : root.getChildren()) {
83
            fo.delete();
84
        }
85
        
86
        super.setUp();
87
    }
88
    
89
    public void testSharedClassObject() throws Exception {
90
        Shared instance = SharedClassObject.findObject(Shared.class, true);
91
        FileObject data = FileUtil.createData(root, "dir/" + Shared.class.getName().replace('.', '-') + ".instance");
92
        Lookup l = Lookups.forPath("dir");
93
        assertSame(instance, l.lookup(Shared.class));
94
        
95
        Shared created = FileUtil.getConfigObject(data.getPath(), Shared.class);
96
        assertSame("Config file found", instance, created);
97
    }
98
    
99
    public static final class Shared extends SharedClassObject {}
100
101
}
(-)a/openide.filesystems.nb/test/unit/src/org/netbeans/modules/openide/filesystems/mime-resolver-filechooser.xml (+63 lines)
Line 0 Link Here
1
<?xml version="1.0"?>
2
<MIME-resolver>
3
    <file>
4
        <ext name="bnm"/>
5
        <resolver mime="text/x-bnm"/>
6
    </file>
7
8
    <!-- BNM PROJECT -->
9
    <file>
10
        <!--
11
            Duplicite resolver that accept less files than the following one.
12
            Should not be used in the filter.
13
        -->
14
        <ext name=""/>
15
        <name name="bnmProject" substring="false" ignorecase="false" />
16
        <resolver mime="text/x-bnm-project"/>
17
    </file>
18
    <file>
19
        <ext name=""/>
20
        <name name="bnmProject" substring="true" ignorecase="false" />
21
        <resolver mime="text/x-bnm-project"/>
22
    </file>
23
24
    <!-- BNM SETTINGS -->
25
    <file>
26
        <ext name=""/>
27
        <name name="bnmSettings" substring="false" />
28
        <resolver mime="text/x-bnm-settings"/>
29
    </file>
30
    <file>
31
        <!--
32
            Duplicite resolver that accept less files than the previous one.
33
            Should not be used in the filter.
34
        -->
35
        <ext name=""/>
36
        <name name="bnmSettings" substring="false" ignorecase="true" />
37
        <resolver mime="text/x-bnm-settings"/>
38
    </file>
39
40
    <!-- BNM INFO -->
41
    <file>
42
        <ext name=""/>
43
        <name name="bnmInfo" substring="true" />
44
        <resolver mime="text/x-bnm-info"/>
45
    </file>
46
    <file>
47
        <!--
48
            Duplicite resolver that accept the same files as the previous one,
49
            only differs in case of file name, that is ignored.
50
            Should not be used in the filter.
51
        -->
52
        <ext name=""/>
53
        <name name="BNMInfo" substring="true" />
54
        <resolver mime="text/x-bnm-info"/>
55
    </file>
56
57
    <!-- BNM HELP -->
58
    <file>
59
        <ext name=""/>
60
        <name name="bnmHelp" substring="false" ignorecase="false" />
61
        <resolver mime="text/x-bnm-help"/>
62
    </file>
63
</MIME-resolver>
(-)a/openide.filesystems.nb/test/unit/src/org/openide/filesystems/FileChooserBuilderTest.java (+417 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2008 Sun Microsystems, Inc.
41
 */
42
43
package org.openide.filesystems;
44
45
import java.awt.Component;
46
import java.awt.Dialog;
47
import javax.swing.UIManager;
48
import javax.swing.JRootPane;
49
import java.util.concurrent.atomic.AtomicReference;
50
import java.lang.reflect.InvocationTargetException;
51
import java.util.concurrent.CountDownLatch;
52
import java.awt.Container;
53
import java.awt.EventQueue;
54
import java.io.File;
55
import java.io.IOException;
56
import java.util.Arrays;
57
import java.util.HashSet;
58
import java.util.Set;
59
import javax.swing.AbstractButton;
60
import javax.swing.JFileChooser;
61
import javax.swing.RootPaneContainer;
62
import javax.swing.UnsupportedLookAndFeelException;
63
import javax.swing.event.AncestorEvent;
64
import javax.swing.event.AncestorListener;
65
import javax.swing.filechooser.FileFilter;
66
import javax.swing.plaf.metal.MetalLookAndFeel;
67
import org.netbeans.junit.NbTestCase;
68
import org.openide.util.RequestProcessor;
69
import static org.junit.Assert.*;
70
import org.netbeans.junit.RandomlyFails;
71
72
/**
73
 * @author tim
74
 */
75
public class FileChooserBuilderTest extends NbTestCase {
76
77
    public FileChooserBuilderTest(String name) {
78
        super(name);
79
    }
80
81
    /**
82
     * Test of setDirectoriesOnly method, of class FileChooserBuilder.
83
     */
84
    public void testSetDirectoriesOnly() {
85
        FileChooserBuilder instance = new FileChooserBuilder("x");
86
        boolean dirsOnly = instance.createFileChooser().getFileSelectionMode() == JFileChooser.DIRECTORIES_ONLY;
87
        assertFalse(dirsOnly);
88
        instance.setDirectoriesOnly(true);
89
        dirsOnly = instance.createFileChooser().getFileSelectionMode() == JFileChooser.DIRECTORIES_ONLY;
90
        assertTrue(dirsOnly);
91
    }
92
93
    /**
94
     * Test of setFilesOnly method, of class FileChooserBuilder.
95
     */
96
    public void testSetFilesOnly() {
97
        FileChooserBuilder instance = new FileChooserBuilder("y");
98
        boolean filesOnly = instance.createFileChooser().getFileSelectionMode() == JFileChooser.FILES_ONLY;
99
        assertFalse(filesOnly);
100
        instance.setFilesOnly(true);
101
        filesOnly = instance.createFileChooser().getFileSelectionMode() == JFileChooser.FILES_ONLY;
102
        assertTrue(filesOnly);
103
    }
104
105
    /**
106
     * Test of setTitle method, of class FileChooserBuilder.
107
     */
108
    public void testSetTitle() {
109
        FileChooserBuilder instance = new FileChooserBuilder("a");
110
        assertNull(instance.createFileChooser().getDialogTitle());
111
        instance.setTitle("foo");
112
        assertEquals("foo", instance.createFileChooser().getDialogTitle());
113
    }
114
115
    /**
116
     * Test of setApproveText method, of class FileChooserBuilder.
117
     */
118
    public void testSetApproveText() {
119
        FileChooserBuilder instance = new FileChooserBuilder("b");
120
        assertNull(instance.createFileChooser().getDialogTitle());
121
        instance.setApproveText("bar");
122
        assertEquals("bar", instance.createFileChooser().getApproveButtonText());
123
    }
124
125
    /**
126
     * Test of setFileFilter method, of class FileChooserBuilder.
127
     */
128
    public void testSetFileFilter() {
129
        FileFilter filter = new FileFilter() {
130
131
            @Override
132
            public boolean accept(File f) {
133
                return true;
134
            }
135
136
            @Override
137
            public String getDescription() {
138
                return "X";
139
            }
140
        };
141
        FileChooserBuilder instance = new FileChooserBuilder("c");
142
        instance.setFileFilter(filter);
143
        assertEquals(filter, instance.createFileChooser().getFileFilter());
144
    }
145
146
    /**
147
     * Test of setDefaultWorkingDirectory method, of class FileChooserBuilder.
148
     */
149
    public void testSetDefaultWorkingDirectory() throws IOException {
150
        FileChooserBuilder instance = new FileChooserBuilder("d");
151
        File dir = getWorkDir();
152
        assertTrue("tmpdir is not sane", dir.exists() && dir.isDirectory());
153
        instance.setDefaultWorkingDirectory(dir);
154
        assertEquals(dir, instance.createFileChooser().getCurrentDirectory());
155
    }
156
157
    /**
158
     * Test of setFileHiding method, of class FileChooserBuilder.
159
     */
160
    public void testSetFileHiding() {
161
        FileChooserBuilder instance = new FileChooserBuilder("e");
162
        assertFalse(instance.createFileChooser().isFileHidingEnabled());
163
        instance.setFileHiding(true);
164
        assertTrue(instance.createFileChooser().isFileHidingEnabled());
165
    }
166
167
    /**
168
     * Test of setControlButtonsAreShown method, of class FileChooserBuilder.
169
     */
170
    public void testSetControlButtonsAreShown() {
171
        FileChooserBuilder instance = new FileChooserBuilder("f");
172
        assertTrue(instance.createFileChooser().getControlButtonsAreShown());
173
        instance.setControlButtonsAreShown(false);
174
        assertFalse(instance.createFileChooser().getControlButtonsAreShown());
175
    }
176
177
    /**
178
     * Test of setAccessibleDescription method, of class FileChooserBuilder.
179
     */
180
    public void testSetAccessibleDescription() {
181
        FileChooserBuilder instance = new FileChooserBuilder("g");
182
        String desc = "desc";
183
        instance.setAccessibleDescription(desc);
184
        assertEquals(desc, instance.createFileChooser().getAccessibleContext().getAccessibleDescription());
185
    }
186
187
    /**
188
     * Test of createFileChooser method, of class FileChooserBuilder.
189
     */
190
    public void testCreateFileChooser() {
191
        FileChooserBuilder instance = new FileChooserBuilder("h");
192
        assertNotNull(instance.createFileChooser());
193
    }
194
195
    public void testSetSelectionApprover() throws Exception {
196
        FileChooserBuilder instance = new FileChooserBuilder("i");
197
        File tmp = new File(System.getProperty("java.io.tmpdir"));
198
        assertTrue ("Environment is insane", tmp.exists() && tmp.isDirectory());
199
        File sel = new File("tmp" + System.currentTimeMillis());
200
        if (!sel.exists()) {
201
            assertTrue (sel.createNewFile());
202
        }
203
        instance.setDefaultWorkingDirectory(tmp);
204
        SA sa = new SA();
205
        instance.setSelectionApprover(sa);
206
        JFileChooser ch = instance.createFileChooser();
207
        ch.setSelectedFile(sel);
208
        ch.approveSelection();
209
        sa.assertApproveInvoked(sel);
210
    }
211
212
    public void testAddFileFilter() {
213
        FileChooserBuilder instance = new FileChooserBuilder("j");
214
        FF one = new FF ("a");
215
        FF two = new FF ("b");
216
        instance.addFileFilter(one);
217
        instance.addFileFilter(two);
218
        JFileChooser ch = instance.createFileChooser();
219
        Set<FileFilter> ff = new HashSet<FileFilter>(Arrays.asList(one, two));
220
        Set<FileFilter> actual = new HashSet<FileFilter>(Arrays.asList(ch.getChoosableFileFilters()));
221
        assertTrue (actual.containsAll(ff));
222
        //actual should also contain JFileChooser.getAcceptAllFileFilter()
223
        assertEquals (ff.size() + 1, actual.size());
224
    }
225
226
    public void testSetAcceptAllFileFilterUsed() {
227
        FileChooserBuilder instance = new FileChooserBuilder("k");
228
        assertTrue(instance.createFileChooser().isAcceptAllFileFilterUsed());
229
        instance.setAcceptAllFileFilterUsed(false);
230
        assertFalse(instance.createFileChooser().isAcceptAllFileFilterUsed());
231
    }
232
233
    private static final class FF extends FileFilter {
234
        private String x;
235
        FF(String x) {
236
            this.x = x;
237
        }
238
239
        @Override
240
        public boolean accept(File f) {
241
            return f.getName().endsWith(x);
242
        }
243
244
        @Override
245
        public String getDescription() {
246
            return x;
247
        }
248
249
    }
250
251
    private static final class SA implements FileChooserBuilder.SelectionApprover {
252
        private File[] selection;
253
        @Override
254
        public boolean approve(File[] selection) {
255
            this.selection = selection;
256
            return true;
257
        }
258
259
        void assertApproveInvoked(File selected) {
260
            assertNotNull ("approve method called", selection);
261
            assertEquals("One selected file", 1, selection.length);
262
            assertEquals("It is the one", selected, selection[0]);
263
        }
264
    }
265
266
    private static AbstractButton findDefaultButton(Container c, String txt) {
267
        if (c instanceof RootPaneContainer) {
268
            JRootPane root = ((RootPaneContainer) c).getRootPane();
269
            if (root == null) {
270
                return null;
271
            }
272
            AbstractButton btn = root.getDefaultButton();
273
            if (btn == null) {
274
                //Metal L&F does not set default button for JFileChooser
275
                Container parent = c;
276
                while (parent.getParent() != null && !(parent instanceof Dialog)) {
277
                    parent = parent.getParent();
278
                }
279
                if (parent instanceof Dialog) {
280
                    return findFileChooserAcceptButton ((Dialog) parent, txt);
281
                }
282
            } else {
283
                return btn;
284
            }
285
        }
286
        return null;
287
    }
288
289
    private static AbstractButton findFileChooserAcceptButton(Dialog dlg, String txt) {
290
        for (Component c : dlg.getComponents()) {
291
            if (c instanceof Container) {
292
                AbstractButton result = scanForButton((Container) c, txt);
293
                if (result != null) {
294
                    return result;
295
                }
296
            }
297
        }
298
        return null;
299
    }
300
301
    private static AbstractButton scanForButton(Container container, String txt) {
302
        assertNotNull (container);
303
        assertNotNull (txt);
304
        if (container instanceof AbstractButton) {
305
            if (txt.equals(((AbstractButton) container).getText())) {
306
                return ((AbstractButton) container);
307
            }
308
        } else {
309
            for (Component c : container.getComponents()) {
310
                if (c instanceof Container) {
311
                    AbstractButton b = scanForButton ((Container) c, txt);
312
                    if (b != null) {
313
                        return b;
314
                    }
315
                }
316
            }
317
        }
318
        return null;
319
    }
320
321
    @RandomlyFails // NB-Core-Build #8038: Button is visible
322
    public void testForceUseOfDefaultWorkingDirectory() throws InterruptedException, IOException, InvocationTargetException, UnsupportedLookAndFeelException {
323
        UIManager.setLookAndFeel(new MetalLookAndFeel());
324
        FileChooserBuilder instance = new FileChooserBuilder("i").setApproveText("__OK");
325
        instance.setDirectoriesOnly(true);
326
        final File toDir = getWorkDir();
327
        final File selDir = new File(toDir, "sel" + System.currentTimeMillis());
328
        if (!selDir.exists()) {
329
            assertTrue(selDir.mkdirs());
330
        }
331
332
        final JFileChooser ch = instance.createFileChooser();
333
        assertEquals ("__OK", ch.getApproveButtonText());
334
        final CountDownLatch showLatch = new CountDownLatch(1);
335
        ch.addAncestorListener (new AncestorListener() {
336
337
            @Override
338
            public void ancestorAdded(AncestorEvent event) {
339
                if (ch.isShowing()) {
340
                    ch.removeAncestorListener(this);
341
                    showLatch.countDown();
342
                }
343
            }
344
345
            @Override
346
            public void ancestorRemoved(AncestorEvent event) {
347
348
            }
349
350
            @Override
351
            public void ancestorMoved(AncestorEvent event) {
352
353
            }
354
355
        });
356
357
        final AtomicReference<Object> chooserRes = new AtomicReference<Object>();
358
        RequestProcessor.Task task = RequestProcessor.getDefault().post(new Runnable() {
359
360
            @Override
361
            public void run() {
362
                Object r = ch.showOpenDialog(null);
363
                chooserRes.set(r);
364
            }
365
366
        });
367
368
369
        showLatch.await();
370
        EventQueue.invokeAndWait (new Runnable() {
371
            @Override
372
            public void run() {
373
                ch.setCurrentDirectory(toDir);
374
            }
375
        });
376
        EventQueue.invokeAndWait (new Runnable() {
377
            @Override
378
            public void run() {
379
                ch.setSelectedFile (selDir);
380
            }
381
        });
382
        assertTrue ("Button is visible: " + ch, ch.isShowing());
383
        final AtomicReference<AbstractButton> btn = new AtomicReference<AbstractButton>();
384
        EventQueue.invokeAndWait(new Runnable() {
385
386
            @Override
387
            public void run() {
388
                AbstractButton defButton = findDefaultButton(ch.getTopLevelAncestor(), ch.getApproveButtonText());
389
                btn.set(defButton);
390
            }
391
392
        });
393
        assertNotNull("have a button", btn.get());
394
        assertTrue(btn.get().isEnabled());
395
        EventQueue.invokeAndWait(new Runnable() {
396
            @Override
397
            public void run() {
398
                AbstractButton defButton = btn.get();
399
                defButton.doClick();
400
            }
401
        });
402
403
        task.waitFinished();
404
        assertEquals(JFileChooser.APPROVE_OPTION, chooserRes.get());
405
406
        assertEquals(toDir, ch.getCurrentDirectory());
407
408
        instance = new FileChooserBuilder("i");
409
        assertEquals("Directory not retained", toDir, instance.createFileChooser().getCurrentDirectory());
410
411
        File userHome = new File(System.getProperty("user.home"));
412
        assertTrue("Environment not sane", userHome.exists() && userHome.isDirectory());
413
        instance.forceUseOfDefaultWorkingDirectory(true).setDefaultWorkingDirectory(userHome);
414
415
        assertEquals(userHome, instance.createFileChooser().getCurrentDirectory());
416
    }
417
}
(-)a/openide.filesystems/apichanges.xml (+75 lines)
Lines 49-54 Link Here
49
        <apidef name="filesystems">Filesystems API</apidef>
49
        <apidef name="filesystems">Filesystems API</apidef>
50
    </apidefs>
50
    </apidefs>
51
    <changes>
51
    <changes>
52
        <change id="FileSystemStatus.icons">
53
            <api name="filesystems"/>
54
            <summary>FileSystem.Status icon annotation moved</summary>
55
            <version major="9" minor="0"/>
56
            <date year="2014" month="4" day="11"/>
57
            <author login="sdedic"/>
58
            <compatibility modification="yes" addition="yes" binary="compatible" source="compatible" semantic="incompatible"/>
59
            <description>
60
                <p>
61
                    The default implementation of FileSystem.Status annotated file's icon using ImageUtilities
62
                    which uses AWT graphics etc. Such dependency is not desirable in a standalone FileSystem API
63
                    library.
64
                </p>
65
                <p>
66
                    The builtin implementation now does not work with the icon at all and returns null. A proper
67
                    implementation for FileSystem.Status is looked up in default Lookup and is implemented
68
                    properly (with Icon annotations) in <code>openide.filesystems.nb</code> module.
69
                </p>
70
            </description>
71
            <issue number="243561"/>
72
        </change>
73
        <change id="SharedClassObject.separate">
74
            <api name="filesystems"/>
75
            <summary>Removed dependency on SharedClassObject</summary>
76
            <version major="9" minor="0"/>
77
            <date year="2014" month="4" day="11"/>
78
            <author login="sdedic"/>
79
            <compatibility modification="yes" addition="yes" binary="compatible" source="compatible" semantic="incompatible"/>
80
            <description>
81
                <p>
82
                    If the FileSystems API encounters a <a href="@openide-util@/org/openide/util/SharedClassObject.html#find">SharedClassObject</a> subclass in the <code>instanceClass</code> attribute,
83
                    or derives the subclass from FileObject's name, it does not create the instance using the default
84
                    constructor, but rather using <a href="@openide-util@/org/openide/util/SharedClassObject.html#find">SharedClassObject.find</a>
85
                    method.
86
                    The <code>SharedClassObject</code> is long deprecated and adds unwanted dependency on desktop
87
                    utilities to FileSystems API. 
88
                </p>
89
                <p>
90
                    A new SPI, <a href="@TOP@/org/openide/filesystems/spi/CustomInstanceFactory.html">CustomInstanceFactory</a> is created
91
                    to create instances based on the type. The instance is searched for in the default Lookup. 
92
                    The NetBeans Platform will provide an implementation that handles <code>SharedClassObjects</code>,
93
                    but FileSystems API library no longer implements that behaviour. A compatible implementation
94
                    of <code>CustomInstanceFactory</code> is provided by the <code>openide.filesystems.nb</code>
95
                    module.
96
                </p>
97
            </description>
98
            <issue number="243561"/>
99
        </change>
100
        <change id="RemoveDeprecatedAndObsolete.8">
101
            <api name="filesystems"/>
102
            <summary>Remove dependency on Swing (SystemAction) and obsolete APIs</summary>
103
            <version major="9" minor="0"/>
104
            <date year="2014" month="4" day="11"/>
105
            <author login="sdedic"/>
106
            <compatibility modification="yes" binary="compatible" source="incompatible" deletion="yes" semantic="compatible"/>
107
            <description>
108
                <p>
109
                    The primary goal of the change is to remove dependencies on Swing APIs - FileSystems should not depend
110
                    or directly use <code>SystemAction</code> extends <code>javax.swing.Action</code>. At the same time, 
111
                    methods or classes which are long @deprecated and have no semantic value are removed from the APIs.
112
                </p>
113
                <p>
114
                    The changes are binary-compatible; a compatibility module is created as <code>org.openide.filesystems.compat8</code>.
115
                    Live code (<a href="@openide-filesystems-compat8@/org/openide/filesystems/FileChooserBuilder.html">FileChooserBuilder</a>
116
                    is moved to a new module <code>org.openide.filesystems.nb</code> with automatic dependency in place for client which
117
                    use filesystems in their old API version.
118
                </p>
119
                <p>
120
                    It's strongly discouraged to compile against the <code>compat8</code> module. Its contents will be maintained only to
121
                    ensure binary compatibility with FileSystems API 8.x, API users should not rely on any contract exposed directly by the compat8
122
                    module.
123
                </p>
124
            </description>
125
            <issue number="243561"/>
126
        </change>
52
        <change id="MultiFileObject.revealEntriesAttribute">
127
        <change id="MultiFileObject.revealEntriesAttribute">
53
            <api name="filesystems"/>
128
            <api name="filesystems"/>
54
            <summary>Allowed to reveal deleted files, or original files overriden by writable layer</summary>
129
            <summary>Allowed to reveal deleted files, or original files overriden by writable layer</summary>
(-)a/openide.filesystems/arch.xml (-2 / +10 lines)
Lines 544-550 Link Here
544
        </question>
544
        </question>
545
-->
545
-->
546
<answer id="lookup-lookup">
546
<answer id="lookup-lookup">
547
Implementations of MIMEResolver and URLMapper are looked up .
547
    The following services are looked up:
548
    <ul>
549
        <li>Implementations of MIMEResolver and URLMapper are looked up</li>
550
        <li>instance of <a href="@TOP@/org/openide/filesystems/FileSystem.Status.html">FileSystem.Status</a> which is
551
            used as the Status of the <b>default</b> FileSystem</li>
552
        <li>instance of <a href="@TOP@/org/openide/filesystems/spi/CustomInstanceFactory.html">CustomInstanceFactory</a>
553
            which is used to create instances for FileSystem files without <code>instanceCreate</code> attribute</li>
554
    </ul>
548
</answer>
555
</answer>
549
556
550
557
Lines 560-566 Link Here
560
        </question>
567
        </question>
561
-->
568
-->
562
<answer id="lookup-register">
569
<answer id="lookup-register">
563
No
570
    <code>URLStreamHandlerFactory</code> implementations for <b>nbfs:</b> and
571
    <b>memory:</b> protocols are registered as named services.
564
</answer>
572
</answer>
565
573
566
574
(-)a/openide.filesystems/manifest.mf (-1 / +1 lines)
Lines 2-6 Link Here
2
OpenIDE-Module: org.openide.filesystems
2
OpenIDE-Module: org.openide.filesystems
3
OpenIDE-Module-Localizing-Bundle: org/openide/filesystems/Bundle.properties
3
OpenIDE-Module-Localizing-Bundle: org/openide/filesystems/Bundle.properties
4
OpenIDE-Module-Layer: org/openide/filesystems/resources/layer.xml
4
OpenIDE-Module-Layer: org/openide/filesystems/resources/layer.xml
5
OpenIDE-Module-Specification-Version: 8.11
5
OpenIDE-Module-Specification-Version: 9.0
6
6
(-)a/openide.filesystems/module-auto-deps.xml (+15 lines)
Lines 61-64 Link Here
61
        </transformation>
61
        </transformation>
62
    </transformationgroup>
62
    </transformationgroup>
63
63
64
    <transformationgroup>
65
        <description>Separation of desktop and cleanup</description>
66
        <transformation>
67
            <trigger-dependency type="older">
68
                <module-dependency codenamebase="org.openide.filesystems" spec="9.0"/>
69
            </trigger-dependency>
70
            <implies>
71
                <result>
72
                    <module-dependency codenamebase="org.openide.filesystems.nb"/>
73
                    <module-dependency codenamebase="org.openide.filesystems.compat8"/>
74
                </result>
75
            </implies>
76
        </transformation>
77
    </transformationgroup>
78
64
</transformations>
79
</transformations>
(-)a/openide.filesystems/nbproject/project.xml (-9 / +7 lines)
Lines 50-63 Link Here
50
            <code-name-base>org.openide.filesystems</code-name-base>
50
            <code-name-base>org.openide.filesystems</code-name-base>
51
            <module-dependencies>
51
            <module-dependencies>
52
                <dependency>
52
                <dependency>
53
                    <code-name-base>org.openide.util</code-name-base>
54
                    <build-prerequisite/>
55
                    <compile-dependency/>
56
                    <run-dependency>
57
                        <specification-version>9.0</specification-version>
58
                    </run-dependency>
59
                </dependency>
60
                <dependency>
61
                    <code-name-base>org.openide.util.base</code-name-base>
53
                    <code-name-base>org.openide.util.base</code-name-base>
62
                    <build-prerequisite/>
54
                    <build-prerequisite/>
63
                    <compile-dependency/>
55
                    <compile-dependency/>
Lines 91-98 Link Here
91
                        <recursive/>
83
                        <recursive/>
92
                        <compile-dependency/>
84
                        <compile-dependency/>
93
                    </test-dependency>
85
                    </test-dependency>
86
<!--                    <test-dependency>
87
                        <code-name-base>org.openide.util</code-name-base>
88
                        <compile-dependency/>
89
                        <test/>
90
                    </test-dependency>-->
94
                    <test-dependency>
91
                    <test-dependency>
95
                        <code-name-base>org.openide.util</code-name-base>
92
                        <code-name-base>org.openide.util.base</code-name-base>
96
                        <compile-dependency/>
93
                        <compile-dependency/>
97
                        <test/>
94
                        <test/>
98
                    </test-dependency>
95
                    </test-dependency>
Lines 106-111 Link Here
106
            <public-packages>
103
            <public-packages>
107
                <package>org.openide.filesystems</package>
104
                <package>org.openide.filesystems</package>
108
                <package>org.openide.filesystems.annotations</package>
105
                <package>org.openide.filesystems.annotations</package>
106
                <package>org.openide.filesystems.spi</package>
109
            </public-packages>
107
            </public-packages>
110
        </data>
108
        </data>
111
    </configuration>
109
    </configuration>
(-)a/openide.filesystems/src/org/netbeans/modules/openide/filesystems/FileFilterSupport.java (-470 lines)
Lines 1-470 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2012 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.modules.openide.filesystems;
43
44
import java.io.File;
45
import java.util.ArrayList;
46
import java.util.Collections;
47
import java.util.Comparator;
48
import java.util.HashMap;
49
import java.util.HashSet;
50
import java.util.LinkedList;
51
import java.util.List;
52
import java.util.Map;
53
import java.util.Set;
54
import java.util.logging.Level;
55
import java.util.logging.Logger;
56
import java.util.regex.Matcher;
57
import java.util.regex.Pattern;
58
import javax.swing.filechooser.FileFilter;
59
import org.openide.filesystems.FileObject;
60
import org.openide.filesystems.FileUtil;
61
62
/**
63
 * Support methods for creation of registered {@link FileFilter file filters}.
64
 */
65
public final class FileFilterSupport {
66
67
    /**
68
     * The logger.
69
     */
70
    private static final Logger LOG = Logger.getLogger(
71
            FileFilterSupport.class.getName());
72
73
    /**
74
     * Hide the default constructor.
75
     */
76
    private FileFilterSupport() {
77
    }
78
79
    /**
80
     * Construct description for {@link FileFilter} that accepts files with
81
     * specified extension.
82
     *
83
     * @param displayName Human readable display name (e.g. "HTML files")
84
     * @param elements List of accepted filter elements.
85
     *
86
     * @return Display name (description) for the filter.
87
     */
88
    private static String constructFilterDisplayName(String displayName,
89
            List<FilterElement> elements) {
90
        StringBuilder sb = new StringBuilder(displayName);
91
        boolean first = true;
92
        sb.append(" [");                                                //NOI18N
93
        for (FilterElement el : elements) {
94
            if (first) {
95
                first = false;
96
            } else {
97
                sb.append(", ");                                        //NOI18N
98
            }
99
            sb.append(el.getName());
100
        }
101
        sb.append("]");                                                 //NOI18N
102
        return sb.toString();
103
    }
104
105
    /**
106
     * Check whether passed file is accepted by filter for specified list of
107
     * extensions.
108
     *
109
     * @param file File to be accepted or rejected.
110
     * @param elements List of accepted filter elements.
111
     *
112
     * @return True if the file is accepted, false if it is rejected.
113
     *
114
     * @see FileFilterSupport
115
     */
116
    private static boolean accept(File file, List<FilterElement> elements) {
117
        if (file != null) {
118
            if (file.isDirectory()) {
119
                return true;
120
            }
121
            for (FilterElement elm : elements) {
122
                if (elm.accept(file)) {
123
                    return true;
124
                }
125
            }
126
        }
127
        return false;
128
    }
129
130
    public static List<FileFilter> findRegisteredFileFilters() {
131
        List<FileFilter> filters = new LinkedList<FileFilter>();
132
        FileObject root = FileUtil.getConfigFile(
133
                "Services/MIMEResolver");                               //NOI18N
134
        Map<String, Set<FileObject>> filterNameToResolversMap =
135
                new HashMap<String, Set<FileObject>>();
136
        for (FileObject child : root.getChildren()) {
137
            if (child.isFolder()) {
138
                continue;
139
            }
140
            int i = 0;
141
            String f;
142
            while ((f = (String) child.getAttribute("fileChooser." + i))//NOI18N
143
                    != null) {
144
                Set<FileObject> set = filterNameToResolversMap.get(f);
145
                if (set == null) {
146
                    set = new HashSet<FileObject>();
147
                    filterNameToResolversMap.put(f, set);
148
                }
149
                set.add(child);
150
                i++;
151
            }
152
        }
153
        for (Map.Entry<String, Set<FileObject>> e :
154
                filterNameToResolversMap.entrySet()) {
155
            filters.add(createFilter(e.getKey(), e.getValue()));
156
        }
157
        return sortFiltersByDescription(filters);
158
    }
159
160
    private static FileFilter createFilter(final String name,
161
            final Set<FileObject> resolvers) {
162
        ArrayList<FilterElement> elems = new ArrayList<FilterElement>(3);
163
        String lastAtt;
164
        for (FileObject fo : resolvers) {
165
            int i = 0;
166
            while ((lastAtt = (String) fo.getAttribute(
167
                    "ext." + i)) != null) { //NOI18N
168
                addExtensionToList(elems, lastAtt);
169
                i++;
170
            }
171
            int n = 0;
172
            while ((lastAtt = (String) fo.getAttribute("fileName." //NOI18N
173
                    + (n++))) != null) {
174
                addNameToList(elems, lastAtt);
175
            }
176
            String type;
177
            if ((type = (String) fo.getAttribute("mimeType")) != null) {//NOI18N
178
                addMimeTypeExts(elems, type);
179
            }
180
            int t = 0;
181
            while ((type = (String) fo.getAttribute(
182
                    "mimeType." + (t++))) != null) {     //NOI18N
183
                addMimeTypeExts(elems, type);
184
            }
185
        }
186
        sortFilterElements(elems);
187
        return new FileFilterImpl(name, elems);
188
    }
189
190
    /**
191
     * Add all extensions assigned to a MIME Type to the extension list.
192
     */
193
    private static void addMimeTypeExts(List<FilterElement> exts, String type) {
194
        addAllExtensionsToList(exts, FileUtil.getMIMETypeExtensions(type));
195
    }
196
197
    /**
198
     * Add new items to list of extensions, prevent duplicates.
199
     *
200
     * @param list List of extensions to alter.
201
     * @param toAdd List of extensions (without starting dot) to add.
202
     */
203
    private static void addAllExtensionsToList(List<FilterElement> list,
204
            List<String> toAdd) {
205
        for (String s : toAdd) {
206
            addExtensionToList(list, s);
207
        }
208
    }
209
210
    /**
211
     * Add new item to list of extensions, prevent duplacates.
212
     *
213
     * @param list List of extensions to alter.
214
     * @param s Extensions without starting dot.
215
     */
216
    private static void addExtensionToList(List<FilterElement> list,
217
            String ext) {
218
        addFilterElementToList(list, FilterElement.createForExtension(ext));
219
    }
220
221
    private static void addNameToList(List<FilterElement> list, String name) {
222
        Pattern p = Pattern.compile(
223
                "\\[([^,]+), (true|false), (true|false)\\](\\S*)");     //NOI18N
224
        Matcher m = p.matcher(name);
225
        if (m.find()) {
226
            String fileName = m.group(1);
227
            boolean substring = m.group(2).equals("true");              //NOI18N
228
            boolean ignoreCase = m.group(3).equals("true");             //NOI18N
229
            String extension = m.group(4);
230
            addFilterElementToList(list, FilterElement.createForFileName(
231
                    fileName, extension, substring, ignoreCase));
232
        } else {
233
            LOG.log(Level.INFO, "Incorrect name pattern {0}", name);    //NOI18N
234
        }
235
    }
236
237
    private static void addFilterElementToList(List<FilterElement> list,
238
            FilterElement newItem) {
239
240
        for (int i = 0; i < list.size(); i++) {
241
            FilterElement el = list.get(i);
242
            FilterElement.ComparisonResult result = newItem.compare(el);
243
            switch (result) {
244
                case DIFFERENT:
245
                    continue;
246
                case THE_SAME:
247
                case WORSE:
248
                    return;
249
                case BETTER:
250
                    list.set(i, newItem);
251
                    return;
252
            }
253
        }
254
        list.add(newItem);
255
    }
256
257
    private static List<FileFilter> sortFiltersByDescription(
258
            List<FileFilter> list) {
259
260
        Collections.sort(list, new Comparator<FileFilter>() {
261
            @Override
262
            public int compare(FileFilter o1, FileFilter o2) {
263
                return o1.getDescription().compareTo(o2.getDescription());
264
            }
265
        });
266
        return list;
267
    }
268
269
    private static List<FilterElement> sortFilterElements(
270
            List<FilterElement> elements) {
271
        Collections.sort(elements, new Comparator<FilterElement>() {
272
            @Override
273
            public int compare(FilterElement o1, FilterElement o2) {
274
                return o1.getName().compareTo(o2.getName());
275
            }
276
        });
277
        return elements;
278
    }
279
280
    private static class FileFilterImpl extends FileFilter {
281
282
        private final String name;
283
        List<FilterElement> filterElements;
284
285
        public FileFilterImpl(String name, List<FilterElement> elements) {
286
            this.name = name;
287
            this.filterElements = elements;
288
        }
289
290
        @Override
291
        public boolean accept(File pathname) {
292
            return FileFilterSupport.accept(pathname, filterElements);
293
        }
294
295
        @Override
296
        public String getDescription() {
297
            return FileFilterSupport.constructFilterDisplayName(
298
                    name, filterElements);
299
        }
300
    }
301
302
    /**
303
     * Element of File Filter. One accepted extension or file name pattern.
304
     */
305
    private static abstract class FilterElement {
306
307
        public abstract String getName();
308
309
        public abstract boolean accept(File f);
310
311
        /**
312
         * Compare two filter elements. Correct implementation of this method
313
         * prevents adding duplicite elements to the filter.
314
         */
315
        public abstract ComparisonResult compare(FilterElement e);
316
317
        public static FilterElement createForExtension(String ext) {
318
            return new ExtensionBasedFilterElement(ext);
319
        }
320
321
        public static FilterElement createForFileName(String name,
322
                String extension, boolean substring, boolean ignoreCase) {
323
            return new NameBasedFilterElement(name, extension,
324
                    substring, ignoreCase);
325
        }
326
327
        public static enum ComparisonResult {
328
329
            THE_SAME, BETTER, WORSE, DIFFERENT
330
        }
331
332
        private static class ExtensionBasedFilterElement extends FilterElement {
333
334
            private final String extension;
335
336
            public ExtensionBasedFilterElement(String extension) {
337
                if (extension != null) {
338
                    this.extension = extension;
339
                } else {
340
                    throw new NullPointerException();
341
                }
342
            }
343
344
            @Override
345
            public String getName() {
346
                return "." + extension;                                 //NOI18N
347
            }
348
349
            @Override
350
            public boolean accept(File f) {
351
                return f.getName().toLowerCase().endsWith(
352
                        "." + extension.toLowerCase());                 //NOI18N
353
            }
354
355
            @Override
356
            public ComparisonResult compare(FilterElement e) {
357
                if (!(e instanceof ExtensionBasedFilterElement)) {
358
                    return ComparisonResult.DIFFERENT;
359
                }
360
                ExtensionBasedFilterElement x = (ExtensionBasedFilterElement) e;
361
                if (x == null) {
362
                    throw new NullPointerException();
363
                }
364
                if (this.extension.equals(x.extension)) {
365
                    return ComparisonResult.THE_SAME;
366
                } else if (this.extension.equalsIgnoreCase(x.extension)
367
                        && this.extension.length() > 1) {
368
                    if (Character.isUpperCase(x.extension.charAt(0))) {
369
                        return ComparisonResult.BETTER; //this better, x worse
370
                    } else {
371
                        return ComparisonResult.WORSE; // this worse, x better
372
                    }
373
                } else {
374
                    return ComparisonResult.DIFFERENT;
375
                }
376
            }
377
        }
378
379
        private static class NameBasedFilterElement extends FilterElement {
380
381
            String name;
382
            String ext;
383
            boolean substring;
384
            boolean ignoreCase;
385
            Pattern p;
386
387
            public NameBasedFilterElement(String name, String ext,
388
                    boolean substring, boolean ignoreCase) {
389
                this.name = name;
390
                this.ext = ext;
391
                this.substring = substring;
392
                this.ignoreCase = ignoreCase;
393
                StringBuilder sb = new StringBuilder();
394
                if (ignoreCase) {
395
                    sb.append("(?i)");                                  //NOI18N
396
                }
397
                if (substring) {
398
                    sb.append(".*");                                    //NOI18N
399
                }
400
                sb.append(name);                                        //NOI18N
401
                if (substring) {
402
                    sb.append(".*");                                    //NOI18N
403
                }
404
                if (!ext.isEmpty()) {
405
                    sb.append("\\.");                                   //NOI18N
406
                    sb.append(ext);
407
                }
408
                p = Pattern.compile(sb.toString());
409
            }
410
411
            @Override
412
            public String getName() {
413
                return name + (ext.isEmpty() ? "" : "." + ext);         //NOI18N
414
            }
415
416
            @Override
417
            public boolean accept(File f) {
418
                return p.matcher(f.getName()).matches();
419
            }
420
421
            @Override
422
            public ComparisonResult compare(FilterElement e) {
423
                if (e == null) {
424
                    throw new NullPointerException();
425
                } else if (!(e instanceof NameBasedFilterElement)) {
426
                    return ComparisonResult.DIFFERENT;
427
                }
428
                NameBasedFilterElement x = (NameBasedFilterElement) e;
429
                if (this.name.equals(x.name) && this.ext.equals(x.ext)) {
430
                    if (this.substring == x.substring
431
                            && this.ignoreCase == x.ignoreCase) {
432
                        return ComparisonResult.THE_SAME;
433
                    } else {
434
                        return compareFlags(x);
435
                    }
436
                } else if (this.ext.equalsIgnoreCase(x.ext)
437
                        && this.name.equalsIgnoreCase(x.name)
438
                        && (this.ignoreCase || x.ignoreCase)) {
439
                    if (this.substring == x.substring
440
                            && this.ignoreCase == x.ignoreCase) {
441
                        if (Character.isLowerCase(this.name.charAt(0))) {
442
                            return ComparisonResult.BETTER;
443
                        } else {
444
                            return ComparisonResult.WORSE;
445
                        }
446
                    } else {
447
                        return compareFlags(x);
448
                    }
449
                } else {
450
                    return ComparisonResult.DIFFERENT;
451
                }
452
            }
453
454
            private ComparisonResult compareFlags(NameBasedFilterElement x) {
455
                if (this.substring == x.substring
456
                        && this.ignoreCase) {
457
                    return ComparisonResult.BETTER;
458
                } else if (this.ignoreCase == x.ignoreCase
459
                        && this.substring) {
460
                    return ComparisonResult.BETTER;
461
                } else if (this.substring != x.substring
462
                        && this.ignoreCase != x.ignoreCase) {
463
                    return ComparisonResult.DIFFERENT;
464
                } else {
465
                    return ComparisonResult.WORSE;
466
                }
467
            }
468
        }
469
    }
470
}
(-)a/openide.filesystems/src/org/netbeans/modules/openide/filesystems/RecognizeInstanceFiles.java (-9 / +71 lines)
Lines 30-42 Link Here
30
 * Software is Sun Microsystems, Inc.
30
 * Software is Sun Microsystems, Inc.
31
 *
31
 *
32
 * Portions Copyrighted 2007 Sun Microsystems, Inc.
32
 * Portions Copyrighted 2007 Sun Microsystems, Inc.
33
 *//*
34
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
35
 *
36
 * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
37
 *
38
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
39
 * Other names may be trademarks of their respective owners.
40
 *
41
 * The contents of this file are subject to the terms of either the GNU
42
 * General Public License Version 2 only ("GPL") or the Common
43
 * Development and Distribution License("CDDL") (collectively, the
44
 * "License"). You may not use this file except in compliance with the
45
 * License. You can obtain a copy of the License at
46
 * http://www.netbeans.org/cddl-gplv2.html
47
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
48
 * specific language governing permissions and limitations under the
49
 * License.  When distributing the software, include this License Header
50
 * Notice in each file and include the License file at
51
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
52
 * particular file as subject to the "Classpath" exception as provided
53
 * by Oracle in the GPL Version 2 section of the License file that
54
 * accompanied this code. If applicable, add the following below the
55
 * License Header, with the fields enclosed by brackets [] replaced by
56
 * your own identifying information:
57
 * "Portions Copyrighted [year] [name of copyright owner]"
58
 *
59
 * Contributor(s):
60
 *
61
 * The Original Software is NetBeans. The Initial Developer of the Original
62
 * Software is Sun Microsystems, Inc.
63
 *
64
 * Portions Copyrighted 2007 Sun Microsystems, Inc.
33
 */
65
 */
34
66
35
package org.netbeans.modules.openide.filesystems;
67
package org.netbeans.modules.openide.filesystems;
36
68
37
import java.lang.ref.Reference;
69
import java.lang.ref.Reference;
38
import java.lang.ref.WeakReference;
70
import java.lang.ref.WeakReference;
71
import java.lang.reflect.Constructor;
72
import java.lang.reflect.InvocationTargetException;
39
import java.util.ArrayList;
73
import java.util.ArrayList;
74
import java.util.Collection;
40
import java.util.Collections;
75
import java.util.Collections;
41
import java.util.Enumeration;
76
import java.util.Enumeration;
42
import java.util.LinkedHashMap;
77
import java.util.LinkedHashMap;
Lines 53-62 Link Here
53
import org.openide.filesystems.FileStateInvalidException;
88
import org.openide.filesystems.FileStateInvalidException;
54
import org.openide.filesystems.FileSystem;
89
import org.openide.filesystems.FileSystem;
55
import org.openide.filesystems.FileUtil;
90
import org.openide.filesystems.FileUtil;
91
import org.openide.filesystems.spi.CustomInstanceFactory;
92
import org.openide.util.BaseUtilities;
56
import org.openide.util.Exceptions;
93
import org.openide.util.Exceptions;
57
import org.openide.util.Lookup;
94
import org.openide.util.Lookup;
58
import org.openide.util.SharedClassObject;
59
import org.openide.util.Utilities;
60
import org.openide.util.lookup.AbstractLookup;
95
import org.openide.util.lookup.AbstractLookup;
61
import org.openide.util.lookup.Lookups;
96
import org.openide.util.lookup.Lookups;
62
import org.openide.util.lookup.ProxyLookup;
97
import org.openide.util.lookup.ProxyLookup;
Lines 200-205 Link Here
200
        }
235
        }
201
    } // end of OverFiles
236
    } // end of OverFiles
202
    
237
    
238
    private static volatile Lookup.Result<CustomInstanceFactory> factories;
239
    
240
    private static Collection<? extends CustomInstanceFactory> getInstanceFactories() {
241
        Lookup.Result<CustomInstanceFactory> fr;
242
        
243
        if ((fr = factories) == null) {
244
            factories = fr = Lookup.getDefault().lookupResult(CustomInstanceFactory.class);
245
        }
246
        return fr.allInstances();
247
    }
248
            
249
    public static final <T> T createInstance(Class<T> type) throws InstantiationException, 
250
            IllegalAccessException, InvocationTargetException, NoSuchMethodException {
251
        T r = null;
252
        for (CustomInstanceFactory fif : getInstanceFactories()) {
253
            r = (T)fif.createInstance(type);
254
            if (r != null) {
255
                break;
256
            }
257
        }
258
        if (r == null) {
259
            Constructor<T> init = type.getDeclaredConstructor();
260
            init.setAccessible(true);
261
            r = init.newInstance();
262
        }
263
        return r;
264
    }
203
    
265
    
204
    private static final class FOItem extends AbstractLookup.Pair<Object> {
266
    private static final class FOItem extends AbstractLookup.Pair<Object> {
205
        private static Reference<Object> EMPTY = new WeakReference<Object>(null);
267
        private static Reference<Object> EMPTY = new WeakReference<Object>(null);
Lines 257-271 Link Here
257
                    if (type == null) {
319
                    if (type == null) {
258
                        return null;
320
                        return null;
259
                    }
321
                    }
260
                    if (SharedClassObject.class.isAssignableFrom(type)) {
322
                    r = createInstance(type);
261
                        r = SharedClassObject.findObject(type.asSubclass(SharedClassObject.class), true);
262
                    } else {
263
                        r = type.newInstance();
264
                    }
265
                } catch (InstantiationException ex) {
323
                } catch (InstantiationException ex) {
266
                    Exceptions.printStackTrace(ex);
324
                    Exceptions.printStackTrace(ex);
267
                } catch (IllegalAccessException ex) {
325
                } catch (IllegalAccessException ex) {
268
                    Exceptions.printStackTrace(ex);
326
                    Exceptions.printStackTrace(ex);
327
                } catch (InvocationTargetException ex) {
328
                    Exceptions.printStackTrace(ex);
329
                } catch (NoSuchMethodException ex) {
330
                    Exceptions.printStackTrace(ex);
269
                }
331
                }
270
            }
332
            }
271
            return resultType.isInstance(r) ? resultType.cast(r) : null;
333
            return resultType.isInstance(r) ? resultType.cast(r) : null;
Lines 312-318 Link Here
312
            // first of all try "instanceClass" property of the primary file
374
            // first of all try "instanceClass" property of the primary file
313
            Object attr = fo.getAttribute ("instanceClass");
375
            Object attr = fo.getAttribute ("instanceClass");
314
            if (attr instanceof String) {
376
            if (attr instanceof String) {
315
                return Utilities.translate((String) attr);
377
                return BaseUtilities.translate((String) attr);
316
            } else if (attr != null) {
378
            } else if (attr != null) {
317
                LOG.warning(
379
                LOG.warning(
318
                    "instanceClass was a " + attr.getClass().getName()); // NOI18N
380
                    "instanceClass was a " + attr.getClass().getName()); // NOI18N
Lines 350-356 Link Here
350
            }
412
            }
351
413
352
            name = name.replace ('-', '.');
414
            name = name.replace ('-', '.');
353
            name = Utilities.translate(name);
415
            name = BaseUtilities.translate(name);
354
416
355
            //System.out.println ("Original: " + getPrimaryFile ().getName () + " new one: " + name); // NOI18N
417
            //System.out.println ("Original: " + getPrimaryFile ().getName () + " new one: " + name); // NOI18N
356
            return name;
418
            return name;
(-)a/openide.filesystems/src/org/netbeans/modules/openide/filesystems/declmime/FileElement.java (-2 / +2 lines)
Lines 49-55 Link Here
49
import java.util.logging.Logger;
49
import java.util.logging.Logger;
50
import org.openide.filesystems.FileObject;
50
import org.openide.filesystems.FileObject;
51
import org.openide.filesystems.FileUtil;
51
import org.openide.filesystems.FileUtil;
52
import org.openide.util.Utilities;
52
import org.openide.util.BaseUtilities;
53
import org.openide.xml.XMLUtil;
53
import org.openide.xml.XMLUtil;
54
54
55
/**
55
/**
Lines 529-535 Link Here
529
        /** #26521, 114976 - ignore not readable and windows' locked files. */
529
        /** #26521, 114976 - ignore not readable and windows' locked files. */
530
        private static void handleIOException(FileObject fo, IOException ioe) throws IOException {
530
        private static void handleIOException(FileObject fo, IOException ioe) throws IOException {
531
            if (fo.canRead()) {
531
            if (fo.canRead()) {
532
                if (!Utilities.isWindows() || !(ioe instanceof FileNotFoundException) || !fo.isValid() || !fo.getName().toLowerCase().contains("ntuser")) {//NOI18N
532
                if (!BaseUtilities.isWindows() || !(ioe instanceof FileNotFoundException) || !fo.isValid() || !fo.getName().toLowerCase().contains("ntuser")) {//NOI18N
533
                    throw ioe;
533
                    throw ioe;
534
                }
534
                }
535
            }
535
            }
(-)a/openide.filesystems/src/org/netbeans/modules/openide/filesystems/declmime/MIMEResolverImpl.java (-2 / +2 lines)
Lines 57-63 Link Here
57
import org.openide.filesystems.MIMEResolver;
57
import org.openide.filesystems.MIMEResolver;
58
import org.openide.util.Exceptions;
58
import org.openide.util.Exceptions;
59
import org.openide.util.Parameters;
59
import org.openide.util.Parameters;
60
import org.openide.util.Utilities;
60
import org.openide.util.BaseUtilities;
61
import org.openide.xml.XMLUtil;
61
import org.openide.xml.XMLUtil;
62
import org.w3c.dom.Document;
62
import org.w3c.dom.Document;
63
import org.w3c.dom.Element;
63
import org.w3c.dom.Element;
Lines 75-81 Link Here
75
    // enable some tracing
75
    // enable some tracing
76
    private static final Logger ERR = Logger.getLogger(MIMEResolverImpl.class.getName());
76
    private static final Logger ERR = Logger.getLogger(MIMEResolverImpl.class.getName());
77
        
77
        
78
    static final boolean CASE_INSENSITIVE = Utilities.getOperatingSystem() == Utilities.OS_VMS;
78
    static final boolean CASE_INSENSITIVE = BaseUtilities.getOperatingSystem() == BaseUtilities.OS_VMS;
79
79
80
    // notification limit in bytes for reading file content. It should not exceed 4192 (4kB) because it is read in one disk touch.
80
    // notification limit in bytes for reading file content. It should not exceed 4192 (4kB) because it is read in one disk touch.
81
    private static final int READ_LIMIT = 4000;
81
    private static final int READ_LIMIT = 4000;
(-)a/openide.filesystems/src/org/openide/filesystems/AbstractFileObject.java (-40 lines)
Lines 1233-1276 Link Here
1233
        }
1233
        }
1234
    }
1234
    }
1235
     // end of Invalid
1235
     // end of Invalid
1236
1237
    /** Replace that stores name of fs and file.
1238
     * @deprecated In favor of AbstractFolder.Replace.
1239
    */
1240
    @Deprecated
1241
    static final class Replace extends Object implements Serializable {
1242
        /** generated Serialized Version UID */
1243
        static final long serialVersionUID = -8543432135435542113L;
1244
        private String fsName;
1245
        private String fileName;
1246
1247
        /** Constructor
1248
        */
1249
        public Replace(String fsName, String fileName) {
1250
            this.fsName = fsName;
1251
            this.fileName = fileName;
1252
        }
1253
1254
        /** Finds the right file.
1255
        */
1256
        public Object readResolve() {
1257
            Repository rep = Repository.getDefault();
1258
            @SuppressWarnings("deprecation") // FileSystem.systemName historical part of serial form
1259
            FileSystem fs = rep.findFileSystem(fsName);
1260
            FileObject fo = null;
1261
1262
            if (fs != null) {
1263
                // scan desired system
1264
                fo = fs.findResource(fileName);
1265
            }
1266
1267
            if (fo == null) {
1268
                // create invalid file instead
1269
                return new Invalid(fsName, fileName);
1270
            }
1271
1272
            return fo;
1273
        }
1274
    }
1275
     // end of Replace
1276
}
1236
}
(-)a/openide.filesystems/src/org/openide/filesystems/AbstractFileSystem.java (-75 lines)
Lines 57-67 Link Here
57
import java.util.Date;
57
import java.util.Date;
58
import java.util.Enumeration;
58
import java.util.Enumeration;
59
import java.util.StringTokenizer;
59
import java.util.StringTokenizer;
60
import org.openide.util.Enumerations;
61
import org.openide.util.Lookup;
62
import org.openide.util.NbCollections;
60
import org.openide.util.NbCollections;
63
import org.openide.util.SharedClassObject;
64
import org.openide.util.actions.SystemAction;
65
61
66
/**
62
/**
67
 * This convenience implementation does much of the hard work of
63
 * This convenience implementation does much of the hard work of
Lines 126-137 Link Here
126
    /** generated Serialized Version UID */
122
    /** generated Serialized Version UID */
127
    private static final long serialVersionUID = -3345098214331282438L;
123
    private static final long serialVersionUID = -3345098214331282438L;
128
124
129
    /** system actions for this FS if it has refreshTime != 0 */
130
    private static SystemAction[] SYSTEM_ACTIONS;
131
132
    /** system actions for this FS */
133
    private static final SystemAction[] NO_SYSTEM_ACTIONS = new SystemAction[] {  };
134
135
    /** cached last value of Enumeration which holds resource name (enumeration like StringTokenizer)*/
125
    /** cached last value of Enumeration which holds resource name (enumeration like StringTokenizer)*/
136
    static transient private PathElements lastEnum;
126
    static transient private PathElements lastEnum;
137
127
Lines 181-218 Link Here
181
        return getAbstractRoot();
171
        return getAbstractRoot();
182
    }
172
    }
183
173
184
    /* Finds file when its name is provided.
185
    *
186
    * @param aPackage package name where each package is separated by a dot
187
    * @param name name of the file (without dots) or <CODE>null</CODE> if
188
    *    one want to obtain name of package and not file in it
189
    * @param ext extension of the file or <CODE>null</CODE> if one needs
190
    *    package and not file name
191
    *
192
    * @warning when one of name or ext is <CODE>null</CODE> then name and
193
    *    ext should be ignored and scan should look only for a package
194
    *
195
    * @return FileObject that represents file with given name or
196
    *   <CODE>null</CODE> if the file does not exist
197
    */
198
    @Deprecated
199
    public FileObject find(String aPackage, String name, String ext) {
200
        // create enumeration of name to look for
201
        Enumeration<String> st = NbCollections.checkedEnumerationByFilter(new StringTokenizer(aPackage, "."), String.class, true); // NOI18N
202
203
        if ((name == null) || (ext == null)) {
204
            // search for folder, return the object only if it is folder
205
            FileObject fo = getAbstractRoot().find(st);
206
207
            return ((fo != null) && fo.isFolder()) ? fo : null;
208
        } else {
209
            Enumeration<String> en = Enumerations.concat(st, Enumerations.singleton(name + '.' + ext));
210
211
            // tries to find it (can return null)
212
            return getAbstractRoot().find(en);
213
        }
214
    }
215
216
    /* Finds file when its resource name is given.
174
    /* Finds file when its resource name is given.
217
    * The name has the usual format for the {@link ClassLoader#getResource(String)}
175
    * The name has the usual format for the {@link ClassLoader#getResource(String)}
218
    * method. So it may consist of "package1/package2/filename.ext".
176
    * method. So it may consist of "package1/package2/filename.ext".
Lines 270-308 Link Here
270
        return (refresher != null);
228
        return (refresher != null);
271
    }
229
    }
272
230
273
    /* Action for this filesystem.
274
    *
275
    * @return refresh action
276
    */
277
    public SystemAction[] getActions() {
278
        if (!isEnabledRefreshFolder()) {
279
            return NO_SYSTEM_ACTIONS;
280
        } else {
281
            if (SYSTEM_ACTIONS == null) {
282
                try {
283
                    ClassLoader l = Lookup.getDefault().lookup(ClassLoader.class);
284
285
                    if (l == null) {
286
                        l = getClass().getClassLoader();
287
                    }
288
289
                    Class<?> c = Class.forName("org.openide.actions.FileSystemRefreshAction", true, l); // NOI18N
290
                    SystemAction ra = SharedClassObject.findObject(c.asSubclass(SystemAction.class), true);
291
292
                    // initialize the SYSTEM_ACTIONS
293
                    SYSTEM_ACTIONS = new SystemAction[] { ra };
294
                } catch (Exception ex) {
295
                    // ok, we are probably running in standalone mode and
296
                    // classes needed to initialize the RefreshAction are
297
                    // not available
298
                    SYSTEM_ACTIONS = NO_SYSTEM_ACTIONS;
299
                }
300
            }
301
302
            return SYSTEM_ACTIONS;
303
        }
304
    }
305
306
    /** Set the number of milliseconds between automatic
231
    /** Set the number of milliseconds between automatic
307
    * refreshes of the directory structure.
232
    * refreshes of the directory structure.
308
    *
233
    *
(-)a/openide.filesystems/src/org/openide/filesystems/AbstractFolder.java (-2 / +2 lines)
Lines 64-70 Link Here
64
import java.util.Set;
64
import java.util.Set;
65
import org.openide.util.Enumerations;
65
import org.openide.util.Enumerations;
66
import org.openide.util.NbBundle;
66
import org.openide.util.NbBundle;
67
import org.openide.util.Utilities;
67
import org.openide.util.BaseUtilities;
68
68
69
/** Implementation of the file object that simplyfies common
69
/** Implementation of the file object that simplyfies common
70
* tasks with hierarchy of objects for AbstractFileObject and MultiFileObject.
70
* tasks with hierarchy of objects for AbstractFileObject and MultiFileObject.
Lines 348-354 Link Here
348
            //On OpenVMS, see if the name is stored in a different case
348
            //On OpenVMS, see if the name is stored in a different case
349
            //to work around a JVM bug.
349
            //to work around a JVM bug.
350
            //
350
            //
351
            if (Utilities.getOperatingSystem() == Utilities.OS_VMS) {
351
            if (BaseUtilities.getOperatingSystem() == BaseUtilities.OS_VMS) {
352
                if (Character.isLowerCase(name.charAt(0))) {
352
                if (Character.isLowerCase(name.charAt(0))) {
353
                    r = map.get(name.toUpperCase());
353
                    r = map.get(name.toUpperCase());
354
                } else {
354
                } else {
(-)a/openide.filesystems/src/org/openide/filesystems/DeepListener.java (-2 / +2 lines)
Lines 52-58 Link Here
52
import java.util.concurrent.Callable;
52
import java.util.concurrent.Callable;
53
import java.util.logging.Level;
53
import java.util.logging.Level;
54
import java.util.logging.Logger;
54
import java.util.logging.Logger;
55
import org.openide.util.Utilities;
55
import org.openide.util.BaseUtilities;
56
import org.openide.util.WeakSet;
56
import org.openide.util.WeakSet;
57
57
58
/**
58
/**
Lines 71-77 Link Here
71
    private final int hash;
71
    private final int hash;
72
72
73
    DeepListener(FileChangeListener listener, File path, FileFilter ff, Callable<Boolean> stop) {
73
    DeepListener(FileChangeListener listener, File path, FileFilter ff, Callable<Boolean> stop) {
74
        super(listener, Utilities.activeReferenceQueue());
74
        super(listener, BaseUtilities.activeReferenceQueue());
75
        this.path = path;
75
        this.path = path;
76
        this.stop = stop;
76
        this.stop = stop;
77
        this.filter = ff;
77
        this.filter = ff;
(-)a/openide.filesystems/src/org/openide/filesystems/DefaultAttributes.java (-3 / +3 lines)
Lines 73-79 Link Here
73
import javax.xml.parsers.ParserConfigurationException;
73
import javax.xml.parsers.ParserConfigurationException;
74
import org.openide.util.Enumerations;
74
import org.openide.util.Enumerations;
75
import org.openide.util.NbBundle;
75
import org.openide.util.NbBundle;
76
import org.openide.util.Utilities;
76
import org.openide.util.BaseUtilities;
77
import org.openide.util.io.NbMarshalledObject;
77
import org.openide.util.io.NbMarshalledObject;
78
import org.openide.xml.XMLUtil;
78
import org.openide.xml.XMLUtil;
79
import org.xml.sax.Attributes;
79
import org.xml.sax.Attributes;
Lines 238-244 Link Here
238
            // However, OpenVMS now supports a file name beginning with "."
238
            // However, OpenVMS now supports a file name beginning with "."
239
            // So we now have to copy the existing "_nbattrs." file into ".nbattrs"
239
            // So we now have to copy the existing "_nbattrs." file into ".nbattrs"
240
            //
240
            //
241
            if ((Utilities.getOperatingSystem() == Utilities.OS_VMS) && (arr[0] != null) && (f != null)) {
241
            if ((BaseUtilities.getOperatingSystem() == BaseUtilities.OS_VMS) && (arr[0] != null) && (f != null)) {
242
                if (arr[0].equalsIgnoreCase("_nbattrs.")) {
242
                if (arr[0].equalsIgnoreCase("_nbattrs.")) {
243
                    try {
243
                    try {
244
                        deleteFile(f + "/" + arr[0]); // NOI18N
244
                        deleteFile(f + "/" + arr[0]); // NOI18N
Lines 264-270 Link Here
264
            // However, OpenVMS now supports a file name beginning with "."
264
            // However, OpenVMS now supports a file name beginning with "."
265
            // So we now have to copy the existing "_nbattrs." file into ".nbattrs"
265
            // So we now have to copy the existing "_nbattrs." file into ".nbattrs"
266
            //
266
            //
267
            if ((Utilities.getOperatingSystem() == Utilities.OS_VMS) && (arr[i] != null) && (f != null)) {
267
            if ((BaseUtilities.getOperatingSystem() == BaseUtilities.OS_VMS) && (arr[i] != null) && (f != null)) {
268
                if (arr[i].equalsIgnoreCase("_nbattrs.")) {
268
                if (arr[i].equalsIgnoreCase("_nbattrs.")) {
269
                    try {
269
                    try {
270
                        File fp = new File(f + "/" + ".nbattrs");
270
                        File fp = new File(f + "/" + ".nbattrs");
(-)a/openide.filesystems/src/org/openide/filesystems/EnvironmentNotSupportedException.java (-86 lines)
Lines 1-86 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * Contributor(s):
28
 *
29
 * The Original Software is NetBeans. The Initial Developer of the Original
30
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
31
 * Microsystems, Inc. All Rights Reserved.
32
 *
33
 * If you wish your version of this file to be governed by only the CDDL
34
 * or only the GPL Version 2, indicate your decision by adding
35
 * "[Contributor] elects to include this software in this distribution
36
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
37
 * single choice of license, a recipient has the option to distribute
38
 * your version of this file under either the CDDL, the GPL Version 2 or
39
 * to extend the choice of license to its licensees as provided above.
40
 * However, if you add GPL Version 2 code and therefore, elected the GPL
41
 * Version 2 license, then the option applies only if the new code is
42
 * made subject to such option by the copyright holder.
43
 */
44
45
package org.openide.filesystems;
46
47
import java.io.IOException;
48
49
/** Exception thrown to signal that external
50
* execution and compilation is not supported on a given filesystem.
51
*
52
* @author Jaroslav Tulach
53
* @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
54
*/
55
@Deprecated
56
public class EnvironmentNotSupportedException extends IOException {
57
    /** generated Serialized Version UID */
58
    static final long serialVersionUID = -1138390681913514558L;
59
60
    /** the throwing exception */
61
    private FileSystem fs;
62
63
    /**
64
    * @param fs filesystem that caused the error
65
    */
66
    public EnvironmentNotSupportedException(FileSystem fs) {
67
        this.fs = fs;
68
        assert false : "Deprecated.";
69
    }
70
71
    /**
72
    * @param fs filesystem that caused the error
73
    * @param reason text description for the error
74
    */
75
    public EnvironmentNotSupportedException(FileSystem fs, String reason) {
76
        super(reason);
77
        this.fs = fs;
78
        assert false : "Deprecated.";
79
    }
80
81
    /** Getter for the filesystem that does not support environment operations.
82
    */
83
    public FileSystem getFileSystem() {
84
        return fs;
85
    }
86
}
(-)a/openide.filesystems/src/org/openide/filesystems/FileChangeImpl.java (-3 / +3 lines)
Lines 50-56 Link Here
50
import java.util.concurrent.Callable;
50
import java.util.concurrent.Callable;
51
import java.util.logging.Level;
51
import java.util.logging.Level;
52
import java.util.logging.Logger;
52
import java.util.logging.Logger;
53
import org.openide.util.Utilities;
53
import org.openide.util.BaseUtilities;
54
54
55
/** Holds FileChangeListener and File pair and handle movement of auxiliary
55
/** Holds FileChangeListener and File pair and handle movement of auxiliary
56
 * FileChangeListener to the first existing upper folder and firing appropriate events.
56
 * FileChangeListener to the first existing upper folder and firing appropriate events.
Lines 66-72 Link Here
66
    private boolean isOnTarget = false;
66
    private boolean isOnTarget = false;
67
67
68
    public FileChangeImpl(FileChangeListener listener, File path) {
68
    public FileChangeImpl(FileChangeListener listener, File path) {
69
        super(listener, Utilities.activeReferenceQueue());
69
        super(listener, BaseUtilities.activeReferenceQueue());
70
        assert path != null;
70
        assert path != null;
71
        this.path = path;
71
        this.path = path;
72
    }
72
    }
Lines 241-247 Link Here
241
    }
241
    }
242
242
243
    static FileChangeListener removeFileChangeListenerImpl(Logger logger, FileChangeListener listener, File path) {
243
    static FileChangeListener removeFileChangeListenerImpl(Logger logger, FileChangeListener listener, File path) {
244
        assert FileUtil.assertNormalized(path, Utilities.isMac());
244
        assert FileUtil.assertNormalized(path, BaseUtilities.isMac());
245
        logger.log(Level.FINE, "removeFileChangeListener {0} @ {1}", new Object[]{listener, path});
245
        logger.log(Level.FINE, "removeFileChangeListener {0} @ {1}", new Object[]{listener, path});
246
        synchronized (holders) {
246
        synchronized (holders) {
247
            Map<File, FileChangeImpl> f2H = holders.get(listener);
247
            Map<File, FileChangeImpl> f2H = holders.get(listener);
(-)a/openide.filesystems/src/org/openide/filesystems/FileChooserBuilder.java (-687 lines)
Lines 1-687 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * Contributor(s):
28
 *
29
 * The Original Software is NetBeans. The Initial Developer of the Original
30
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
31
 * Microsystems, Inc. All Rights Reserved.
32
 *
33
 * If you wish your version of this file to be governed by only the CDDL
34
 * or only the GPL Version 2, indicate your decision by adding
35
 * "[Contributor] elects to include this software in this distribution
36
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
37
 * single choice of license, a recipient has the option to distribute
38
 * your version of this file under either the CDDL, the GPL Version 2 or
39
 * to extend the choice of license to its licensees as provided above.
40
 * However, if you add GPL Version 2 code and therefore, elected the GPL
41
 * Version 2 license, then the option applies only if the new code is
42
 * made subject to such option by the copyright holder.
43
 */
44
package org.openide.filesystems;
45
46
import java.awt.Component;
47
import java.awt.FileDialog;
48
import java.awt.Frame;
49
import java.awt.HeadlessException;
50
import java.awt.KeyboardFocusManager;
51
import java.io.File;
52
import java.util.ArrayList;
53
import java.util.List;
54
import javax.swing.Icon;
55
import javax.swing.JFileChooser;
56
import javax.swing.SwingUtilities;
57
import javax.swing.filechooser.FileFilter;
58
import javax.swing.filechooser.FileSystemView;
59
import javax.swing.filechooser.FileView;
60
import org.netbeans.modules.openide.filesystems.FileFilterSupport;
61
import org.openide.util.*;
62
63
/**
64
 * Utility class for working with JFileChoosers.  In particular, remembering
65
 * the last-used directory for a given file is made transparent.  You pass an
66
 * ad-hoc string key to the constructor (the fully qualified name of the
67
 * calling class is good for uniqueness, and there is a constructor that takes
68
 * a <code>Class</code> object as an argument for this purpose).  That key is
69
 * used to look up the most recently-used directory from any previous invocations
70
 * with the same key.  This makes it easy to have your user interface
71
 * &ldquo;remember&rdquo; where the user keeps particular types of files, and
72
 * saves the user from having to navigate through the same set of directories
73
 * every time they need to locate a file from a particular place.
74
 * <p/>
75
 * <code>FileChooserBuilder</code>'s methods each return <code>this</code>, so
76
 * it is possible to chain invocations to simplify setting up a file chooser.
77
 * Example usage:
78
 * <pre>
79
 *      <font color="gray">//The default dir to use if no value is stored</font>
80
 *      File home = new File (System.getProperty("user.home") + File.separator + "lib");
81
 *      <font color="gray">//Now build a file chooser and invoke the dialog in one line of code</font>
82
 *      <font color="gray">//&quot;libraries-dir&quot; is our unique key</font>
83
 *      File toAdd = new FileChooserBuilder ("libraries-dir").setTitle("Add Library").
84
 *              setDefaultWorkingDirectory(home).setApproveText("Add").showOpenDialog();
85
 *      <font color="gray">//Result will be null if the user clicked cancel or closed the dialog w/o OK</font>
86
 *      if (toAdd != null) {
87
 *          //do something
88
 *      }
89
 *</pre>
90
 * <p/>
91
 * Instances of this class are intended to be thrown away after use.  Typically
92
 * you create a builder, set it to create file choosers as you wish, then
93
 * use it to show a dialog or create a file chooser you then do something
94
 * with.
95
 * <p/>
96
 * Supports the most common subset of JFileChooser functionality;  if you
97
 * need to do something exotic with a file chooser, you are probably better
98
 * off creating your own.
99
 * <p/>
100
 * <b>Note:</b> If you use the constructor that takes a <code>Class</code> object,
101
 * please use <code>new FileChooserBuilder(MyClass.class)</code>, not
102
 * <code>new FileChooserBuilder(getClass())</code>.  This avoids unexpected
103
 * behavior in the case of subclassing.
104
 *
105
 * @author Tim Boudreau
106
 */
107
public class FileChooserBuilder {
108
    private boolean dirsOnly;
109
    private BadgeProvider badger;
110
    private String title;
111
    private String approveText;
112
    //Just in case...
113
    private static boolean PREVENT_SYMLINK_TRAVERSAL =
114
            !Boolean.getBoolean("allow.filechooser.symlink.traversal"); //NOI18N
115
    private final String dirKey;
116
    private File failoverDir;
117
    private FileFilter filter;
118
    private boolean fileHiding;
119
    private boolean controlButtonsShown = true;
120
    private String aDescription;
121
    private boolean filesOnly;
122
    private static final boolean DONT_STORE_DIRECTORIES =
123
            Boolean.getBoolean("forget.recent.dirs");
124
    private SelectionApprover approver;
125
    private final List<FileFilter> filters = new ArrayList<FileFilter>(3);
126
    private boolean useAcceptAllFileFilter = true;
127
    /**
128
     * Create a new FileChooserBuilder using the name of the passed class
129
     * as the metadata for looking up a starting directory from previous
130
     * application sessions or invocations.
131
     * @param type A non-null class object, typically the calling class
132
     */
133
    public FileChooserBuilder(Class type) {
134
        this(type.getName());
135
    }
136
137
    /**
138
     * Create a new FileChooserBuilder.  The passed key is used as a key
139
     * into NbPreferences to look up the directory the file chooser should
140
     * initially be rooted on.
141
     *
142
     * @param dirKey A non-null ad-hoc string.  If a FileChooser was previously
143
     * used with the same string as is passed, then the initial directory
144
     */
145
    public FileChooserBuilder(String dirKey) {
146
        Parameters.notNull("dirKey", dirKey);
147
        this.dirKey = dirKey;
148
    }
149
150
    /**
151
     * Set whether or not any file choosers created by this builder will show
152
     * only directories.
153
     * @param val true if files should not be shown
154
     * @return this
155
     */
156
    public FileChooserBuilder setDirectoriesOnly(boolean val) {
157
        dirsOnly = val;
158
        assert !filesOnly : "FilesOnly and DirsOnly are mutually exclusive";
159
        return this;
160
    }
161
162
    public FileChooserBuilder setFilesOnly(boolean val) {
163
        filesOnly = val;
164
        assert !dirsOnly : "FilesOnly and DirsOnly are mutually exclusive";
165
        return this;
166
    }
167
168
    /**
169
     * Provide an implementation of BadgeProvider which will "badge" the
170
     * icons of some files.
171
     *
172
     * @param provider A badge provider which will alter the icon of files
173
     * or folders that may be of particular interest to the user
174
     * @return this
175
     */
176
    public FileChooserBuilder setBadgeProvider(BadgeProvider provider) {
177
        this.badger = provider;
178
        return this;
179
    }
180
181
    /**
182
     * Set the dialog title for any JFileChoosers created by this builder.
183
     * @param val A localized, human-readable title
184
     * @return this
185
     */
186
    public FileChooserBuilder setTitle(String val) {
187
        title = val;
188
        return this;
189
    }
190
191
    /**
192
     * Set the text on the OK button for any file chooser dialogs produced
193
     * by this builder.
194
     * @param val A short, localized, human-readable string
195
     * @return this
196
     */
197
    public FileChooserBuilder setApproveText(String val) {
198
        approveText = val;
199
        return this;
200
    }
201
202
    /**
203
     * Set a file filter which filters the list of selectable files.
204
     * @param filter
205
     * @return this
206
     */
207
    public FileChooserBuilder setFileFilter (FileFilter filter) {
208
        this.filter = filter;
209
        return this;
210
    }
211
212
    /**
213
     * Determines whether the <code>AcceptAll FileFilter</code> is used
214
     * as an available choice in the choosable filter list.
215
     * If false, the <code>AcceptAll</code> file filter is removed from
216
     * the list of available file filters.
217
     * If true, the <code>AcceptAll</code> file filter will become the
218
     * the actively used file filter.
219
     * @param accept whether the <code>AcceptAll FileFilter</code> is used
220
     * @return this
221
     * @since 8.3
222
     */
223
    public FileChooserBuilder setAcceptAllFileFilterUsed(boolean accept) {
224
        useAcceptAllFileFilter = accept;
225
        return this;
226
    }
227
228
    /**
229
     * Set the current directory which should be used <b>only if</b>
230
     * a last-used directory cannot be found for the key string passed
231
     * into this builder's constructor.
232
     * @param dir A directory to root any created file choosers on if
233
     * there is no stored path for this builder's key
234
     * @return this
235
     */
236
    public FileChooserBuilder setDefaultWorkingDirectory (File dir) {
237
        failoverDir = dir;
238
        return this;
239
    }
240
241
    /**
242
     * Enable file hiding in any created file choosers
243
     * @param fileHiding Whether or not to hide files.  Default is no.
244
     * @return this
245
     */
246
    public FileChooserBuilder setFileHiding(boolean fileHiding) {
247
        this.fileHiding = fileHiding;
248
        return this;
249
    }
250
251
    /**
252
     * Show/hide control buttons
253
     * @param val Whether or not to hide files.  Default is no.
254
     * @return this
255
     */
256
    public FileChooserBuilder setControlButtonsAreShown(boolean val) {
257
        this.controlButtonsShown = val;
258
        return this;
259
    }
260
261
    /**
262
     * Set the accessible description for any file choosers created by this
263
     * builder
264
     * @param aDescription The description
265
     * @return this
266
     */
267
    public FileChooserBuilder setAccessibleDescription(String aDescription) {
268
        this.aDescription = aDescription;
269
        return this;
270
    }
271
272
    /**
273
     * Create a JFileChooser that conforms to the parameters set in this
274
     * builder.
275
     * @return A file chooser
276
     */
277
    public JFileChooser createFileChooser() {
278
        JFileChooser result = new SavedDirFileChooser(dirKey, failoverDir,
279
                force, approver);
280
        prepareFileChooser(result);
281
        return result;
282
    }
283
284
    private boolean force = false;
285
    /**
286
     * Force use of the failover directory - i.e. ignore the directory key
287
     * passed in.
288
     * @param val
289
     * @return this
290
     */
291
    public FileChooserBuilder forceUseOfDefaultWorkingDirectory(boolean val) {
292
        this.force = val;
293
        return this;
294
    }
295
296
    /**
297
     * Tries to find an appropriate component to parent the file chooser to
298
     * when showing a dialog.
299
     * @return this
300
     */
301
    private Component findDialogParent() {
302
        Component parent = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
303
        if (parent == null) {
304
            parent = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
305
        }
306
        if (parent == null) {
307
            Frame[] f = Frame.getFrames();
308
            parent = f.length == 0 ? null : f[f.length - 1];
309
        }
310
        return parent;
311
    }
312
313
    /**
314
     * Show an open dialog that allows multiple selection.
315
     * @return An array of files, or null if the user cancelled the dialog
316
     */
317
    public File[] showMultiOpenDialog() {
318
        JFileChooser chooser = createFileChooser();
319
        chooser.setMultiSelectionEnabled(true);
320
        int result = chooser.showOpenDialog(findDialogParent());
321
        if (JFileChooser.APPROVE_OPTION == result) {
322
            File[] files = chooser.getSelectedFiles();
323
            return files == null ? new File[0] : files;
324
        } else {
325
            return null;
326
        }
327
    }
328
329
    /**
330
     * Show an open dialog with a file chooser set up according to the
331
     * parameters of this builder.
332
     * @return A file if the user clicks the accept button and a file or
333
     * folder was selected at the time the user clicked cancel.
334
     */
335
    public File showOpenDialog() {
336
        JFileChooser chooser = createFileChooser();
337
        if( Boolean.getBoolean("nb.native.filechooser") ) { //NOI18N
338
            FileDialog fileDialog = createFileDialog( chooser.getCurrentDirectory() );
339
            if( null != fileDialog ) {
340
                return showFileDialog(fileDialog, FileDialog.LOAD );
341
            }
342
        }
343
        chooser.setMultiSelectionEnabled(false);
344
        int dlgResult = chooser.showOpenDialog(findDialogParent());
345
        if (JFileChooser.APPROVE_OPTION == dlgResult) {
346
            File result = chooser.getSelectedFile();
347
            if (result != null && !result.exists()) {
348
                result = null;
349
            }
350
            return result;
351
        } else {
352
            return null;
353
        }
354
355
    }
356
357
    /**
358
     * Show a save dialog with the file chooser set up according to the
359
     * parameters of this builder.
360
     * @return A file if the user clicks the accept button and a file or
361
     * folder was selected at the time the user clicked cancel.
362
     */
363
    public File showSaveDialog() {
364
        JFileChooser chooser = createFileChooser();
365
        if( Boolean.getBoolean("nb.native.filechooser") ) { //NOI18N
366
            FileDialog fileDialog = createFileDialog( chooser.getCurrentDirectory() );
367
            if( null != fileDialog ) {
368
                return showFileDialog( fileDialog, FileDialog.SAVE );
369
            }
370
        }
371
        int result = chooser.showSaveDialog(findDialogParent());
372
        if (JFileChooser.APPROVE_OPTION == result) {
373
            return chooser.getSelectedFile();
374
        } else {
375
            return null;
376
        }
377
    }
378
    
379
    private File showFileDialog( FileDialog fileDialog, int mode ) {
380
        String oldFileDialogProp = System.getProperty("apple.awt.fileDialogForDirectories"); //NOI18N
381
        if( dirsOnly ) {
382
            System.setProperty("apple.awt.fileDialogForDirectories", "true"); //NOI18N
383
        }
384
        fileDialog.setMode( mode );
385
        fileDialog.setVisible(true);
386
        if( dirsOnly ) {
387
            if( null != oldFileDialogProp ) {
388
                System.setProperty("apple.awt.fileDialogForDirectories", oldFileDialogProp); //NOI18N
389
            } else {
390
                System.clearProperty("apple.awt.fileDialogForDirectories"); //NOI18N
391
            }
392
        }
393
        if( fileDialog.getDirectory() != null && fileDialog.getFile() != null ) {
394
            String selFile = fileDialog.getFile();
395
            File dir = new File( fileDialog.getDirectory() );
396
            return new File( dir, selFile );
397
        }
398
        return null;
399
    }
400
    
401
    private void prepareFileChooser(JFileChooser chooser) {
402
        chooser.setFileSelectionMode(dirsOnly ? JFileChooser.DIRECTORIES_ONLY
403
                : filesOnly ? JFileChooser.FILES_ONLY :
404
                JFileChooser.FILES_AND_DIRECTORIES);
405
        chooser.setFileHidingEnabled(fileHiding);
406
        chooser.setControlButtonsAreShown(controlButtonsShown);
407
        chooser.setAcceptAllFileFilterUsed(useAcceptAllFileFilter);
408
        if (title != null) {
409
            chooser.setDialogTitle(title);
410
        }
411
        if (approveText != null) {
412
            chooser.setApproveButtonText(approveText);
413
        }
414
        if (badger != null) {
415
            chooser.setFileView(new CustomFileView(new BadgeIconProvider(badger),
416
                    chooser.getFileSystemView()));
417
        }
418
        if (PREVENT_SYMLINK_TRAVERSAL) {
419
            FileUtil.preventFileChooserSymlinkTraversal(chooser,
420
                    chooser.getCurrentDirectory());
421
        }
422
        if (filter != null) {
423
            chooser.setFileFilter(filter);
424
        }
425
        if (aDescription != null) {
426
            chooser.getAccessibleContext().setAccessibleDescription(aDescription);
427
        }
428
        if (!filters.isEmpty()) {
429
            for (FileFilter f : filters) {
430
                chooser.addChoosableFileFilter(f);
431
            }
432
        }
433
    }
434
435
    private FileDialog createFileDialog( File currentDirectory ) {
436
        if( badger != null )
437
            return null;
438
        if( !Boolean.getBoolean("nb.native.filechooser") )
439
            return null;
440
        if( dirsOnly && !Utilities.isMac() )
441
            return null;
442
        Component parentComponent = findDialogParent();
443
        Frame parentFrame = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parentComponent);
444
        FileDialog fileDialog = new FileDialog(parentFrame);
445
        if (title != null) {
446
            fileDialog.setTitle(title);
447
        }
448
        if( null != currentDirectory )
449
            fileDialog.setDirectory(currentDirectory.getAbsolutePath());
450
        return fileDialog;
451
    }
452
    
453
    /**
454
     * Equivalent to calling <code>JFileChooser.addChoosableFileFilter(filter)</code>.
455
     * Adds another file filter that can be displayed in the file filters combo
456
     * box in the file chooser.
457
     *
458
     * @param filter The file filter to add
459
     * @return this
460
     * @since 7.26.0
461
     */
462
    public FileChooserBuilder addFileFilter (FileFilter filter) {
463
        filters.add (filter);
464
        return this;
465
    }
466
467
    /**
468
     * Add all default file filters to the file chooser.
469
     *
470
     * @see MIMEResolver.Registration#showInFileChooser()
471
     * @see MIMEResolver.ExtensionRegistration#showInFileChooser()
472
     * @return this
473
     * @since 8.1
474
     */
475
    public FileChooserBuilder addDefaultFileFilters() {
476
        filters.addAll(FileFilterSupport.findRegisteredFileFilters());
477
        return this;
478
    }
479
480
    /**
481
     * Set a selection approver which can display an &quot;Overwrite file?&quot;
482
     * or similar dialog if necessary, when the user presses the accept button
483
     * in the file chooser dialog.
484
     *
485
     * @param approver A SelectionApprover which will determine if the selection
486
     * is valid
487
     * @return this
488
     * @since 7.26.0
489
     */
490
    public FileChooserBuilder setSelectionApprover (SelectionApprover approver) {
491
        this.approver = approver;
492
        return this;
493
    }
494
495
    /**
496
     * Object which can approve the selection (enabling the OK button or
497
     * equivalent) in a JFileChooser.  Equivalent to overriding
498
     * <code>JFileChooser.approveSelection()</code>
499
     * @since 7.26.0
500
     */
501
    public interface SelectionApprover {
502
        /**
503
         * Approve the selection, enabling the dialog to be closed.  Called by
504
         * the JFileChooser's <code>approveSelection()</code> method.  Use this
505
         * interface if you want to, for example, show a dialog asking
506
         * &quot;Overwrite File X?&quot; or similar.
507
         *
508
         * @param selection The selected file(s) at the time the user presses
509
         * the Open, Save or OK button
510
         * @return true if the selection is accepted, false if it is not and
511
         * the dialog should not be closed
512
         */
513
        public boolean approve (File[] selection);
514
    }
515
516
    private static final class SavedDirFileChooser extends JFileChooser {
517
        private final String dirKey;
518
        private final SelectionApprover approver;
519
        SavedDirFileChooser(String dirKey, File failoverDir, boolean force, SelectionApprover approver) {
520
            this.dirKey = dirKey;
521
            this.approver = approver;
522
            if (force && failoverDir != null && failoverDir.exists() && failoverDir.isDirectory()) {
523
                setCurrentDirectory(failoverDir);
524
            } else {
525
                String path = DONT_STORE_DIRECTORIES ? null :
526
                    NbPreferences.forModule(FileChooserBuilder.class).get(dirKey, null);
527
                if (path != null) {
528
                    File f = new File(path);
529
                    if (f.exists() && f.isDirectory()) {
530
                        setCurrentDirectory(f);
531
                    } else if (failoverDir != null) {
532
                        setCurrentDirectory(failoverDir);
533
                    }
534
                } else if (failoverDir != null) {
535
                    setCurrentDirectory(failoverDir);
536
                }
537
            }
538
        }
539
540
        @Override
541
        public void approveSelection() {
542
            if (approver != null) {
543
                File[] selected = getSelectedFiles();
544
                final File sf = getSelectedFile();
545
                if ((selected == null || selected.length == 0) && sf != null) {
546
                    selected = new File[] { sf };
547
                }
548
                boolean approved = approver.approve(selected);
549
                if (approved) {
550
                    super.approveSelection();
551
                }
552
            } else {
553
                super.approveSelection();
554
            }
555
        }
556
557
        @Override
558
        public int showDialog(Component parent, String approveButtonText) throws HeadlessException {
559
            int result = super.showDialog(parent, approveButtonText);
560
            if (result == APPROVE_OPTION) {
561
                saveCurrentDir();
562
            }
563
            return result;
564
        }
565
566
        private void saveCurrentDir() {
567
            File dir = super.getCurrentDirectory();
568
            if (!DONT_STORE_DIRECTORIES && dir != null && dir.exists() && dir.isDirectory()) {
569
                NbPreferences.forModule(FileChooserBuilder.class).put(dirKey, dir.getPath());
570
            }
571
        }
572
    }
573
574
    //Can open this API later if there is a use-case
575
    interface IconProvider {
576
        public Icon getIcon(File file, Icon orig);
577
    }
578
579
    /**
580
     * Provides "badges" for icons that indicate files or folders of particular
581
     * interest to the user.
582
     * @see FileChooserBuilder#setBadgeProvider
583
     */
584
    public interface BadgeProvider {
585
        /**
586
         *  Get the badge the passed file should use.  <b>Note:</b> this method
587
         * is called for every visible file.  The negative test (deciding
588
         * <i>not</i> to badge a file) should be very, very fast and immediately
589
         * return null.
590
         * @param file The file in question
591
         * @return an icon or null if no change to the appearance of the file
592
         * is needed
593
         */
594
        public Icon getBadge(File file);
595
596
        /**
597
         * Get the x offset for badges produced by this provider.  This is
598
         * the location of the badge icon relative to the real icon for the
599
         * file.
600
         * @return  a rightward pixel offset
601
         */
602
        public int getXOffset();
603
604
        /**
605
         * Get the y offset for badges produced by this provider.  This is
606
         * the location of the badge icon relative to the real icon for the
607
         * file.
608
         * @return  a downward pixel offset
609
         */
610
        public int getYOffset();
611
    }
612
613
    private static final class BadgeIconProvider implements IconProvider {
614
615
        private final BadgeProvider badger;
616
617
        public BadgeIconProvider(BadgeProvider badger) {
618
            this.badger = badger;
619
        }
620
621
        public Icon getIcon(File file, Icon orig) {
622
            Icon badge = badger.getBadge(file);
623
            if (badge != null && orig != null) {
624
                return new MergedIcon(orig, badge, badger.getXOffset(),
625
                        badger.getYOffset());
626
            }
627
            return orig;
628
        }
629
    }
630
631
    private static final class CustomFileView extends FileView {
632
633
        private final IconProvider provider;
634
        private final FileSystemView view;
635
636
        CustomFileView(IconProvider provider, FileSystemView view) {
637
            this.provider = provider;
638
            this.view = view;
639
        }
640
641
        @Override
642
        public Icon getIcon(File f) {
643
            Icon result = view.getSystemIcon(f);
644
            result = provider.getIcon(f, result);
645
            return result;
646
        }
647
    }
648
649
    private static class MergedIcon implements Icon {
650
651
        private Icon icon1;
652
        private Icon icon2;
653
        private int xMerge;
654
        private int yMerge;
655
656
        MergedIcon(Icon icon1, Icon icon2, int xMerge, int yMerge) {
657
            assert icon1 != null;
658
            assert icon2 != null;
659
            this.icon1 = icon1;
660
            this.icon2 = icon2;
661
662
            if (xMerge == -1) {
663
                xMerge = icon1.getIconWidth() - icon2.getIconWidth();
664
            }
665
666
            if (yMerge == -1) {
667
                yMerge = icon1.getIconHeight() - icon2.getIconHeight();
668
            }
669
670
            this.xMerge = xMerge;
671
            this.yMerge = yMerge;
672
        }
673
674
        public int getIconHeight() {
675
            return Math.max(icon1.getIconHeight(), yMerge + icon2.getIconHeight());
676
        }
677
678
        public int getIconWidth() {
679
            return Math.max(icon1.getIconWidth(), yMerge + icon2.getIconWidth());
680
        }
681
682
        public void paintIcon(java.awt.Component c, java.awt.Graphics g, int x, int y) {
683
            icon1.paintIcon(c, g, x, y);
684
            icon2.paintIcon(c, g, x + xMerge, y + yMerge);
685
        }
686
    }
687
}
(-)a/openide.filesystems/src/org/openide/filesystems/FileObject.java (-3 / +2 lines)
Lines 68-74 Link Here
68
import org.openide.util.NbBundle;
68
import org.openide.util.NbBundle;
69
import org.openide.util.Lookup;
69
import org.openide.util.Lookup;
70
import org.openide.util.Lookup.Result;
70
import org.openide.util.Lookup.Result;
71
import org.openide.util.UserQuestionException;
72
71
73
/** This is the base for all implementations of file objects on a filesystem.
72
/** This is the base for all implementations of file objects on a filesystem.
74
* Provides basic information about the object (its name, parent,
73
* Provides basic information about the object (its name, parent,
Lines 838-844 Link Here
838
    /** Lock this file.
837
    /** Lock this file.
839
    * @return lock that can be used to perform various modifications on the file
838
    * @return lock that can be used to perform various modifications on the file
840
    * @throws FileAlreadyLockedException if the file is already locked
839
    * @throws FileAlreadyLockedException if the file is already locked
841
    * @throws UserQuestionException in case when the lock cannot be obtained now,
840
    * @throws IOException (UserQuestionException) in case when the lock cannot be obtained now,
842
    *    but the underlaying implementation is able to do it after some
841
    *    but the underlaying implementation is able to do it after some
843
    *    complex/dangerous/long-lasting operation and request confirmation
842
    *    complex/dangerous/long-lasting operation and request confirmation
844
    *    from the user
843
    *    from the user
Lines 1093-1099 Link Here
1093
     * <li>Then:
1092
     * <li>Then:
1094
     * <ul>
1093
     * <ul>
1095
     * <li>If no exception is thrown, proceed with the operation.
1094
     * <li>If no exception is thrown, proceed with the operation.
1096
     * <li>If a {@link UserQuestionException} is thrown,
1095
     * <li>If a UserQuestionException is thrown,
1097
     * call {@link UserQuestionException#confirmed} on it
1096
     * call {@link UserQuestionException#confirmed} on it
1098
     * (asynchronously - do not block any important threads). If <code>true</code>,
1097
     * (asynchronously - do not block any important threads). If <code>true</code>,
1099
     * proceed with the operation. If <code>false</code>, exit.
1098
     * proceed with the operation. If <code>false</code>, exit.
(-)a/openide.filesystems/src/org/openide/filesystems/FileSystem.java (-200 / +12 lines)
Lines 45-52 Link Here
45
package org.openide.filesystems;
45
package org.openide.filesystems;
46
46
47
import java.awt.Image;
47
import java.awt.Image;
48
import java.awt.Toolkit;
49
import java.beans.BeanInfo;
50
import java.beans.PropertyChangeEvent;
48
import java.beans.PropertyChangeEvent;
51
import java.beans.PropertyChangeListener;
49
import java.beans.PropertyChangeListener;
52
import java.beans.PropertyChangeSupport;
50
import java.beans.PropertyChangeSupport;
Lines 57-62 Link Here
57
import java.net.URL;
55
import java.net.URL;
58
import java.util.Arrays;
56
import java.util.Arrays;
59
import java.util.Collection;
57
import java.util.Collection;
58
import java.util.Iterator;
60
import java.util.List;
59
import java.util.List;
61
import java.util.MissingResourceException;
60
import java.util.MissingResourceException;
62
import java.util.ResourceBundle;
61
import java.util.ResourceBundle;
Lines 64-70 Link Here
64
import java.util.logging.Level;
63
import java.util.logging.Level;
65
import java.util.logging.Logger;
64
import java.util.logging.Logger;
66
import org.openide.util.*;
65
import org.openide.util.*;
67
import org.openide.util.actions.SystemAction;
68
import org.openide.util.lookup.ServiceProvider;
66
import org.openide.util.lookup.ServiceProvider;
69
import org.openide.util.lookup.ServiceProviders;
67
import org.openide.util.lookup.ServiceProviders;
70
68
Lines 159-167 Link Here
159
    /** Property name giving read-only state. */
157
    /** Property name giving read-only state. */
160
    public static final String PROP_READ_ONLY = "readOnly"; // NOI18N
158
    public static final String PROP_READ_ONLY = "readOnly"; // NOI18N
161
159
162
    /** Property name giving capabilities state. @deprecated No more capabilities. */
163
    static final String PROP_CAPABILITIES = "capabilities"; // NOI18N    
164
165
    /** Used for synchronization purpose*/
160
    /** Used for synchronization purpose*/
166
    private static final Object internLock = new Object();
161
    private static final Object internLock = new Object();
167
    private transient static ThreadLocal<EventControl> thrLocal = new ThreadLocal<EventControl>();
162
    private transient static ThreadLocal<EventControl> thrLocal = new ThreadLocal<EventControl>();
Lines 192-209 Link Here
192
    private transient Repository repository = null;
187
    private transient Repository repository = null;
193
    private transient FCLSupport fclSupport;
188
    private transient FCLSupport fclSupport;
194
189
195
    /** Describes capabilities of the filesystem.
196
    */
197
    @Deprecated // have to store it for compat
198
    private /* XXX JDK #6460147: javac still reports it even though @Deprecated,
199
               and @SuppressWarnings("deprecation") does not help either: FileSystemCapability*/Object capability;
200
201
    /** property listener on FileSystemCapability. */
202
    private transient PropertyChangeListener capabilityListener;
203
204
    /** hidden flag */
205
    private boolean hidden = false;
206
207
    /** system name */
190
    /** system name */
208
    private String systemName = ""; // NOI18N
191
    private String systemName = ""; // NOI18N
209
192
Lines 250-296 Link Here
250
        }
233
        }
251
    }
234
    }
252
235
253
    /** Set hidden state of the object.
254
     * A hidden filesystem is not presented to the user in the Repository list (though it may be present in the Repository Settings list).
255
    *
256
    * @param hide <code>true</code> if the filesystem should be hidden
257
     * @deprecated This property is now useless.
258
    */
259
    @Deprecated
260
    public final void setHidden(boolean hide) {
261
        if (hide != hidden) {
262
            hidden = hide;
263
            firePropertyChange(PROP_HIDDEN, (!hide) ? Boolean.TRUE : Boolean.FALSE, hide ? Boolean.TRUE : Boolean.FALSE);
264
        }
265
    }
266
267
    /** Getter for the hidden property.
268
     * @return the hidden property.
269
     * @deprecated This property is now useless.
270
    */
271
    @Deprecated
272
    public final boolean isHidden() {
273
        return hidden;
274
    }
275
276
    /** Tests whether filesystem will survive reloading of system pool.
277
    * If true then when
278
    * {@link Repository} is reloading its content, it preserves this
279
    * filesystem in the pool.
280
    * <P>
281
    * This can be used when the pool contains system level and user level
282
    * filesystems. The system ones should be preserved when the user changes
283
    * the content (for example when he is loading a new project).
284
    * <p>The default implementation returns <code>false</code>.
285
    *
286
    * @return true if the filesystem should be persistent
287
     * @deprecated This property is long since useless.
288
    */
289
    @Deprecated
290
    protected boolean isPersistent() {
291
        return false;
292
    }
293
294
    /** Provides a name for the system that can be presented to the user.
236
    /** Provides a name for the system that can be presented to the user.
295
    * <P>
237
    * <P>
296
    * This call should <STRONG>never</STRONG> be used to attempt to identify the file root
238
    * This call should <STRONG>never</STRONG> be used to attempt to identify the file root
Lines 468-494 Link Here
468
        throw new IOException("Unsupported operation"); // NOI18N
410
        throw new IOException("Unsupported operation"); // NOI18N
469
    }
411
    }
470
        
412
        
471
    /** Returns an array of actions that can be invoked on any file in
472
    * this filesystem.
473
    * These actions should preferably
474
    * support the {@link org.openide.util.actions.Presenter.Menu Menu},
475
    * {@link org.openide.util.actions.Presenter.Popup Popup},
476
    * and {@link org.openide.util.actions.Presenter.Toolbar Toolbar} presenters.
477
    *
478
    * @return array of available actions
479
    */
480
    public abstract SystemAction[] getActions();
481
482
    /**
483
     * Get actions appropriate to a certain file selection.
484
     * By default, returns the same list as {@link #getActions()}.
485
     * @param foSet one or more files which may be selected
486
     * @return zero or more actions appropriate to those files
487
     */
488
    public SystemAction[] getActions(Set<FileObject> foSet) {
489
        return this.getActions();
490
    }
491
492
    /** Reads object from stream and creates listeners.
413
    /** Reads object from stream and creates listeners.
493
    * @param in the input stream to read from
414
    * @param in the input stream to read from
494
    * @exception IOException error during read
415
    * @exception IOException error during read
Lines 498-531 Link Here
498
    private void readObject(java.io.ObjectInputStream in)
419
    private void readObject(java.io.ObjectInputStream in)
499
    throws java.io.IOException, java.lang.ClassNotFoundException {
420
    throws java.io.IOException, java.lang.ClassNotFoundException {
500
        in.defaultReadObject();
421
        in.defaultReadObject();
501
502
        if (capability != null) {
503
            ((FileSystemCapability) capability).addPropertyChangeListener(getCapabilityChangeListener());
504
        }
505
    }
422
    }
506
423
507
    @Override
424
    @Override
508
    public String toString() {
425
    public String toString() {
509
        return getSystemName() + "[" + super.toString() + "]"; // NOI18N
426
        return getSystemName() + "[" + super.toString() + "]"; // NOI18N
510
    }
427
    }
511
428
    
512
    /** Allows filesystems to set up the environment for external execution
429
    private static volatile Lookup.Result<FileSystem.Status> statusResult;
513
    * and compilation.
430
    
514
    * Each filesystem can add its own values that
431
    private static FileSystem.Status defaultStatus() {
515
    * influence the environment. The set of operations that can modify
432
        if (statusResult == null) {
516
    * environment is described by the {@link Environment} interface.
433
            statusResult = Lookup.getDefault().lookupResult(FileSystem.Status.class);
517
    * <P>
434
        }
518
    * The default implementation throws an exception to signal that it does not
435
        Iterator<? extends FileSystem.Status> it = statusResult.allInstances().iterator();
519
    * support external compilation or execution.
436
        return it.hasNext() ? it.next() : SFS_STATUS;
520
    *
521
    * @param env the environment to setup
522
    * @exception EnvironmentNotSupportedException if external execution
523
    *    and compilation cannot be supported
524
    * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
525
    */
526
    @Deprecated
527
    public void prepareEnvironment(Environment env) throws EnvironmentNotSupportedException {
528
        throw new EnvironmentNotSupportedException(this);
529
    }
437
    }
530
438
531
    /**
439
    /**
Lines 552-591 Link Here
552
     * @return the status object for this filesystem
460
     * @return the status object for this filesystem
553
     */
461
     */
554
    public Status getStatus() {
462
    public Status getStatus() {
555
        return isDefault() ? SFS_STATUS : STATUS_NONE;
463
        return isDefault() ? defaultStatus() : STATUS_NONE;
556
    }
557
558
    /** The object describing capabilities of this filesystem.
559
     * Subclasses cannot override it.
560
     * @return object describing capabilities of this filesystem.
561
     * @deprecated Capabilities are no longer used.
562
     */
563
    @Deprecated
564
    public final FileSystemCapability getCapability() {
565
        if (capability == null) {
566
            capability = new FileSystemCapability.Bean();
567
            ((FileSystemCapability) capability).addPropertyChangeListener(getCapabilityChangeListener());
568
        }
569
570
        return (FileSystemCapability) capability;
571
    }
572
573
    /** Allows subclasses to change a set of capabilities of the
574
    * filesystem.
575
    * @param capability the capability to use
576
     * @deprecated Capabilities are no longer used.
577
    */
578
    @Deprecated
579
    protected final void setCapability(FileSystemCapability capability) {
580
        if (this.capability != null) {
581
            ((FileSystemCapability) this.capability).removePropertyChangeListener(getCapabilityChangeListener());
582
        }
583
584
        this.capability = capability;
585
586
        if (this.capability != null) {
587
            ((FileSystemCapability) this.capability).addPropertyChangeListener(getCapabilityChangeListener());
588
        }
589
    }
464
    }
590
465
591
    /** Executes atomic action. The atomic action represents a set of
466
    /** Executes atomic action. The atomic action represents a set of
Lines 644-664 Link Here
644
        getEventControl().dispatchEvent(run);
519
        getEventControl().dispatchEvent(run);
645
    }
520
    }
646
521
647
    /** returns property listener on FileSystemCapability. */
648
    private synchronized PropertyChangeListener getCapabilityChangeListener() {
649
        if (capabilityListener == null) {
650
            capabilityListener = new PropertyChangeListener() {
651
                        public void propertyChange(java.beans.PropertyChangeEvent propertyChangeEvent) {
652
                            firePropertyChange(
653
                                PROP_CAPABILITIES, propertyChangeEvent.getOldValue(), propertyChangeEvent.getNewValue()
654
                            );
655
                        }
656
                    };
657
        }
658
659
        return capabilityListener;
660
    }
661
662
    private final EventControl getEventControl() {
522
    private final EventControl getEventControl() {
663
        EventControl evnCtrl = thrLocal.get();
523
        EventControl evnCtrl = thrLocal.get();
664
524
Lines 971-997 Link Here
971
        public String annotateNameHtml(String name, Set<? extends FileObject> files);
831
        public String annotateNameHtml(String name, Set<? extends FileObject> files);
972
    }
832
    }
973
833
974
    /** Interface that allows filesystems to set up the Java environment
975
    * for external execution and compilation.
976
    * Currently just used to append entries to the external class path.
977
    * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
978
    */
979
    @Deprecated
980
    public static abstract class Environment extends Object {
981
        /** Deprecated. */
982
        public Environment() {
983
            assert false : "Deprecated.";
984
        }
985
986
        /** Adds one element to the class path environment variable.
987
        * @param classPathElement string representing the one element
988
        * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
989
        */
990
        @Deprecated
991
        public void addClassPath(String classPathElement) {
992
        }
993
    }
994
995
    /** Class used to notify events for the filesystem.
834
    /** Class used to notify events for the filesystem.
996
    */
835
    */
997
    static abstract class EventDispatcher extends Object implements Runnable {
836
    static abstract class EventDispatcher extends Object implements Runnable {
Lines 1052-1058 Link Here
1052
            String bundleName = (String) fo.getAttribute("SystemFileSystem.localizingBundle"); // NOI18N
891
            String bundleName = (String) fo.getAttribute("SystemFileSystem.localizingBundle"); // NOI18N
1053
            if (bundleName != null) {
892
            if (bundleName != null) {
1054
                try {
893
                try {
1055
                    bundleName = Utilities.translate(bundleName);
894
                    bundleName = BaseUtilities.translate(bundleName);
1056
                    ResourceBundle b = NbBundle.getBundle(bundleName);
895
                    ResourceBundle b = NbBundle.getBundle(bundleName);
1057
                    try {
896
                    try {
1058
                        return b.getString(fo.getPath());
897
                        return b.getString(fo.getPath());
Lines 1087-1119 Link Here
1087
        }
926
        }
1088
927
1089
        private Image annotateIcon(FileObject fo, int type) {
928
        private Image annotateIcon(FileObject fo, int type) {
1090
            String attr = null;
1091
            if (type == BeanInfo.ICON_COLOR_16x16) {
1092
                attr = "SystemFileSystem.icon"; // NOI18N
1093
            } else if (type == BeanInfo.ICON_COLOR_32x32) {
1094
                attr = "SystemFileSystem.icon32"; // NOI18N
1095
            }
1096
            if (attr != null) {
1097
                Object value = fo.getAttribute(attr);
1098
                if (value != null) {
1099
                    if (value instanceof URL) {
1100
                        return Toolkit.getDefaultToolkit().getImage((URL) value);
1101
                    } else if (value instanceof Image) {
1102
                        // #18832
1103
                        return (Image) value;
1104
                    } else {
1105
                        LOG.warning("Attribute " + attr + " on " + fo + " expected to be a URL or Image; was: " + value);
1106
                    }
1107
                }
1108
            }
1109
            String base = (String) fo.getAttribute("iconBase"); // NOI18N
1110
            if (base != null) {
1111
                if (type == BeanInfo.ICON_COLOR_16x16) {
1112
                    return ImageUtilities.loadImage(base, true);
1113
                } else if (type == BeanInfo.ICON_COLOR_32x32) {
1114
                    return ImageUtilities.loadImage(insertBeforeSuffix(base, "_32"), true); // NOI18N
1115
                }
1116
            }
1117
            return null;
929
            return null;
1118
        }
930
        }
1119
931
(-)a/openide.filesystems/src/org/openide/filesystems/FileSystemCapability.java (-435 lines)
Lines 1-435 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * Contributor(s):
28
 *
29
 * The Original Software is NetBeans. The Initial Developer of the Original
30
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
31
 * Microsystems, Inc. All Rights Reserved.
32
 *
33
 * If you wish your version of this file to be governed by only the CDDL
34
 * or only the GPL Version 2, indicate your decision by adding
35
 * "[Contributor] elects to include this software in this distribution
36
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
37
 * single choice of license, a recipient has the option to distribute
38
 * your version of this file under either the CDDL, the GPL Version 2 or
39
 * to extend the choice of license to its licensees as provided above.
40
 * However, if you add GPL Version 2 code and therefore, elected the GPL
41
 * Version 2 license, then the option applies only if the new code is
42
 * made subject to such option by the copyright holder.
43
 */
44
45
package org.openide.filesystems;
46
47
import java.beans.PropertyChangeListener;
48
import java.beans.PropertyChangeSupport;
49
import java.util.Collection;
50
import java.util.Enumeration;
51
import java.util.Vector;
52
53
/** This class defines the capabilities of a filesystem to
54
* take part in different operations. Some filesystems are
55
* not designed to allow compilation on them, some do not want
56
* to be present in class path when executing or debugging
57
* a program.
58
* <P>
59
* Moreover there can be additional capabilities to check
60
* and this class defines ways how one can communicated with
61
* a filesystem to find out whether the system is "capable"
62
* enough to be used in the operation.
63
*
64
* @author Jaroslav Tulach
65
 * @deprecated Now useless.
66
*/
67
@Deprecated
68
public class FileSystemCapability extends Object {
69
    /** Object that is capable of every thing.
70
    */
71
    public static final FileSystemCapability ALL = new FileSystemCapability() {
72
            public boolean capableOf(FileSystemCapability c) {
73
                return true;
74
            }
75
        };
76
77
    /** Well known capability of being compiled.
78
     * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
79
     */
80
    @Deprecated
81
    public static final FileSystemCapability COMPILE = new FileSystemCapability();
82
83
    /** Well known ability to be executed.
84
     * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
85
     */
86
    @Deprecated
87
    public static final FileSystemCapability EXECUTE = new FileSystemCapability();
88
89
    /** Well known ability to be debugged.
90
     * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
91
     */
92
    @Deprecated
93
    public static final FileSystemCapability DEBUG = new FileSystemCapability();
94
95
    /** Well known ability to contain documentation files
96
     * @deprecated Please use <a href="@org-netbeans-api-java@/org/netbeans/api/queries/JavadocForBinaryQuery.html"><code>JavadocForBinaryQuery</code></a> instead.
97
     */
98
    @Deprecated
99
    public static final FileSystemCapability DOC = new FileSystemCapability();
100
101
    public FileSystemCapability() {
102
        if (DOC == null) {
103
            // do not report static initializers
104
            return;
105
        }
106
107
        assert false : "Deprecated.";
108
    }
109
110
    /** Basic operation that tests whether this object
111
    * is capable to do different capability.
112
    * <P>
113
    * The default implementation claims that it is
114
    * capable to handle only identical capability (==).
115
    *
116
    * @param c capability to test
117
    * @return true if yes
118
    */
119
    public boolean capableOf(FileSystemCapability c) {
120
        return c == this;
121
    }
122
123
    /** All filesystems that are capable of this capability.
124
    * @return enumeration of FileSystems that satifies this capability
125
    * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
126
    */
127
    @Deprecated
128
    public Enumeration<? extends FileSystem> fileSystems() {
129
        class FFS implements org.openide.util.Enumerations.Processor<FileSystem, FileSystem> {
130
            @Deprecated
131
            public FileSystem process(FileSystem fs, Collection<FileSystem> ignore) {
132
                return fs.getCapability().capableOf(FileSystemCapability.this) ? fs : null;
133
            }
134
        }
135
136
        return org.openide.util.Enumerations.filter(Repository.getDefault().fileSystems(), new FFS());
137
    }
138
139
    /** Find a resource in repository, ignoring not capable filesystems.
140
    * @param resName name of the resource
141
    * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
142
    */
143
    @Deprecated
144
    public FileObject findResource(String resName) {
145
        Enumeration<? extends FileSystem> en = fileSystems();
146
147
        while (en.hasMoreElements()) {
148
            FileSystem fs = en.nextElement();
149
            FileObject fo = fs.findResource(resName);
150
151
            if (fo != null) {
152
                // object found
153
                return fo;
154
            }
155
        }
156
157
        return null;
158
    }
159
160
    /** Searches for the given resource among all filesystems
161
    * that satifies this capability, returning all matches.
162
    * @param name name of the resource
163
    * @return enumeration of {@link FileObject}s
164
    * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
165
    */
166
    @Deprecated
167
    public Enumeration<? extends FileObject> findAllResources(String name) {
168
        Vector<FileObject> v = new Vector<FileObject>(8);
169
        Enumeration<? extends FileSystem> en = fileSystems();
170
171
        while (en.hasMoreElements()) {
172
            FileSystem fs = en.nextElement();
173
            FileObject fo = fs.findResource(name);
174
175
            if (fo != null) {
176
                v.addElement(fo);
177
            }
178
        }
179
180
        return v.elements();
181
    }
182
183
    /** Finds file when its name is provided. It scans in the list of
184
    * filesystems and asks them for the specified file by a call to
185
    * {@link FileSystem#find find}. The first object that is found is returned or <CODE>null</CODE>
186
    * if none of the filesystems contain such a file.
187
    *
188
    * @param aPackage package name where each package is separated by a dot
189
    * @param name name of the file (without dots) or <CODE>null</CODE> if
190
    *    one wants to obtain the name of a package and not a file in it
191
    * @param ext extension of the file or <CODE>null</CODE> if one needs
192
    *    a package and not a file name
193
    *
194
    * @return {@link FileObject} that represents file with given name or
195
    *   <CODE>null</CODE> if the file does not exist
196
    * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
197
    */
198
    @Deprecated
199
    public final FileObject find(String aPackage, String name, String ext) {
200
        Enumeration<? extends FileSystem> en = fileSystems();
201
202
        while (en.hasMoreElements()) {
203
            FileSystem fs = en.nextElement();
204
            FileObject fo = fs.find(aPackage, name, ext);
205
206
            if (fo != null) {
207
                // object found
208
                return fo;
209
            }
210
        }
211
212
        return null;
213
    }
214
215
    /** Finds all files among all filesystems with this capability
216
    * that match a given name, returning all matches.
217
    * All filesystems are queried with {@link FileSystem#find}.
218
    *
219
    * @param aPackage package name where each package is separated by a dot
220
    * @param name name of the file (without dots) or <CODE>null</CODE> if
221
    *    one wants to obtain the name of a package and not a file in it
222
    * @param ext extension of the file or <CODE>null</CODE> if one needs
223
    *    a package and not a file name
224
    *
225
    * @return enumeration of {@link FileObject}s
226
    * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
227
    */
228
    @Deprecated
229
    public final Enumeration<? extends FileObject> findAll(String aPackage, String name, String ext) {
230
        Enumeration<? extends FileSystem> en = fileSystems();
231
        Vector<FileObject> ret = new Vector<FileObject>();
232
233
        while (en.hasMoreElements()) {
234
            FileSystem fs = (FileSystem) en.nextElement();
235
            FileObject fo = fs.find(aPackage, name, ext);
236
237
            if (fo != null) {
238
                ret.addElement(fo);
239
            }
240
        }
241
242
        return ret.elements();
243
    }
244
245
    /** Adds PropertyChange listener. Every class which implements changes of capabilities
246
    * has to implement it's property change support.
247
    * @param l the listener to be added.
248
    */
249
    public synchronized void addPropertyChangeListener(PropertyChangeListener l) {
250
    }
251
252
    /** Removes PropertyChange listener. Every class which implements changes of capabilities
253
    * has to implement it's property change support.
254
    * @param l the listener to be removed.
255
    */
256
    public void removePropertyChangeListener(PropertyChangeListener l) {
257
    }
258
259
    /** Default implementation of capabilities, that behaves like
260
    * JavaBean and allows to set whether the well known
261
    * capabilities (like compile, execute) should be enabled
262
    * or not.
263
     * @deprecated For the same reason the whole class is.
264
    */
265
    @Deprecated
266
    public static class Bean extends FileSystemCapability implements java.io.Serializable {
267
        static final long serialVersionUID = 627905674809532736L;
268
269
        /** change listeners */
270
        private transient PropertyChangeSupport supp;
271
272
        /** compilation */
273
        private boolean compilation = true;
274
275
        /** execution */
276
        private boolean execution = true;
277
278
        /** debugging */
279
        private boolean debug = true;
280
281
        /** doc */
282
        private boolean doc = false;
283
284
        /** Checks for well known capabilities and if they are allowed.
285
        *
286
        * @param c capability to test
287
        * @return true if yes
288
        */
289
        public boolean capableOf(FileSystemCapability c) {
290
            if (c == COMPILE) {
291
                return compilation;
292
            }
293
294
            if (c == EXECUTE) {
295
                return execution;
296
            }
297
298
            if (c == DEBUG) {
299
                return debug;
300
            }
301
302
            if (c == DOC) {
303
                return doc;
304
            }
305
306
            if (c == ALL) {
307
                return true;
308
            }
309
310
            if (!(c instanceof Bean)) {
311
                return false;
312
            }
313
314
            // try match of values
315
            Bean b = (Bean) c;
316
317
            return (compilation == b.compilation) && (execution == b.execution) && (debug == b.debug) &&
318
            (doc == b.doc);
319
        }
320
321
        /** Getter for value of compiling capability.
322
         * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
323
        */
324
        @Deprecated
325
        public boolean getCompile() {
326
            return compilation;
327
        }
328
329
        /** Setter for allowing compiling capability.
330
         * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
331
        */
332
        @Deprecated
333
        public void setCompile(boolean val) {
334
            if (val != compilation) {
335
                compilation = val;
336
337
                if (supp != null) {
338
                    supp.firePropertyChange(
339
                        "compile", // NOI18N
340
                        (!val) ? Boolean.TRUE : Boolean.FALSE, val ? Boolean.TRUE : Boolean.FALSE
341
                    );
342
                }
343
            }
344
        }
345
346
        /** Getter for value of executiong capability.
347
         * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
348
        */
349
        @Deprecated
350
        public boolean getExecute() {
351
            return execution;
352
        }
353
354
        /** Setter for allowing executing capability.
355
         * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
356
        */
357
        @Deprecated
358
        public void setExecute(boolean val) {
359
            if (val != execution) {
360
                execution = val;
361
362
                if (supp != null) {
363
                    supp.firePropertyChange(
364
                        "execute", // NOI18N
365
                        (!val) ? Boolean.TRUE : Boolean.FALSE, val ? Boolean.TRUE : Boolean.FALSE
366
                    );
367
                }
368
            }
369
        }
370
371
        /** Getter for value of debugging capability.
372
         * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
373
        */
374
        @Deprecated
375
        public boolean getDebug() {
376
            return debug;
377
        }
378
379
        /** Setter for allowing debugging capability.
380
         * @deprecated Please use the <a href="@org-netbeans-api-java-classpath@/org/netbeans/api/java/classpath/ClassPath.html">ClassPath API</a> instead.
381
        */
382
        @Deprecated
383
        public void setDebug(boolean val) {
384
            if (val != debug) {
385
                debug = val;
386
387
                if (supp != null) {
388
                    supp.firePropertyChange(
389
                        "debug", // NOI18N
390
                        (!val) ? Boolean.TRUE : Boolean.FALSE, val ? Boolean.TRUE : Boolean.FALSE
391
                    );
392
                }
393
            }
394
        }
395
396
        /** Getter for value of doc capability.
397
         * @deprecated Please use <a href="@org-netbeans-api-java@/org/netbeans/api/queries/JavadocForBinaryQuery.html"><code>JavadocForBinaryQuery</code></a> instead.
398
        */
399
        @Deprecated
400
        public boolean getDoc() {
401
            return doc;
402
        }
403
404
        /** Setter for allowing debugging capability.
405
         * @deprecated Please use <a href="@org-netbeans-api-java@/org/netbeans/api/queries/JavadocForBinaryQuery.html"><code>JavadocForBinaryQuery</code></a> instead.
406
        */
407
        @Deprecated
408
        public void setDoc(boolean val) {
409
            if (val != doc) {
410
                doc = val;
411
412
                if (supp != null) {
413
                    supp.firePropertyChange(
414
                        "doc", // NOI18N
415
                        (!val) ? Boolean.TRUE : Boolean.FALSE, val ? Boolean.TRUE : Boolean.FALSE
416
                    );
417
                }
418
            }
419
        }
420
421
        public synchronized void addPropertyChangeListener(PropertyChangeListener l) {
422
            if (supp == null) {
423
                supp = new PropertyChangeSupport(this);
424
            }
425
426
            supp.addPropertyChangeListener(l);
427
        }
428
429
        public void removePropertyChangeListener(PropertyChangeListener l) {
430
            if (supp != null) {
431
                supp.removePropertyChangeListener(l);
432
            }
433
        }
434
    }
435
}
(-)a/openide.filesystems/src/org/openide/filesystems/FileUtil.java (-137 / +17 lines)
Lines 84-99 Link Here
84
import java.util.jar.JarInputStream;
84
import java.util.jar.JarInputStream;
85
import java.util.logging.Level;
85
import java.util.logging.Level;
86
import java.util.logging.Logger;
86
import java.util.logging.Logger;
87
import javax.swing.Icon;
88
import javax.swing.JFileChooser;
89
import javax.swing.filechooser.FileSystemView;
90
import org.netbeans.modules.openide.filesystems.declmime.MIMEResolverImpl;
87
import org.netbeans.modules.openide.filesystems.declmime.MIMEResolverImpl;
91
import org.openide.filesystems.FileSystem.AtomicAction;
88
import org.openide.filesystems.FileSystem.AtomicAction;
92
import org.openide.util.Exceptions;
89
import org.openide.util.Exceptions;
93
import org.openide.util.NbBundle;
90
import org.openide.util.NbBundle;
94
import org.openide.util.Parameters;
91
import org.openide.util.Parameters;
95
import org.openide.util.RequestProcessor;
92
import org.openide.util.RequestProcessor;
96
import org.openide.util.Utilities;
93
import org.openide.util.BaseUtilities;
97
import org.openide.util.WeakListeners;
94
import org.openide.util.WeakListeners;
98
import org.openide.util.lookup.implspi.NamedServicesProvider;
95
import org.openide.util.lookup.implspi.NamedServicesProvider;
99
96
Lines 835-844 Link Here
835
            }
832
            }
836
833
837
            if ((fileURL != null) && "file".equals(fileURL.getProtocol())) {
834
            if ((fileURL != null) && "file".equals(fileURL.getProtocol())) {
838
                retVal = Utilities.toFile(URI.create(fileURL.toExternalForm()));
835
                retVal = BaseUtilities.toFile(URI.create(fileURL.toExternalForm()));
839
            }
836
            }
840
        }
837
        }
841
        assert assertNormalized(retVal, Utilities.isMac()); // #240180
838
        assert assertNormalized(retVal, BaseUtilities.isMac()); // #240180
842
        return retVal;
839
        return retVal;
843
    }
840
    }
844
841
Lines 885-891 Link Here
885
882
886
        FileObject retVal = null;
883
        FileObject retVal = null;
887
        try {
884
        try {
888
            URL url = Utilities.toURI(file).toURL();
885
            URL url = BaseUtilities.toURI(file).toURL();
889
            retVal = URLMapper.findFileObject(url);
886
            retVal = URLMapper.findFileObject(url);
890
887
891
            /*probably temporary piece of code to catch the cause of #46630*/
888
            /*probably temporary piece of code to catch the cause of #46630*/
Lines 928-934 Link Here
928
        }
925
        }
929
926
930
        try {
927
        try {
931
            URL url = (Utilities.toURI(file).toURL());
928
            URL url = (BaseUtilities.toURI(file).toURL());
932
            retVal = URLMapper.findFileObjects(url);
929
            retVal = URLMapper.findFileObjects(url);
933
        } catch (MalformedURLException e) {
930
        } catch (MalformedURLException e) {
934
            retVal = null;
931
            retVal = null;
Lines 1212-1218 Link Here
1212
     * @return true, if such name does not exists
1209
     * @return true, if such name does not exists
1213
     */
1210
     */
1214
    private static boolean checkFreeName(FileObject fo, String name, String ext) {
1211
    private static boolean checkFreeName(FileObject fo, String name, String ext) {
1215
        if ((Utilities.isWindows() || (Utilities.getOperatingSystem() == Utilities.OS_OS2)) || Utilities.isMac()) {
1212
        if ((BaseUtilities.isWindows() || (BaseUtilities.getOperatingSystem() == BaseUtilities.OS_OS2)) || BaseUtilities.isMac()) {
1216
            // case-insensitive, do some special check
1213
            // case-insensitive, do some special check
1217
            Enumeration<? extends FileObject> en = fo.getChildren(false);
1214
            Enumeration<? extends FileObject> en = fo.getChildren(false);
1218
1215
Lines 1607-1615 Link Here
1607
        LOG.log(Level.FINE, "FileUtil.normalizeFile for {0}", file); // NOI18N
1604
        LOG.log(Level.FINE, "FileUtil.normalizeFile for {0}", file); // NOI18N
1608
1605
1609
        long now = System.currentTimeMillis();
1606
        long now = System.currentTimeMillis();
1610
        if ((Utilities.isWindows() || (Utilities.getOperatingSystem() == Utilities.OS_OS2))) {
1607
        if ((BaseUtilities.isWindows() || (BaseUtilities.getOperatingSystem() == BaseUtilities.OS_OS2))) {
1611
            retFile = normalizeFileOnWindows(file);
1608
            retFile = normalizeFileOnWindows(file);
1612
        } else if (Utilities.isMac()) {
1609
        } else if (BaseUtilities.isMac()) {
1613
            retFile = normalizeFileOnMac(file);
1610
            retFile = normalizeFileOnMac(file);
1614
        } else {
1611
        } else {
1615
            retFile = normalizeFileOnUnixAlike(file);
1612
            retFile = normalizeFileOnUnixAlike(file);
Lines 1625-1631 Link Here
1625
    private static File normalizeFileOnUnixAlike(File file) {
1622
    private static File normalizeFileOnUnixAlike(File file) {
1626
        // On Unix, do not want to traverse symlinks.
1623
        // On Unix, do not want to traverse symlinks.
1627
        // URI.normalize removes ../ and ./ sequences nicely.
1624
        // URI.normalize removes ../ and ./ sequences nicely.
1628
        file = Utilities.toFile(Utilities.toURI(file).normalize()).getAbsoluteFile();
1625
        file = BaseUtilities.toFile(BaseUtilities.toURI(file).normalize()).getAbsoluteFile();
1629
        while (file.getAbsolutePath().startsWith("/../")) { // NOI18N
1626
        while (file.getAbsolutePath().startsWith("/../")) { // NOI18N
1630
            file = new File(file.getAbsolutePath().substring(3));
1627
            file = new File(file.getAbsolutePath().substring(3));
1631
        }
1628
        }
Lines 1641-1647 Link Here
1641
1638
1642
        try {
1639
        try {
1643
            // URI.normalize removes ../ and ./ sequences nicely.            
1640
            // URI.normalize removes ../ and ./ sequences nicely.            
1644
            File absoluteFile = Utilities.toFile(Utilities.toURI(file).normalize());
1641
            File absoluteFile = BaseUtilities.toFile(BaseUtilities.toURI(file).normalize());
1645
            File canonicalFile = file.getCanonicalFile();
1642
            File canonicalFile = file.getCanonicalFile();
1646
            String absolutePath = absoluteFile.getAbsolutePath();
1643
            String absolutePath = absoluteFile.getAbsolutePath();
1647
            if (absolutePath.equals("/..")) { // NOI18N
1644
            if (absolutePath.equals("/..")) { // NOI18N
Lines 1738-1744 Link Here
1738
            }
1735
            }
1739
        }
1736
        }
1740
        // #135547 - on Windows Vista map "Documents and Settings\<username>\My Documents" to "Users\<username>\Documents"
1737
        // #135547 - on Windows Vista map "Documents and Settings\<username>\My Documents" to "Users\<username>\Documents"
1741
        if((Utilities.getOperatingSystem() & Utilities.OS_WINVISTA) != 0) {
1738
        if((BaseUtilities.getOperatingSystem() & BaseUtilities.OS_WINVISTA) != 0) {
1742
            if(retVal == null) {
1739
            if(retVal == null) {
1743
                retVal = file.getAbsoluteFile();
1740
                retVal = file.getAbsoluteFile();
1744
            }
1741
            }
Lines 1987-1993 Link Here
1987
            do {
1984
            do {
1988
                wasDir = entry.isDirectory();
1985
                wasDir = entry.isDirectory();
1989
                LOG.finest("urlForArchiveOrDir:toURI:entry");   //NOI18N
1986
                LOG.finest("urlForArchiveOrDir:toURI:entry");   //NOI18N
1990
                u = Utilities.toURI(entry).toURL();
1987
                u = BaseUtilities.toURI(entry).toURL();
1991
                isDir = entry.isDirectory();
1988
                isDir = entry.isDirectory();
1992
            } while (wasDir ^ isDir);
1989
            } while (wasDir ^ isDir);
1993
            if (isArchiveFile(u) || entry.isFile() && entry.length() < 4) {
1990
            if (isArchiveFile(u) || entry.isFile() && entry.length() < 4) {
Lines 2022-2030 Link Here
2022
    public static File archiveOrDirForURL(URL entry) {
2019
    public static File archiveOrDirForURL(URL entry) {
2023
        String u = entry.toString();
2020
        String u = entry.toString();
2024
        if (u.startsWith("jar:file:") && u.endsWith("!/")) { // NOI18N
2021
        if (u.startsWith("jar:file:") && u.endsWith("!/")) { // NOI18N
2025
            return Utilities.toFile(URI.create(u.substring(4, u.length() - 2)));
2022
            return BaseUtilities.toFile(URI.create(u.substring(4, u.length() - 2)));
2026
        } else if (u.startsWith("file:")) { // NOI18N
2023
        } else if (u.startsWith("file:")) { // NOI18N
2027
            return Utilities.toFile(URI.create(u));
2024
            return BaseUtilities.toFile(URI.create(u));
2028
        } else {
2025
        } else {
2029
            return null;
2026
            return null;
2030
        }
2027
        }
Lines 2034-2047 Link Here
2034
     * Make sure that a JFileChooser does not traverse symlinks on Unix.
2031
     * Make sure that a JFileChooser does not traverse symlinks on Unix.
2035
     * @param chooser a file chooser
2032
     * @param chooser a file chooser
2036
     * @param currentDirectory if not null, a file to set as the current directory
2033
     * @param currentDirectory if not null, a file to set as the current directory
2037
     *                         using {@link JFileChooser#setCurrentDirectory} without canonicalizing
2034
     *                         using {@link javax.swing.JFileChooser#setCurrentDirectory} without canonicalizing
2038
     * @see <a href="http://www.netbeans.org/issues/show_bug.cgi?id=46459">Issue #46459</a>
2035
     * @see <a href="http://www.netbeans.org/issues/show_bug.cgi?id=46459">Issue #46459</a>
2039
     * @see <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4906607">JRE bug #4906607</a>
2036
     * @see <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4906607">JRE bug #4906607</a>
2040
     * @since org.openide/1 4.42
2037
     * @since org.openide/1 4.42
2041
     * @deprecated Just use {@link JFileChooser#setCurrentDirectory}. JDK 6 does not have this bug.
2038
     * @deprecated Just use {@link javax.swing.JFileChooser#setCurrentDirectory}. JDK 6 does not have this bug.
2042
     */
2039
     */
2043
    @Deprecated
2040
    @Deprecated
2044
    public static void preventFileChooserSymlinkTraversal(JFileChooser chooser, File currentDirectory) {
2041
    public static void preventFileChooserSymlinkTraversal(javax.swing.JFileChooser chooser, File currentDirectory) {
2045
        chooser.setCurrentDirectory(currentDirectory);
2042
        chooser.setCurrentDirectory(currentDirectory);
2046
    }
2043
    }
2047
2044
Lines 2211-2333 Link Here
2211
        }
2208
        }
2212
    }
2209
    }
2213
2210
2214
    private static final class NonCanonicalizingFileSystemView extends FileSystemView {
2215
        private final FileSystemView delegate = FileSystemView.getFileSystemView();
2216
2217
        public NonCanonicalizingFileSystemView() {
2218
        }
2219
2220
        @Override
2221
        public boolean isFloppyDrive(File dir) {
2222
            return delegate.isFloppyDrive(dir);
2223
        }
2224
2225
        @Override
2226
        public boolean isComputerNode(File dir) {
2227
            return delegate.isComputerNode(dir);
2228
        }
2229
2230
        public File createNewFolder(File containingDir)
2231
        throws IOException {
2232
            return wrapFileNoCanonicalize(delegate.createNewFolder(containingDir));
2233
        }
2234
2235
        @Override
2236
        public boolean isDrive(File dir) {
2237
            return delegate.isDrive(dir);
2238
        }
2239
2240
        @Override
2241
        public boolean isFileSystemRoot(File dir) {
2242
            return delegate.isFileSystemRoot(dir);
2243
        }
2244
2245
        @Override
2246
        public File getHomeDirectory() {
2247
            return wrapFileNoCanonicalize(delegate.getHomeDirectory());
2248
        }
2249
2250
        @Override
2251
        public File createFileObject(File dir, String filename) {
2252
            return wrapFileNoCanonicalize(delegate.createFileObject(dir, filename));
2253
        }
2254
2255
        @Override
2256
        public Boolean isTraversable(File f) {
2257
            return delegate.isTraversable(f);
2258
        }
2259
2260
        @Override
2261
        public boolean isFileSystem(File f) {
2262
            return delegate.isFileSystem(f);
2263
        }
2264
2265
        /*
2266
        protected File createFileSystemRoot(File f) {
2267
            return translate(delegate.createFileSystemRoot(f));
2268
        }
2269
         */
2270
        @Override
2271
        public File getChild(File parent, String fileName) {
2272
            return wrapFileNoCanonicalize(delegate.getChild(parent, fileName));
2273
        }
2274
2275
        @Override
2276
        public File getParentDirectory(File dir) {
2277
            return wrapFileNoCanonicalize(delegate.getParentDirectory(dir));
2278
        }
2279
2280
        @Override
2281
        public Icon getSystemIcon(File f) {
2282
            return delegate.getSystemIcon(f);
2283
        }
2284
2285
        @Override
2286
        public boolean isParent(File folder, File file) {
2287
            return delegate.isParent(folder, file);
2288
        }
2289
2290
        @Override
2291
        public String getSystemTypeDescription(File f) {
2292
            return delegate.getSystemTypeDescription(f);
2293
        }
2294
2295
        @Override
2296
        public File getDefaultDirectory() {
2297
            return wrapFileNoCanonicalize(delegate.getDefaultDirectory());
2298
        }
2299
2300
        @Override
2301
        public String getSystemDisplayName(File f) {
2302
            return delegate.getSystemDisplayName(f);
2303
        }
2304
2305
        @Override
2306
        public File[] getRoots() {
2307
            return wrapFilesNoCanonicalize(delegate.getRoots());
2308
        }
2309
2310
        @Override
2311
        public boolean isHiddenFile(File f) {
2312
            return delegate.isHiddenFile(f);
2313
        }
2314
2315
        @Override
2316
        public File[] getFiles(File dir, boolean useFileHiding) {
2317
            return wrapFilesNoCanonicalize(delegate.getFiles(dir, useFileHiding));
2318
        }
2319
2320
        @Override
2321
        public boolean isRoot(File f) {
2322
            return delegate.isRoot(f);
2323
        }
2324
2325
        @Override
2326
        public File createFileObject(String path) {
2327
            return wrapFileNoCanonicalize(delegate.createFileObject(path));
2328
        }
2329
    }
2330
    
2331
    private static FileSystem getDiskFileSystem() {
2211
    private static FileSystem getDiskFileSystem() {
2332
        synchronized (FileUtil.class) {
2212
        synchronized (FileUtil.class) {
2333
            return diskFileSystem;
2213
            return diskFileSystem;
(-)a/openide.filesystems/src/org/openide/filesystems/JarFileSystem.java (-27 / +4 lines)
Lines 80-86 Link Here
80
import org.openide.util.NbBundle;
80
import org.openide.util.NbBundle;
81
import org.openide.util.RequestProcessor;
81
import org.openide.util.RequestProcessor;
82
import org.openide.util.RequestProcessor.Task;
82
import org.openide.util.RequestProcessor.Task;
83
import org.openide.util.Utilities;
83
import org.openide.util.BaseUtilities;
84
84
85
/** A virtual filesystem based on a JAR archive.
85
/** A virtual filesystem based on a JAR archive.
86
* <p>For historical reasons many AbstractFileSystem.* methods are implemented
86
* <p>For historical reasons many AbstractFileSystem.* methods are implemented
Lines 167-184 Link Here
167
        this.attr = impl;
167
        this.attr = impl;
168
    }
168
    }
169
169
170
    /**
170
   /** Creates new JAR for a given JAR file. This constructor
171
    * Constructor that can provide own capability for the filesystem.
172
    * @param cap the capability
173
     * @deprecated Useless.
174
    */
175
    @Deprecated
176
    public JarFileSystem(FileSystemCapability cap) {
177
        this();
178
        setCapability(cap);
179
    }
180
181
    /** Creates new JAR for a given JAR file. This constructor
182
     * behaves basically like:
171
     * behaves basically like:
183
     * <pre>
172
     * <pre>
184
     * JarFileSystem fs = new JarFileSystem();
173
     * JarFileSystem fs = new JarFileSystem();
Lines 427-444 Link Here
427
    //        super.addNotify ();
416
    //        super.addNotify ();
428
    //    }
417
    //    }
429
418
430
    /** Prepare environment for external compilation or execution.
431
    * <P>
432
    * Adds name of the ZIP/JAR file, if it has been set, to the class path.
433
     * @deprecated Useless.
434
    */
435
    @Deprecated
436
    @Override
437
    public void prepareEnvironment(Environment env) {
438
        if (root != null) {
439
            env.addClassPath(root.getAbsolutePath());
440
        }
441
    }
442
419
443
    //
420
    //
444
    // List
421
    // List
Lines 985-991 Link Here
985
    }
962
    }
986
    
963
    
987
    private static void dumpFDs() {
964
    private static void dumpFDs() {
988
        if (Utilities.isUnix()) {
965
        if (BaseUtilities.isUnix()) {
989
            String selfName = ManagementFactory.getRuntimeMXBean().getName().replaceAll("@.*", ""); // NOI18N
966
            String selfName = ManagementFactory.getRuntimeMXBean().getName().replaceAll("@.*", ""); // NOI18N
990
            LOGGER.log(Level.INFO, "Dumping file descriptors for pid {0}", selfName); // NOI18N
967
            LOGGER.log(Level.INFO, "Dumping file descriptors for pid {0}", selfName); // NOI18N
991
            int pid;
968
            int pid;
Lines 1017-1023 Link Here
1017
     */
994
     */
1018
    private class Ref<T extends FileObject> extends WeakReference<T> implements Runnable {
995
    private class Ref<T extends FileObject> extends WeakReference<T> implements Runnable {
1019
        public Ref(T fo) {
996
        public Ref(T fo) {
1020
            super(fo, Utilities.activeReferenceQueue());
997
            super(fo, BaseUtilities.activeReferenceQueue());
1021
        }
998
        }
1022
999
1023
        // do the cleanup
1000
        // do the cleanup
(-)a/openide.filesystems/src/org/openide/filesystems/LocalFileSystem.java (-25 / +4 lines)
Lines 61-67 Link Here
61
import java.util.logging.Level;
61
import java.util.logging.Level;
62
import org.openide.util.Exceptions;
62
import org.openide.util.Exceptions;
63
import org.openide.util.NbBundle;
63
import org.openide.util.NbBundle;
64
import org.openide.util.Utilities;
64
import org.openide.util.BaseUtilities;
65
65
66
/** Local filesystem. Provides access to files on local disk.
66
/** Local filesystem. Provides access to files on local disk.
67
* <p>For historical reasons many AbstractFileSystem.* methods are implemented
67
* <p>For historical reasons many AbstractFileSystem.* methods are implemented
Lines 103-119 Link Here
103
        setRefreshTime(REFRESH_TIME);
103
        setRefreshTime(REFRESH_TIME);
104
    }
104
    }
105
105
106
    /** Constructor. Allows user to provide own capabilities
107
    * for this filesystem.
108
    * @param cap capabilities for this filesystem
109
     * @deprecated Useless.
110
    */
111
    @Deprecated
112
    public LocalFileSystem(FileSystemCapability cap) {
113
        this();
114
        setCapability(cap);
115
    }
116
117
    /* Human presentable name */
106
    /* Human presentable name */
118
    public String getDisplayName() {
107
    public String getDisplayName() {
119
        return rootFile.getAbsolutePath();
108
        return rootFile.getAbsolutePath();
Lines 170-185 Link Here
170
        return readOnly;
159
        return readOnly;
171
    }
160
    }
172
161
173
    /** Prepare environment by adding the root directory of the filesystem to the class path.
174
    * @param environment the environment to add to
175
     * @deprecated Useless.
176
    */
177
    @Deprecated
178
    @Override
179
    public void prepareEnvironment(FileSystem.Environment environment) {
180
        environment.addClassPath(rootFile.getAbsolutePath());
181
    }
182
183
    /** Compute the system name of this filesystem for a given root directory.
162
    /** Compute the system name of this filesystem for a given root directory.
184
    * <P>
163
    * <P>
185
    * The default implementation simply returns the filename separated by slashes.
164
    * The default implementation simply returns the filename separated by slashes.
Lines 190-196 Link Here
190
    protected String computeSystemName(File rootFile) {
169
    protected String computeSystemName(File rootFile) {
191
        String retVal = rootFile.getAbsolutePath().replace(File.separatorChar, '/');
170
        String retVal = rootFile.getAbsolutePath().replace(File.separatorChar, '/');
192
171
193
        return ((Utilities.isWindows() || (Utilities.getOperatingSystem() == Utilities.OS_OS2))) ? retVal.toLowerCase()
172
        return ((BaseUtilities.isWindows() || (BaseUtilities.getOperatingSystem() == BaseUtilities.OS_OS2))) ? retVal.toLowerCase()
194
                                                                                                 : retVal;
173
                                                                                                 : retVal;
195
    }
174
    }
196
175
Lines 301-307 Link Here
301
            // #7086 - (nf.exists() && !nf.equals(of)) instead of nf.exists() - fix for Win32
280
            // #7086 - (nf.exists() && !nf.equals(of)) instead of nf.exists() - fix for Win32
302
            boolean existsNF = nf.exists();
281
            boolean existsNF = nf.exists();
303
            boolean equalsOF = nf.equals(of);
282
            boolean equalsOF = nf.equals(of);
304
            if (Utilities.isMac()) {
283
            if (BaseUtilities.isMac()) {
305
                // File.equal on mac is not case insensitive (which it should be), 
284
                // File.equal on mac is not case insensitive (which it should be), 
306
                // so try harder
285
                // so try harder
307
                equalsOF = of.getCanonicalFile().equals(nf.getCanonicalFile());
286
                equalsOF = of.getCanonicalFile().equals(nf.getCanonicalFile());
Lines 465-471 Link Here
465
        OutputStream retVal = new BufferedOutputStream(new FileOutputStream(f));
444
        OutputStream retVal = new BufferedOutputStream(new FileOutputStream(f));
466
445
467
        // workaround for #42624
446
        // workaround for #42624
468
        if (Utilities.isMac()) {
447
        if (BaseUtilities.isMac()) {
469
            retVal = getOutputStreamForMac42624(retVal, name);
448
            retVal = getOutputStreamForMac42624(retVal, name);
470
        }
449
        }
471
450
(-)a/openide.filesystems/src/org/openide/filesystems/MultiFileSystem.java (-70 lines)
Lines 45-51 Link Here
45
package org.openide.filesystems;
45
package org.openide.filesystems;
46
46
47
import java.io.IOException;
47
import java.io.IOException;
48
import java.util.ArrayList;
49
import java.util.Arrays;
48
import java.util.Arrays;
50
import java.util.Collection;
49
import java.util.Collection;
51
import java.util.Collections;
50
import java.util.Collections;
Lines 57-63 Link Here
57
import org.openide.util.Enumerations;
56
import org.openide.util.Enumerations;
58
import org.openide.util.NbBundle;
57
import org.openide.util.NbBundle;
59
import org.openide.util.NbCollections;
58
import org.openide.util.NbCollections;
60
import org.openide.util.actions.SystemAction;
61
59
62
/**
60
/**
63
 * General base class for filesystems which proxy to others.
61
 * General base class for filesystems which proxy to others.
Lines 287-340 Link Here
287
        return root;
285
        return root;
288
    }
286
    }
289
287
290
    /** Merge actions from all delegates.
291
    */
292
    public @Override SystemAction[] getActions() {
293
        List<SystemAction> al = new ArrayList<SystemAction>(101); // randomly choosen constant
294
        Set<SystemAction> uniq = new HashSet<SystemAction>(101); // not that randommly choosen
295
296
        FileSystem[] del = this.getDelegates();
297
298
        for (int i = 0; i < del.length; i++) {
299
            if (del[i] == null) {
300
                continue;
301
            }
302
303
            SystemAction[] acts = del[i].getActions();
304
305
            for (int j = 0; j < acts.length; j++) {
306
                if (uniq.add(acts[j])) {
307
                    al.add(acts[j]);
308
                }
309
            }
310
        }
311
312
        return al.toArray(new SystemAction[al.size()]);
313
    }
314
315
    public @Override SystemAction[] getActions(final Set<FileObject> foSet) {
316
        List<SystemAction> al = new ArrayList<SystemAction>(101); // randomly choosen constant
317
        Set<SystemAction> uniq = new HashSet<SystemAction>(101); // not that randommly choosen
318
319
        final FileSystem[] del = this.getDelegates();
320
321
        for (int i = 0; i < del.length; i++) {
322
            if (del[i] == null) {
323
                continue;
324
            }
325
326
            final SystemAction[] acts = del[i].getActions(foSet);
327
328
            for (int j = 0; j < acts.length; j++) {
329
                if (uniq.add(acts[j])) {
330
                    al.add(acts[j]);
331
                }
332
            }
333
        }
334
335
        return al.toArray(new SystemAction[al.size()]);
336
    }
337
338
    @Deprecated // have to override for compat
288
    @Deprecated // have to override for compat
339
    public @Override FileObject find(String aPackage, String name, String ext) {
289
    public @Override FileObject find(String aPackage, String name, String ext) {
340
        // create enumeration of name to look for
290
        // create enumeration of name to look for
Lines 544-569 Link Here
544
    protected void markUnimportant(FileObject fo) {
494
    protected void markUnimportant(FileObject fo) {
545
    }
495
    }
546
496
547
    /** Lets any sub filesystems prepare the environment.
548
     * If they do not support it, it does not care.
549
     * @deprecated Useless.
550
     */
551
    @Deprecated
552
    public @Override void prepareEnvironment(FileSystem.Environment env)
553
    throws EnvironmentNotSupportedException {
554
        FileSystem[] layers = getDelegates();
555
556
        for (int i = 0; i < layers.length; i++) {
557
            if (layers[i] != null) {
558
                try {
559
                    layers[i].prepareEnvironment(env);
560
                } catch (EnvironmentNotSupportedException ense) {
561
                    // Fine.
562
                }
563
            }
564
        }
565
    }
566
567
    /** Notifies all encapsulated filesystems in advance
497
    /** Notifies all encapsulated filesystems in advance
568
    * to superclass behaviour. */
498
    * to superclass behaviour. */
569
    public @Override void addNotify() {
499
    public @Override void addNotify() {
(-)a/openide.filesystems/src/org/openide/filesystems/Ordering.java (-2 / +2 lines)
Lines 47-53 Link Here
47
import java.util.logging.Logger;
47
import java.util.logging.Logger;
48
import org.openide.util.NbCollections;
48
import org.openide.util.NbCollections;
49
import org.openide.util.TopologicalSortException;
49
import org.openide.util.TopologicalSortException;
50
import org.openide.util.Utilities;
50
import org.openide.util.BaseUtilities;
51
51
52
/**
52
/**
53
 * Implements folder ordering logic in {@link FileUtil}.
53
 * Implements folder ordering logic in {@link FileUtil}.
Lines 209-215 Link Here
209
            return new ArrayList<FileObject>(children);
209
            return new ArrayList<FileObject>(children);
210
        } else {
210
        } else {
211
            try {
211
            try {
212
                return Utilities.topologicalSort(children, edges);
212
                return BaseUtilities.topologicalSort(children, edges);
213
            } catch (TopologicalSortException x) {
213
            } catch (TopologicalSortException x) {
214
                if (logWarnings) {
214
                if (logWarnings) {
215
                    LOG.log(Level.WARNING, "Contradictory partial ordering in " + parent.getPath(), x);
215
                    LOG.log(Level.WARNING, "Contradictory partial ordering in " + parent.getPath(), x);
(-)a/openide.filesystems/src/org/openide/filesystems/Repository.java (-2 / +2 lines)
Lines 631-637 Link Here
631
        while (iter.hasNext()) {
631
        while (iter.hasNext()) {
632
            FileSystem fs = (FileSystem) iter.next();
632
            FileSystem fs = (FileSystem) iter.next();
633
633
634
            if (!fs.isDefault() && !fs.isPersistent()) {
634
            if (!fs.isDefault()) {
635
                oos.writeObject(new NbMarshalledObject(fs));
635
                oos.writeObject(new NbMarshalledObject(fs));
636
            }
636
            }
637
        }
637
        }
Lines 688-694 Link Here
688
        while (ee.hasMoreElements()) {
688
        while (ee.hasMoreElements()) {
689
            fs = ee.nextElement();
689
            fs = ee.nextElement();
690
690
691
            if (!fs.isPersistent()) {
691
            if (!fs.isDefault()) {
692
                removeFileSystem(fs);
692
                removeFileSystem(fs);
693
            }
693
            }
694
        }
694
        }
(-)a/openide.filesystems/src/org/openide/filesystems/URLMapper.java (-4 / +4 lines)
Lines 64-70 Link Here
64
import org.openide.util.Lookup;
64
import org.openide.util.Lookup;
65
import org.openide.util.LookupEvent;
65
import org.openide.util.LookupEvent;
66
import org.openide.util.LookupListener;
66
import org.openide.util.LookupListener;
67
import org.openide.util.Utilities;
67
import org.openide.util.BaseUtilities;
68
68
69
/** Mapper from FileObject -> URL.
69
/** Mapper from FileObject -> URL.
70
 * Should be registered in default lookup. For details see {@link Lookup#getDefault()}.
70
 * Should be registered in default lookup. For details see {@link Lookup#getDefault()}.
Lines 422-428 Link Here
422
                    // XXX clumsy; see ArchiveURLMapper for possible cleaner style
422
                    // XXX clumsy; see ArchiveURLMapper for possible cleaner style
423
                    String toReplace = "__EXCLAMATION_REPLACEMENT__";//NOI18N
423
                    String toReplace = "__EXCLAMATION_REPLACEMENT__";//NOI18N
424
                    retURL = new URL(
424
                    retURL = new URL(
425
                            "jar:" + Utilities.toURI(new File(f,toReplace + fo.getPath())).toString().replaceFirst("/"+toReplace,"!/") + // NOI18N
425
                            "jar:" + BaseUtilities.toURI(new File(f,toReplace + fo.getPath())).toString().replaceFirst("/"+toReplace,"!/") + // NOI18N
426
                            ((fo.isFolder() && !fo.isRoot()) ? "/" : "")
426
                            ((fo.isFolder() && !fo.isRoot()) ? "/" : "")
427
                        ); // NOI18N
427
                        ); // NOI18N
428
                } catch (MalformedURLException mfx) {
428
                } catch (MalformedURLException mfx) {
Lines 460-466 Link Here
460
        }
460
        }
461
461
462
        private static URL toURL(File fFile, FileObject fo) throws MalformedURLException {
462
        private static URL toURL(File fFile, FileObject fo) throws MalformedURLException {
463
            URL retVal = Utilities.toURI(fFile).toURL();
463
            URL retVal = BaseUtilities.toURI(fFile).toURL();
464
            if (retVal != null && fo.isFolder()) {
464
            if (retVal != null && fo.isFolder()) {
465
                // #155742,160333 - URL for folder must always end with slash
465
                // #155742,160333 - URL for folder must always end with slash
466
                final String urlDef = retVal.toExternalForm();
466
                final String urlDef = retVal.toExternalForm();
Lines 529-535 Link Here
529
            try {
529
            try {
530
                URI uri = new URI(u.toExternalForm());
530
                URI uri = new URI(u.toExternalForm());
531
531
532
                return FileUtil.normalizeFile(Utilities.toFile(uri));
532
                return FileUtil.normalizeFile(BaseUtilities.toFile(uri));
533
            } catch (URISyntaxException use) {
533
            } catch (URISyntaxException use) {
534
                // malformed URL
534
                // malformed URL
535
                return null;
535
                return null;
(-)a/openide.filesystems/src/org/openide/filesystems/XMLFileSystem.java (-3 / +3 lines)
Lines 74-80 Link Here
74
import org.openide.util.Enumerations;
74
import org.openide.util.Enumerations;
75
import org.openide.util.Exceptions;
75
import org.openide.util.Exceptions;
76
import org.openide.util.NbBundle;
76
import org.openide.util.NbBundle;
77
import org.openide.util.Utilities;
77
import org.openide.util.BaseUtilities;
78
import org.openide.xml.XMLUtil;
78
import org.openide.xml.XMLUtil;
79
import org.xml.sax.Attributes;
79
import org.xml.sax.Attributes;
80
import org.xml.sax.InputSource;
80
import org.xml.sax.InputSource;
Lines 240-251 Link Here
240
    * for this filesystem.
240
    * for this filesystem.
241
    * @param cap capabilities for this filesystem
241
    * @param cap capabilities for this filesystem
242
     * @deprecated Useless.
242
     * @deprecated Useless.
243
    */
244
    @Deprecated
243
    @Deprecated
245
    public XMLFileSystem(FileSystemCapability cap) {
244
    public XMLFileSystem(FileSystemCapability cap) {
246
        this();
245
        this();
247
        setCapability(cap);
246
        setCapability(cap);
248
    }
247
    }
248
    */
249
249
250
    /** Getter of url field.
250
    /** Getter of url field.
251
     * @return URL associated with XMLFileSystem or null if no URL was set.
251
     * @return URL associated with XMLFileSystem or null if no URL was set.
Lines 1113-1119 Link Here
1113
                
1113
                
1114
                if ("file".equals(protocol)) { //NOI18N
1114
                if ("file".equals(protocol)) { //NOI18N
1115
                    try {
1115
                    try {
1116
                        File f = Utilities.toFile(URI.create(url.toExternalForm()));
1116
                        File f = BaseUtilities.toFile(URI.create(url.toExternalForm()));
1117
                        if (!f.equals(lastFile)) {
1117
                        if (!f.equals(lastFile)) {
1118
                            lastFile = f;
1118
                            lastFile = f;
1119
                            lastFileDate = new Date(f.lastModified());
1119
                            lastFileDate = new Date(f.lastModified());
(-)a/openide.filesystems/src/org/openide/filesystems/XMLMapAttr.java (-12 / +5 lines)
Lines 65-73 Link Here
65
import java.util.TreeSet;
65
import java.util.TreeSet;
66
import java.util.concurrent.atomic.AtomicBoolean;
66
import java.util.concurrent.atomic.AtomicBoolean;
67
import java.util.logging.Level;
67
import java.util.logging.Level;
68
import org.netbeans.modules.openide.filesystems.RecognizeInstanceFiles;
68
import org.openide.util.NbBundle;
69
import org.openide.util.NbBundle;
69
import org.openide.util.SharedClassObject;
70
import org.openide.util.BaseUtilities;
70
import org.openide.util.Utilities;
71
import org.openide.util.io.NbMarshalledObject;
71
import org.openide.util.io.NbMarshalledObject;
72
import org.openide.util.io.NbObjectInputStream;
72
import org.openide.util.io.NbObjectInputStream;
73
73
Lines 824-830 Link Here
824
                    case 11:
824
                    case 11:
825
                        return URL.class;
825
                        return URL.class;
826
                    case 12:
826
                    case 12:
827
                        return ExternalUtil.findClass(Utilities.translate(value));
827
                        return ExternalUtil.findClass(BaseUtilities.translate(value));
828
                    case 13:
828
                    case 13:
829
                        return String.class;
829
                        return String.class;
830
                }
830
                }
Lines 967-981 Link Here
967
                        return new URL(value);
967
                        return new URL(value);
968
                    case 12:
968
                    case 12:
969
                        // special support for singletons
969
                        // special support for singletons
970
                        Class cls = ExternalUtil.findClass(Utilities.translate(value));
970
                        Class cls = ExternalUtil.findClass(BaseUtilities.translate(value));
971
971
                        return RecognizeInstanceFiles.createInstance(cls);
972
                        if (SharedClassObject.class.isAssignableFrom(cls)) {
973
                            return SharedClassObject.findObject(cls, true);
974
                        } else {
975
                            Constructor<?> init = cls.getDeclaredConstructor();
976
                            init.setAccessible(true);
977
                            return init.newInstance((Object[]) null);
978
                        }
979
                    case 13:
972
                    case 13:
980
                        String[] arr = value.split("#", 2); // NOI18N
973
                        String[] arr = value.split("#", 2); // NOI18N
981
                        return NbBundle.getBundle(arr[0]).getObject(arr[1]);
974
                        return NbBundle.getBundle(arr[0]).getObject(arr[1]);
(-)a/openide.filesystems/src/org/openide/filesystems/spi/CustomInstanceFactory.java (+71 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2014 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2014 Sun Microsystems, Inc.
41
 */
42
43
package org.openide.filesystems.spi;
44
45
/**
46
 * Creates instance of the desired class based on the file.
47
 * Module providers may register factories to control creation of instances
48
 * from files that use only file name or {@code instanceClass} attribute.
49
 * <p/>
50
 * Registered factories are called in the registration order, until one provides
51
 * a non-null result, which become the file's created instance. If all factories
52
 * return {@code null}, the FileSystems API will create the instance using the default
53
 * constructor.
54
 * 
55
 * <p/>
56
 * Module implementors are encouraged to use the <code>instanceCreate</code> attribute
57
 * instead.
58
 * 
59
 * @author sdedic
60
 * @since 9.0
61
 */
62
public interface CustomInstanceFactory {
63
    /**
64
     * Creates an instance of the class.
65
     * 
66
     * @param <T> the desired type
67
     * @param clazz the desired type
68
     * @return an instance of the `clazz' or <code>null</code>
69
     */
70
    public <T> T createInstance(Class<T> clazz);
71
}
(-)a/openide.filesystems/test/unit/src/org/netbeans/modules/openide/filesystems/FSFoldersInLookupTest.java (-2 / +1 lines)
Lines 51-57 Link Here
51
import org.openide.filesystems.FileObject;
51
import org.openide.filesystems.FileObject;
52
import org.openide.filesystems.FileUtil;
52
import org.openide.filesystems.FileUtil;
53
import org.openide.util.Lookup;
53
import org.openide.util.Lookup;
54
import org.openide.util.SharedClassObject;
55
54
56
/** 
55
/** 
57
 * @author Jaroslav Tulach
56
 * @author Jaroslav Tulach
Lines 104-109 Link Here
104
        assertNull("not found again", Lookup.getDefault().lookup(Shared.class));
103
        assertNull("not found again", Lookup.getDefault().lookup(Shared.class));
105
    }
104
    }
106
105
107
    public static final class Shared extends SharedClassObject {}
106
    public static final class Shared {}
108
107
109
}
108
}
(-)a/openide.filesystems/test/unit/src/org/netbeans/modules/openide/filesystems/FileFilterSupportTest.java (-113 lines)
Lines 1-113 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2012 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.modules.openide.filesystems;
43
44
import java.io.File;
45
import java.util.List;
46
import javax.swing.filechooser.FileFilter;
47
import org.netbeans.junit.NbTestCase;
48
import org.openide.filesystems.MIMEResolver;
49
import org.openide.util.NbBundle;
50
51
/**
52
 * Test registered FileFilters.
53
 *
54
 * @author jhavlin
55
 */
56
@NbBundle.Messages({
57
    "RESOLVER=Resolver",
58
    "FILECHOOSER=BNM Files"
59
})
60
@MIMEResolver.Registration(
61
    displayName = "#RESOLVER",
62
resource = "mime-resolver-filechooser.xml",
63
showInFileChooser = "#FILECHOOSER", position=543543)
64
public class FileFilterSupportTest extends NbTestCase {
65
66
    public FileFilterSupportTest(String name) {
67
        super(name);
68
    }
69
70
    /**
71
     * This test, although it is quite short, tests a lot of ascpects of default
72
     * file filters. The resolver definition XML file contains several
73
     * duplicities, which are detected and ignored. If this detection fails,
74
     * filter description and {@code accept} method is changed, and it is cought
75
     * by this test.
76
     */
77
    public void testRegisteredFilters() {
78
        List<FileFilter> list = FileFilterSupport.findRegisteredFileFilters();
79
        assertNotNull(list);
80
        assertFalse(list.isEmpty());
81
82
        boolean found = false;
83
        for (FileFilter filter : list) {
84
85
            if (filter.getDescription().startsWith("BNM Files")) {
86
                found = true;
87
                checkBnmFilesFilter(filter);
88
            }
89
        }
90
        assertTrue("Registered File Filter was not found.", found);
91
    }
92
93
    private void checkBnmFilesFilter(FileFilter f) {
94
        assertEquals("BNM Files [.bnm, bnmHelp, bnmProject, bnminfo, bnmsettings]",
95
                f.getDescription());
96
        assertTrue(f.accept(new File("first.bnm")));
97
        assertTrue(f.accept(new File("second.BNM")));
98
        assertTrue(f.accept(new File("third.bNm")));
99
        assertTrue(f.accept(new File("bnmProject")));
100
        assertTrue(f.accept(new File("PREFIXbnmProjectAndSuFfIx")));
101
        assertFalse(f.accept(new File("bnmproject")));
102
        assertTrue(f.accept(new File("bnmSettings")));
103
        assertTrue(f.accept(new File("BNMSETTINGS")));
104
        assertFalse(f.accept(new File("bnmSettingsX")));
105
        assertTrue(f.accept(new File("bnmInfo")));
106
        assertTrue(f.accept(new File("AbnmInfoB")));
107
        assertTrue(f.accept(new File("aBNMINFOb")));
108
        assertTrue(f.accept(new File("bnmHelp")));
109
        assertFalse(f.accept(new File("bnmhelp")));
110
        assertFalse(f.accept(new File("bnmHelpX")));
111
        assertFalse(f.accept(new File("foo.txt")));
112
    }
113
}
(-)a/openide.filesystems/test/unit/src/org/netbeans/modules/openide/filesystems/RecognizeInstanceFilesTest.java (-11 / +1 lines)
Lines 55-61 Link Here
55
import org.openide.filesystems.FileSystem;
55
import org.openide.filesystems.FileSystem;
56
import org.openide.filesystems.FileUtil;
56
import org.openide.filesystems.FileUtil;
57
import org.openide.util.Lookup;
57
import org.openide.util.Lookup;
58
import org.openide.util.SharedClassObject;
59
import org.openide.util.lookup.Lookups;
58
import org.openide.util.lookup.Lookups;
60
import org.openide.util.lookup.NamedServicesLookupTest;
59
import org.openide.util.lookup.NamedServicesLookupTest;
61
60
Lines 228-249 Link Here
228
    public static final class Inst extends Object {
227
    public static final class Inst extends Object {
229
    }
228
    }
230
229
231
    public void testSharedClassObject() throws Exception {
232
        Shared instance = SharedClassObject.findObject(Shared.class, true);
233
        FileObject data = FileUtil.createData(root, "dir/" + Shared.class.getName().replace('.', '-') + ".instance");
234
        Lookup l = Lookups.forPath("dir");
235
        assertSame(instance, l.lookup(Shared.class));
236
        
237
        Shared created = FileUtil.getConfigObject(data.getPath(), Shared.class);
238
        assertSame("Config file found", instance, created);
239
    }
240
    public void testNullForFolders() throws Exception {
230
    public void testNullForFolders() throws Exception {
241
        FileObject data = FileUtil.createFolder(root, "dir/" + Shared.class.getName().replace('.', '-') + ".instance");
231
        FileObject data = FileUtil.createFolder(root, "dir/" + Shared.class.getName().replace('.', '-') + ".instance");
242
        Shared nul = FileUtil.getConfigObject(data.getPath(), Shared.class);
232
        Shared nul = FileUtil.getConfigObject(data.getPath(), Shared.class);
243
        assertNull("No object for folders", nul);
233
        assertNull("No object for folders", nul);
244
    }
234
    }
245
235
246
    public static final class Shared extends SharedClassObject {}
236
    public static final class Shared {}
247
237
248
    public void testDoNotCreateFoldersJustBecauseILookedThemUp() throws Exception {
238
    public void testDoNotCreateFoldersJustBecauseILookedThemUp() throws Exception {
249
        assertEquals(0, Lookups.forPath("nonexistent").lookupAll(Object.class).size());
239
        assertEquals(0, Lookups.forPath("nonexistent").lookupAll(Object.class).size());
(-)a/openide.filesystems/test/unit/src/org/netbeans/modules/openide/filesystems/mime-resolver-filechooser.xml (-63 lines)
Lines 1-63 Link Here
1
<?xml version="1.0"?>
2
<MIME-resolver>
3
    <file>
4
        <ext name="bnm"/>
5
        <resolver mime="text/x-bnm"/>
6
    </file>
7
8
    <!-- BNM PROJECT -->
9
    <file>
10
        <!--
11
            Duplicite resolver that accept less files than the following one.
12
            Should not be used in the filter.
13
        -->
14
        <ext name=""/>
15
        <name name="bnmProject" substring="false" ignorecase="false" />
16
        <resolver mime="text/x-bnm-project"/>
17
    </file>
18
    <file>
19
        <ext name=""/>
20
        <name name="bnmProject" substring="true" ignorecase="false" />
21
        <resolver mime="text/x-bnm-project"/>
22
    </file>
23
24
    <!-- BNM SETTINGS -->
25
    <file>
26
        <ext name=""/>
27
        <name name="bnmSettings" substring="false" />
28
        <resolver mime="text/x-bnm-settings"/>
29
    </file>
30
    <file>
31
        <!--
32
            Duplicite resolver that accept less files than the previous one.
33
            Should not be used in the filter.
34
        -->
35
        <ext name=""/>
36
        <name name="bnmSettings" substring="false" ignorecase="true" />
37
        <resolver mime="text/x-bnm-settings"/>
38
    </file>
39
40
    <!-- BNM INFO -->
41
    <file>
42
        <ext name=""/>
43
        <name name="bnmInfo" substring="true" />
44
        <resolver mime="text/x-bnm-info"/>
45
    </file>
46
    <file>
47
        <!--
48
            Duplicite resolver that accept the same files as the previous one,
49
            only differs in case of file name, that is ignored.
50
            Should not be used in the filter.
51
        -->
52
        <ext name=""/>
53
        <name name="BNMInfo" substring="true" />
54
        <resolver mime="text/x-bnm-info"/>
55
    </file>
56
57
    <!-- BNM HELP -->
58
    <file>
59
        <ext name=""/>
60
        <name name="bnmHelp" substring="false" ignorecase="false" />
61
        <resolver mime="text/x-bnm-help"/>
62
    </file>
63
</MIME-resolver>
(-)a/openide.filesystems/test/unit/src/org/openide/filesystems/AttributesTestHidden.java (-2 / +2 lines)
Lines 48-54 Link Here
48
import java.util.*;
48
import java.util.*;
49
import java.io.*;
49
import java.io.*;
50
import java.lang.reflect.Method;
50
import java.lang.reflect.Method;
51
import org.openide.util.Utilities;
51
import org.openide.util.BaseUtilities;
52
52
53
/**
53
/**
54
 *
54
 *
Lines 306-312 Link Here
306
        ).getBytes());
306
        ).getBytes());
307
        fos.close();
307
        fos.close();
308
308
309
        XMLFileSystem xfs = new XMLFileSystem(Utilities.toURI(f).toURL());
309
        XMLFileSystem xfs = new XMLFileSystem(BaseUtilities.toURI(f).toURL());
310
        FileObject template = xfs.findResource("Templates/Other/special");
310
        FileObject template = xfs.findResource("Templates/Other/special");
311
        assertNotNull("template found", template);
311
        assertNotNull("template found", template);
312
        FileObject foTested = testedFS.getRoot().createData("copiedTemplate");
312
        FileObject foTested = testedFS.getRoot().createData("copiedTemplate");
(-)a/openide.filesystems/test/unit/src/org/openide/filesystems/FileChooserBuilderTest.java (-417 lines)
Lines 1-417 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2008 Sun Microsystems, Inc.
41
 */
42
43
package org.openide.filesystems;
44
45
import java.awt.Component;
46
import java.awt.Dialog;
47
import javax.swing.UIManager;
48
import javax.swing.JRootPane;
49
import java.util.concurrent.atomic.AtomicReference;
50
import java.lang.reflect.InvocationTargetException;
51
import java.util.concurrent.CountDownLatch;
52
import java.awt.Container;
53
import java.awt.EventQueue;
54
import java.io.File;
55
import java.io.IOException;
56
import java.util.Arrays;
57
import java.util.HashSet;
58
import java.util.Set;
59
import javax.swing.AbstractButton;
60
import javax.swing.JFileChooser;
61
import javax.swing.RootPaneContainer;
62
import javax.swing.UnsupportedLookAndFeelException;
63
import javax.swing.event.AncestorEvent;
64
import javax.swing.event.AncestorListener;
65
import javax.swing.filechooser.FileFilter;
66
import javax.swing.plaf.metal.MetalLookAndFeel;
67
import org.netbeans.junit.NbTestCase;
68
import org.openide.util.RequestProcessor;
69
import static org.junit.Assert.*;
70
import org.netbeans.junit.RandomlyFails;
71
72
/**
73
 * @author tim
74
 */
75
public class FileChooserBuilderTest extends NbTestCase {
76
77
    public FileChooserBuilderTest(String name) {
78
        super(name);
79
    }
80
81
    /**
82
     * Test of setDirectoriesOnly method, of class FileChooserBuilder.
83
     */
84
    public void testSetDirectoriesOnly() {
85
        FileChooserBuilder instance = new FileChooserBuilder("x");
86
        boolean dirsOnly = instance.createFileChooser().getFileSelectionMode() == JFileChooser.DIRECTORIES_ONLY;
87
        assertFalse(dirsOnly);
88
        instance.setDirectoriesOnly(true);
89
        dirsOnly = instance.createFileChooser().getFileSelectionMode() == JFileChooser.DIRECTORIES_ONLY;
90
        assertTrue(dirsOnly);
91
    }
92
93
    /**
94
     * Test of setFilesOnly method, of class FileChooserBuilder.
95
     */
96
    public void testSetFilesOnly() {
97
        FileChooserBuilder instance = new FileChooserBuilder("y");
98
        boolean filesOnly = instance.createFileChooser().getFileSelectionMode() == JFileChooser.FILES_ONLY;
99
        assertFalse(filesOnly);
100
        instance.setFilesOnly(true);
101
        filesOnly = instance.createFileChooser().getFileSelectionMode() == JFileChooser.FILES_ONLY;
102
        assertTrue(filesOnly);
103
    }
104
105
    /**
106
     * Test of setTitle method, of class FileChooserBuilder.
107
     */
108
    public void testSetTitle() {
109
        FileChooserBuilder instance = new FileChooserBuilder("a");
110
        assertNull(instance.createFileChooser().getDialogTitle());
111
        instance.setTitle("foo");
112
        assertEquals("foo", instance.createFileChooser().getDialogTitle());
113
    }
114
115
    /**
116
     * Test of setApproveText method, of class FileChooserBuilder.
117
     */
118
    public void testSetApproveText() {
119
        FileChooserBuilder instance = new FileChooserBuilder("b");
120
        assertNull(instance.createFileChooser().getDialogTitle());
121
        instance.setApproveText("bar");
122
        assertEquals("bar", instance.createFileChooser().getApproveButtonText());
123
    }
124
125
    /**
126
     * Test of setFileFilter method, of class FileChooserBuilder.
127
     */
128
    public void testSetFileFilter() {
129
        FileFilter filter = new FileFilter() {
130
131
            @Override
132
            public boolean accept(File f) {
133
                return true;
134
            }
135
136
            @Override
137
            public String getDescription() {
138
                return "X";
139
            }
140
        };
141
        FileChooserBuilder instance = new FileChooserBuilder("c");
142
        instance.setFileFilter(filter);
143
        assertEquals(filter, instance.createFileChooser().getFileFilter());
144
    }
145
146
    /**
147
     * Test of setDefaultWorkingDirectory method, of class FileChooserBuilder.
148
     */
149
    public void testSetDefaultWorkingDirectory() throws IOException {
150
        FileChooserBuilder instance = new FileChooserBuilder("d");
151
        File dir = getWorkDir();
152
        assertTrue("tmpdir is not sane", dir.exists() && dir.isDirectory());
153
        instance.setDefaultWorkingDirectory(dir);
154
        assertEquals(dir, instance.createFileChooser().getCurrentDirectory());
155
    }
156
157
    /**
158
     * Test of setFileHiding method, of class FileChooserBuilder.
159
     */
160
    public void testSetFileHiding() {
161
        FileChooserBuilder instance = new FileChooserBuilder("e");
162
        assertFalse(instance.createFileChooser().isFileHidingEnabled());
163
        instance.setFileHiding(true);
164
        assertTrue(instance.createFileChooser().isFileHidingEnabled());
165
    }
166
167
    /**
168
     * Test of setControlButtonsAreShown method, of class FileChooserBuilder.
169
     */
170
    public void testSetControlButtonsAreShown() {
171
        FileChooserBuilder instance = new FileChooserBuilder("f");
172
        assertTrue(instance.createFileChooser().getControlButtonsAreShown());
173
        instance.setControlButtonsAreShown(false);
174
        assertFalse(instance.createFileChooser().getControlButtonsAreShown());
175
    }
176
177
    /**
178
     * Test of setAccessibleDescription method, of class FileChooserBuilder.
179
     */
180
    public void testSetAccessibleDescription() {
181
        FileChooserBuilder instance = new FileChooserBuilder("g");
182
        String desc = "desc";
183
        instance.setAccessibleDescription(desc);
184
        assertEquals(desc, instance.createFileChooser().getAccessibleContext().getAccessibleDescription());
185
    }
186
187
    /**
188
     * Test of createFileChooser method, of class FileChooserBuilder.
189
     */
190
    public void testCreateFileChooser() {
191
        FileChooserBuilder instance = new FileChooserBuilder("h");
192
        assertNotNull(instance.createFileChooser());
193
    }
194
195
    public void testSetSelectionApprover() throws Exception {
196
        FileChooserBuilder instance = new FileChooserBuilder("i");
197
        File tmp = new File(System.getProperty("java.io.tmpdir"));
198
        assertTrue ("Environment is insane", tmp.exists() && tmp.isDirectory());
199
        File sel = new File("tmp" + System.currentTimeMillis());
200
        if (!sel.exists()) {
201
            assertTrue (sel.createNewFile());
202
        }
203
        instance.setDefaultWorkingDirectory(tmp);
204
        SA sa = new SA();
205
        instance.setSelectionApprover(sa);
206
        JFileChooser ch = instance.createFileChooser();
207
        ch.setSelectedFile(sel);
208
        ch.approveSelection();
209
        sa.assertApproveInvoked(sel);
210
    }
211
212
    public void testAddFileFilter() {
213
        FileChooserBuilder instance = new FileChooserBuilder("j");
214
        FF one = new FF ("a");
215
        FF two = new FF ("b");
216
        instance.addFileFilter(one);
217
        instance.addFileFilter(two);
218
        JFileChooser ch = instance.createFileChooser();
219
        Set<FileFilter> ff = new HashSet<FileFilter>(Arrays.asList(one, two));
220
        Set<FileFilter> actual = new HashSet<FileFilter>(Arrays.asList(ch.getChoosableFileFilters()));
221
        assertTrue (actual.containsAll(ff));
222
        //actual should also contain JFileChooser.getAcceptAllFileFilter()
223
        assertEquals (ff.size() + 1, actual.size());
224
    }
225
226
    public void testSetAcceptAllFileFilterUsed() {
227
        FileChooserBuilder instance = new FileChooserBuilder("k");
228
        assertTrue(instance.createFileChooser().isAcceptAllFileFilterUsed());
229
        instance.setAcceptAllFileFilterUsed(false);
230
        assertFalse(instance.createFileChooser().isAcceptAllFileFilterUsed());
231
    }
232
233
    private static final class FF extends FileFilter {
234
        private String x;
235
        FF(String x) {
236
            this.x = x;
237
        }
238
239
        @Override
240
        public boolean accept(File f) {
241
            return f.getName().endsWith(x);
242
        }
243
244
        @Override
245
        public String getDescription() {
246
            return x;
247
        }
248
249
    }
250
251
    private static final class SA implements FileChooserBuilder.SelectionApprover {
252
        private File[] selection;
253
        @Override
254
        public boolean approve(File[] selection) {
255
            this.selection = selection;
256
            return true;
257
        }
258
259
        void assertApproveInvoked(File selected) {
260
            assertNotNull ("approve method called", selection);
261
            assertEquals("One selected file", 1, selection.length);
262
            assertEquals("It is the one", selected, selection[0]);
263
        }
264
    }
265
266
    private static AbstractButton findDefaultButton(Container c, String txt) {
267
        if (c instanceof RootPaneContainer) {
268
            JRootPane root = ((RootPaneContainer) c).getRootPane();
269
            if (root == null) {
270
                return null;
271
            }
272
            AbstractButton btn = root.getDefaultButton();
273
            if (btn == null) {
274
                //Metal L&F does not set default button for JFileChooser
275
                Container parent = c;
276
                while (parent.getParent() != null && !(parent instanceof Dialog)) {
277
                    parent = parent.getParent();
278
                }
279
                if (parent instanceof Dialog) {
280
                    return findFileChooserAcceptButton ((Dialog) parent, txt);
281
                }
282
            } else {
283
                return btn;
284
            }
285
        }
286
        return null;
287
    }
288
289
    private static AbstractButton findFileChooserAcceptButton(Dialog dlg, String txt) {
290
        for (Component c : dlg.getComponents()) {
291
            if (c instanceof Container) {
292
                AbstractButton result = scanForButton((Container) c, txt);
293
                if (result != null) {
294
                    return result;
295
                }
296
            }
297
        }
298
        return null;
299
    }
300
301
    private static AbstractButton scanForButton(Container container, String txt) {
302
        assertNotNull (container);
303
        assertNotNull (txt);
304
        if (container instanceof AbstractButton) {
305
            if (txt.equals(((AbstractButton) container).getText())) {
306
                return ((AbstractButton) container);
307
            }
308
        } else {
309
            for (Component c : container.getComponents()) {
310
                if (c instanceof Container) {
311
                    AbstractButton b = scanForButton ((Container) c, txt);
312
                    if (b != null) {
313
                        return b;
314
                    }
315
                }
316
            }
317
        }
318
        return null;
319
    }
320
321
    @RandomlyFails // NB-Core-Build #8038: Button is visible
322
    public void testForceUseOfDefaultWorkingDirectory() throws InterruptedException, IOException, InvocationTargetException, UnsupportedLookAndFeelException {
323
        UIManager.setLookAndFeel(new MetalLookAndFeel());
324
        FileChooserBuilder instance = new FileChooserBuilder("i").setApproveText("__OK");
325
        instance.setDirectoriesOnly(true);
326
        final File toDir = getWorkDir();
327
        final File selDir = new File(toDir, "sel" + System.currentTimeMillis());
328
        if (!selDir.exists()) {
329
            assertTrue(selDir.mkdirs());
330
        }
331
332
        final JFileChooser ch = instance.createFileChooser();
333
        assertEquals ("__OK", ch.getApproveButtonText());
334
        final CountDownLatch showLatch = new CountDownLatch(1);
335
        ch.addAncestorListener (new AncestorListener() {
336
337
            @Override
338
            public void ancestorAdded(AncestorEvent event) {
339
                if (ch.isShowing()) {
340
                    ch.removeAncestorListener(this);
341
                    showLatch.countDown();
342
                }
343
            }
344
345
            @Override
346
            public void ancestorRemoved(AncestorEvent event) {
347
348
            }
349
350
            @Override
351
            public void ancestorMoved(AncestorEvent event) {
352
353
            }
354
355
        });
356
357
        final AtomicReference<Object> chooserRes = new AtomicReference<Object>();
358
        RequestProcessor.Task task = RequestProcessor.getDefault().post(new Runnable() {
359
360
            @Override
361
            public void run() {
362
                Object r = ch.showOpenDialog(null);
363
                chooserRes.set(r);
364
            }
365
366
        });
367
368
369
        showLatch.await();
370
        EventQueue.invokeAndWait (new Runnable() {
371
            @Override
372
            public void run() {
373
                ch.setCurrentDirectory(toDir);
374
            }
375
        });
376
        EventQueue.invokeAndWait (new Runnable() {
377
            @Override
378
            public void run() {
379
                ch.setSelectedFile (selDir);
380
            }
381
        });
382
        assertTrue ("Button is visible: " + ch, ch.isShowing());
383
        final AtomicReference<AbstractButton> btn = new AtomicReference<AbstractButton>();
384
        EventQueue.invokeAndWait(new Runnable() {
385
386
            @Override
387
            public void run() {
388
                AbstractButton defButton = findDefaultButton(ch.getTopLevelAncestor(), ch.getApproveButtonText());
389
                btn.set(defButton);
390
            }
391
392
        });
393
        assertNotNull("have a button", btn.get());
394
        assertTrue(btn.get().isEnabled());
395
        EventQueue.invokeAndWait(new Runnable() {
396
            @Override
397
            public void run() {
398
                AbstractButton defButton = btn.get();
399
                defButton.doClick();
400
            }
401
        });
402
403
        task.waitFinished();
404
        assertEquals(JFileChooser.APPROVE_OPTION, chooserRes.get());
405
406
        assertEquals(toDir, ch.getCurrentDirectory());
407
408
        instance = new FileChooserBuilder("i");
409
        assertEquals("Directory not retained", toDir, instance.createFileChooser().getCurrentDirectory());
410
411
        File userHome = new File(System.getProperty("user.home"));
412
        assertTrue("Environment not sane", userHome.exists() && userHome.isDirectory());
413
        instance.forceUseOfDefaultWorkingDirectory(true).setDefaultWorkingDirectory(userHome);
414
415
        assertEquals(userHome, instance.createFileChooser().getCurrentDirectory());
416
    }
417
}
(-)a/openide.filesystems/test/unit/src/org/openide/filesystems/FileObjectTestHid.java (-2 / +2 lines)
Lines 1101-1108 Link Here
1101
    
1101
    
1102
    public void  testGetPath3() throws  IOException{
1102
    public void  testGetPath3() throws  IOException{
1103
        /** There is no possible to create filenames ending in dots on Win platforms*/
1103
        /** There is no possible to create filenames ending in dots on Win platforms*/
1104
        if ((org.openide.util.Utilities.isWindows () ||
1104
        if ((org.openide.util.BaseUtilities.isWindows () ||
1105
                (org.openide.util.Utilities.getOperatingSystem () == org.openide.util.Utilities.OS_OS2))) {
1105
                (org.openide.util.BaseUtilities.getOperatingSystem () == BaseUtilities.OS_OS2))) {
1106
            return;
1106
            return;
1107
        }
1107
        }
1108
        checkSetUp();
1108
        checkSetUp();
(-)a/openide.filesystems/test/unit/src/org/openide/filesystems/FileUtilTest.java (-9 / +9 lines)
Lines 68-74 Link Here
68
import org.openide.util.Exceptions;
68
import org.openide.util.Exceptions;
69
import org.openide.util.Lookup;
69
import org.openide.util.Lookup;
70
import org.openide.util.RequestProcessor;
70
import org.openide.util.RequestProcessor;
71
import org.openide.util.Utilities;
71
import org.openide.util.BaseUtilities;
72
import org.openide.util.test.MockLookup;
72
import org.openide.util.test.MockLookup;
73
73
74
/**
74
/**
Lines 113-119 Link Here
113
    }
113
    }
114
114
115
    public void testLowerAndCapitalNormalization() throws IOException {
115
    public void testLowerAndCapitalNormalization() throws IOException {
116
        if (!Utilities.isWindows()) {
116
        if (!BaseUtilities.isWindows()) {
117
            return;
117
            return;
118
        }
118
        }
119
        clearWorkDir();
119
        clearWorkDir();
Lines 148-154 Link Here
148
    }
148
    }
149
149
150
    public void testToFileObjectSlash() throws Exception { // #98388
150
    public void testToFileObjectSlash() throws Exception { // #98388
151
        if (!Utilities.isUnix()) {
151
        if (!BaseUtilities.isUnix()) {
152
            return;
152
            return;
153
        }
153
        }
154
        File root = new File("/");
154
        File root = new File("/");
Lines 225-236 Link Here
225
    }
225
    }
226
    private void assertCorrectURL(String filename, String expectedURLPrefix, String expectedURLSuffix) throws Exception {
226
    private void assertCorrectURL(String filename, String expectedURLPrefix, String expectedURLSuffix) throws Exception {
227
        File d = getWorkDir();
227
        File d = getWorkDir();
228
        assertEquals(expectedURLSuffix == null ? null : new URL(expectedURLPrefix + Utilities.toURI(d) + expectedURLSuffix),
228
        assertEquals(expectedURLSuffix == null ? null : new URL(expectedURLPrefix + BaseUtilities.toURI(d) + expectedURLSuffix),
229
                FileUtil.urlForArchiveOrDir(new File(d, filename)));
229
                FileUtil.urlForArchiveOrDir(new File(d, filename)));
230
    }
230
    }
231
    private void assertCorrectFile(String expectedFilename, String urlPrefix, String urlSuffix) throws Exception {
231
    private void assertCorrectFile(String expectedFilename, String urlPrefix, String urlSuffix) throws Exception {
232
        assertEquals(expectedFilename == null ? null : new File(getWorkDir(), expectedFilename),
232
        assertEquals(expectedFilename == null ? null : new File(getWorkDir(), expectedFilename),
233
                FileUtil.archiveOrDirForURL(new URL(urlPrefix + Utilities.toURI(getWorkDir()) + urlSuffix)));
233
                FileUtil.archiveOrDirForURL(new URL(urlPrefix + BaseUtilities.toURI(getWorkDir()) + urlSuffix)));
234
    }
234
    }
235
235
236
    /** Tests translation from jar resource url to jar archive url. */
236
    /** Tests translation from jar resource url to jar archive url. */
Lines 299-305 Link Here
299
        };
299
        };
300
        log.addHandler(handler);
300
        log.addHandler(handler);
301
        try {
301
        try {
302
            final boolean result = FileUtil.isArchiveFile(Utilities.toURI(testFile).toURL());
302
            final boolean result = FileUtil.isArchiveFile(BaseUtilities.toURI(testFile).toURL());
303
            assertTrue("The test.jar should be archive.",result);   //NOI18N
303
            assertTrue("The test.jar should be archive.",result);   //NOI18N
304
        } finally {
304
        } finally {
305
            log.removeHandler(handler);
305
            log.removeHandler(handler);
Lines 319-325 Link Here
319
    }
319
    }
320
    
320
    
321
    public void testNormalizeNonExistingButNotAccessibleRootOnWindows() throws IOException {
321
    public void testNormalizeNonExistingButNotAccessibleRootOnWindows() throws IOException {
322
        if (!Utilities.isWindows()) {
322
        if (!BaseUtilities.isWindows()) {
323
            return;
323
            return;
324
        }
324
        }
325
        for (File r : File.listRoots()) {
325
        for (File r : File.listRoots()) {
Lines 362-368 Link Here
362
    private Map<String, String> createNormalizedPaths() throws IOException {
362
    private Map<String, String> createNormalizedPaths() throws IOException {
363
        // pairs of path before and after normalization
363
        // pairs of path before and after normalization
364
        Map<String, String> paths = new HashMap<String, String>();
364
        Map<String, String> paths = new HashMap<String, String>();
365
        if (Utilities.isWindows()) {
365
        if (BaseUtilities.isWindows()) {
366
            paths.put("A:\\", "A:\\");
366
            paths.put("A:\\", "A:\\");
367
            paths.put("A:\\dummy", "A:\\dummy");
367
            paths.put("A:\\dummy", "A:\\dummy");
368
            paths.put("a:\\", "A:\\");
368
            paths.put("a:\\", "A:\\");
Lines 403-409 Link Here
403
    }
403
    }
404
    
404
    
405
    public void testNormalizePathChangeCase() throws Exception {
405
    public void testNormalizePathChangeCase() throws Exception {
406
        if (!Utilities.isWindows()) {
406
        if (!BaseUtilities.isWindows()) {
407
            return;
407
            return;
408
        }
408
        }
409
        clearWorkDir();
409
        clearWorkDir();
(-)a/openide.filesystems/test/unit/src/org/openide/filesystems/FileUtilTestHidden.java (-4 / +4 lines)
Lines 48-54 Link Here
48
import java.net.URL;
48
import java.net.URL;
49
import java.util.List;
49
import java.util.List;
50
import java.util.ArrayList;
50
import java.util.ArrayList;
51
import org.openide.util.Utilities;
51
import org.openide.util.BaseUtilities;
52
52
53
public class FileUtilTestHidden extends TestBaseHid {
53
public class FileUtilTestHidden extends TestBaseHid {
54
54
Lines 144-150 Link Here
144
        file2 = FileUtil.normalizeFile(file);
144
        file2 = FileUtil.normalizeFile(file);
145
        assertEquals(file2, file);
145
        assertEquals(file2, file);
146
146
147
        if (Utilities.isUnix()) {
147
        if (BaseUtilities.isUnix()) {
148
            assertEquals(new File("/"), FileUtil.normalizeFile(new File("/..")));
148
            assertEquals(new File("/"), FileUtil.normalizeFile(new File("/..")));
149
            assertEquals(new File("/"), FileUtil.normalizeFile(new File("/../.")));
149
            assertEquals(new File("/"), FileUtil.normalizeFile(new File("/../.")));
150
            assertEquals(new File("/tmp"), FileUtil.normalizeFile(new File("/../../tmp")));
150
            assertEquals(new File("/tmp"), FileUtil.normalizeFile(new File("/../../tmp")));
Lines 152-158 Link Here
152
    }
152
    }
153
153
154
    public void testNormalizeFile2() throws Exception {
154
    public void testNormalizeFile2() throws Exception {
155
        if (!Utilities.isWindows()) {
155
        if (!BaseUtilities.isWindows()) {
156
            return;
156
            return;
157
        }
157
        }
158
        File rootFile = FileUtil.toFile(root);
158
        File rootFile = FileUtil.toFile(root);
Lines 182-188 Link Here
182
    }
182
    }
183
183
184
    public void testIsArchiveFile() throws Exception {
184
    public void testIsArchiveFile() throws Exception {
185
        final String base = Utilities.toURI(getWorkDir()).toURL().toExternalForm();
185
        final String base = BaseUtilities.toURI(getWorkDir()).toURL().toExternalForm();
186
        URL url = new URL(base + "test.jar");    //NOI18N
186
        URL url = new URL(base + "test.jar");    //NOI18N
187
        assertTrue("test.jar has to be an archive", FileUtil.isArchiveFile(url));  //NOI18N
187
        assertTrue("test.jar has to be an archive", FileUtil.isArchiveFile(url));  //NOI18N
188
        url = new URL(base + ".hidden.jar");   //NOI18N
188
        url = new URL(base + ".hidden.jar");   //NOI18N
(-)a/openide.filesystems/test/unit/src/org/openide/filesystems/MIMESupport68318Test.java (-2 / +1 lines)
Lines 44-50 Link Here
44
package org.openide.filesystems;
44
package org.openide.filesystems;
45
import java.io.IOException;
45
import java.io.IOException;
46
import org.netbeans.junit.NbTestCase;
46
import org.netbeans.junit.NbTestCase;
47
import org.openide.ErrorManager;
48
import org.openide.util.Lookup;
47
import org.openide.util.Lookup;
49
import org.openide.util.lookup.InstanceContent;
48
import org.openide.util.lookup.InstanceContent;
50
49
Lines 62-68 Link Here
62
    }
61
    }
63
62
64
    protected void setUp() throws Exception {
63
    protected void setUp() throws Exception {
65
        ErrorManager.getDefault().log("Just initialize the ErrorManager");
64
//        ErrorManager.getDefault().log("Just initialize the ErrorManager");
66
    }
65
    }
67
66
68
    public void testQueryMIMEFromInsideTheLookup() throws IOException {
67
    public void testQueryMIMEFromInsideTheLookup() throws IOException {
(-)a/openide.filesystems/test/unit/src/org/openide/filesystems/MultiFileObjectTestHid.java (-2 / +2 lines)
Lines 49-55 Link Here
49
import java.util.ArrayList;
49
import java.util.ArrayList;
50
import java.util.Arrays;
50
import java.util.Arrays;
51
import java.util.List;
51
import java.util.List;
52
import org.openide.util.Utilities;
52
import org.openide.util.BaseUtilities;
53
53
54
public class MultiFileObjectTestHid extends TestBaseHid {
54
public class MultiFileObjectTestHid extends TestBaseHid {
55
    private static String[] resources = new String [] {
55
    private static String[] resources = new String [] {
Lines 236-242 Link Here
236
                + "      </folder>\n"
236
                + "      </folder>\n"
237
                + "    </folder>\n"
237
                + "    </folder>\n"
238
                + "</filesystem>");
238
                + "</filesystem>");
239
        XMLFileSystem xml = new XMLFileSystem(Utilities.toURI(f).toURL());
239
        XMLFileSystem xml = new XMLFileSystem(BaseUtilities.toURI(f).toURL());
240
        all.add(xml);
240
        all.add(xml);
241
        mfs.setDelegates(all.toArray(new FileSystem[0]));
241
        mfs.setDelegates(all.toArray(new FileSystem[0]));
242
242
(-)a/openide.filesystems/test/unit/src/org/openide/filesystems/TestUtilHid.java (-3 / +3 lines)
Lines 58-64 Link Here
58
import java.util.Iterator;
58
import java.util.Iterator;
59
import java.util.Map;
59
import java.util.Map;
60
import java.util.StringTokenizer;
60
import java.util.StringTokenizer;
61
import org.openide.util.Utilities;
61
import org.openide.util.BaseUtilities;
62
62
63
/**
63
/**
64
 * @author  rm111737
64
 * @author  rm111737
Lines 178-184 Link Here
178
178
179
        XMLFileSystem xfs = new XMLFileSystem  ();
179
        XMLFileSystem xfs = new XMLFileSystem  ();
180
        try {
180
        try {
181
            xfs.setXmlUrl(Utilities.toURI(xmlFile).toURL());
181
            xfs.setXmlUrl(BaseUtilities.toURI(xmlFile).toURL());
182
        } catch (Exception ex) {}
182
        } catch (Exception ex) {}
183
        
183
        
184
        return xfs;
184
        return xfs;
Lines 189-195 Link Here
189
        
189
        
190
        XMLFileSystem xfs = new XMLFileSystem  ();
190
        XMLFileSystem xfs = new XMLFileSystem  ();
191
        try {
191
        try {
192
            xfs.setXmlUrl(Utilities.toURI(xmlFile).toURL());
192
            xfs.setXmlUrl(BaseUtilities.toURI(xmlFile).toURL());
193
        } catch (Exception ex) {}
193
        } catch (Exception ex) {}
194
        
194
        
195
        return xfs;
195
        return xfs;
(-)a/openide.filesystems/test/unit/src/org/openide/filesystems/URLMapper50852Test.java (-3 / +2 lines)
Lines 46-56 Link Here
46
46
47
47
48
import org.netbeans.junit.*;
48
import org.netbeans.junit.*;
49
import org.openide.util.Lookup;
50
49
51
import java.net.URL;
50
import java.net.URL;
52
import java.io.File;
51
import java.io.File;
53
import org.openide.util.Utilities;
52
import org.openide.util.BaseUtilities;
54
53
55
/**
54
/**
56
 * Simulates issue 50852.
55
 * Simulates issue 50852.
Lines 77-83 Link Here
77
     */
76
     */
78
    protected void setUp() throws Exception {
77
    protected void setUp() throws Exception {
79
        File workdir = getWorkDir();
78
        File workdir = getWorkDir();
80
        testURL = Utilities.toURI(workdir).toURL();
79
        testURL = BaseUtilities.toURI(workdir).toURL();
81
        System.setProperty("org.openide.util.Lookup", "org.openide.filesystems.URLMapper50852Test$Lkp");
80
        System.setProperty("org.openide.util.Lookup", "org.openide.filesystems.URLMapper50852Test$Lkp");
82
        MAPPER_INSTANCE = new MyURLMapper ();
81
        MAPPER_INSTANCE = new MyURLMapper ();
83
        Lkp lkp = (Lkp)org.openide.util.Lookup.getDefault();
82
        Lkp lkp = (Lkp)org.openide.util.Lookup.getDefault();
(-)a/openide.filesystems/test/unit/src/org/openide/filesystems/URLMapperTest.java (-4 / +3 lines)
Lines 51-63 Link Here
51
import java.io.OutputStream;
51
import java.io.OutputStream;
52
import java.net.URL;
52
import java.net.URL;
53
import java.util.Arrays;
53
import java.util.Arrays;
54
import java.util.Collections;
55
import java.util.jar.JarEntry;
54
import java.util.jar.JarEntry;
56
import java.util.jar.JarOutputStream;
55
import java.util.jar.JarOutputStream;
57
import java.util.zip.CRC32;
56
import java.util.zip.CRC32;
58
import java.util.zip.ZipEntry;
57
import java.util.zip.ZipEntry;
59
import org.netbeans.junit.NbTestCase;
58
import org.netbeans.junit.NbTestCase;
60
import org.openide.util.Utilities;
59
import org.openide.util.BaseUtilities;
61
60
62
/**
61
/**
63
 * Test functionality of URLMapper.
62
 * Test functionality of URLMapper.
Lines 77-83 Link Here
77
        lfs.setRootDirectory(getWorkDir());
76
        lfs.setRootDirectory(getWorkDir());
78
        Repository.getDefault().addFileSystem(lfs);
77
        Repository.getDefault().addFileSystem(lfs);
79
        
78
        
80
        URL uPlus = Utilities.toURI(plus).toURL();
79
        URL uPlus = BaseUtilities.toURI(plus).toURL();
81
        FileObject fo = URLMapper.findFileObject(uPlus);
80
        FileObject fo = URLMapper.findFileObject(uPlus);
82
        assertNotNull("File object found", fo);
81
        assertNotNull("File object found", fo);
83
        assertEquals("plus+plus", fo.getNameExt());
82
        assertEquals("plus+plus", fo.getNameExt());
Lines 117-123 Link Here
117
        FileObject rootFO = jfs.getRoot();
116
        FileObject rootFO = jfs.getRoot();
118
        FileObject textFO = jfs.findResource(textPath);
117
        FileObject textFO = jfs.findResource(textPath);
119
        assertNotNull("JAR contains a/b.txt", textFO);
118
        assertNotNull("JAR contains a/b.txt", textFO);
120
        String rootS = "jar:" + Utilities.toURI(jar) + "!/";
119
        String rootS = "jar:" + BaseUtilities.toURI(jar) + "!/";
121
        URL rootU = new URL(rootS);
120
        URL rootU = new URL(rootS);
122
        URL textU = new URL(rootS + textPath);
121
        URL textU = new URL(rootS + textPath);
123
        assertEquals("correct FO -> URL for root", rootU, URLMapper.findURL(rootFO, URLMapper.EXTERNAL));
122
        assertEquals("correct FO -> URL for root", rootU, URLMapper.findURL(rootFO, URLMapper.EXTERNAL));
(-)a/openide.filesystems/test/unit/src/org/openide/filesystems/XMLFileSystemTestHid.java (-41 / +41 lines)
Lines 62-68 Link Here
62
import java.util.jar.JarEntry;
62
import java.util.jar.JarEntry;
63
import java.util.jar.JarOutputStream;
63
import java.util.jar.JarOutputStream;
64
import org.openide.util.Enumerations;
64
import org.openide.util.Enumerations;
65
import org.openide.util.Utilities;
65
import org.openide.util.BaseUtilities;
66
66
67
public class XMLFileSystemTestHid extends TestBaseHid {
67
public class XMLFileSystemTestHid extends TestBaseHid {
68
    /** Factory for all filesystems that want to use TCK in this class.
68
    /** Factory for all filesystems that want to use TCK in this class.
Lines 107-113 Link Here
107
        
107
        
108
        resources = new String[] {"a/b/c","a/b1/c"};
108
        resources = new String[] {"a/b/c","a/b1/c"};
109
109
110
        if (!FileSystemFactoryHid.switchXMLSystem(xfs, this, Utilities.toURI(createXMLLayer()).toURL())) {
110
        if (!FileSystemFactoryHid.switchXMLSystem(xfs, this, BaseUtilities.toURI(createXMLLayer()).toURL())) {
111
            // OK, unsupported
111
            // OK, unsupported
112
            return;
112
            return;
113
        }
113
        }
Lines 120-126 Link Here
120
    @Override
120
    @Override
121
    protected void setUp() throws Exception {
121
    protected void setUp() throws Exception {
122
        File f = createXMLLayer();
122
        File f = createXMLLayer();
123
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL());
123
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL());
124
        this.testedFS = xfs;
124
        this.testedFS = xfs;
125
        this.allTestedFS = new FileSystem[] { xfs };
125
        this.allTestedFS = new FileSystem[] { xfs };
126
        super.setUp();
126
        super.setUp();
Lines 152-164 Link Here
152
        
152
        
153
        
153
        
154
        
154
        
155
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL());
155
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL());
156
        
156
        
157
        FileObject fo = xfs.findResource ("TestModule/sample.txt");
157
        FileObject fo = xfs.findResource ("TestModule/sample.txt");
158
        assertEquals ("Four bytes there", 4, fo.getSize ());
158
        assertEquals ("Four bytes there", 4, fo.getSize ());
159
        registerDefaultListener (fo);
159
        registerDefaultListener (fo);
160
        
160
        
161
        if (!FileSystemFactoryHid.switchXMLSystem(xfs, this, Utilities.toURI(f2).toURL())) {
161
        if (!FileSystemFactoryHid.switchXMLSystem(xfs, this, BaseUtilities.toURI(f2).toURL())) {
162
            // OK, unsupported
162
            // OK, unsupported
163
            return;
163
            return;
164
        }
164
        }
Lines 191-203 Link Here
191
        
191
        
192
        
192
        
193
        
193
        
194
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL());
194
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL());
195
        
195
        
196
        FileObject fo = xfs.findResource ("TestModule/sample.txt");
196
        FileObject fo = xfs.findResource ("TestModule/sample.txt");
197
        assertEquals ("Four bytes there", 4, fo.getSize ());
197
        assertEquals ("Four bytes there", 4, fo.getSize ());
198
        registerDefaultListener (fo);
198
        registerDefaultListener (fo);
199
        
199
        
200
        if (!FileSystemFactoryHid.switchXMLSystem(xfs, this, Utilities.toURI(f2).toURL())) {
200
        if (!FileSystemFactoryHid.switchXMLSystem(xfs, this, BaseUtilities.toURI(f2).toURL())) {
201
            // OK, unsupported
201
            // OK, unsupported
202
            return;
202
            return;
203
        }
203
        }
Lines 231-243 Link Here
231
        
231
        
232
        
232
        
233
        
233
        
234
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL());
234
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL());
235
        
235
        
236
        FileObject fo = xfs.findResource ("TestModule/sample.txt");
236
        FileObject fo = xfs.findResource ("TestModule/sample.txt");
237
        assertEquals("Old value is in the attribute", "old", fo.getAttribute("value"));
237
        assertEquals("Old value is in the attribute", "old", fo.getAttribute("value"));
238
        registerDefaultListener (fo);
238
        registerDefaultListener (fo);
239
        
239
        
240
        if (!FileSystemFactoryHid.switchXMLSystem(xfs, this, Utilities.toURI(f2).toURL())) {
240
        if (!FileSystemFactoryHid.switchXMLSystem(xfs, this, BaseUtilities.toURI(f2).toURL())) {
241
            // OK, unsupported
241
            // OK, unsupported
242
            return;
242
            return;
243
        }
243
        }
Lines 265-277 Link Here
265
        
265
        
266
        
266
        
267
        
267
        
268
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL());
268
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL());
269
        
269
        
270
        FileObject fo = xfs.findResource("TestModule/sample.txt");
270
        FileObject fo = xfs.findResource("TestModule/sample.txt");
271
        assertEquals("Four bytes there", 4, fo.getSize());
271
        assertEquals("Four bytes there", 4, fo.getSize());
272
        registerDefaultListener(fo);
272
        registerDefaultListener(fo);
273
        
273
        
274
        if (!FileSystemFactoryHid.switchXMLSystem(xfs, this, Utilities.toURI(f2).toURL())) {
274
        if (!FileSystemFactoryHid.switchXMLSystem(xfs, this, BaseUtilities.toURI(f2).toURL())) {
275
            // OK, unsupported
275
            // OK, unsupported
276
            return;
276
            return;
277
        }
277
        }
Lines 301-307 Link Here
301
                f.lastModified() < f2.lastModified()
301
                f.lastModified() < f2.lastModified()
302
            );
302
            );
303
        }
303
        }
304
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL());
304
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL());
305
        FileObject fo = xfs.findResource ("TestModule/sample.txt");
305
        FileObject fo = xfs.findResource ("TestModule/sample.txt");
306
        assertNotNull(fo);
306
        assertNotNull(fo);
307
        assertEquals(fo.lastModified().getTime(), f.lastModified());        
307
        assertEquals(fo.lastModified().getTime(), f.lastModified());        
Lines 326-332 Link Here
326
                "</filesystem>\n"
326
                "</filesystem>\n"
327
                );
327
                );
328
328
329
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL());
329
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL());
330
        FileObject fo = xfs.findResource ("TestModule/sample.txt");
330
        FileObject fo = xfs.findResource ("TestModule/sample.txt");
331
        assertNotNull(fo);
331
        assertNotNull(fo);
332
        
332
        
Lines 350-356 Link Here
350
                + "    </folder>\n"
350
                + "    </folder>\n"
351
                + "</filesystem>");
351
                + "</filesystem>");
352
352
353
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL());
353
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL());
354
        final LocalFileSystem lfs = new LocalFileSystem();
354
        final LocalFileSystem lfs = new LocalFileSystem();
355
        lfs.setRootDirectory(getWorkDir());
355
        lfs.setRootDirectory(getWorkDir());
356
        MultiFileSystem mfs = new MultiFileSystem(lfs, xfs);
356
        MultiFileSystem mfs = new MultiFileSystem(lfs, xfs);
Lines 377-383 Link Here
377
                );
377
                );
378
        Count.cnt = 0;
378
        Count.cnt = 0;
379
379
380
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL());
380
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL());
381
        /** the following is a fake implementation of filesystem that
381
        /** the following is a fake implementation of filesystem that
382
         * allows us to prevent calls to fileObject.getAttributes()
382
         * allows us to prevent calls to fileObject.getAttributes()
383
         */
383
         */
Lines 500-506 Link Here
500
                "</filesystem>\n"
500
                "</filesystem>\n"
501
                );
501
                );
502
502
503
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL());
503
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL());
504
        FileObject fo = xfs.findResource ("TestModule/sample.txt");
504
        FileObject fo = xfs.findResource ("TestModule/sample.txt");
505
        assertNotNull(fo);
505
        assertNotNull(fo);
506
506
Lines 525-531 Link Here
525
                "</filesystem>\n"
525
                "</filesystem>\n"
526
                );
526
                );
527
527
528
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL());
528
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL());
529
        FileObject fo = xfs.findResource ("TestModule/sample.txt");
529
        FileObject fo = xfs.findResource ("TestModule/sample.txt");
530
        assertNotNull(fo);
530
        assertNotNull(fo);
531
531
Lines 550-556 Link Here
550
            "</filesystem>\n"
550
            "</filesystem>\n"
551
        );
551
        );
552
552
553
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL());
553
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL());
554
        FileObject fo = xfs.findResource ("TestModule/sample.txt");
554
        FileObject fo = xfs.findResource ("TestModule/sample.txt");
555
        assertNotNull(fo);
555
        assertNotNull(fo);
556
556
Lines 580-590 Link Here
580
            "</filesystem>\n"
580
            "</filesystem>\n"
581
        );
581
        );
582
582
583
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL());
583
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL());
584
        FileObject fo = xfs.findResource ("TestModule/sample.txt");
584
        FileObject fo = xfs.findResource ("TestModule/sample.txt");
585
        assertNotNull(fo);
585
        assertNotNull(fo);
586
586
587
        XMLFileSystem realXMLFS = new XMLFileSystem(Utilities.toURI(f).toURL());
587
        XMLFileSystem realXMLFS = new XMLFileSystem(BaseUtilities.toURI(f).toURL());
588
        FileObject realfo = realXMLFS.findResource("TestModule/sample.txt");
588
        FileObject realfo = realXMLFS.findResource("TestModule/sample.txt");
589
        assertNotNull(realfo);
589
        assertNotNull(realfo);
590
590
Lines 621-627 Link Here
621
            "</filesystem>\n"
621
            "</filesystem>\n"
622
        );
622
        );
623
623
624
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL());
624
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL());
625
        FileObject fo = xfs.findResource ("TestModule/sample.txt");
625
        FileObject fo = xfs.findResource ("TestModule/sample.txt");
626
        FileObject snd = xfs.findResource ("TestModule/snd.txt");
626
        FileObject snd = xfs.findResource ("TestModule/snd.txt");
627
        assertNotNull(fo);
627
        assertNotNull(fo);
Lines 722-728 Link Here
722
                "</filesystem>\n"
722
                "</filesystem>\n"
723
                );
723
                );
724
724
725
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL());
725
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL());
726
        FileObject fo = xfs.findResource ("TestModule/sample.txt");
726
        FileObject fo = xfs.findResource ("TestModule/sample.txt");
727
        assertNotNull(fo);
727
        assertNotNull(fo);
728
728
Lines 771-778 Link Here
771
            )
771
            )
772
        );
772
        );
773
773
774
        URL url1 = new URL("jar:" + Utilities.toURI(jar1) + "!/layer.xml");
774
        URL url1 = new URL("jar:" + BaseUtilities.toURI(jar1) + "!/layer.xml");
775
        URL url2 = new URL("jar:" + Utilities.toURI(jar2) + "!/layer.xml");
775
        URL url2 = new URL("jar:" + BaseUtilities.toURI(jar2) + "!/layer.xml");
776
776
777
        FileSystem xfs1 = FileSystemFactoryHid.createXMLSystem(getName(), this, url1);
777
        FileSystem xfs1 = FileSystemFactoryHid.createXMLSystem(getName(), this, url1);
778
        FileObject fo1 = xfs1.findResource("dir/file");
778
        FileObject fo1 = xfs1.findResource("dir/file");
Lines 902-908 Link Here
902
        File f2 = changeOfAnAttributeInLayerIsFiredgenerateLayer("Folder", "java.awt.Button");
902
        File f2 = changeOfAnAttributeInLayerIsFiredgenerateLayer("Folder", "java.awt.Button");
903
        File f3 = changeOfAnAttributeInLayerIsFiredgenerateLayer("NoChange", "nochange");
903
        File f3 = changeOfAnAttributeInLayerIsFiredgenerateLayer("NoChange", "nochange");
904
904
905
        fs.setXmlUrls (new URL[] { Utilities.toURI(f1).toURL(), Utilities.toURI(f3).toURL() } );
905
        fs.setXmlUrls (new URL[] { BaseUtilities.toURI(f1).toURL(), BaseUtilities.toURI(f3).toURL() } );
906
        
906
        
907
        FileObject file = fs.findResource("Folder/empty.xml");
907
        FileObject file = fs.findResource("Folder/empty.xml");
908
        assertNotNull("File found in layer", file);
908
        assertNotNull("File found in layer", file);
Lines 918-924 Link Here
918
        assertAttr("The first value is list", file, "value", "java.awt.List");
918
        assertAttr("The first value is list", file, "value", "java.awt.List");
919
        assertAttr("Imutable value is nochange", nochange, "value", "nochange");
919
        assertAttr("Imutable value is nochange", nochange, "value", "nochange");
920
        
920
        
921
        fs.setXmlUrls (new URL[] { Utilities.toURI(f2).toURL(), Utilities.toURI(f3).toURL() } );
921
        fs.setXmlUrls (new URL[] { BaseUtilities.toURI(f2).toURL(), BaseUtilities.toURI(f3).toURL() } );
922
        String v2 = (String) file.getAttribute("value");
922
        String v2 = (String) file.getAttribute("value");
923
        assertEquals("The second value is button", "java.awt.Button", v2);
923
        assertEquals("The second value is button", "java.awt.Button", v2);
924
        
924
        
Lines 953-959 Link Here
953
        LocalFileSystem target = new LocalFileSystem();
953
        LocalFileSystem target = new LocalFileSystem();
954
        target.setRootDirectory(r);
954
        target.setRootDirectory(r);
955
955
956
        FileSystem source = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f).toURL());
956
        FileSystem source = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f).toURL());
957
        FileObject template = source.findResource("Templates/Other/special");
957
        FileObject template = source.findResource("Templates/Other/special");
958
        assertNotNull("template found", template);
958
        assertNotNull("template found", template);
959
        FileObject foTested = target.getRoot().createData("copiedTemplate");
959
        FileObject foTested = target.getRoot().createData("copiedTemplate");
Lines 1078-1084 Link Here
1078
            w.close();
1078
            w.close();
1079
        }
1079
        }
1080
1080
1081
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f1).toURL(), Utilities.toURI(f2).toURL());
1081
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f1).toURL(), BaseUtilities.toURI(f2).toURL());
1082
1082
1083
1083
1084
        FileObject just1 = xfs.findResource("just1/empty.xml");
1084
        FileObject just1 = xfs.findResource("just1/empty.xml");
Lines 1090-1108 Link Here
1090
        String layers2 = layers(just2);
1090
        String layers2 = layers(just2);
1091
        String layersB = layers(both);
1091
        String layersB = layers(both);
1092
1092
1093
        if (!layersR.contains(Utilities.toURI(f1).toString())) {
1093
        if (!layersR.contains(BaseUtilities.toURI(f1).toString())) {
1094
            fail("Missing " + Utilities.toURI(f1).toString() + "\ninside: " + layersR);
1094
            fail("Missing " + BaseUtilities.toURI(f1).toString() + "\ninside: " + layersR);
1095
        }
1095
        }
1096
        if (!layersR.contains(Utilities.toURI(f2).toString())) {
1096
        if (!layersR.contains(BaseUtilities.toURI(f2).toString())) {
1097
            fail("Missing " + Utilities.toURI(f2).toString() + "\ninside: " + layersR);
1097
            fail("Missing " + BaseUtilities.toURI(f2).toString() + "\ninside: " + layersR);
1098
        }
1098
        }
1099
1099
1100
        assertEquals(Utilities.toURI(f1).toString(), layers1);
1100
        assertEquals(BaseUtilities.toURI(f1).toString(), layers1);
1101
        assertEquals(Utilities.toURI(f2).toString(), layers2);
1101
        assertEquals(BaseUtilities.toURI(f2).toString(), layers2);
1102
        if (!layersB.contains(Utilities.toURI(f1).toString())) {
1102
        if (!layersB.contains(BaseUtilities.toURI(f1).toString())) {
1103
            fail("Missing " + f1 + "\ninside: " + layersB);
1103
            fail("Missing " + f1 + "\ninside: " + layersB);
1104
        }
1104
        }
1105
        if (!layersB.contains(Utilities.toURI(f2).toString())) {
1105
        if (!layersB.contains(BaseUtilities.toURI(f2).toString())) {
1106
            fail("Missing " + f2 + "\ninside: " + layersB);
1106
            fail("Missing " + f2 + "\ninside: " + layersB);
1107
        }
1107
        }
1108
    }
1108
    }
Lines 1120-1126 Link Here
1120
            + "</filesystem>");
1120
            + "</filesystem>");
1121
        w.close();
1121
        w.close();
1122
1122
1123
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(layer).toURL());
1123
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(layer).toURL());
1124
1124
1125
        FileObject fo = xfs.findResource("f/empty.xml");
1125
        FileObject fo = xfs.findResource("f/empty.xml");
1126
        assertNotNull("File found", fo);
1126
        assertNotNull("File found", fo);
Lines 1143-1167 Link Here
1143
        File f1 = writeFile("layer1.xml",
1143
        File f1 = writeFile("layer1.xml",
1144
                "<filesystem>\n" +
1144
                "<filesystem>\n" +
1145
                "<folder name='d'>\n" +
1145
                "<folder name='d'>\n" +
1146
                "<file name='f' url='" + Utilities.toURI(c1) + "'/>" +
1146
                "<file name='f' url='" + BaseUtilities.toURI(c1) + "'/>" +
1147
                "</folder>\n" +
1147
                "</folder>\n" +
1148
                "</filesystem>\n"
1148
                "</filesystem>\n"
1149
                );
1149
                );
1150
        File f2 = writeFile("layer2.xml",
1150
        File f2 = writeFile("layer2.xml",
1151
                "<filesystem>\n" +
1151
                "<filesystem>\n" +
1152
                "<folder name='d'>\n" +
1152
                "<folder name='d'>\n" +
1153
                "<file name='f' url='" + Utilities.toURI(c2) + "'>" +
1153
                "<file name='f' url='" + BaseUtilities.toURI(c2) + "'>" +
1154
                "  <attr name='weight' intvalue='100'/>" +
1154
                "  <attr name='weight' intvalue='100'/>" +
1155
                "</file>\n" +
1155
                "</file>\n" +
1156
                "</folder>\n" +
1156
                "</folder>\n" +
1157
                "</filesystem>\n"
1157
                "</filesystem>\n"
1158
                );
1158
                );
1159
1159
1160
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f2).toURL(), Utilities.toURI(f1).toURL());
1160
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f2).toURL(), BaseUtilities.toURI(f1).toURL());
1161
        FileObject fo = xfs.findResource("d/f");
1161
        FileObject fo = xfs.findResource("d/f");
1162
        assertNotNull(fo);
1162
        assertNotNull(fo);
1163
        assertEquals(6, fo.getSize());
1163
        assertEquals(6, fo.getSize());
1164
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, Utilities.toURI(f1).toURL(), Utilities.toURI(f2).toURL());
1164
        xfs = FileSystemFactoryHid.createXMLSystem(getName(), this, BaseUtilities.toURI(f1).toURL(), BaseUtilities.toURI(f2).toURL());
1165
        fo = xfs.findResource("d/f");
1165
        fo = xfs.findResource("d/f");
1166
        assertNotNull(fo);
1166
        assertNotNull(fo);
1167
        assertEquals(6, fo.getSize());
1167
        assertEquals(6, fo.getSize());
(-)a/openide.filesystems/test/unit/src/org/openide/filesystems/annotations/LayerBuilderTest.java (-5 / +5 lines)
Lines 67-73 Link Here
67
import org.netbeans.junit.NbTestCase;
67
import org.netbeans.junit.NbTestCase;
68
import org.openide.filesystems.FileObject;
68
import org.openide.filesystems.FileObject;
69
import org.openide.filesystems.XMLFileSystem;
69
import org.openide.filesystems.XMLFileSystem;
70
import org.openide.util.Utilities;
70
import org.openide.util.BaseUtilities;
71
import org.openide.util.lookup.ServiceProvider;
71
import org.openide.util.lookup.ServiceProvider;
72
import org.openide.util.test.AnnotationProcessorTestUtils;
72
import org.openide.util.test.AnnotationProcessorTestUtils;
73
import org.openide.util.test.TestFileUtils;
73
import org.openide.util.test.TestFileUtils;
Lines 304-315 Link Here
304
        File j = TestFileUtils.writeZipFile(new File(getWorkDir(), "cp.jar"), "other/x1:x1");
304
        File j = TestFileUtils.writeZipFile(new File(getWorkDir(), "cp.jar"), "other/x1:x1");
305
        TestFileUtils.writeFile(new File(src, "p/resources/x2"), "x2");
305
        TestFileUtils.writeFile(new File(src, "p/resources/x2"), "x2");
306
        ByteArrayOutputStream err = new ByteArrayOutputStream();
306
        ByteArrayOutputStream err = new ByteArrayOutputStream();
307
        boolean status = AnnotationProcessorTestUtils.runJavac(src, null, dest, new File[] {j, Utilities.toFile(LayerBuilderTest.class.getProtectionDomain().getCodeSource().getLocation().toURI())}, err);
307
        boolean status = AnnotationProcessorTestUtils.runJavac(src, null, dest, new File[] {j, BaseUtilities.toFile(LayerBuilderTest.class.getProtectionDomain().getCodeSource().getLocation().toURI())}, err);
308
        String msgs = err.toString();
308
        String msgs = err.toString();
309
        assertTrue(msgs, status);
309
        assertTrue(msgs, status);
310
        assertTrue(msgs, msgs.contains("r1=x1") ^ AnnotationProcessorTestUtils.searchClasspathBroken());
310
        assertTrue(msgs, msgs.contains("r1=x1") ^ AnnotationProcessorTestUtils.searchClasspathBroken());
311
        assertTrue(msgs, msgs.contains("r2=x2"));
311
        assertTrue(msgs, msgs.contains("r2=x2"));
312
        FileObject f = new XMLFileSystem(Utilities.toURI(new File(dest, "META-INF/generated-layer.xml")).toURL()).findResource("f");
312
        FileObject f = new XMLFileSystem(BaseUtilities.toURI(new File(dest, "META-INF/generated-layer.xml")).toURL()).findResource("f");
313
        assertNotNull(f);
313
        assertNotNull(f);
314
        assertEquals("other/x1", f.getAttribute("r1"));
314
        assertEquals("other/x1", f.getAttribute("r1"));
315
        assertEquals("p/resources/x2", f.getAttribute("r2"));
315
        assertEquals("p/resources/x2", f.getAttribute("r2"));
Lines 320-333 Link Here
320
        File j = TestFileUtils.writeZipFile(new File(getWorkDir(), "cp.jar"), "other/x1:x1");
320
        File j = TestFileUtils.writeZipFile(new File(getWorkDir(), "cp.jar"), "other/x1:x1");
321
        TestFileUtils.writeFile(new File(src, "p/resources/x2"), "x2");
321
        TestFileUtils.writeFile(new File(src, "p/resources/x2"), "x2");
322
        ByteArrayOutputStream err = new ByteArrayOutputStream();
322
        ByteArrayOutputStream err = new ByteArrayOutputStream();
323
        boolean status = AnnotationProcessorTestUtils.runJavac(src, null, dest, new File[] {j, Utilities.toFile(LayerBuilderTest.class.getProtectionDomain().getCodeSource().getLocation().toURI())}, err);
323
        boolean status = AnnotationProcessorTestUtils.runJavac(src, null, dest, new File[] {j, BaseUtilities.toFile(LayerBuilderTest.class.getProtectionDomain().getCodeSource().getLocation().toURI())}, err);
324
        String msgs = err.toString();
324
        String msgs = err.toString();
325
        assertFalse(msgs, status);
325
        assertFalse(msgs, status);
326
        assertTrue(msgs, msgs.contains("resourcez"));
326
        assertTrue(msgs, msgs.contains("resourcez"));
327
        assertTrue(msgs, msgs.contains("r1=x1") ^ AnnotationProcessorTestUtils.searchClasspathBroken());
327
        assertTrue(msgs, msgs.contains("r1=x1") ^ AnnotationProcessorTestUtils.searchClasspathBroken());
328
        AnnotationProcessorTestUtils.makeSource(src, "p.C", "@" + V.class.getCanonicalName() + "(r1=\"othr/x1\", r2=\"resources/x2\") public class C {}");
328
        AnnotationProcessorTestUtils.makeSource(src, "p.C", "@" + V.class.getCanonicalName() + "(r1=\"othr/x1\", r2=\"resources/x2\") public class C {}");
329
        err = new ByteArrayOutputStream();
329
        err = new ByteArrayOutputStream();
330
        status = AnnotationProcessorTestUtils.runJavac(src, null, dest, new File[] {j, Utilities.toFile(LayerBuilderTest.class.getProtectionDomain().getCodeSource().getLocation().toURI())}, err);
330
        status = AnnotationProcessorTestUtils.runJavac(src, null, dest, new File[] {j, BaseUtilities.toFile(LayerBuilderTest.class.getProtectionDomain().getCodeSource().getLocation().toURI())}, err);
331
        msgs = err.toString();
331
        msgs = err.toString();
332
        assertFalse(msgs, status ^ AnnotationProcessorTestUtils.searchClasspathBroken());
332
        assertFalse(msgs, status ^ AnnotationProcessorTestUtils.searchClasspathBroken());
333
        assertTrue(msgs, msgs.contains("othr") ^ AnnotationProcessorTestUtils.searchClasspathBroken());
333
        assertTrue(msgs, msgs.contains("othr") ^ AnnotationProcessorTestUtils.searchClasspathBroken());
(-)a/openide.util.base/src/org/netbeans/modules/openide/util/ProxyURLStreamHandlerFactory.java (+91 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2009 Sun Microsystems, Inc.
41
 */
42
43
package org.netbeans.modules.openide.util;
44
45
import java.net.URLStreamHandler;
46
import java.net.URLStreamHandlerFactory;
47
import java.util.Arrays;
48
import java.util.Collection;
49
import java.util.HashMap;
50
import java.util.HashSet;
51
import java.util.Map;
52
import java.util.Set;
53
import org.openide.util.Lookup;
54
import org.openide.util.LookupEvent;
55
import org.openide.util.LookupListener;
56
import org.openide.util.URLStreamHandlerRegistration;
57
import org.openide.util.lookup.Lookups;
58
import org.openide.util.lookup.ServiceProvider;
59
60
/**
61
 * @see URLStreamHandlerRegistration
62
 */
63
@ServiceProvider(service=URLStreamHandlerFactory.class)
64
public final class ProxyURLStreamHandlerFactory implements URLStreamHandlerFactory {
65
    /** prevents GC only */
66
    private final Map<String, Lookup.Result<URLStreamHandler>> results = new HashMap<String, Lookup.Result<URLStreamHandler>>();
67
    private final Map<String, URLStreamHandler> handlers = new HashMap<String, URLStreamHandler>();
68
    private static final Set<String> STANDARD_PROTOCOLS = new HashSet<String>(Arrays.asList("jar", "file", "http", "https", "resource")); // NOI18N
69
70
    public @Override synchronized URLStreamHandler createURLStreamHandler(final String protocol) {
71
        if (STANDARD_PROTOCOLS.contains(protocol)) {
72
            // Well-known handlers in JRE. Do not try to initialize lookup.
73
            return null;
74
        }
75
        if (!results.containsKey(protocol)) {
76
            final Lookup.Result<URLStreamHandler> result = Lookups.forPath("URLStreamHandler/" + protocol).lookupResult(URLStreamHandler.class);
77
            LookupListener listener = new LookupListener() {
78
                public @Override void resultChanged(LookupEvent ev) {
79
                    synchronized (ProxyURLStreamHandlerFactory.this) {
80
                        Collection<? extends URLStreamHandler> instances = result.allInstances();
81
                        handlers.put(protocol, instances.isEmpty() ? null : instances.iterator().next());
82
                    }
83
                }
84
            };
85
            result.addLookupListener(listener);
86
            listener.resultChanged(null);
87
            results.put(protocol, result);
88
        }
89
        return handlers.get(protocol);
90
    }
91
}
(-)a/openide.util.base/src/org/openide/util/URLStreamHandlerRegistration.java (+83 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2009 Sun Microsystems, Inc.
41
 */
42
43
package org.openide.util;
44
45
import java.lang.annotation.ElementType;
46
import java.lang.annotation.Retention;
47
import java.lang.annotation.RetentionPolicy;
48
import java.lang.annotation.Target;
49
import java.net.URL;
50
import java.net.URLStreamHandler;
51
import java.net.URLStreamHandlerFactory;
52
import org.openide.util.lookup.NamedServiceDefinition;
53
54
/**
55
 * Replacement for {@link URLStreamHandlerFactory} within the NetBeans platform.
56
 * (The JVM only permits one global factory to be set at a time,
57
 * whereas various independent modules may wish to register handlers.)
58
 * May be placed on a {@link URLStreamHandler} implementation to register it.
59
 * Your handler will be loaded and used if and when a URL of a matching protocol is created.
60
 * <p>A {@link URLStreamHandlerFactory} which uses these registrations may be found in {@link Lookup#getDefault}.
61
 * This factory is active whenever the module system is loaded.
62
 * You may also wish to call {@link URL#setURLStreamHandlerFactory}
63
 * from a unit test or otherwise without the module system active.
64
 * @since org.openide.util 7.31
65
 */
66
@NamedServiceDefinition(path="URLStreamHandler/@protocol()", serviceType=URLStreamHandler.class)
67
@Retention(RetentionPolicy.SOURCE)
68
@Target(ElementType.TYPE)
69
public @interface URLStreamHandlerRegistration {
70
71
    /**
72
     * URL protocol(s) which are handled.
73
     * {@link URLStreamHandler#openConnection} will be called with a matching {@link URL#getProtocol}.
74
     */
75
    String[] protocol();
76
77
    /**
78
     * An optional position in which to register this handler relative to others.
79
     * The lowest-numbered handler is used in favor of any others, including unnumbered handlers.
80
     */
81
    int position() default Integer.MAX_VALUE;
82
83
}
(-)a/openide.util.base/test/unit/src/org/openide/util/test/JarBuilder.java (+126 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2011 Sun Microsystems, Inc.
41
 */
42
43
package org.openide.util.test;
44
45
import java.io.File;
46
import java.io.FileOutputStream;
47
import java.io.OutputStream;
48
import java.util.ArrayList;
49
import java.util.Arrays;
50
import java.util.List;
51
import java.util.Map;
52
import java.util.TreeMap;
53
import org.netbeans.junit.NbTestCase;
54
55
// XXX could add methods to add a JAR manifest, include text or binary resources, ...
56
57
/**
58
 * Builder for compiling some source files and packing the result into a JAR.
59
 */
60
public final class JarBuilder {
61
62
    private final File src, dest, jar;
63
    private List<File> classpath;
64
65
    /**
66
     * @param workdir as in {@link NbTestCase#getWorkDir}
67
     */
68
    public JarBuilder(File workdir) throws Exception {
69
        jar = File.createTempFile("test", ".jar", workdir);
70
        String n = jar.getName().replaceAll("^test|[.]jar$", "");
71
        src = new File(workdir, "src" + n);
72
        dest = new File(workdir, "classes" + n);
73
    }
74
75
    /**
76
     * Optional classpath for compiling sources.
77
     * If unspecified, use Java classpath of test.)
78
     */
79
    public JarBuilder classpath(File... cp) {
80
        if (classpath == null) {
81
            classpath = new ArrayList<File>();
82
        }
83
        classpath.addAll(Arrays.asList(cp));
84
        return this;
85
    }
86
87
    /**
88
     * Adds a source file to compile.
89
     * @see AnnotationProcessorTestUtils#makeSource
90
     */
91
    public JarBuilder source(String clazz, String... content) throws Exception {
92
        AnnotationProcessorTestUtils.makeSource(src, clazz, content);
93
        return this;
94
    }
95
96
    /**
97
     * Compiles sources and creates resulting JAR.
98
     * @return the created JAR file
99
     */
100
    public File build() throws Exception {
101
        if (!AnnotationProcessorTestUtils.runJavac(src, null, dest, classpath != null ? classpath.toArray(new File[0]) : null, null)) {
102
            throw new Exception("compilation failed");
103
        }
104
        Map<String,byte[]> data = new TreeMap<String,byte[]>();
105
        scan(data, dest, "");
106
        OutputStream os = new FileOutputStream(jar);
107
        try {
108
            TestFileUtils.writeZipFile(os, data);
109
        } finally {
110
            os.close();
111
        }
112
        return jar;
113
    }
114
115
    private static void scan(Map<String,byte[]> data, File d, String prefix) throws Exception {
116
        for (File kid : d.listFiles()) {
117
            String prefixName = prefix + kid.getName();
118
            if (kid.isDirectory()) {
119
                scan(data, kid, prefixName + '/');
120
            } else {
121
                data.put(prefixName, TestFileUtils.readFileBin(kid));
122
            }
123
        }
124
    }
125
126
}
(-)a/openide.util.base/test/unit/src/org/openide/util/test/MockChangeListenerTest.java (+145 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * Contributor(s):
28
 *
29
 * The Original Software is NetBeans. The Initial Developer of the Original
30
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
31
 * Microsystems, Inc. All Rights Reserved.
32
 *
33
 * If you wish your version of this file to be governed by only the CDDL
34
 * or only the GPL Version 2, indicate your decision by adding
35
 * "[Contributor] elects to include this software in this distribution
36
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
37
 * single choice of license, a recipient has the option to distribute
38
 * your version of this file under either the CDDL, the GPL Version 2 or
39
 * to extend the choice of license to its licensees as provided above.
40
 * However, if you add GPL Version 2 code and therefore, elected the GPL
41
 * Version 2 license, then the option applies only if the new code is
42
 * made subject to such option by the copyright holder.
43
 */
44
45
package org.openide.util.test;
46
47
import junit.framework.AssertionFailedError;
48
import org.netbeans.junit.NbTestCase;
49
import org.netbeans.junit.RandomlyFails;
50
import org.openide.util.ChangeSupport;
51
52
public class MockChangeListenerTest extends NbTestCase {
53
54
    public MockChangeListenerTest(String n) {
55
        super(n);
56
    }
57
58
    Object source;
59
    ChangeSupport cs;
60
    MockChangeListener l;
61
62
    @Override
63
    protected void setUp() throws Exception {
64
        super.setUp();
65
        source = new Object();
66
        cs = new ChangeSupport(source);
67
        l = new MockChangeListener();
68
        cs.addChangeListener(l);
69
    }
70
71
    public void testBasicUsage() throws Exception {
72
        l.assertNoEvents();
73
        l.assertEventCount(0);
74
        try {
75
            l.assertEvent();
76
            assert false;
77
        } catch (AssertionFailedError e) {}
78
        try {
79
            l.assertEventCount(1);
80
            assert false;
81
        } catch (AssertionFailedError e) {}
82
        cs.fireChange();
83
        l.assertEvent();
84
        l.assertNoEvents();
85
        l.assertEventCount(0);
86
        cs.fireChange();
87
        cs.fireChange();
88
        l.assertEventCount(2);
89
        cs.fireChange();
90
        l.assertEvent();
91
        l.assertNoEvents();
92
        l.assertNoEvents();
93
        cs.fireChange();
94
        l.reset();
95
        l.assertNoEvents();
96
        cs.fireChange();
97
        cs.fireChange();
98
        assertEquals(2, l.allEvents().size());
99
    }
100
101
    public void testMessages() throws Exception {
102
        try {
103
            l.assertEvent();
104
            assert false;
105
        } catch (AssertionFailedError e) {}
106
        try {
107
            l.msg("stuff").assertEvent();
108
            assert false;
109
        } catch (AssertionFailedError e) {
110
            assertTrue(e.getMessage().contains("stuff"));
111
        }
112
        try {
113
            l.assertEvent();
114
            assert false;
115
        } catch (AssertionFailedError e) {
116
            assertFalse(String.valueOf(e.getMessage()).contains("stuff"));
117
        }
118
    }
119
120
    @RandomlyFails // NB-Core-Build #8154
121
    public void testExpect() throws Exception {
122
        l.expectNoEvents(1000);
123
        cs.fireChange();
124
        l.expectEvent(1000);
125
        l.assertNoEvents();
126
        new Thread() {
127
            @Override public void run() {
128
                try {
129
                    Thread.sleep(2000);
130
                } catch (InterruptedException x) {
131
                    assert false;
132
                }
133
                cs.fireChange();
134
            }
135
        }.start();
136
        try {
137
            l.expectEvent(1000);
138
            assert false;
139
        } catch (AssertionFailedError e) {}
140
        l.expectEvent(2000);
141
        l.assertNoEvents();
142
        l.expectNoEvents(1000);
143
    }
144
145
}
(-)a/openide.util.base/test/unit/src/org/openide/util/test/MockPropertyChangeListener.java (+227 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * Contributor(s):
28
 *
29
 * The Original Software is NetBeans. The Initial Developer of the Original
30
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
31
 * Microsystems, Inc. All Rights Reserved.
32
 *
33
 * If you wish your version of this file to be governed by only the CDDL
34
 * or only the GPL Version 2, indicate your decision by adding
35
 * "[Contributor] elects to include this software in this distribution
36
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
37
 * single choice of license, a recipient has the option to distribute
38
 * your version of this file under either the CDDL, the GPL Version 2 or
39
 * to extend the choice of license to its licensees as provided above.
40
 * However, if you add GPL Version 2 code and therefore, elected the GPL
41
 * Version 2 license, then the option applies only if the new code is
42
 * made subject to such option by the copyright holder.
43
 */
44
45
package org.openide.util.test;
46
47
import java.beans.PropertyChangeEvent;
48
import java.beans.PropertyChangeListener;
49
import java.util.ArrayList;
50
import java.util.Arrays;
51
import java.util.HashMap;
52
import java.util.HashSet;
53
import java.util.List;
54
import java.util.Map;
55
import java.util.Set;
56
import java.util.TreeSet;
57
import static junit.framework.Assert.*;
58
import junit.framework.AssertionFailedError;
59
60
/**
61
 * A scriptable property change listener.
62
 */
63
public class MockPropertyChangeListener implements PropertyChangeListener {
64
65
    private final List<PropertyChangeEvent> events = new ArrayList<PropertyChangeEvent>();
66
    private final Set<String> whitelist;
67
    private final Set<String> blacklist = new HashSet<String>();
68
    private final Set<String> ignored = new HashSet<String>();
69
    private String msg;
70
71
    /**
72
     * Makes a fresh listener.
73
     * @param whiteListedPropertyNames an optional list of property names; if any others are received, an assertion will be thrown
74
     */
75
    public MockPropertyChangeListener(String... whitelistedPropertyNames) {
76
        whitelist = whitelistedPropertyNames.length > 0 ? new HashSet<String>(Arrays.asList(whitelistedPropertyNames)) : null;
77
    }
78
79
    /**
80
     * Marks certain property names as being definitely not expected.
81
     * If any are received henceforth, an assertion will be thrown.
82
     */
83
    public synchronized void blacklist(String... blacklistedPropertyNames) {
84
        assertNull("Meaningless to blacklist some properties while there is an active whitelist", whitelist);
85
        blacklist.addAll(Arrays.asList(blacklistedPropertyNames));
86
    }
87
88
    /**
89
     * Marks certain property names as being ignored.
90
     * If any are received henceforth, no action will be taken.
91
     */
92
    public synchronized void ignore(String... ignoredPropertyNames) {
93
        ignored.addAll(Arrays.asList(ignoredPropertyNames));
94
    }
95
96
    public synchronized void propertyChange(PropertyChangeEvent ev) {
97
        String propname = ev.getPropertyName();
98
        if (ignored.contains(propname)) {
99
            return;
100
        }
101
        assertTrue("Property name " + propname + " not expected", whitelist == null || whitelist.contains(propname));
102
        assertFalse("Property name " + propname + " not expected", blacklist.contains(propname));
103
        if (propname == null) {
104
            assertNull("null prop name -> null old value", ev.getOldValue());
105
            assertNull("null prop name -> null new value", ev.getNewValue());
106
        }
107
        events.add(ev);
108
        notifyAll();
109
    }
110
111
    /**
112
     * Specifies a failure message to use for the next assertion.
113
     * @return this object, for convenient chaining
114
     */
115
    public MockPropertyChangeListener msg(String msg) {
116
        this.msg = msg;
117
        return this;
118
    }
119
120
    private String compose(String msg) {
121
        return this.msg == null ? msg : msg + ": " + this.msg;
122
    }
123
124
    /**
125
     * Asserts that the set of property change event names fired matches an expected list.
126
     * (Order and multiplicity of events is not considered.)
127
     * After this call, the list of received events is reset, so each call checks events since the last call.
128
     */
129
    public synchronized void assertEvents(String... expectedPropertyNames) throws AssertionFailedError {
130
        try {
131
            Set<String> actualEvents = new TreeSet<String>();
132
            for (PropertyChangeEvent ev : events) {
133
                actualEvents.add(ev.getPropertyName());
134
            }
135
            assertEquals(msg, new TreeSet<String>(Arrays.asList(expectedPropertyNames)).toString(), actualEvents.toString());
136
        } finally {
137
            reset();
138
        }
139
    }
140
141
    /**
142
     * Asserts that a certain number of events have been received.
143
     * (Property name is not considered.)
144
     * After this call, the list of received events is reset, so each call checks events since the last call.
145
     */
146
    public synchronized void assertEventCount(int expectedCount) throws AssertionFailedError {
147
        try {
148
            assertEquals(msg, expectedCount, events.size());
149
        } finally {
150
            reset();
151
        }
152
    }
153
154
    /**
155
     * Asserts that some events were received with particular old and new values.
156
     * After this call, the list of received events is reset, so each call checks events since the last call.
157
     * @param expectedOldValues mapping from expected property names to old values (may be left null to skip this check)
158
     * @param expectedNewValues mapping from expected property names to new values
159
     */
160
    public synchronized void assertEventsAndValues(Map<String,?> expectedOldValues, Map<String,?> expectedNewValues) throws AssertionFailedError {
161
        try {
162
            if (expectedOldValues != null) {
163
                Map<String,Object> actualOldValues = new HashMap<String,Object>();
164
                for (PropertyChangeEvent ev : events) {
165
                    actualOldValues.put(ev.getPropertyName(), ev.getOldValue());
166
                }
167
                assertEquals(msg, expectedOldValues, actualOldValues);
168
            }
169
            Map<String,Object> actualNewValues = new HashMap<String,Object>();
170
            for (PropertyChangeEvent ev : events) {
171
                actualNewValues.put(ev.getPropertyName(), ev.getNewValue());
172
            }
173
            assertEquals(msg, expectedNewValues, actualNewValues);
174
        } finally {
175
            reset();
176
        }
177
    }
178
179
    /**
180
     * Expects a single event to be fired.
181
     * After this call, the list of received events is reset, so each call checks events since the last call.
182
     * @param propertyName optional property name which is expected (or null for any)
183
     * @param timeout a timeout in milliseconds (zero means no timeout)
184
     */
185
    public synchronized void expectEvent(String expectedPropertyName, long timeout) throws AssertionFailedError {
186
        try {
187
            if (events.isEmpty()) {
188
                try {
189
                    wait(timeout);
190
                } catch (InterruptedException x) {
191
                    fail(compose("Timed out waiting for event"));
192
                }
193
            }
194
            assertFalse(compose("Did not get event"), events.isEmpty());
195
            assertFalse(compose("Got too many events"), events.size() > 1);
196
            PropertyChangeEvent received = events.iterator().next();
197
            if (expectedPropertyName != null) {
198
                assertEquals(msg, expectedPropertyName, received.getPropertyName());
199
            }
200
        } finally {
201
            reset();
202
        }
203
    }
204
205
    /**
206
     * Gets a list of all received events, for special processing.
207
     * (For example, checking of source, ...)
208
     * After this call, the list of received events is reset, so each call checks events since the last call.
209
     */
210
    public synchronized List<PropertyChangeEvent> allEvents() {
211
        try {
212
            return new ArrayList<PropertyChangeEvent>(events);
213
        } finally {
214
            reset();
215
        }
216
    }
217
218
    /**
219
     * Simply resets the list of events without checking anything.
220
     * Also resets any failure message.
221
     */
222
    public synchronized void reset() {
223
        msg = null;
224
        events.clear();
225
    }
226
227
}
(-)a/openide.util.base/test/unit/src/org/openide/util/test/MockPropertyChangeListenerTest.java (+169 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * Contributor(s):
28
 *
29
 * The Original Software is NetBeans. The Initial Developer of the Original
30
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
31
 * Microsystems, Inc. All Rights Reserved.
32
 *
33
 * If you wish your version of this file to be governed by only the CDDL
34
 * or only the GPL Version 2, indicate your decision by adding
35
 * "[Contributor] elects to include this software in this distribution
36
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
37
 * single choice of license, a recipient has the option to distribute
38
 * your version of this file under either the CDDL, the GPL Version 2 or
39
 * to extend the choice of license to its licensees as provided above.
40
 * However, if you add GPL Version 2 code and therefore, elected the GPL
41
 * Version 2 license, then the option applies only if the new code is
42
 * made subject to such option by the copyright holder.
43
 */
44
45
package org.openide.util.test;
46
47
import java.beans.PropertyChangeSupport;
48
import java.util.Collections;
49
import junit.framework.AssertionFailedError;
50
import junit.framework.TestCase;
51
52
public class MockPropertyChangeListenerTest extends TestCase {
53
54
    public MockPropertyChangeListenerTest(String n) {
55
        super(n);
56
    }
57
58
    Object source;
59
    PropertyChangeSupport pcs;
60
    MockPropertyChangeListener l;
61
62
    @Override
63
    protected void setUp() throws Exception {
64
        super.setUp();
65
        source = new Object();
66
        pcs = new PropertyChangeSupport(source);
67
        l = new MockPropertyChangeListener();
68
        pcs.addPropertyChangeListener(l);
69
    }
70
71
    // XXX test expect
72
73
    public void testBasicUsage() throws Exception {
74
        l.assertEvents();
75
        try {
76
            l.assertEvents("whatever");
77
            assert false;
78
        } catch (AssertionFailedError e) {}
79
        pcs.firePropertyChange("foo", null, null);
80
        l.assertEvents("foo");
81
        try {
82
            l.assertEvents("foo");
83
            assert false;
84
        } catch (AssertionFailedError e) {}
85
        l.assertEventCount(0);
86
        pcs.firePropertyChange("bar", null, null);
87
        pcs.firePropertyChange("baz", null, null);
88
        l.assertEventCount(2);
89
        try {
90
            l.assertEventCount(2);
91
            assert false;
92
        } catch (AssertionFailedError e) {}
93
        assertEquals(0, l.allEvents().size());
94
        pcs.firePropertyChange("bar", null, null);
95
        pcs.firePropertyChange("baz", null, null);
96
        assertEquals(2, l.allEvents().size());
97
        assertEquals(0, l.allEvents().size());
98
        pcs.firePropertyChange("foo", "old", "new");
99
        l.assertEventsAndValues(null, Collections.singletonMap("foo", "new"));
100
        pcs.firePropertyChange("foo", "old2", "new2");
101
        l.assertEventsAndValues(Collections.singletonMap("foo", "old2"), Collections.singletonMap("foo", "new2"));
102
        try {
103
            l.assertEventsAndValues(null, Collections.singletonMap("foo", "new2"));
104
            assert false;
105
        } catch (AssertionFailedError e) {}
106
        pcs.firePropertyChange("foo", null, null);
107
        l.reset();
108
        l.assertEvents();
109
        pcs.firePropertyChange("x", null, null);
110
        try {
111
            l.assertEvents();
112
            assert false;
113
        } catch (AssertionFailedError e) {}
114
        l.assertEvents();
115
    }
116
117
    public void testMessages() throws Exception {
118
        pcs.firePropertyChange("foo", null, null);
119
        try {
120
            l.assertEvents();
121
            assert false;
122
        } catch (AssertionFailedError e) {}
123
        pcs.firePropertyChange("foo", null, null);
124
        try {
125
            l.msg("stuff").assertEvents();
126
            assert false;
127
        } catch (AssertionFailedError e) {
128
            assertTrue(e.getMessage().contains("stuff"));
129
        }
130
        pcs.firePropertyChange("foo", null, null);
131
        try {
132
            l.assertEvents();
133
            assert false;
134
        } catch (AssertionFailedError e) {
135
            assertFalse(e.getMessage().contains("stuff"));
136
        }
137
    }
138
139
    public void testPropertyNameFiltering() throws Exception {
140
        l.ignore("irrelevant");
141
        l.blacklist("bad", "worse");
142
        pcs.firePropertyChange("relevant", null, null);
143
        l.assertEvents("relevant");
144
        pcs.firePropertyChange("irrelevant", null, null);
145
        l.assertEvents();
146
        try {
147
            pcs.firePropertyChange("bad", null, null);
148
            assert false;
149
        } catch (AssertionFailedError e) {}
150
        try {
151
            pcs.firePropertyChange("worse", null, null);
152
            assert false;
153
        } catch (AssertionFailedError e) {}
154
        pcs.removePropertyChangeListener(l);
155
        l = new MockPropertyChangeListener("expected1", "expected2");
156
        pcs.addPropertyChangeListener(l);
157
        l.ignore("irrelevant");
158
        pcs.firePropertyChange("expected1", null, null);
159
        pcs.firePropertyChange("expected2", null, null);
160
        l.assertEvents("expected1", "expected2");
161
        pcs.firePropertyChange("irrelevant", null, null);
162
        l.assertEvents();
163
        try {
164
            pcs.firePropertyChange("other", null, null);
165
            assert false;
166
        } catch (AssertionFailedError e) {}
167
    }
168
169
}
(-)a/openide.util.base/test/unit/src/org/openide/util/test/RestrictThreadCreation.java (+130 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * Contributor(s):
28
 *
29
 * Portions Copyrighted 2007 Sun Microsystems, Inc.
30
 */
31
32
package org.openide.util.test;
33
34
import java.security.Permission;
35
import java.util.Arrays;
36
import java.util.HashSet;
37
import java.util.Set;
38
39
/**
40
 * Permits unit tests to limit creation of threads.
41
 * Unexpected thread creation can make tests fail randomly, which makes debugging difficult.
42
 * <p>Start off calling {@link #permitStandard} and {@link #forbidNewThreads}.
43
 * To determine which methods to permit, just try running the test;
44
 * if you see any {@link SecurityException}s which look like harmless thread creation
45
 * activities, just copy the appropriate part of the stack trace and pass to {@link #permit}.
46
 * <p>Use non-strict mode for {@link #forbidNewThreads} if you suspect some code
47
 * might be catching and not reporting {@link SecurityException}s; or you may prefer
48
 * to simply use non-strict mode while developing the test and then switch to strict
49
 * mode once it begins passing.
50
 * <p>Place calls to this class early in your test's initialization, e.g. in a static block.
51
 * (Not suitable for use from {@link junit.framework.TestCase#setUp}.)
52
 */
53
public class RestrictThreadCreation {
54
55
    private RestrictThreadCreation() {}
56
57
    private static Set<String> currentlyPermitted = new HashSet<String>();
58
59
    /**
60
     * Explicitly permits one or more thread creation idioms.
61
     * Each entry is of the form <samp>fully.qualified.Clazz.methodName</samp>
62
     * and if such a method can be found on the call stack the thread creation
63
     * is permitted.
64
     * @param permitted one or more fully qualified method names to accept
65
     */
66
    public static void permit(String... permitted) {
67
        currentlyPermitted.addAll(Arrays.asList(permitted));
68
    }
69
70
    /**
71
     * Permits a standard set of thread creation idioms which are normally harmless to unit tests.
72
     * Feel free to add to this list if it seems appropriate.
73
     */
74
    public static void permitStandard() {
75
        permit(// Found experimentally:
76
                "org.netbeans.junit.NbTestCase.runBare",
77
                "sun.java2d.Disposer.<clinit>",
78
                "java.awt.Toolkit.getDefaultToolkit",
79
                "java.util.logging.LogManager$Cleaner.<init>",
80
                "org.netbeans.ModuleManager$1.<init>",
81
                "org.netbeans.Stamps$Worker.<init>",
82
                "org.netbeans.core.startup.Splash$SplashComponent.setText",
83
                "org.netbeans.core.startup.preferences.NbPreferences.asyncInvocationOfFlushSpi",
84
                "org.openide.loaders.FolderInstance.waitFinished",
85
                "org.openide.loaders.FolderInstance.postCreationTask",
86
                "org.netbeans.modules.masterfs.filebasedfs.fileobjects.LockForFile.<clinit>",
87
                "org.netbeans.api.java.source.JavaSource.<clinit>",
88
                "org.netbeans.api.java.source.JavaSourceTaskFactory.fileObjectsChanged",
89
                "org.netbeans.modules.progress.spi.Controller.resetTimer",
90
                "org.netbeans.modules.project.ui.problems.BrokenProjectAnnotator.annotateIcon",
91
                "org.netbeans.modules.timers.InstanceWatcher$FinalizingToken.finalize",
92
                "org.openide.util.NbBundle.getBundleFast",
93
                "org.openide.util.RequestProcessor$TickTac.run",
94
                "org.openide.util.Utilities$ActiveQueue.ping",
95
                "javax.swing.JComponent.revalidate",
96
                "javax.swing.ImageIcon.<init>");
97
    }
98
99
    /**
100
     * Install a security manager which prevents new threads from being created
101
     * unless they were explicitly permitted.
102
     * @param strict if true, throw a security exception; if false, just print stack traces
103
     */
104
    public static void forbidNewThreads(final boolean strict) {
105
        System.setSecurityManager(new SecurityManager() {
106
            public @Override void checkAccess(ThreadGroup g) {
107
                boolean inThreadInit = false;
108
                for (StackTraceElement line : Thread.currentThread().getStackTrace()) {
109
                    String id = line.getClassName() + "." + line.getMethodName();
110
                    if (currentlyPermitted.contains(id)) {
111
                        return;
112
                    } else if (id.equals("java.lang.Thread.init") || id.equals("org.openide.util.RequestProcessor$Processor.checkAccess")) {
113
                        inThreadInit = true;
114
                    }
115
                }
116
                if (inThreadInit) {
117
                    SecurityException x = new SecurityException("Unauthorized thread creation");
118
                    if (strict) {
119
                        throw x;
120
                    } else {
121
                        x.printStackTrace();
122
                    }
123
                }
124
            }
125
            public @Override void checkPermission(Permission perm) {}
126
            public @Override void checkPermission(Permission perm, Object context) {}
127
        });
128
    }
129
130
}
(-)a/openide.util.base/test/unit/src/org/openide/util/test/TestFileUtils.java (+271 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2008 Sun Microsystems, Inc.
41
 */
42
43
package org.openide.util.test;
44
45
import java.io.ByteArrayOutputStream;
46
import java.io.File;
47
import java.io.FileInputStream;
48
import java.io.FileOutputStream;
49
import java.io.IOException;
50
import java.io.InputStream;
51
import java.io.OutputStream;
52
import java.io.OutputStreamWriter;
53
import java.io.PrintWriter;
54
import java.util.Collections;
55
import java.util.HashSet;
56
import java.util.LinkedHashMap;
57
import java.util.Map;
58
import java.util.Set;
59
import java.util.zip.CRC32;
60
import java.util.zip.ZipEntry;
61
import java.util.zip.ZipInputStream;
62
import java.util.zip.ZipOutputStream;
63
import junit.framework.Assert;
64
65
/**
66
 * Common utility methods for massaging and inspecting files from tests.
67
 */
68
public class TestFileUtils {
69
70
    private TestFileUtils() {}
71
72
    /**
73
     * Create a new data file with specified initial contents.
74
     * @param f a file to create (parents will be created automatically)
75
     * @param body the complete contents of the new file (in UTF-8 encoding)
76
     */
77
    public static File writeFile(File f, String body) throws IOException {
78
        f.getParentFile().mkdirs();
79
        OutputStream os = new FileOutputStream(f);
80
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, "UTF-8"));
81
        pw.print(body);
82
        pw.flush();
83
        os.close();
84
        return f;
85
    }
86
87
    /**
88
     * Read the contents of a file as a single string.
89
     * @param a data file
90
     * @return its contents (in UTF-8 encoding)
91
     */
92
    public static String readFile(File file) throws IOException {
93
        InputStream is = new FileInputStream(file);
94
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
95
        byte[] buf = new byte[4096];
96
        int read;
97
        while ((read = is.read(buf)) != -1) {
98
            baos.write(buf, 0, read);
99
        }
100
        is.close();
101
        return baos.toString("UTF-8");
102
    }
103
104
    /**
105
     * Read the contents of a file as a byte array.
106
     * @param a data file
107
     * @return its raw binary contents
108
     */
109
    public static byte[] readFileBin(File file) throws IOException {
110
        InputStream is = new FileInputStream(file);
111
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
112
        byte[] buf = new byte[4096];
113
        int read;
114
        while ((read = is.read(buf)) != -1) {
115
            baos.write(buf, 0, read);
116
        }
117
        is.close();
118
        return baos.toByteArray();
119
    }
120
121
    /**
122
     * Create a new ZIP file.
123
     * @param jar the ZIP file to create
124
     * @param entries a list of entries in the form of "filename:UTF8-contents"; parent dirs created automatically
125
     * @return the {@code jar} parameter, for convenience
126
     * @throws IOException for the usual reasons
127
     */
128
    public static File writeZipFile(File jar, String... entries) throws IOException {
129
        jar.getParentFile().mkdirs();
130
        writeZipFile(new FileOutputStream(jar), entries);
131
        return jar;
132
    }
133
134
    /**
135
     * Create a new ZIP file.
136
     * @param os a stream to which the ZIP will be written
137
     * @param entries a list of entries in the form of "filename:UTF8-contents"; parent dirs created automatically
138
     * @throws IOException for the usual reasons
139
     */
140
    public static void writeZipFile(OutputStream os, String... entries) throws IOException {
141
        Map<String,byte[]> binary = new LinkedHashMap<String,byte[]>();
142
        for (String entry : entries) {
143
            int colon = entry.indexOf(':');
144
            assert colon != -1 : entry;
145
            binary.put(entry.substring(0, colon), entry.substring(colon + 1).getBytes("UTF-8"));
146
        }
147
        writeZipFile(os, binary);
148
    }
149
150
    /**
151
     * Create a new ZIP file.
152
     * @param os a stream to which the ZIP will be written
153
     * @param entries entries as maps from filename to binary contents;; parent dirs created automatically
154
     * @throws IOException for the usual reasons
155
     */
156
    public static void writeZipFile(OutputStream os, Map<String,byte[]> entries) throws IOException {
157
        ZipOutputStream zos = new ZipOutputStream(os);
158
        Set<String> parents = new HashSet<String>();
159
        if (entries.isEmpty()) {
160
            entries = Collections.singletonMap("PLACEHOLDER", new byte[0]);
161
        }
162
        for (Map.Entry<String,byte[]> entry : entries.entrySet()) {
163
            String name = entry.getKey();
164
            assert name.length() > 0 && !name.endsWith("/") && !name.startsWith("/") && name.indexOf("//") == -1 : name;
165
            for (int i = 0; i < name.length(); i++) {
166
                if (name.charAt(i) == '/') {
167
                    String parent = name.substring(0, i + 1);
168
                    if (parents.add(parent)) {
169
                        ZipEntry ze = new ZipEntry(parent);
170
                        ze.setMethod(ZipEntry.STORED);
171
                        ze.setSize(0);
172
                        ze.setCrc(0);
173
                        ze.setTime(0);
174
                        zos.putNextEntry(ze);
175
                        zos.closeEntry();
176
                    }
177
                }
178
            }
179
            byte[] data = entry.getValue();
180
            ZipEntry ze = new ZipEntry(name);
181
            ze.setMethod(ZipEntry.STORED);
182
            ze.setSize(data.length);
183
            CRC32 crc = new CRC32();
184
            crc.update(data);
185
            ze.setCrc(crc.getValue());
186
            ze.setTime(0);
187
            zos.putNextEntry(ze);
188
            zos.write(data, 0, data.length);
189
            zos.closeEntry();
190
        }
191
        zos.finish();
192
        zos.close();
193
        os.close();
194
    }
195
196
    /**
197
     * Unpacks a ZIP file to disk.
198
     * All entries are unpacked, even {@code META-INF/MANIFEST.MF} if present.
199
     * Parent directories are created as needed (even if not mentioned in the ZIP);
200
     * empty ZIP directories are created too.
201
     * Existing files are overwritten.
202
     * @param zip a ZIP file
203
     * @param dir the base directory in which to unpack (need not yet exist)
204
     * @throws IOException in case of problems
205
     */
206
    public static void unpackZipFile(File zip, File dir) throws IOException {
207
        byte[] buf = new byte[8192];
208
        InputStream is = new FileInputStream(zip);
209
        try {
210
            ZipInputStream zis = new ZipInputStream(is);
211
            ZipEntry entry;
212
            while ((entry = zis.getNextEntry()) != null) {
213
                String name = entry.getName();
214
                int slash = name.lastIndexOf('/');
215
                File d = new File(dir, name.substring(0, slash).replace('/', File.separatorChar));
216
                if (!d.isDirectory() && !d.mkdirs()) {
217
                    throw new IOException("could not make " + d);
218
                }
219
                if (slash != name.length() - 1) {
220
                    File f = new File(dir, name.replace('/', File.separatorChar));
221
                    OutputStream os = new FileOutputStream(f);
222
                    try {
223
                        int read;
224
                        while ((read = zis.read(buf)) != -1) {
225
                            os.write(buf, 0, read);
226
                        }
227
                    } finally {
228
                        os.close();
229
                    }
230
                }
231
            }
232
        } finally {
233
            is.close();
234
        }
235
    }
236
237
    /**
238
     * Make sure the timestamp on a file changes.
239
     * @param f a file to touch (make newer)
240
     * @param ref if not null, make f newer than this file; else make f newer than it was before
241
     */
242
    @SuppressWarnings("SleepWhileInLoop")
243
    public static void touch(File f, File ref) throws IOException, InterruptedException {
244
        long older = f.lastModified();
245
        if (ref != null) {
246
            older = Math.max(older, ref.lastModified());
247
        } else {
248
            older = Math.max(older, System.currentTimeMillis());
249
        }
250
        int maxPause = 9999;
251
        /* XXX consider this (as yet untested):
252
        long curr = System.currentTimeMillis();
253
        if (older > curr + maxPause) {
254
            throw new IllegalArgumentException("reference too far into the future, by " + (older - curr) + "msec");
255
        }
256
         */
257
        for (long pause = 1; pause < maxPause; pause *= 2) {
258
            Thread.sleep(pause);
259
            f.setLastModified(System.currentTimeMillis() + 1);  // plus 1 needed for FileObject tests (initially FO lastModified is set to currentTimeMillis)
260
            if (f.lastModified() > older) {
261
                while (f.lastModified() >= System.currentTimeMillis()) {
262
//                    LOG.log(Level.INFO, "Modification time is in future {0}", System.currentTimeMillis());
263
                    Thread.sleep(10);
264
                }
265
                return;
266
            }
267
        }
268
        Assert.fail("Did not manage to touch " + f);
269
    }
270
271
}
(-)a/openide.util.base/test/unit/src/org/openide/util/test/package-info.java (+48 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * Contributor(s):
28
 *
29
 * The Original Software is NetBeans. The Initial Developer of the Original
30
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
31
 * Microsystems, Inc. All Rights Reserved.
32
 *
33
 * If you wish your version of this file to be governed by only the CDDL
34
 * or only the GPL Version 2, indicate your decision by adding
35
 * "[Contributor] elects to include this software in this distribution
36
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
37
 * single choice of license, a recipient has the option to distribute
38
 * your version of this file under either the CDDL, the GPL Version 2 or
39
 * to extend the choice of license to its licensees as provided above.
40
 * However, if you add GPL Version 2 code and therefore, elected the GPL
41
 * Version 2 license, then the option applies only if the new code is
42
 * made subject to such option by the copyright holder.
43
 */
44
45
/**
46
 * General utility classes useful for writing unit tests in various modules.
47
 */
48
package org.openide.util.test;
(-)a/openide.util/src/org/netbeans/modules/openide/util/ProxyURLStreamHandlerFactory.java (-91 lines)
Lines 1-91 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2009 Sun Microsystems, Inc.
41
 */
42
43
package org.netbeans.modules.openide.util;
44
45
import java.net.URLStreamHandler;
46
import java.net.URLStreamHandlerFactory;
47
import java.util.Arrays;
48
import java.util.Collection;
49
import java.util.HashMap;
50
import java.util.HashSet;
51
import java.util.Map;
52
import java.util.Set;
53
import org.openide.util.Lookup;
54
import org.openide.util.LookupEvent;
55
import org.openide.util.LookupListener;
56
import org.openide.util.URLStreamHandlerRegistration;
57
import org.openide.util.lookup.Lookups;
58
import org.openide.util.lookup.ServiceProvider;
59
60
/**
61
 * @see URLStreamHandlerRegistration
62
 */
63
@ServiceProvider(service=URLStreamHandlerFactory.class)
64
public final class ProxyURLStreamHandlerFactory implements URLStreamHandlerFactory {
65
    /** prevents GC only */
66
    private final Map<String, Lookup.Result<URLStreamHandler>> results = new HashMap<String, Lookup.Result<URLStreamHandler>>();
67
    private final Map<String, URLStreamHandler> handlers = new HashMap<String, URLStreamHandler>();
68
    private static final Set<String> STANDARD_PROTOCOLS = new HashSet<String>(Arrays.asList("jar", "file", "http", "https", "resource")); // NOI18N
69
70
    public @Override synchronized URLStreamHandler createURLStreamHandler(final String protocol) {
71
        if (STANDARD_PROTOCOLS.contains(protocol)) {
72
            // Well-known handlers in JRE. Do not try to initialize lookup.
73
            return null;
74
        }
75
        if (!results.containsKey(protocol)) {
76
            final Lookup.Result<URLStreamHandler> result = Lookups.forPath("URLStreamHandler/" + protocol).lookupResult(URLStreamHandler.class);
77
            LookupListener listener = new LookupListener() {
78
                public @Override void resultChanged(LookupEvent ev) {
79
                    synchronized (ProxyURLStreamHandlerFactory.this) {
80
                        Collection<? extends URLStreamHandler> instances = result.allInstances();
81
                        handlers.put(protocol, instances.isEmpty() ? null : instances.iterator().next());
82
                    }
83
                }
84
            };
85
            result.addLookupListener(listener);
86
            listener.resultChanged(null);
87
            results.put(protocol, result);
88
        }
89
        return handlers.get(protocol);
90
    }
91
}
(-)a/openide.util/src/org/openide/util/URLStreamHandlerRegistration.java (-83 lines)
Lines 1-83 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2009 Sun Microsystems, Inc.
41
 */
42
43
package org.openide.util;
44
45
import java.lang.annotation.ElementType;
46
import java.lang.annotation.Retention;
47
import java.lang.annotation.RetentionPolicy;
48
import java.lang.annotation.Target;
49
import java.net.URL;
50
import java.net.URLStreamHandler;
51
import java.net.URLStreamHandlerFactory;
52
import org.openide.util.lookup.NamedServiceDefinition;
53
54
/**
55
 * Replacement for {@link URLStreamHandlerFactory} within the NetBeans platform.
56
 * (The JVM only permits one global factory to be set at a time,
57
 * whereas various independent modules may wish to register handlers.)
58
 * May be placed on a {@link URLStreamHandler} implementation to register it.
59
 * Your handler will be loaded and used if and when a URL of a matching protocol is created.
60
 * <p>A {@link URLStreamHandlerFactory} which uses these registrations may be found in {@link Lookup#getDefault}.
61
 * This factory is active whenever the module system is loaded.
62
 * You may also wish to call {@link URL#setURLStreamHandlerFactory}
63
 * from a unit test or otherwise without the module system active.
64
 * @since org.openide.util 7.31
65
 */
66
@NamedServiceDefinition(path="URLStreamHandler/@protocol()", serviceType=URLStreamHandler.class)
67
@Retention(RetentionPolicy.SOURCE)
68
@Target(ElementType.TYPE)
69
public @interface URLStreamHandlerRegistration {
70
71
    /**
72
     * URL protocol(s) which are handled.
73
     * {@link URLStreamHandler#openConnection} will be called with a matching {@link URL#getProtocol}.
74
     */
75
    String[] protocol();
76
77
    /**
78
     * An optional position in which to register this handler relative to others.
79
     * The lowest-numbered handler is used in favor of any others, including unnumbered handlers.
80
     */
81
    int position() default Integer.MAX_VALUE;
82
83
}
(-)a/web.inspect/src/org/netbeans/modules/web/inspect/webkit/RemoteStyleSheetCache.java (-1 lines)
Lines 392-398 Link Here
392
            return null;
392
            return null;
393
        }
393
        }
394
394
395
        @Override
396
        public SystemAction[] getActions() {
395
        public SystemAction[] getActions() {
397
            return new SystemAction[0];
396
            return new SystemAction[0];
398
        }
397
        }

Return to bug 243683