Datasets:

Modalities:
Text
Formats:
json
Languages:
code
Size:
< 1K
Tags:
code
Libraries:
Datasets
pandas
License:
File size: 17,552 Bytes
eb67da4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/*
 *    GeoTools - The Open Source Java GIS Toolkit
 *    http://geotools.org
 *
 *    (C) 2005-2008, Open Source Geospatial Foundation (OSGeo)
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License as published by the Free Software Foundation;
 *    version 2.1 of the License.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 */
package org.geotools.util.factory;

import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

/**
 * Tests {@link org.geotools.util.factory.FactoryRegistry} implementation.
 *
 * @version $Id$
 * @author Martin Desruisseaux
 */
public final class FactoryRegistryTest {
    /**
     * Ensures that class {@link org.geotools.util.factory.Hints} is loaded before {@link
     * DummyFactory}. It is not needed for normal execution, but Maven seems to mess with class
     * loaders.
     */
    @Before
    public void ensureHintsLoaded() {
        assertNotNull(Hints.DATUM_FACTORY.toString());
    }

    /**
     * Creates the factory registry to test. The tests performed in this method are more J2SE tests
     * than Geotools implementation tests. We basically just ensure that we have setup the service
     * registry properly.
     *
     * <p>Factories are specified in arguments as {@link org.geotools.util.factory.Factory} objects
     * in order to avoid the {@link DummyClass} to be initialized before {@link
     * org.geotools.util.factory.Hints}. This is not a problem for normal execution, but Maven seems
     * to mess with class loaders.
     *
     * @param creator {@code true} if the registry should be an instance of {@link
     *     org.geotools.util.factory.FactoryCreator}.
     */
    @SuppressWarnings("PMD.UnusedPrivateMethod") // PMD getting confused here?
    private FactoryRegistry getRegistry(
            final boolean creator,
            final Factory factory1,
            final Factory factory2,
            final Factory factory3) {
        @SuppressWarnings("unchecked")
        final Set<Class<?>> categories = Collections.singleton(DummyFactory.class);
        // The above line fails without the cast, I don't know why...
        final FactoryRegistry registry;
        if (creator) {
            registry = new FactoryCreator(categories);
        } else {
            registry = new FactoryRegistry(categories);
        }
        registry.registerFactory(factory1);
        registry.registerFactory(factory2);
        registry.registerFactory(factory3);
        assertTrue(
                registry.setOrdering(
                        DummyFactory.class, (DummyFactory) factory1, (DummyFactory) factory2));
        assertTrue(
                registry.setOrdering(
                        DummyFactory.class, (DummyFactory) factory2, (DummyFactory) factory3));
        assertTrue(
                registry.setOrdering(
                        DummyFactory.class, (DummyFactory) factory1, (DummyFactory) factory3));

        final List<?> factories =
                registry.getFactories(DummyFactory.class, null, null).collect(toList());
        assertTrue(factories.contains(factory1));
        assertTrue(factories.contains(factory2));
        assertTrue(factories.contains(factory3));
        assertTrue(factories.indexOf(factory1) < factories.indexOf(factory2));
        assertTrue(factories.indexOf(factory2) < factories.indexOf(factory3));
        return registry;
    }

    /**
     * Tests the {@link org.geotools.util.factory.FactoryRegistry#getProvider} method. Note that the
     * tested method do not create any new factory. If no registered factory matching the hints is
     * found, an exception is expected. <br>
     * <br>
     * Three factories are initially registered: factory #1, #2 and #3.
     *
     * <p>Factory #1 has no dependency. Factory #2 uses factory #1. Factory #3 uses factory #2,
     * which implies an indirect dependency to factory #1.
     *
     * <p>Additionnaly, factory #1 uses a KEY_INTERPOLATION hint.
     */
    @Test
    public void testGetProvider() {
        final Hints.Key key = DummyFactory.DUMMY_FACTORY;
        final DummyFactory factory1 = new DummyFactory.Example1();
        final DummyFactory factory2 = new DummyFactory.Example2();
        final DummyFactory factory3 = new DummyFactory.Example3();
        final FactoryRegistry registry = getRegistry(false, factory1, factory2, factory3);
        // ------------------------------------------------
        //     PART 1: SIMPLE HINT (not a Factory hint)
        // ------------------------------------------------
        /*
         * No hints. The fist factory should be selected.
         */
        Hints hints = null;
        DummyFactory factory = registry.getFactory(DummyFactory.class, null, hints, key);
        assertSame("No preferences; should select the first factory. ", factory1, factory);
        /*
         * A hint compatible with one of our factories. Factory #1 declares explicitly that it uses
         * a bilinear interpolation, which is compatible with user's hints. All other factories are
         * indifferent. Since factory #1 is the first one in the list, it should be selected.
         */
        hints = new Hints(Hints.KEY_INTERPOLATION, Hints.VALUE_INTERPOLATION_BILINEAR);
        factory = registry.getFactory(DummyFactory.class, null, hints, key);
        assertSame("First factory matches; it should be selected. ", factory1, factory);
        /*
         * A hint incompatible with all our factories. Factory #1 is the only one to defines
         * explicitly a KEY_INTERPOLATION hint, but all other factories depend on factory #1
         * either directly (factory #2) or indirectly (factory #3, which depends on #2).
         */
        hints = new Hints(Hints.KEY_INTERPOLATION, Hints.VALUE_INTERPOLATION_BICUBIC);
        try {
            factory = registry.getFactory(DummyFactory.class, null, hints, key);
            fail("Found factory " + factory + ", while the hint should have been rejected.");
        } catch (FactoryNotFoundException exception) {
            // This is the expected exception. Continue...
        }
        /*
         * Add a new factory implementation, and try again with exactly the same hints
         * than the previous test. This time, the new factory should be selected since
         * this one doesn't have any dependency toward factory #1.
         */
        final DummyFactory factory4 = new DummyFactory.Example4();
        registry.registerFactory(factory4);
        assertTrue(registry.setOrdering(DummyFactory.class, factory1, factory4));
        factory = registry.getFactory(DummyFactory.class, null, hints, key);
        assertSame("The new factory should be selected. ", factory4, factory);

        // ----------------------------
        //     PART 2: FACTORY HINT
        // ----------------------------
        /*
         * Trivial case: user gives explicitly a factory instance.
         */
        DummyFactory explicit = new DummyFactory.Example3();
        hints = new Hints(DummyFactory.DUMMY_FACTORY, explicit);
        factory = registry.getFactory(DummyFactory.class, null, hints, key);
        assertSame("The user-specified factory should have been selected. ", explicit, factory);
        /*
         * User specifies the expected implementation class rather than an instance.
         */
        hints = new Hints(DummyFactory.DUMMY_FACTORY, DummyFactory.Example2.class);
        factory = registry.getFactory(DummyFactory.class, null, hints, key);
        assertSame("Factory of class #2 were requested. ", factory2, factory);
        /*
         * Same as above, but with classes specified in an array.
         */
        hints =
                new Hints(
                        DummyFactory.DUMMY_FACTORY,
                        new Class<?>[] {DummyFactory.Example3.class, DummyFactory.Example2.class});
        factory = registry.getFactory(DummyFactory.class, null, hints, key);
        assertSame("Factory of class #3 were requested. ", factory3, factory);
        /*
         * The following hint should be ignored by factory #1, since this factory doesn't have
         * any dependency to the INTERNAL_FACTORY hint. Since factory #1 is first in the ordering,
         * it should be selected.
         */
        hints = new Hints(DummyFactory.INTERNAL_FACTORY, DummyFactory.Example2.class);
        factory = registry.getFactory(DummyFactory.class, null, hints, key);
        assertSame("Expected factory #1. ", factory1, factory);
        /*
         * If the user really wants some factory that do have a dependency to factory #2, he should
         * specifies in a DUMMY_FACTORY hint the implementation classes (or a common super-class or
         * interface) that do care about the INTERNAL_FACTORY hint. Note that this extra step should
         * not be a big deal in most real application, because:
         *
         *  1) Either all implementations have this dependency (for example it would be
         *     unusual to see a DatumAuthorityFactory without a DatumFactory dependency);
         *
         *  2) or the user really know the implementation he wants (for example if he specifies a
         *     JTS CoordinateSequenceFactory, he probably wants to use the JTS GeometryFactory).
         *
         * In the particular case of this test suite, this extra step would not be needed
         * neither if factory #1 was last in the ordering rather than first.
         */
        final Hints implementations =
                new Hints(
                        DummyFactory.DUMMY_FACTORY,
                        new Class[] {DummyFactory.Example2.class, DummyFactory.Example3.class});
        /*
         * Now search NOT for factory #1, but rather for a factory using #1 internally.
         * This is the case of factory #2.
         */
        hints = new Hints(DummyFactory.INTERNAL_FACTORY, DummyFactory.Example1.class);
        hints.add(implementations);
        factory = registry.getFactory(DummyFactory.class, null, hints, key);
        assertSame("Expected a factory using #1 internally. ", factory2, factory);
    }

    /**
     * Tests the {@link org.geotools.util.factory.FactoryCreator#getProvider} method. This test
     * tries again the cases that was expected to throws an exception in {@link #testGetProvider}.
     * But now, those cases are expected to creates automatically new factory instances instead of
     * throwing an exception.
     */
    @Test
    public void testCreateProvider() {
        final Hints.Key key = DummyFactory.DUMMY_FACTORY;
        final DummyFactory factory1 = new DummyFactory.Example1();
        final DummyFactory factory2 = new DummyFactory.Example2();
        final DummyFactory factory3 = new DummyFactory.Example3();
        final FactoryRegistry registry = getRegistry(true, factory1, factory2, factory3);
        /*
         * Same tests than above (at least some of them).
         * See comments in 'testGetProvider()' for explanation.
         */
        Hints hints = new Hints(Hints.KEY_INTERPOLATION, Hints.VALUE_INTERPOLATION_BILINEAR);
        DummyFactory factory = registry.getFactory(DummyFactory.class, null, hints, key);
        assertSame("First factory matches; it should be selected. ", factory1, factory);

        hints = new Hints(DummyFactory.DUMMY_FACTORY, DummyFactory.Example2.class);
        factory = registry.getFactory(DummyFactory.class, null, hints, key);
        assertSame("Factory of class #2 were requested. ", factory2, factory);
        /*
         * The following case was throwing an exception in testGetProvider(). It should fails again
         * here, but for a different reason. FactoryCreator is unable to creates automatically a new
         * factory instance, since we gave no implementation hint and no registered factory have a
         * constructor expecting a Hints argument.
         */
        hints = new Hints(Hints.KEY_INTERPOLATION, Hints.VALUE_INTERPOLATION_BICUBIC);
        try {
            factory = registry.getFactory(DummyFactory.class, null, hints, key);
            fail(
                    "Found or created factory "
                            + factory
                            + ", while it should not have been allowed.");
        } catch (FactoryNotFoundException exception) {
            // This is the expected exception. Continue...
        }
        /*
         * Register a DummyFactory with a constructor expecting a Hints argument, and try again
         * with the same hints. Now it should creates a new factory instance, because we are using
         * FactoryCreator instead of FactoryRegistry and an appropriate constructor is found.
         * Note that an AssertionFailedError should be thrown if the no-argument constructor of
         * Example5 is invoked, since the constructor with a Hints argument should have priority.
         */
        final DummyFactory factory5 = new DummyFactory.Example5(null);
        registry.registerFactory(factory5);
        assertTrue(registry.setOrdering(DummyFactory.class, factory1, factory5));
        factory = registry.getFactory(DummyFactory.class, null, hints, key);
        assertSame(
                "An instance of Factory #5 should have been created.",
                factory5.getClass(),
                factory.getClass());
        assertNotSame("A NEW instance of Factory #5 should have been created", factory5, factory);
        /*
         * Tries again with a class explicitly specified as an implementation hint.
         * It doesn't matter if this class is registered or not.
         */
        hints.put(DummyFactory.DUMMY_FACTORY, DummyFactory.Example4.class);
        factory = registry.getFactory(DummyFactory.class, null, hints, key);
        assertEquals(
                "An instance of Factory #4 should have been created.",
                DummyFactory.Example4.class,
                factory.getClass());
    }

    @Ignore
    @Test
    public void testLookupWithExtendedClasspath() throws IOException {
        URL url = getClass().getResource("foo.jar");
        assertNotNull(url);

        FactoryRegistry reg = new FactoryCreator(DummyInterface.class);
        Stream<DummyInterface> factories = reg.getFactories(DummyInterface.class, false);
        assertFalse(factories.findAny().isPresent());

        try (URLClassLoader cl = new URLClassLoader(new URL[] {url})) {
            GeoTools.addClassLoader(cl);
            reg.scanForPlugins();

            Set<String> classes =
                    reg.getFactories(DummyInterface.class, false)
                            .map(factory -> factory.getClass().getName())
                            .collect(toSet());

            assertEquals(2, classes.size());
            assertTrue(classes.contains("pkg.Foo"));
            assertTrue(classes.contains("org.geotools.util.factory.DummyInterfaceImpl"));
        }
    }

    /** Tests for GEOT-2817 */
    @Test
    public void testLookupWithSameFactoryInTwoClassLoaders()
            throws IOException, ClassNotFoundException {
        // create url to this project's classes
        URL projectClasses = getClass().getResource("/");
        // create 2 classloaders with parent null to avoid delegation to the system class loader !
        // this occurs in reality with split class loader hierarchies (e.g. GWT plugin and
        // some application servers)
        try (URLClassLoader cl1 = new URLClassLoader(new URL[] {projectClasses}, null);
                URLClassLoader cl2 = new URLClassLoader(new URL[] {projectClasses}, null)) {
            // extend with both class loaders
            GeoTools.addClassLoader(cl1);
            GeoTools.addClassLoader(cl2);
            // code below was throwing ClassCastException (before java 7) prior to adding
            // isAssignableFrom() check (line 862)
            for (int i = 0; i < 2; i++) {
                ClassLoader loader = (i == 0 ? cl1 : cl2);
                Class dummy = loader.loadClass("org.geotools.util.factory.DummyInterface");
                FactoryRegistry reg = new FactoryCreator(dummy);
                reg.scanForPlugins();
                // we are mocking with two class loaders, trying to make it type safe will make
                // the factory fail to load the factory
                @SuppressWarnings("unchecked")
                Optional factory = reg.getFactories(dummy, false).findFirst();
                assertTrue(factory.isPresent());
                // factory class should have same class loader as interface
                assertSame(loader, factory.get().getClass().getClassLoader());
            }
        }
    }
}