1/* 2 * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24/* 25 * State factory and object factory for the Person class. 26 */ 27 28package org.example.person; 29 30import java.util.Hashtable; 31import javax.naming.*; 32import javax.naming.directory.*; 33import javax.naming.spi.*; 34 35public class PersonFactory implements DirStateFactory, DirObjectFactory { 36 37 public PersonFactory() { 38 } 39 40 @Override 41 public Object getStateToBind(Object obj, Name name, 42 Context nameCtx, Hashtable environment) throws NamingException { 43 44 return null; 45 } 46 47 @Override 48 public DirStateFactory.Result getStateToBind(Object obj, Name name, 49 Context nameCtx, Hashtable environment, Attributes inAttrs) 50 throws NamingException { 51 52 if (obj instanceof Person) { 53 return new DirStateFactory.Result(null, 54 personToAttributes((Person)obj)); 55 } else { 56 return null; 57 } 58 } 59 60 @Override 61 public Object getObjectInstance(Object obj, Name name, Context ctx, 62 Hashtable environment) throws Exception { 63 64 return null; 65 } 66 67 @Override 68 public Object getObjectInstance(Object obj, Name name, Context ctx, 69 Hashtable environment, Attributes attributes) throws Exception { 70 71 if (obj instanceof DirContext) { 72 ((DirContext)obj).close(); // cleanup 73 return attributesToPerson(attributes); 74 75 } else { 76 return null; 77 } 78 } 79 80 private Attributes personToAttributes(Person person) { 81 82 // TBD: build attrs using methods in Person class instead of calling ... 83 84 return person.getAttributes(); 85 } 86 87 private Person attributesToPerson(Attributes attrset) 88 throws NamingException { 89 90 Attributes attrs = (Attributes)attrset; 91 Person person = new Person((String)attrs.get("cn").get(), 92 (String)attrs.get("sn").get()); 93 94 person.setMailAddress((String)attrs.get("mail").get()); 95 96 // TBD: extract any other attributes 97 98 return person; 99 } 100} 101