1 /* 2 * Copyright 2003-2004 The Apache Software Foundation. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 import org.apache.commons.digester.AbstractObjectCreationFactory; 18 19 /** 20 * The Book class doesn't have a no-argument constructor, so the 21 * standard digester ObjectCreateRule can't be used to create instances 22 * of it. 23 * <p> 24 * To resolve this issue, the FactoryCreateRule can be used in 25 * conjunction with an appropriate factory class, like this one. 26 * The "createObject" method of the factory is invoked to generate 27 * object instances when required. 28 * <p> 29 * The factory object can access any xml attributes, plus of course 30 * any values set up within it before digester parsing starts (like 31 * JNDI references, database connections, etc) that it may in the 32 * process of generating an appropriate object. 33 * <p> 34 * Note that it is <i>not</i> possible for any data to be extracted 35 * from the body or subelements of the xml element that caused the 36 * createObject method on this factory to be invoked. For example: 37 * <pre> 38 * [book isdn="12345"] 39 * </pre> 40 * is fine; the isdn value can be accessed during the createObject method. 41 * However, given the xml: 42 * <pre> 43 * [book] 44 * [isdn]12345[/isdn] 45 * ... 46 * </pre> 47 * it is not possible to access the isdn number until after the 48 * Book instance has been created. 49 * <p> 50 * Note that even if the class to be created does have a default constructor, 51 * you may wish to use a factory class, in order to initialise the created 52 * object in specific ways, or insert created objects into a central 53 * register, etc. 54 * <p> 55 * And don't forget, either, that factories may be implemented as 56 * inner classes or anonymous classes if appropriate, reducing the 57 * overhead of using this functionality in many cases. 58 */ 59 public class BookFactory extends AbstractObjectCreationFactory { 60 61 public Object createObject(org.xml.sax.Attributes attributes) 62 throws Exception { 63 String isbn = attributes.getValue("isbn"); 64 65 if (isbn == null) { 66 throw new Exception( 67 "Mandatory isbn attribute not present on book tag."); 68 } 69 70 return new Book(isbn); 71 } 72 } 73