File: DefaultResourceManagerBackend.java

package info (click to toggle)
libloader 1.1.6.dfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 948 kB
  • sloc: java: 6,457; xml: 1,664; makefile: 31
file content (559 lines) | stat: -rw-r--r-- 17,332 bytes parent folder | download | duplicates (3)
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
/*
 * This program is free software; you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
 * Foundation.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this
 * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
 * or from the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * This program 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.
 *
 * Copyright (c) 2006 - 2009 Pentaho Corporation and Contributors.  All rights reserved.
 */

package org.pentaho.reporting.libraries.resourceloader;

import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pentaho.reporting.libraries.base.config.Configuration;
import org.pentaho.reporting.libraries.base.util.ObjectUtilities;

/**
 * Todo: Document Me
 *
 * @author Thomas Morgner
 */
public class DefaultResourceManagerBackend implements ResourceManagerBackend
{
  private static final Log logger = LogFactory.getLog(DefaultResourceManagerBackend.class);

  private ArrayList resourceLoaders;
  private ArrayList resourceBundleLoaders;
  private ArrayList resourceFactories;

  public DefaultResourceManagerBackend()
  {
    resourceLoaders = new ArrayList();
    resourceBundleLoaders = new ArrayList();
    resourceFactories = new ArrayList();
  }

  public synchronized ResourceKey createKey(final Object data, final Map parameters)
      throws ResourceKeyCreationException
  {
    if (data == null)
    {
      throw new NullPointerException("Key data must not be null.");
    }

    final Iterator values = resourceLoaders.iterator();
    while (values.hasNext())
    {
      final ResourceLoader loader = (ResourceLoader) values.next();
      try
      {
        final ResourceKey key = loader.createKey(data, parameters);
        if (key != null)
        {
          return key;
        }
      }
      catch (ResourceKeyCreationException rkce)
      {
        // ignore it.
      }
    }

    throw new ResourceKeyCreationException("Unable to create key: No loader was able to handle the given key data: "
        + data);
  }

  /**
   * Derives a new key from the given resource-key. Only keys for a hierarchical storage system (like file-systems or
   * URLs) can have derived keys. Since LibLoader 0.3.0 only hierarchical keys can be derived. For that, the deriving
   * path must be given as String.
   * <p/>
   * The optional parameter-map will be applied to the derived key after the parent's parameters have been copied to
   * the new key.
   * <p/>
   * Before trying to derive the key, the system tries to interpret the path as absolute key-value.
   *
   * @param parent     the parent key, or null to interpret the path as absolute key.
   * @param path       the relative path, that is used to derive the key.
   * @param parameters a optional map containing resource-key parameters.
   * @return the derived key.
   * @throws ResourceKeyCreationException if deriving the key failed.
   */
  public synchronized ResourceKey deriveKey(final ResourceKey parent, final String path, final Map parameters)
      throws ResourceKeyCreationException
  {
    if (parent == null)
    {
      if (path == null)
      {
        throw new NullPointerException();
      }

      return createKey(path, parameters);
    }

    ResourceKeyCreationException rce = null;
    for (int i = 0; i < resourceBundleLoaders.size(); i++)
    {
      final ResourceBundleLoader bundleLoader = (ResourceBundleLoader) resourceBundleLoaders.get(i);
      if (bundleLoader.isSupportedKey(parent) == false)
      {
        continue;
      }

      try
      {
        final ResourceKey key = bundleLoader.deriveKey(parent, path, parameters);
        if (key != null)
        {
          return key;
        }
      }
      catch (ResourceKeyCreationException rcke)
      {
        rce = rcke;
      }
    }
    
    // First, try to derive the resource directly. This makes sure, that we preserve the parent's context.
    // If a file is derived, we assume that the result will be a file; and only if that fails we'll try to
    // query the other contexts. If the parent is an URL-context, the result is assumed to be an URL as well.
    for (int i = 0; i < resourceLoaders.size(); i++)
    {
      final ResourceLoader loader = (ResourceLoader) resourceLoaders.get(i);
      if (loader.isSupportedKey(parent) == false)
      {
        continue;
      }
      try
      {
        final ResourceKey key = loader.deriveKey(parent, path, parameters);
        if (key != null)
        {
          return key;
        }
      }
      catch (ResourceKeyCreationException rcke)
      {
        rce = rcke;
      }
    }

    if (path != null)
    {
      // Second, try to load the key as absolute value.
      // This assumes, that we have no catch-all implementation.
      for (int i = 0; i < resourceLoaders.size(); i++)
      {
        final ResourceLoader loader = (ResourceLoader) resourceLoaders.get(i);
        final ResourceKey key = loader.createKey(path, parameters);
        if (key != null)
        {
          return key;
        }
      }
    }

    final ResourceKey secondParent = parent.getParent();
    if (secondParent != null)
    {
      // Desperate measures: Maybe the key is relative to the bundle. 
      for (int i = 0; i < resourceLoaders.size(); i++)
      {
        final ResourceLoader loader = (ResourceLoader) resourceLoaders.get(i);
        if (loader.isSupportedKey(secondParent) == false)
        {
          continue;
        }
        try
        {
          final ResourceKey key = loader.deriveKey(secondParent, path, parameters);
          if (key != null)
          {
            return key;
          }
        }
        catch (ResourceKeyCreationException rcke)
        {
          rce = rcke;
        }
      }
    }

    if (rce != null)
    {
      throw rce;
    }
    throw new ResourceKeyCreationException("Unable to create key: No such schema or the key was not recognized.");
  }

  /**
   * Tries to find the first resource-loader that would be able to process the key.
   *
   * @param key the resource-key.
   * @return the resourceloader for that key, or null, if no resource-loader is able to process the key.
   */
  private ResourceLoader findBySchema(final ResourceKey key)
  {
    for (int i = 0; i < resourceLoaders.size(); i++)
    {
      final ResourceLoader loader = (ResourceLoader) resourceLoaders.get(i);
      if (loader.isSupportedKey(key))
      {
        return loader;
      }
    }
    return null;
  }

  public synchronized URL toURL(final ResourceKey key)
  {
    if (key == null)
    {
      throw new NullPointerException();
    }
    final ResourceLoader loader = findBySchema(key);
    if (loader == null)
    {
      return null;
    }
    return loader.toURL(key);
  }

  public synchronized Resource create(final ResourceManager frontEnd, final ResourceData data,
      final ResourceKey context, final Class[] target) throws ResourceLoadingException, ResourceCreationException
  {
    if (frontEnd == null)
    {
      throw new NullPointerException();
    }
    if (data == null)
    {
      throw new NullPointerException("Data must not be null.");
    }

    // AutoMode ..
    if (target == null)
    {
      return autoCreateResource(frontEnd, data, context);
    }

    ResourceCreationException exception = null;
    final int factoryCount = resourceFactories.size();
    final ResourceFactory[] factories = (ResourceFactory[]) resourceFactories
        .toArray(new ResourceFactory[factoryCount]);
    for (int targetIdx = 0; targetIdx < target.length; targetIdx++)
    {
      final Class targetClass = target[targetIdx];
      for (int i = 0; i < factoryCount; i++)
      {
        final ResourceFactory fact = factories[i];
        if (isSupportedTarget(targetClass, fact) == false)
        {
          // Unsupported keys: Try the next factory ..
          continue;
        }

        try
        {
          return fact.create(frontEnd, data, context);
        }
        catch (ContentNotRecognizedException ce)
        {
          // Ignore it, unless it is the last one.
        }
        catch (ResourceCreationException rex)
        {
          // ignore it, try the next factory ...
          exception = rex;
          if (logger.isDebugEnabled())
          {
            logger.debug("Failed at " + fact.getClass() + ": ", rex);
          }
        }
      }
    }

    if (exception != null)
    {
      throw exception;
    }
    throw new ContentNotRecognizedException("None of the selected factories was able to handle the given data: "
        + data.getKey());
  }

  private boolean isSupportedTarget(final Class target, final ResourceFactory fact)
  {
    final Class factoryType = fact.getFactoryType();
    if (target != null && target.isAssignableFrom(factoryType))
    {
      return true;
    }
    return false;
  }

  private Resource autoCreateResource(final ResourceManager frontEnd, final ResourceData data, final ResourceKey context)
      throws ResourceLoadingException, ResourceCreationException
  {
    final Iterator it = resourceFactories.iterator();
    while (it.hasNext())
    {
      final ResourceFactory fact = (ResourceFactory) it.next();
      try
      {
        final Resource res = fact.create(frontEnd, data, context);
        if (res != null)
        {
          return res;
        }
      }
      catch (ResourceCreationException rex)
      {
        // ignore it, try the next factory ...
      }
    }
    throw new ResourceCreationException("No known factory was able to handle the given data.");
  }

  public boolean isResourceUnchanged(final ResourceManager frontEnd, final Resource resource)
      throws ResourceLoadingException
  {
    if (frontEnd == null)
    {
      throw new NullPointerException();
    }
    if (resource == null)
    {
      throw new NullPointerException();
    }

    final ResourceKey[] deps = resource.getDependencies();
    for (int i = 0; i < deps.length; i++)
    {
      final ResourceKey dep = deps[i];
      final long version = resource.getVersion(dep);
      if (version == -1)
      {
        // non-versioning key, ignore it.
        continue;
      }

      final ResourceData data = frontEnd.load(dep);
      if (data.getVersion(frontEnd) != version)
      {
        // oh, my bad, an outdated or changed entry.
        // We have to re-read the whole thing.
        return false;
      }
    }
    // all versions have been confirmed to be valid. Nice, we can use the
    // cached product.
    return true;
  }

  /**
   * Tries to find the first resource-bundle-loader that would be able to process the key.
   *
   * @param key the resource-key.
   * @return the resourceloader for that key, or null, if no resource-loader is able to process the key.
   * @throws ResourceLoadingException if an error occured.
   */
  public synchronized ResourceBundleData loadResourceBundle(final ResourceManager frontEnd, final ResourceKey key)
      throws ResourceLoadingException
  {
    if (frontEnd == null)
    {
      throw new NullPointerException();
    }
    if (key == null)
    {
      throw new NullPointerException();
    }

    for (int i = 0; i < resourceBundleLoaders.size(); i++)
    {
      final ResourceBundleLoader loader = (ResourceBundleLoader) resourceBundleLoaders.get(i);
      final ResourceBundleData resourceBundle = loader.loadBundle(frontEnd, key);
      if (resourceBundle != null)
      {
        return resourceBundle;
      }
    }
    return null;
  }

  public ResourceData loadRawData(final ResourceManager frontEnd, final ResourceKey key)
      throws UnrecognizedLoaderException, ResourceLoadingException
  {
    if (frontEnd == null)
    {
      throw new NullPointerException();
    }
    if (key == null)
    {
      throw new NullPointerException();
    }

    final ResourceLoader loader = findBySchema(key);
    if (loader == null)
    {
      throw new UnrecognizedLoaderException("Invalid key: No resource-loader registered for schema: " + key.getSchema());
    }
    logger.debug("Loaded " + key);
    return loader.load(key);
  }

  public void registerDefaultFactories()
  {
    final Configuration config = LibLoaderBoot.getInstance().getGlobalConfig();
    final Iterator itType = config.findPropertyKeys(ResourceManager.FACTORY_TYPE_PREFIX);
    while (itType.hasNext())
    {
      final String key = (String) itType.next();
      final String factoryClass = config.getConfigProperty(key);

      final Object maybeFactory = ObjectUtilities.loadAndInstantiate(factoryClass, ResourceManager.class,
          ResourceFactory.class);
      if (maybeFactory instanceof ResourceFactory == false)
      {
        continue;
      }

      final ResourceFactory factory = (ResourceFactory) maybeFactory;
      factory.initializeDefaults();
      registerFactory(factory);
    }
  }

  public void registerDefaultLoaders()
  {
    final Configuration config = LibLoaderBoot.getInstance().getGlobalConfig();
    final Iterator it = config.findPropertyKeys(ResourceManager.LOADER_PREFIX);
    while (it.hasNext())
    {
      final String key = (String) it.next();
      final String value = config.getConfigProperty(key);
      final ResourceLoader loader = (ResourceLoader) ObjectUtilities.loadAndInstantiate(value, ResourceManager.class,
          ResourceLoader.class);
      if (loader != null)
      {
        //Log.debug("Registering loader for " + loader.getSchema());
        registerLoader(loader);
      }
    }

    final Iterator bit = config.findPropertyKeys(ResourceManager.BUNDLE_LOADER_PREFIX);
    while (bit.hasNext())
    {
      final String key = (String) bit.next();
      final String value = config.getConfigProperty(key);
      final ResourceBundleLoader loader = (ResourceBundleLoader) ObjectUtilities.loadAndInstantiate(value,
          ResourceManager.class, ResourceBundleLoader.class);
      if (loader != null)
      {
        //Log.debug("Registering loader for " + loader.getSchema());
        registerBundleLoader(loader);
      }
    }
  }

  public void registerBundleLoader(final ResourceBundleLoader loader)
  {
    if (loader == null)
    {
      throw new NullPointerException("ResourceLoader must not be null.");
    }
    resourceBundleLoaders.add(loader);
  }

  public void registerLoader(final ResourceLoader loader)
  {
    if (loader == null)
    {
      throw new NullPointerException("ResourceLoader must not be null.");
    }
    resourceLoaders.add(loader);
  }

  public void registerFactory(final ResourceFactory factory)
  {
    if (factory == null)
    {
      throw new NullPointerException("ResourceFactory must not be null.");
    }
    resourceFactories.add(factory);
  }

  /**
   * Converts a serialized version of a <code>ResourceKey</code> into an actual <code>ResourceKey</code>
   * by locating the proper <code>ResourceLoader</code> that can perform the deserialization.
   *
   * @param bundleKey
   *@param serializedKey the String serialized key to be deserialized  @returns the <code>ResourceKey</code> that has been deserialized
   * @throw ResourceKeyCreationException indicates an error trying to create the <code>ResourceKey</code>
   *   from the deserialized version
   */
  public ResourceKey deserialize(final ResourceKey bundleKey, String serializedKey) throws ResourceKeyCreationException
  {
    if (serializedKey == null)
    {
      throw new NullPointerException("Key data must not be null.");
    }

    final Iterator values = resourceLoaders.iterator();
    while (values.hasNext())
    {
      final ResourceLoader loader = (ResourceLoader) values.next();
      if (loader.isSupportedDeserializer(serializedKey))
      {
        final ResourceKey key = loader.deserialize(bundleKey, serializedKey);
        return key;
      }
    }

    throw new ResourceKeyCreationException
        ("Unable to create key: No loader was able to handle the deserialization of the given key data: " + serializedKey);
  }

  /**
   * Creates a String version of the <code>ResourceKey</code> that can be deserialized with the
   * <code>deserialize()</code> method.
   * @param bundleKey
   *@param key @throw ResourceException indicates an error trying to serialize the key
   * @throw NullPointerException indicates the supplied key is <code>null</code>
   */
  public String serialize(final ResourceKey bundleKey, final ResourceKey key) throws ResourceException
  {
    if (key == null)
    {
      throw new NullPointerException("Key data must not be null.");
    }

    final Iterator values = resourceLoaders.iterator();
    while (values.hasNext())
    {
      final ResourceLoader loader = (ResourceLoader) values.next();
      if (loader.isSupportedKey(key))
      {
        return loader.serialize(bundleKey, key);
      }
    }

    throw new ResourceException("Unable to find resource loader for specified key: " + key);
  }

}