Source Code Cross Referenced for Accessor.java in  » 6.0-JDK-Modules » jaxb-impl » com » sun » xml » bind » v2 » runtime » reflect » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » 6.0 JDK Modules » jaxb impl » com.sun.xml.bind.v2.runtime.reflect 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003:         * 
004:         * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005:         * 
006:         * The contents of this file are subject to the terms of either the GNU
007:         * General Public License Version 2 only ("GPL") or the Common Development
008:         * and Distribution License("CDDL") (collectively, the "License").  You
009:         * may not use this file except in compliance with the License. You can obtain
010:         * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
011:         * or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
012:         * language governing permissions and limitations under the License.
013:         * 
014:         * When distributing the software, include this License Header Notice in each
015:         * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
016:         * Sun designates this particular file as subject to the "Classpath" exception
017:         * as provided by Sun in the GPL Version 2 section of the License file that
018:         * accompanied this code.  If applicable, add the following below the License
019:         * Header, with the fields enclosed by brackets [] replaced by your own
020:         * identifying information: "Portions Copyrighted [year]
021:         * [name of copyright owner]"
022:         * 
023:         * Contributor(s):
024:         * 
025:         * If you wish your version of this file to be governed by only the CDDL or
026:         * only the GPL Version 2, indicate your decision by adding "[Contributor]
027:         * elects to include this software in this distribution under the [CDDL or GPL
028:         * Version 2] license."  If you don't indicate a single choice of license, a
029:         * recipient has the option to distribute your version of this file under
030:         * either the CDDL, the GPL Version 2 or to extend the choice of license to
031:         * its licensees as provided above.  However, if you add GPL Version 2 code
032:         * and therefore, elected the GPL Version 2 license, then the option applies
033:         * only if the new code is made subject to such option by the copyright
034:         * holder.
035:         */
036:
037:        package com.sun.xml.bind.v2.runtime.reflect;
038:
039:        import java.lang.reflect.Field;
040:        import java.lang.reflect.InvocationTargetException;
041:        import java.lang.reflect.Method;
042:        import java.lang.reflect.Modifier;
043:        import java.lang.reflect.Type;
044:        import java.util.HashMap;
045:        import java.util.Map;
046:        import java.util.logging.Level;
047:        import java.util.logging.Logger;
048:
049:        import javax.xml.bind.JAXBElement;
050:        import javax.xml.bind.annotation.adapters.XmlAdapter;
051:
052:        import com.sun.xml.bind.Util;
053:        import com.sun.xml.bind.api.AccessorException;
054:        import com.sun.xml.bind.api.JAXBRIContext;
055:        import com.sun.xml.bind.v2.model.core.Adapter;
056:        import com.sun.xml.bind.v2.model.nav.Navigator;
057:        import com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder;
058:        import com.sun.xml.bind.v2.runtime.reflect.opt.OptimizedAccessorFactory;
059:        import com.sun.xml.bind.v2.runtime.unmarshaller.Loader;
060:        import com.sun.xml.bind.v2.runtime.unmarshaller.Receiver;
061:        import com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext;
062:        import com.sun.xml.bind.v2.runtime.JAXBContextImpl;
063:        import com.sun.istack.Nullable;
064:
065:        import org.xml.sax.SAXException;
066:
067:        /**
068:         * Accesses a particular property of a bean.
069:         *
070:         * <p>
071:         * This interface encapsulates the access to the actual data store.
072:         * The intention is to generate implementations for a particular bean
073:         * and a property to improve the performance.
074:         *
075:         * <p>
076:         * Accessor can be used as a receiver. Upon receiving an object
077:         * it sets that to the field.
078:         *
079:         * @see Accessor.FieldReflection
080:         * @see TransducedAccessor
081:         *
082:         * @author Kohsuke Kawaguchi (kk@kohsuke.org)
083:         */
084:        public abstract class Accessor<BeanT, ValueT> implements  Receiver {
085:
086:            public final Class<ValueT> valueType;
087:
088:            public Class<ValueT> getValueType() {
089:                return valueType;
090:            }
091:
092:            protected Accessor(Class<ValueT> valueType) {
093:                this .valueType = valueType;
094:            }
095:
096:            /**
097:             * Returns the optimized version of the same accessor.
098:             *
099:             * @param context
100:             *      The {@link JAXBContextImpl} that owns the whole thing.
101:             *      (See {@link RuntimeModelBuilder#context}.)
102:             * @return
103:             *      At least the implementation can return <tt>this</tt>.
104:             */
105:            public Accessor<BeanT, ValueT> optimize(@Nullable
106:            JAXBContextImpl context) {
107:                return this ;
108:            }
109:
110:            /**
111:             * Gets the value of the property of the given bean object.
112:             *
113:             * @param bean
114:             *      must not be null.
115:             * @throws AccessorException
116:             *      if failed to set a value. For example, the getter method
117:             *      may throw an exception.
118:             *
119:             * @since 2.0 EA1
120:             */
121:            public abstract ValueT get(BeanT bean) throws AccessorException;
122:
123:            /**
124:             * Sets the value of the property of the given bean object.
125:             *
126:             * @param bean
127:             *      must not be null.
128:             * @param value
129:             *      the value to be set. Setting value to null means resetting
130:             *      to the VM default value (even for primitive properties.)
131:             * @throws AccessorException
132:             *      if failed to set a value. For example, the setter method
133:             *      may throw an exception.
134:             *
135:             * @since 2.0 EA1
136:             */
137:            public abstract void set(BeanT bean, ValueT value)
138:                    throws AccessorException;
139:
140:            /**
141:             * Sets the value without adapting the value.
142:             *
143:             * This ugly entry point is only used by JAX-WS.
144:             * See {@link JAXBRIContext#getElementPropertyAccessor}
145:             */
146:            public Object getUnadapted(BeanT bean) throws AccessorException {
147:                return get(bean);
148:            }
149:
150:            /**
151:             * Returns true if this accessor wraps an adapter.
152:             *
153:             * This method needs to be used with care, but it helps some optimization.
154:             */
155:            public boolean isAdapted() {
156:                return false;
157:            }
158:
159:            /**
160:             * Sets the value without adapting the value.
161:             *
162:             * This ugly entry point is only used by JAX-WS.
163:             * See {@link JAXBRIContext#getElementPropertyAccessor}
164:             */
165:            public void setUnadapted(BeanT bean, Object value)
166:                    throws AccessorException {
167:                set(bean, (ValueT) value);
168:            }
169:
170:            public void receive(UnmarshallingContext.State state, Object o)
171:                    throws SAXException {
172:                try {
173:                    set((BeanT) state.target, (ValueT) o);
174:                } catch (AccessorException e) {
175:                    Loader.handleGenericException(e, true);
176:                }
177:            }
178:
179:            /**
180:             * Wraps this  {@link Accessor} into another {@link Accessor}
181:             * and performs the type adaption as necessary.
182:             */
183:            public final <T> Accessor<BeanT, T> adapt(Class<T> targetType,
184:                    final Class<? extends XmlAdapter<T, ValueT>> adapter) {
185:                return new AdaptedAccessor<BeanT, ValueT, T>(targetType, this ,
186:                        adapter);
187:            }
188:
189:            public final <T> Accessor<BeanT, T> adapt(
190:                    Adapter<Type, Class> adapter) {
191:                return new AdaptedAccessor<BeanT, ValueT, T>(
192:                        (Class<T>) Navigator.REFLECTION
193:                                .erasure(adapter.defaultType), this ,
194:                        adapter.adapterType);
195:            }
196:
197:            /**
198:             * Flag that will be set to true after issueing a warning
199:             * about the lack of permission to access non-public fields.
200:             */
201:            private static boolean accessWarned = false;
202:
203:            /**
204:             * {@link Accessor} that uses Java reflection to access a field.
205:             */
206:            public static class FieldReflection<BeanT, ValueT> extends
207:                    Accessor<BeanT, ValueT> {
208:                public final Field f;
209:
210:                private static final Logger logger = Util.getClassLogger();
211:
212:                // TODO: revisit. this is a security hole because this method can be used by anyone
213:                // to enable access to a field.
214:                public FieldReflection(Field f) {
215:                    super ((Class<ValueT>) f.getType());
216:                    this .f = f;
217:
218:                    int mod = f.getModifiers();
219:                    if (!Modifier.isPublic(mod)
220:                            || Modifier.isFinal(mod)
221:                            || !Modifier.isPublic(f.getDeclaringClass()
222:                                    .getModifiers())) {
223:                        try {
224:                            f.setAccessible(true);
225:                        } catch (SecurityException e) {
226:                            if (!accessWarned)
227:                                // this happens when we don't have enough permission.
228:                                logger
229:                                        .log(
230:                                                Level.WARNING,
231:                                                Messages.UNABLE_TO_ACCESS_NON_PUBLIC_FIELD
232:                                                        .format(
233:                                                                f
234:                                                                        .getDeclaringClass()
235:                                                                        .getName(),
236:                                                                f.getName()), e);
237:                            accessWarned = true;
238:                        }
239:                    }
240:                }
241:
242:                public ValueT get(BeanT bean) {
243:                    try {
244:                        return (ValueT) f.get(bean);
245:                    } catch (IllegalAccessException e) {
246:                        throw new IllegalAccessError(e.getMessage());
247:                    }
248:                }
249:
250:                public void set(BeanT bean, ValueT value) {
251:                    try {
252:                        if (value == null)
253:                            value = (ValueT) uninitializedValues.get(valueType);
254:                        f.set(bean, value);
255:                    } catch (IllegalAccessException e) {
256:                        throw new IllegalAccessError(e.getMessage());
257:                    }
258:                }
259:
260:                @Override
261:                public Accessor<BeanT, ValueT> optimize(JAXBContextImpl context) {
262:                    if (context != null && context.fastBoot)
263:                        // let's not waste time on doing this for the sake of faster boot.
264:                        return this ;
265:                    Accessor<BeanT, ValueT> acc = OptimizedAccessorFactory
266:                            .get(f);
267:                    if (acc != null)
268:                        return acc;
269:                    else
270:                        return this ;
271:                }
272:            }
273:
274:            /**
275:             * Read-only access to {@link Field}. Used to handle a static field.
276:             */
277:            public static final class ReadOnlyFieldReflection<BeanT, ValueT>
278:                    extends FieldReflection<BeanT, ValueT> {
279:                public ReadOnlyFieldReflection(Field f) {
280:                    super (f);
281:                }
282:
283:                public void set(BeanT bean, ValueT value) {
284:                    // noop
285:                }
286:
287:                @Override
288:                public Accessor<BeanT, ValueT> optimize(JAXBContextImpl context) {
289:                    return this ;
290:                }
291:            }
292:
293:            /**
294:             * {@link Accessor} that uses Java reflection to access a getter and a setter.
295:             */
296:            public static class GetterSetterReflection<BeanT, ValueT> extends
297:                    Accessor<BeanT, ValueT> {
298:                public final Method getter;
299:                public final Method setter;
300:
301:                private static final Logger logger = Util.getClassLogger();
302:
303:                public GetterSetterReflection(Method getter, Method setter) {
304:                    super ((Class<ValueT>) (getter != null ? getter
305:                            .getReturnType() : setter.getParameterTypes()[0]));
306:                    this .getter = getter;
307:                    this .setter = setter;
308:
309:                    if (getter != null)
310:                        makeAccessible(getter);
311:                    if (setter != null)
312:                        makeAccessible(setter);
313:                }
314:
315:                private void makeAccessible(Method m) {
316:                    if (!Modifier.isPublic(m.getModifiers())
317:                            || !Modifier.isPublic(m.getDeclaringClass()
318:                                    .getModifiers())) {
319:                        try {
320:                            m.setAccessible(true);
321:                        } catch (SecurityException e) {
322:                            if (!accessWarned)
323:                                // this happens when we don't have enough permission.
324:                                logger
325:                                        .log(
326:                                                Level.WARNING,
327:                                                Messages.UNABLE_TO_ACCESS_NON_PUBLIC_FIELD
328:                                                        .format(
329:                                                                m
330:                                                                        .getDeclaringClass()
331:                                                                        .getName(),
332:                                                                m.getName()), e);
333:                            accessWarned = true;
334:                        }
335:                    }
336:                }
337:
338:                public ValueT get(BeanT bean) throws AccessorException {
339:                    try {
340:                        return (ValueT) getter.invoke(bean);
341:                    } catch (IllegalAccessException e) {
342:                        throw new IllegalAccessError(e.getMessage());
343:                    } catch (InvocationTargetException e) {
344:                        throw handleInvocationTargetException(e);
345:                    }
346:                }
347:
348:                public void set(BeanT bean, ValueT value)
349:                        throws AccessorException {
350:                    try {
351:                        if (value == null)
352:                            value = (ValueT) uninitializedValues.get(valueType);
353:                        setter.invoke(bean, value);
354:                    } catch (IllegalAccessException e) {
355:                        throw new IllegalAccessError(e.getMessage());
356:                    } catch (InvocationTargetException e) {
357:                        throw handleInvocationTargetException(e);
358:                    }
359:                }
360:
361:                private AccessorException handleInvocationTargetException(
362:                        InvocationTargetException e) {
363:                    // don't block a problem in the user code
364:                    Throwable t = e.getTargetException();
365:                    if (t instanceof  RuntimeException)
366:                        throw (RuntimeException) t;
367:                    if (t instanceof  Error)
368:                        throw (Error) t;
369:
370:                    // otherwise it's a checked exception.
371:                    // I'm not sure how to handle this.
372:                    // we can throw a checked exception from here,
373:                    // but because get/set would be called from so many different places,
374:                    // the handling would be tedious.
375:                    return new AccessorException(t);
376:                }
377:
378:                @Override
379:                public Accessor<BeanT, ValueT> optimize(JAXBContextImpl context) {
380:                    if (getter == null || setter == null)
381:                        // if we aren't complete, OptimizedAccessor won't always work
382:                        return this ;
383:                    if (context != null && context.fastBoot)
384:                        // let's not waste time on doing this for the sake of faster boot.
385:                        return this ;
386:
387:                    Accessor<BeanT, ValueT> acc = OptimizedAccessorFactory.get(
388:                            getter, setter);
389:                    if (acc != null)
390:                        return acc;
391:                    else
392:                        return this ;
393:                }
394:            }
395:
396:            /**
397:             * A version of {@link GetterSetterReflection} thaat doesn't have any setter.
398:             *
399:             * <p>
400:             * This provides a user-friendly error message.
401:             */
402:            public static class GetterOnlyReflection<BeanT, ValueT> extends
403:                    GetterSetterReflection<BeanT, ValueT> {
404:                public GetterOnlyReflection(Method getter) {
405:                    super (getter, null);
406:                }
407:
408:                @Override
409:                public void set(BeanT bean, ValueT value)
410:                        throws AccessorException {
411:                    throw new AccessorException(Messages.NO_SETTER
412:                            .format(getter.toString()));
413:                }
414:            }
415:
416:            /**
417:             * A version of {@link GetterSetterReflection} thaat doesn't have any getter.
418:             *
419:             * <p>
420:             * This provides a user-friendly error message.
421:             */
422:            public static class SetterOnlyReflection<BeanT, ValueT> extends
423:                    GetterSetterReflection<BeanT, ValueT> {
424:                public SetterOnlyReflection(Method setter) {
425:                    super (null, setter);
426:                }
427:
428:                @Override
429:                public ValueT get(BeanT bean) throws AccessorException {
430:                    throw new AccessorException(Messages.NO_GETTER
431:                            .format(setter.toString()));
432:                }
433:            }
434:
435:            /**
436:             * Gets the special {@link Accessor} used to recover from errors.
437:             */
438:            @SuppressWarnings("unchecked")
439:            public static <A, B> Accessor<A, B> getErrorInstance() {
440:                return ERROR;
441:            }
442:
443:            private static final Accessor ERROR = new Accessor<Object, Object>(
444:                    Object.class) {
445:                public Object get(Object o) {
446:                    return null;
447:                }
448:
449:                public void set(Object o, Object o1) {
450:                }
451:            };
452:
453:            /**
454:             * {@link Accessor} for {@link JAXBElement#getValue()}.
455:             */
456:            public static final Accessor<JAXBElement, Object> JAXB_ELEMENT_VALUE = new Accessor<JAXBElement, Object>(
457:                    Object.class) {
458:                public Object get(JAXBElement jaxbElement) {
459:                    return jaxbElement.getValue();
460:                }
461:
462:                public void set(JAXBElement jaxbElement, Object o) {
463:                    jaxbElement.setValue(o);
464:                }
465:            };
466:
467:            /**
468:             * Uninitialized map keyed by their classes.
469:             */
470:            private static final Map<Class, Object> uninitializedValues = new HashMap<Class, Object>();
471:
472:            static {
473:                /*
474:                 static byte default_value_byte = 0;
475:                 static boolean default_value_boolean = false;
476:                 static char default_value_char = 0;
477:                 static float default_value_float = 0;
478:                 static double default_value_double = 0;
479:                 static int default_value_int = 0;
480:                 static long default_value_long = 0;
481:                 static short default_value_short = 0;
482:                 */
483:                uninitializedValues.put(byte.class, Byte.valueOf((byte) 0));
484:                uninitializedValues.put(boolean.class, false);
485:                uninitializedValues
486:                        .put(char.class, Character.valueOf((char) 0));
487:                uninitializedValues.put(float.class, Float.valueOf(0));
488:                uninitializedValues.put(double.class, Double.valueOf(0));
489:                uninitializedValues.put(int.class, Integer.valueOf(0));
490:                uninitializedValues.put(long.class, Long.valueOf(0));
491:                uninitializedValues.put(short.class, Short.valueOf((short) 0));
492:            }
493:
494:        }
w___ww__.__j___a_v__a__2___s___._c_om | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.