1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.jnet;
18
19 import java.lang.reflect.Field;
20 import java.lang.reflect.Modifier;
21 import java.net.URL;
22 import java.net.URLStreamHandlerFactory;
23
24
25
26
27
28
29
30 public class Installer {
31
32
33
34
35
36
37 public static void setURLStreamHandlerFactory(URLStreamHandlerFactory factory)
38 throws Exception {
39 try {
40
41 URL.setURLStreamHandlerFactory(factory);
42 } catch (Error err) {
43
44 final Field[] fields = URL.class.getDeclaredFields();
45 int index = 0;
46 Field factoryField = null;
47 while ( factoryField == null && index < fields.length ) {
48 final Field current = fields[index];
49 if ( Modifier.isStatic( current.getModifiers() ) && current.getType().equals( URLStreamHandlerFactory.class ) ) {
50 factoryField = current;
51 factoryField.setAccessible(true);
52 } else {
53 index++;
54 }
55 }
56 if ( factoryField == null ) {
57 throw new Exception("Unable to detect static field in the URL class for the URLStreamHandlerFactory. Please report this error together with your exact environment to the Apache Excalibur project.");
58 }
59 try {
60 URLStreamHandlerFactory oldFactory = (URLStreamHandlerFactory)factoryField.get(null);
61 if ( factory instanceof ParentAwareURLStreamHandlerFactory ) {
62 ((ParentAwareURLStreamHandlerFactory)factory).setParentFactory(oldFactory);
63 }
64 factoryField.set(null, factory);
65 } catch (IllegalArgumentException e) {
66 throw new Exception("Unable to set url stream handler factory " + factory);
67 } catch (IllegalAccessException e) {
68 throw new Exception("Unable to set url stream handler factory " + factory);
69 }
70 }
71 }
72
73 protected static Field getStaticURLStreamHandlerFactoryField() {
74 Field[] fields = URL.class.getDeclaredFields();
75 for ( int i = 0; i < fields.length; i++ ) {
76 if ( Modifier.isStatic( fields[i].getModifiers() ) && fields[i].getType().equals( URLStreamHandlerFactory.class ) ) {
77 fields[i].setAccessible( true );
78 return fields[i];
79 }
80 }
81 return null;
82 }
83 }