1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 package org.apache.commons.jnet; 18 19 import java.net.URLStreamHandler; 20 import java.net.URLStreamHandlerFactory; 21 22 /** 23 * A dynamic url stream handler factory that stores the current delegate factory 24 * in a thread local variable. 25 * 26 * This allows to change the url handler factory at runtime dynamically through 27 * the {@link #push(URLStreamHandlerFactory)} and {@link #pop()} methods. 28 */ 29 public class DynamicURLStreamHandlerFactory extends ParentAwareURLStreamHandlerFactory { 30 31 /** The thread local holding the current factory. */ 32 protected static final ThreadLocal FACTORY = new InheritableThreadLocal(); 33 34 /** 35 * Push a url stream handler factory on top of the stack. 36 */ 37 public static void push(URLStreamHandlerFactory factory) { 38 // no need to synchronize as we use a thread local 39 if ( !(factory instanceof ParentAwareURLStreamHandlerFactory) ) { 40 factory = new URLStreamHandlerFactoryWrapper(factory); 41 } 42 URLStreamHandlerFactory old = (URLStreamHandlerFactory) FACTORY.get(); 43 ((ParentAwareURLStreamHandlerFactory)factory).setParentFactory(old); 44 FACTORY.set(factory); 45 } 46 47 /** 48 * Pop the lastest url stream handler factory from the stack. 49 */ 50 public static void pop() { 51 ParentAwareURLStreamHandlerFactory factory = (ParentAwareURLStreamHandlerFactory)FACTORY.get(); 52 if ( factory != null ) { 53 FACTORY.set(factory.getParent()); 54 } 55 } 56 57 /** 58 * @see org.apache.commons.jnet.ParentAwareURLStreamHandlerFactory#create(java.lang.String) 59 */ 60 protected URLStreamHandler create(String protocol) { 61 ParentAwareURLStreamHandlerFactory factory = (ParentAwareURLStreamHandlerFactory)FACTORY.get(); 62 if ( factory != null ) { 63 return factory.createURLStreamHandler(protocol); 64 } 65 return null; 66 } 67 }