src/share/jaxws_classes/com/sun/xml/internal/bind/v2/runtime/unmarshaller/UnmarshallingContext.java

Sun, 31 Aug 2014 16:14:36 +0400

author
aefimov
date
Sun, 31 Aug 2014 16:14:36 +0400
changeset 650
121e938cb9c3
parent 397
b99d7e355d4b
child 760
e530533619ec
permissions
-rw-r--r--

8036981: JAXB not preserving formatting for xsd:any Mixed content
Reviewed-by: lancea, mkos

ohair@286 1 /*
aefimov@650 2 * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
ohair@286 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
ohair@286 4 *
ohair@286 5 * This code is free software; you can redistribute it and/or modify it
ohair@286 6 * under the terms of the GNU General Public License version 2 only, as
ohair@286 7 * published by the Free Software Foundation. Oracle designates this
ohair@286 8 * particular file as subject to the "Classpath" exception as provided
ohair@286 9 * by Oracle in the LICENSE file that accompanied this code.
ohair@286 10 *
ohair@286 11 * This code is distributed in the hope that it will be useful, but WITHOUT
ohair@286 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
ohair@286 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
ohair@286 14 * version 2 for more details (a copy is included in the LICENSE file that
ohair@286 15 * accompanied this code).
ohair@286 16 *
ohair@286 17 * You should have received a copy of the GNU General Public License version
ohair@286 18 * 2 along with this work; if not, write to the Free Software Foundation,
ohair@286 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
ohair@286 20 *
ohair@286 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
ohair@286 22 * or visit www.oracle.com if you need additional information or have any
ohair@286 23 * questions.
ohair@286 24 */
ohair@286 25
ohair@286 26 package com.sun.xml.internal.bind.v2.runtime.unmarshaller;
ohair@286 27
ohair@286 28 import java.lang.reflect.InvocationTargetException;
ohair@286 29 import java.lang.reflect.Method;
ohair@286 30 import java.util.ArrayList;
ohair@286 31 import java.util.Collection;
ohair@286 32 import java.util.Collections;
ohair@286 33 import java.util.HashMap;
ohair@286 34 import java.util.Iterator;
ohair@286 35 import java.util.List;
ohair@286 36 import java.util.Map;
ohair@286 37 import java.util.concurrent.Callable;
ohair@286 38
ohair@286 39 import javax.xml.XMLConstants;
ohair@286 40 import javax.xml.bind.JAXBElement;
ohair@286 41 import javax.xml.bind.UnmarshalException;
ohair@286 42 import javax.xml.bind.Unmarshaller;
ohair@286 43 import javax.xml.bind.ValidationEvent;
ohair@286 44 import javax.xml.bind.ValidationEventHandler;
ohair@286 45 import javax.xml.bind.ValidationEventLocator;
ohair@286 46 import javax.xml.bind.helpers.ValidationEventImpl;
ohair@286 47 import javax.xml.namespace.NamespaceContext;
ohair@286 48 import javax.xml.namespace.QName;
ohair@286 49
ohair@286 50 import com.sun.istack.internal.NotNull;
ohair@286 51 import com.sun.istack.internal.Nullable;
ohair@286 52 import com.sun.istack.internal.SAXParseException2;
ohair@286 53 import com.sun.xml.internal.bind.IDResolver;
mkos@397 54 import com.sun.xml.internal.bind.Util;
ohair@286 55 import com.sun.xml.internal.bind.api.AccessorException;
ohair@286 56 import com.sun.xml.internal.bind.api.ClassResolver;
ohair@286 57 import com.sun.xml.internal.bind.unmarshaller.InfosetScanner;
ohair@286 58 import com.sun.xml.internal.bind.v2.ClassFactory;
ohair@286 59 import com.sun.xml.internal.bind.v2.runtime.AssociationMap;
ohair@286 60 import com.sun.xml.internal.bind.v2.runtime.Coordinator;
ohair@286 61 import com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl;
ohair@286 62 import com.sun.xml.internal.bind.v2.runtime.JaxBeanInfo;
mkos@397 63 import java.util.logging.Level;
mkos@397 64 import java.util.logging.Logger;
ohair@286 65
ohair@286 66 import org.xml.sax.ErrorHandler;
ohair@286 67 import org.xml.sax.SAXException;
ohair@286 68 import org.xml.sax.helpers.LocatorImpl;
ohair@286 69
ohair@286 70 /**
ohair@286 71 * Center of the unmarshalling.
ohair@286 72 *
ohair@286 73 * <p>
ohair@286 74 * This object is responsible for coordinating {@link Loader}s to
ohair@286 75 * perform the whole unmarshalling.
ohair@286 76 *
ohair@286 77 * @author Kohsuke Kawaguchi
ohair@286 78 */
ohair@286 79 public final class UnmarshallingContext extends Coordinator
ohair@286 80 implements NamespaceContext, ValidationEventHandler, ErrorHandler, XmlVisitor, XmlVisitor.TextPredictor {
ohair@286 81
mkos@397 82 private static final Logger logger = Logger.getLogger(UnmarshallingContext.class.getName());
mkos@397 83
ohair@286 84 /**
ohair@286 85 * Root state.
ohair@286 86 */
ohair@286 87 private final State root;
ohair@286 88
ohair@286 89 /**
ohair@286 90 * The currently active state.
ohair@286 91 */
ohair@286 92 private State current;
ohair@286 93
ohair@286 94 private static final LocatorEx DUMMY_INSTANCE;
ohair@286 95
ohair@286 96 static {
ohair@286 97 LocatorImpl loc = new LocatorImpl();
ohair@286 98 loc.setPublicId(null);
ohair@286 99 loc.setSystemId(null);
ohair@286 100 loc.setLineNumber(-1);
ohair@286 101 loc.setColumnNumber(-1);
ohair@286 102 DUMMY_INSTANCE = new LocatorExWrapper(loc);
ohair@286 103 }
ohair@286 104
ohair@286 105 private @NotNull LocatorEx locator = DUMMY_INSTANCE;
ohair@286 106
ohair@286 107 /** Root object that is being unmarshalled. */
ohair@286 108 private Object result;
ohair@286 109
ohair@286 110 /**
ohair@286 111 * If non-null, this unmarshaller will unmarshal {@code JAXBElement<EXPECTEDTYPE>}
ohair@286 112 * regardless of the tag name, as opposed to deciding the root object by using
ohair@286 113 * the tag name.
ohair@286 114 *
ohair@286 115 * The property has a package-level access, because we cannot copy this value
ohair@286 116 * to {@link UnmarshallingContext} when it is created. The property
ohair@286 117 * on {@link Unmarshaller} could be changed after the handler is created.
ohair@286 118 */
ohair@286 119 private JaxBeanInfo expectedType;
ohair@286 120
ohair@286 121 /**
ohair@286 122 * Handles ID/IDREF.
ohair@286 123 */
ohair@286 124 private IDResolver idResolver;
ohair@286 125
ohair@286 126 /**
ohair@286 127 * This flag is set to true at the startDocument event
ohair@286 128 * and false at the endDocument event.
ohair@286 129 *
ohair@286 130 * Until the first document is unmarshalled, we don't
ohair@286 131 * want to return an object. So this variable is initialized
ohair@286 132 * to true.
ohair@286 133 */
ohair@286 134 private boolean isUnmarshalInProgress = true;
ohair@286 135 private boolean aborted = false;
ohair@286 136
ohair@286 137 public final UnmarshallerImpl parent;
ohair@286 138
ohair@286 139 /**
ohair@286 140 * If the unmarshaller is doing associative unmarshalling,
ohair@286 141 * this field is initialized to non-null.
ohair@286 142 */
ohair@286 143 private final AssociationMap assoc;
ohair@286 144
ohair@286 145 /**
ohair@286 146 * Indicates whether we are doing in-place unmarshalling
ohair@286 147 * or not.
ohair@286 148 *
ohair@286 149 * <p>
ohair@286 150 * This flag is unused when {@link #assoc}==null.
ohair@286 151 * If it's non-null, then <tt>true</tt> indicates
ohair@286 152 * that we are doing in-place associative unmarshalling.
ohair@286 153 * If <tt>false</tt>, then we are doing associative unmarshalling
ohair@286 154 * without object reuse.
ohair@286 155 */
ohair@286 156 private boolean isInplaceMode;
ohair@286 157
ohair@286 158 /**
ohair@286 159 * This object is consulted to get the element object for
ohair@286 160 * the current element event.
ohair@286 161 *
ohair@286 162 * This is used when we are building an association map.
ohair@286 163 */
ohair@286 164 private InfosetScanner scanner;
ohair@286 165
ohair@286 166 private Object currentElement;
ohair@286 167
ohair@286 168 /**
ohair@286 169 * @see XmlVisitor#startDocument(LocatorEx, NamespaceContext)
ohair@286 170 */
ohair@286 171 private NamespaceContext environmentNamespaceContext;
ohair@286 172
ohair@286 173 /**
ohair@286 174 * Used to discover additional classes when we hit unknown elements/types.
ohair@286 175 */
ohair@286 176 public @Nullable ClassResolver classResolver;
ohair@286 177
ohair@286 178 /**
ohair@286 179 * User-supplied {@link ClassLoader} for converting name to {@link Class}.
ohair@286 180 * For backward compatibility, when null, use thread context classloader.
ohair@286 181 */
ohair@286 182 public @Nullable ClassLoader classLoader;
ohair@286 183
ohair@286 184 /**
mkos@397 185 * The variable introduced to avoid reporting n^10 similar errors.
mkos@397 186 * After error is reported counter is decremented. When it became 0 - errors should not be reported any more.
mkos@397 187 *
mkos@397 188 * volatile is required to ensure that concurrent threads will see changed value
mkos@397 189 */
mkos@397 190 private static volatile int errorsCounter = 10;
mkos@397 191
mkos@397 192 /**
ohair@286 193 * State information for each element.
ohair@286 194 */
ohair@286 195 public final class State {
ohair@286 196 /**
ohair@286 197 * Loader that owns this element.
ohair@286 198 */
aefimov@650 199 private Loader loader;
ohair@286 200 /**
ohair@286 201 * Once {@link #loader} is completed, this receiver
ohair@286 202 * receives the result.
ohair@286 203 */
aefimov@650 204 private Receiver receiver;
ohair@286 205
aefimov@650 206 private Intercepter intercepter;
ohair@286 207
ohair@286 208 /**
ohair@286 209 * Object being unmarshalled by this {@link #loader}.
ohair@286 210 */
aefimov@650 211 private Object target;
ohair@286 212
ohair@286 213 /**
ohair@286 214 * Hack for making JAXBElement unmarshalling work.
ohair@286 215 *
ohair@286 216 * <p>
ohair@286 217 * While the unmarshalling is in progress, the {@link #target} field stores the object being unmarshalled.
ohair@286 218 * This makes it convenient to keep track of the unmarshalling activity in context of XML infoset, but
ohair@286 219 * since there's only one {@link State} per element, this mechanism only works when there's one object
ohair@286 220 * per element, which breaks down when we have {@link JAXBElement}, since the presence of JAXBElement
ohair@286 221 * requires that we have two objects unmarshalled (a JAXBElement X and a value object Y bound to an XML type.)
ohair@286 222 *
ohair@286 223 * <p>
ohair@286 224 * So to make room for storing both, this {@link #backup} field is used. When we create X instance
ohair@286 225 * in the above example, we set that to {@code state.prev.target} and displace its old value to
ohair@286 226 * {@code state.prev.backup} (where Y goes to {@code state.target}.) Upon the completion of the unmarshalling
ohair@286 227 * of Y, we revert this.
ohair@286 228 *
ohair@286 229 * <p>
ohair@286 230 * While this attributes X incorrectly to its parent element, this preserves the parent/child
ohair@286 231 * relationship between unmarshalled objects and {@link State} parent/child relationship, and
ohair@286 232 * it thereby makes {@link Receiver} mechanism simpler.
ohair@286 233 *
ohair@286 234 * <p>
ohair@286 235 * Yes, I know this is a hack, and no, I'm not proud of it.
ohair@286 236 *
ohair@286 237 * @see ElementBeanInfoImpl.IntercepterLoader#startElement(State, TagName)
ohair@286 238 * @see ElementBeanInfoImpl.IntercepterLoader#intercept(State, Object)
ohair@286 239 */
aefimov@650 240 private Object backup;
ohair@286 241
ohair@286 242 /**
ohair@286 243 * Number of {@link UnmarshallingContext#nsBind}s declared thus far.
ohair@286 244 * (The value of {@link UnmarshallingContext#nsLen} when this state is pushed.
ohair@286 245 */
ohair@286 246 private int numNsDecl;
ohair@286 247
ohair@286 248 /**
ohair@286 249 * If this element has an element default value.
ohair@286 250 *
ohair@286 251 * This should be set by either a parent {@link Loader} when
ohair@286 252 * {@link Loader#childElement(State, TagName)} is called
ohair@286 253 * or by a child {@link Loader} when
ohair@286 254 * {@link Loader#startElement(State, TagName)} is called.
ohair@286 255 */
aefimov@650 256 private String elementDefaultValue;
ohair@286 257
ohair@286 258 /**
ohair@286 259 * {@link State} for the parent element
ohair@286 260 *
ohair@286 261 * {@link State} objects form a doubly linked list.
ohair@286 262 */
aefimov@650 263 private State prev;
ohair@286 264 private State next;
ohair@286 265
aefimov@650 266 private boolean nil = false;
aefimov@650 267
aefimov@650 268 /**
aefimov@650 269 * specifies that we are working with mixed content
aefimov@650 270 */
aefimov@650 271 private boolean mixed = false;
ohair@286 272
ohair@286 273 /**
ohair@286 274 * Gets the context.
ohair@286 275 */
ohair@286 276 public UnmarshallingContext getContext() {
ohair@286 277 return UnmarshallingContext.this;
ohair@286 278 }
ohair@286 279
mkos@397 280 @SuppressWarnings("LeakingThisInConstructor")
ohair@286 281 private State(State prev) {
ohair@286 282 this.prev = prev;
mkos@397 283 if (prev!=null) {
ohair@286 284 prev.next = this;
aefimov@650 285 if (prev.mixed) // parent is in mixed mode
aefimov@650 286 this.mixed = true;
mkos@397 287 }
ohair@286 288 }
ohair@286 289
ohair@286 290 private void push() {
mkos@397 291 if (logger.isLoggable(Level.FINEST)) {
mkos@397 292 logger.log(Level.FINEST, "State.push");
mkos@397 293 }
mkos@397 294 if (next==null) {
mkos@397 295 assert current == this;
aefimov@650 296 next = new State(this);
mkos@397 297 }
mkos@397 298 nil = false;
ohair@286 299 State n = next;
ohair@286 300 n.numNsDecl = nsLen;
ohair@286 301 current = n;
ohair@286 302 }
ohair@286 303
ohair@286 304 private void pop() {
mkos@397 305 if (logger.isLoggable(Level.FINEST)) {
mkos@397 306 logger.log(Level.FINEST, "State.pop");
mkos@397 307 }
ohair@286 308 assert prev!=null;
ohair@286 309 loader = null;
ohair@286 310 nil = false;
aefimov@650 311 mixed = false;
ohair@286 312 receiver = null;
ohair@286 313 intercepter = null;
ohair@286 314 elementDefaultValue = null;
ohair@286 315 target = null;
ohair@286 316 current = prev;
aefimov@650 317 next = null;
aefimov@650 318 }
aefimov@650 319
aefimov@650 320 public boolean isMixed() {
aefimov@650 321 return mixed;
aefimov@650 322 }
aefimov@650 323
aefimov@650 324 public Object getTarget() {
aefimov@650 325 return target;
aefimov@650 326 }
aefimov@650 327
aefimov@650 328 public void setLoader(Loader loader) {
aefimov@650 329 if (loader instanceof StructureLoader) // set mixed mode
aefimov@650 330 mixed = !((StructureLoader)loader).getBeanInfo().hasElementOnlyContentModel();
aefimov@650 331 this.loader = loader;
aefimov@650 332 }
aefimov@650 333
aefimov@650 334 public void setReceiver(Receiver receiver) {
aefimov@650 335 this.receiver = receiver;
aefimov@650 336 }
aefimov@650 337
aefimov@650 338 public State getPrev() {
aefimov@650 339 return prev;
aefimov@650 340 }
aefimov@650 341
aefimov@650 342 public void setIntercepter(Intercepter intercepter) {
aefimov@650 343 this.intercepter = intercepter;
aefimov@650 344 }
aefimov@650 345
aefimov@650 346 public void setBackup(Object backup) {
aefimov@650 347 this.backup = backup;
aefimov@650 348 }
aefimov@650 349
aefimov@650 350 public void setTarget(Object target) {
aefimov@650 351 this.target = target;
aefimov@650 352 }
aefimov@650 353
aefimov@650 354 public Object getBackup() {
aefimov@650 355 return backup;
aefimov@650 356 }
aefimov@650 357
aefimov@650 358 public boolean isNil() {
aefimov@650 359 return nil;
aefimov@650 360 }
aefimov@650 361
aefimov@650 362 public void setNil(boolean nil) {
aefimov@650 363 this.nil = nil;
aefimov@650 364 }
aefimov@650 365
aefimov@650 366 public Loader getLoader() {
aefimov@650 367 return loader;
aefimov@650 368 }
aefimov@650 369
aefimov@650 370 public String getElementDefaultValue() {
aefimov@650 371 return elementDefaultValue;
aefimov@650 372 }
aefimov@650 373
aefimov@650 374 public void setElementDefaultValue(String elementDefaultValue) {
aefimov@650 375 this.elementDefaultValue = elementDefaultValue;
ohair@286 376 }
ohair@286 377 }
ohair@286 378
ohair@286 379 /**
ohair@286 380 * Stub to the user-specified factory method.
ohair@286 381 */
ohair@286 382 private static class Factory {
ohair@286 383 private final Object factorInstance;
ohair@286 384 private final Method method;
ohair@286 385
ohair@286 386 public Factory(Object factorInstance, Method method) {
ohair@286 387 this.factorInstance = factorInstance;
ohair@286 388 this.method = method;
ohair@286 389 }
ohair@286 390
ohair@286 391 public Object createInstance() throws SAXException {
ohair@286 392 try {
ohair@286 393 return method.invoke(factorInstance);
ohair@286 394 } catch (IllegalAccessException e) {
ohair@286 395 getInstance().handleError(e,false);
ohair@286 396 } catch (InvocationTargetException e) {
ohair@286 397 getInstance().handleError(e,false);
ohair@286 398 }
ohair@286 399 return null; // can never be executed
ohair@286 400 }
ohair@286 401 }
ohair@286 402
ohair@286 403
ohair@286 404 /**
ohair@286 405 * Creates a new unmarshaller.
ohair@286 406 *
ohair@286 407 * @param assoc
ohair@286 408 * Must be both non-null when the unmarshaller does the
ohair@286 409 * in-place unmarshalling. Otherwise must be both null.
ohair@286 410 */
ohair@286 411 public UnmarshallingContext( UnmarshallerImpl _parent, AssociationMap assoc) {
ohair@286 412 this.parent = _parent;
ohair@286 413 this.assoc = assoc;
ohair@286 414 this.root = this.current = new State(null);
ohair@286 415 }
ohair@286 416
ohair@286 417 public void reset(InfosetScanner scanner,boolean isInplaceMode, JaxBeanInfo expectedType, IDResolver idResolver) {
ohair@286 418 this.scanner = scanner;
ohair@286 419 this.isInplaceMode = isInplaceMode;
ohair@286 420 this.expectedType = expectedType;
ohair@286 421 this.idResolver = idResolver;
ohair@286 422 }
ohair@286 423
ohair@286 424 public JAXBContextImpl getJAXBContext() {
ohair@286 425 return parent.context;
ohair@286 426 }
ohair@286 427
ohair@286 428 public State getCurrentState() {
ohair@286 429 return current;
ohair@286 430 }
ohair@286 431
ohair@286 432 /**
ohair@286 433 * On top of {@link JAXBContextImpl#selectRootLoader(State, TagName)},
ohair@286 434 * this method also consults {@link ClassResolver}.
ohair@286 435 *
ohair@286 436 * @throws SAXException
ohair@286 437 * if {@link ValidationEventHandler} reported a failure.
ohair@286 438 */
ohair@286 439 public Loader selectRootLoader(State state, TagName tag) throws SAXException {
ohair@286 440 try {
ohair@286 441 Loader l = getJAXBContext().selectRootLoader(state, tag);
ohair@286 442 if(l!=null) return l;
ohair@286 443
ohair@286 444 if(classResolver!=null) {
ohair@286 445 Class<?> clazz = classResolver.resolveElementName(tag.uri, tag.local);
ohair@286 446 if(clazz!=null) {
ohair@286 447 JAXBContextImpl enhanced = getJAXBContext().createAugmented(clazz);
ohair@286 448 JaxBeanInfo<?> bi = enhanced.getBeanInfo(clazz);
ohair@286 449 return bi.getLoader(enhanced,true);
ohair@286 450 }
ohair@286 451 }
ohair@286 452 } catch (RuntimeException e) {
ohair@286 453 throw e;
ohair@286 454 } catch (Exception e) {
ohair@286 455 handleError(e);
ohair@286 456 }
ohair@286 457
ohair@286 458 return null;
ohair@286 459 }
ohair@286 460
ohair@286 461 public void clearStates() {
ohair@286 462 State last = current;
ohair@286 463 while (last.next != null) last = last.next;
ohair@286 464 while (last.prev != null) {
ohair@286 465 last.loader = null;
ohair@286 466 last.nil = false;
ohair@286 467 last.receiver = null;
ohair@286 468 last.intercepter = null;
ohair@286 469 last.elementDefaultValue = null;
ohair@286 470 last.target = null;
ohair@286 471 last = last.prev;
ohair@286 472 last.next.prev = null;
ohair@286 473 last.next = null;
ohair@286 474 }
ohair@286 475 current = last;
ohair@286 476 }
ohair@286 477
ohair@286 478 /**
ohair@286 479 * User-specified factory methods.
ohair@286 480 */
ohair@286 481 private final Map<Class,Factory> factories = new HashMap<Class, Factory>();
ohair@286 482
ohair@286 483 public void setFactories(Object factoryInstances) {
ohair@286 484 factories.clear();
ohair@286 485 if(factoryInstances==null) {
ohair@286 486 return;
ohair@286 487 }
ohair@286 488 if(factoryInstances instanceof Object[]) {
ohair@286 489 for( Object factory : (Object[])factoryInstances ) {
ohair@286 490 // look for all the public methods inlcuding derived ones
ohair@286 491 addFactory(factory);
ohair@286 492 }
ohair@286 493 } else {
ohair@286 494 addFactory(factoryInstances);
ohair@286 495 }
ohair@286 496 }
ohair@286 497
ohair@286 498 private void addFactory(Object factory) {
ohair@286 499 for( Method m : factory.getClass().getMethods() ) {
ohair@286 500 // look for methods whose signature is T createXXX()
ohair@286 501 if(!m.getName().startsWith("create"))
ohair@286 502 continue;
ohair@286 503 if(m.getParameterTypes().length>0)
ohair@286 504 continue;
ohair@286 505
ohair@286 506 Class type = m.getReturnType();
ohair@286 507
ohair@286 508 factories.put(type,new Factory(factory,m));
ohair@286 509 }
ohair@286 510 }
ohair@286 511
mkos@397 512 @Override
ohair@286 513 public void startDocument(LocatorEx locator, NamespaceContext nsContext) throws SAXException {
ohair@286 514 if(locator!=null)
ohair@286 515 this.locator = locator;
ohair@286 516 this.environmentNamespaceContext = nsContext;
ohair@286 517 // reset the object
ohair@286 518 result = null;
ohair@286 519 current = root;
ohair@286 520
ohair@286 521 patchersLen=0;
ohair@286 522 aborted = false;
ohair@286 523 isUnmarshalInProgress = true;
ohair@286 524 nsLen=0;
ohair@286 525
ohair@286 526 if(expectedType!=null)
ohair@286 527 root.loader = EXPECTED_TYPE_ROOT_LOADER;
ohair@286 528 else
ohair@286 529 root.loader = DEFAULT_ROOT_LOADER;
ohair@286 530
ohair@286 531 idResolver.startDocument(this);
ohair@286 532 }
ohair@286 533
mkos@397 534 @Override
ohair@286 535 public void startElement(TagName tagName) throws SAXException {
ohair@286 536 pushCoordinator();
ohair@286 537 try {
ohair@286 538 _startElement(tagName);
ohair@286 539 } finally {
ohair@286 540 popCoordinator();
ohair@286 541 }
ohair@286 542 }
ohair@286 543
ohair@286 544 private void _startElement(TagName tagName) throws SAXException {
ohair@286 545 // remember the current element if we are interested in it.
ohair@286 546 // because the inner peer might not be found while we consume
ohair@286 547 // the enter element token, we need to keep this information
ohair@286 548 // longer than this callback. That's why we assign it to a field.
ohair@286 549 if( assoc!=null )
ohair@286 550 currentElement = scanner.getCurrentElement();
ohair@286 551
ohair@286 552 Loader h = current.loader;
ohair@286 553 current.push();
ohair@286 554
ohair@286 555 // tell the parent about the new child
ohair@286 556 h.childElement(current,tagName);
ohair@286 557 assert current.loader!=null; // the childElement should register this
ohair@286 558 // and tell the new child that you are activated
ohair@286 559 current.loader.startElement(current,tagName);
ohair@286 560 }
ohair@286 561
mkos@397 562 @Override
ohair@286 563 public void text(CharSequence pcdata) throws SAXException {
ohair@286 564 pushCoordinator();
ohair@286 565 try {
aefimov@650 566 if (current.elementDefaultValue != null) {
aefimov@650 567 if (pcdata.length() == 0) {
ohair@286 568 // send the default value into the unmarshaller instead
aefimov@650 569 pcdata = current.elementDefaultValue;
ohair@286 570 }
ohair@286 571 }
aefimov@650 572 current.loader.text(current, pcdata);
ohair@286 573 } finally {
ohair@286 574 popCoordinator();
ohair@286 575 }
ohair@286 576 }
ohair@286 577
mkos@397 578 @Override
ohair@286 579 public final void endElement(TagName tagName) throws SAXException {
ohair@286 580 pushCoordinator();
ohair@286 581 try {
ohair@286 582 State child = current;
ohair@286 583
ohair@286 584 // tell the child that your time is up
ohair@286 585 child.loader.leaveElement(child,tagName);
ohair@286 586
ohair@286 587 // child.pop will erase them so store them now
ohair@286 588 Object target = child.target;
ohair@286 589 Receiver recv = child.receiver;
ohair@286 590 Intercepter intercepter = child.intercepter;
ohair@286 591 child.pop();
ohair@286 592
ohair@286 593 // then let the parent know
ohair@286 594 if(intercepter!=null)
ohair@286 595 target = intercepter.intercept(current,target);
ohair@286 596 if(recv!=null)
ohair@286 597 recv.receive(current,target);
ohair@286 598 } finally {
ohair@286 599 popCoordinator();
ohair@286 600 }
ohair@286 601 }
ohair@286 602
mkos@397 603 @Override
ohair@286 604 public void endDocument() throws SAXException {
ohair@286 605 runPatchers();
ohair@286 606 idResolver.endDocument();
ohair@286 607
ohair@286 608 isUnmarshalInProgress = false;
ohair@286 609 currentElement = null;
ohair@286 610 locator = DUMMY_INSTANCE;
ohair@286 611 environmentNamespaceContext = null;
ohair@286 612
ohair@286 613 // at the successful completion, scope must be all closed
ohair@286 614 assert root==current;
ohair@286 615 }
ohair@286 616
ohair@286 617 /**
ohair@286 618 * You should be always calling this through {@link TextPredictor}.
ohair@286 619 */
ohair@286 620 @Deprecated
mkos@397 621 @Override
ohair@286 622 public boolean expectText() {
ohair@286 623 return current.loader.expectText;
ohair@286 624 }
ohair@286 625
ohair@286 626 /**
ohair@286 627 * You should be always getting {@link TextPredictor} from {@link XmlVisitor}.
ohair@286 628 */
ohair@286 629 @Deprecated
mkos@397 630 @Override
ohair@286 631 public TextPredictor getPredictor() {
ohair@286 632 return this;
ohair@286 633 }
ohair@286 634
mkos@397 635 @Override
ohair@286 636 public UnmarshallingContext getContext() {
ohair@286 637 return this;
ohair@286 638 }
ohair@286 639
ohair@286 640 /**
ohair@286 641 * Gets the result of the unmarshalling
ohair@286 642 */
ohair@286 643 public Object getResult() throws UnmarshalException {
ohair@286 644 if(isUnmarshalInProgress)
ohair@286 645 throw new IllegalStateException();
ohair@286 646
ohair@286 647 if(!aborted) return result;
ohair@286 648
ohair@286 649 // there was an error.
ohair@286 650 throw new UnmarshalException((String)null);
ohair@286 651 }
ohair@286 652
ohair@286 653 void clearResult() {
ohair@286 654 if (isUnmarshalInProgress) {
ohair@286 655 throw new IllegalStateException();
ohair@286 656 }
ohair@286 657 result = null;
ohair@286 658 }
ohair@286 659
ohair@286 660 /**
ohair@286 661 * Creates a new instance of the specified class.
ohair@286 662 * In the unmarshaller, we need to check the user-specified factory class.
ohair@286 663 */
ohair@286 664 public Object createInstance( Class<?> clazz ) throws SAXException {
ohair@286 665 if(!factories.isEmpty()) {
ohair@286 666 Factory factory = factories.get(clazz);
ohair@286 667 if(factory!=null)
ohair@286 668 return factory.createInstance();
ohair@286 669 }
ohair@286 670 return ClassFactory.create(clazz);
ohair@286 671 }
ohair@286 672
ohair@286 673 /**
ohair@286 674 * Creates a new instance of the specified class.
ohair@286 675 * In the unmarshaller, we need to check the user-specified factory class.
ohair@286 676 */
ohair@286 677 public Object createInstance( JaxBeanInfo beanInfo ) throws SAXException {
ohair@286 678 if(!factories.isEmpty()) {
ohair@286 679 Factory factory = factories.get(beanInfo.jaxbType);
ohair@286 680 if(factory!=null)
ohair@286 681 return factory.createInstance();
ohair@286 682 }
ohair@286 683 try {
ohair@286 684 return beanInfo.createInstance(this);
ohair@286 685 } catch (IllegalAccessException e) {
ohair@286 686 Loader.reportError("Unable to create an instance of "+beanInfo.jaxbType.getName(),e,false);
ohair@286 687 } catch (InvocationTargetException e) {
ohair@286 688 Loader.reportError("Unable to create an instance of "+beanInfo.jaxbType.getName(),e,false);
ohair@286 689 } catch (InstantiationException e) {
ohair@286 690 Loader.reportError("Unable to create an instance of "+beanInfo.jaxbType.getName(),e,false);
ohair@286 691 }
ohair@286 692 return null; // can never be here
ohair@286 693 }
ohair@286 694
ohair@286 695
ohair@286 696
ohair@286 697 //
ohair@286 698 //
ohair@286 699 // error handling
ohair@286 700 //
ohair@286 701 //
ohair@286 702
ohair@286 703 /**
ohair@286 704 * Reports an error to the user, and asks if s/he wants
ohair@286 705 * to recover. If the canRecover flag is false, regardless
ohair@286 706 * of the client instruction, an exception will be thrown.
ohair@286 707 *
ohair@286 708 * Only if the flag is true and the user wants to recover from an error,
ohair@286 709 * the method returns normally.
ohair@286 710 *
ohair@286 711 * The thrown exception will be catched by the unmarshaller.
ohair@286 712 */
ohair@286 713 public void handleEvent(ValidationEvent event, boolean canRecover ) throws SAXException {
ohair@286 714 ValidationEventHandler eventHandler = parent.getEventHandler();
ohair@286 715
ohair@286 716 boolean recover = eventHandler.handleEvent(event);
ohair@286 717
ohair@286 718 // if the handler says "abort", we will not return the object
ohair@286 719 // from the unmarshaller.getResult()
ohair@286 720 if(!recover) aborted = true;
ohair@286 721
ohair@286 722 if( !canRecover || !recover )
ohair@286 723 throw new SAXParseException2( event.getMessage(), locator,
ohair@286 724 new UnmarshalException(
ohair@286 725 event.getMessage(),
ohair@286 726 event.getLinkedException() ) );
ohair@286 727 }
ohair@286 728
mkos@397 729 @Override
ohair@286 730 public boolean handleEvent(ValidationEvent event) {
ohair@286 731 try {
ohair@286 732 // if the handler says "abort", we will not return the object.
ohair@286 733 boolean recover = parent.getEventHandler().handleEvent(event);
ohair@286 734 if(!recover) aborted = true;
ohair@286 735 return recover;
ohair@286 736 } catch( RuntimeException re ) {
ohair@286 737 // if client event handler causes a runtime exception, then we
ohair@286 738 // have to return false.
ohair@286 739 return false;
ohair@286 740 }
ohair@286 741 }
ohair@286 742
ohair@286 743 /**
ohair@286 744 * Reports an exception found during the unmarshalling to the user.
ohair@286 745 * This method is a convenience method that calls into
ohair@286 746 * {@link #handleEvent(ValidationEvent, boolean)}
ohair@286 747 */
ohair@286 748 public void handleError(Exception e) throws SAXException {
ohair@286 749 handleError(e,true);
ohair@286 750 }
ohair@286 751
ohair@286 752 public void handleError(Exception e,boolean canRecover) throws SAXException {
ohair@286 753 handleEvent(new ValidationEventImpl(ValidationEvent.ERROR,e.getMessage(),locator.getLocation(),e),canRecover);
ohair@286 754 }
ohair@286 755
ohair@286 756 public void handleError(String msg) {
ohair@286 757 handleEvent(new ValidationEventImpl(ValidationEvent.ERROR,msg,locator.getLocation()));
ohair@286 758 }
ohair@286 759
mkos@397 760 @Override
ohair@286 761 protected ValidationEventLocator getLocation() {
ohair@286 762 return locator.getLocation();
ohair@286 763 }
ohair@286 764
ohair@286 765 /**
ohair@286 766 * Gets the current source location information in SAX {@link Locator}.
ohair@286 767 * <p>
ohair@286 768 * Sometimes the unmarshaller works against a different kind of XML source,
ohair@286 769 * making this information meaningless.
ohair@286 770 */
ohair@286 771 public LocatorEx getLocator() { return locator; }
ohair@286 772
ohair@286 773 /**
ohair@286 774 * Called when there's no corresponding ID value.
ohair@286 775 */
ohair@286 776 public void errorUnresolvedIDREF(Object bean, String idref, LocatorEx loc) throws SAXException {
ohair@286 777 handleEvent( new ValidationEventImpl(
ohair@286 778 ValidationEvent.ERROR,
ohair@286 779 Messages.UNRESOLVED_IDREF.format(idref),
ohair@286 780 loc.getLocation()), true );
ohair@286 781 }
ohair@286 782
ohair@286 783
ohair@286 784 //
ohair@286 785 //
ohair@286 786 // ID/IDREF related code
ohair@286 787 //
ohair@286 788 //
ohair@286 789 /**
ohair@286 790 * Submitted patchers in the order they've submitted.
ohair@286 791 * Many XML vocabulary doesn't use ID/IDREF at all, so we
ohair@286 792 * initialize it with null.
ohair@286 793 */
ohair@286 794 private Patcher[] patchers = null;
ohair@286 795 private int patchersLen = 0;
ohair@286 796
ohair@286 797 /**
ohair@286 798 * Adds a job that will be executed at the last of the unmarshalling.
ohair@286 799 * This method is used to support ID/IDREF feature, but it can be used
ohair@286 800 * for other purposes as well.
ohair@286 801 *
ohair@286 802 * @param job
ohair@286 803 * The run method of this object is called.
ohair@286 804 */
ohair@286 805 public void addPatcher( Patcher job ) {
ohair@286 806 // re-allocate buffer if necessary
ohair@286 807 if( patchers==null )
ohair@286 808 patchers = new Patcher[32];
ohair@286 809 if( patchers.length == patchersLen ) {
ohair@286 810 Patcher[] buf = new Patcher[patchersLen*2];
ohair@286 811 System.arraycopy(patchers,0,buf,0,patchersLen);
ohair@286 812 patchers = buf;
ohair@286 813 }
ohair@286 814 patchers[patchersLen++] = job;
ohair@286 815 }
ohair@286 816
ohair@286 817 /** Executes all the patchers. */
ohair@286 818 private void runPatchers() throws SAXException {
ohair@286 819 if( patchers!=null ) {
ohair@286 820 for( int i=0; i<patchersLen; i++ ) {
ohair@286 821 patchers[i].run();
ohair@286 822 patchers[i] = null; // free memory
ohair@286 823 }
ohair@286 824 }
ohair@286 825 }
ohair@286 826
ohair@286 827 /**
ohair@286 828 * Adds the object which is currently being unmarshalled
ohair@286 829 * to the ID table.
ohair@286 830 *
ohair@286 831 * @return
ohair@286 832 * Returns the value passed as the parameter.
ohair@286 833 * This is a hack, but this makes it easier for ID
ohair@286 834 * transducer to do its job.
ohair@286 835 */
ohair@286 836 // TODO: what shall we do if the ID is already declared?
ohair@286 837 //
ohair@286 838 // throwing an exception is one way. Overwriting the previous one
ohair@286 839 // is another way. The latter allows us to process invalid documents,
ohair@286 840 // while the former makes it impossible to handle them.
ohair@286 841 //
ohair@286 842 // I prefer to be flexible in terms of invalid document handling,
ohair@286 843 // so chose not to throw an exception.
ohair@286 844 //
ohair@286 845 // I believe this is an implementation choice, not the spec issue.
ohair@286 846 // -kk
ohair@286 847 public String addToIdTable( String id ) throws SAXException {
ohair@286 848 // Hmm...
ohair@286 849 // in cases such as when ID is used as an attribute, or as @XmlValue
ohair@286 850 // the target wilil be current.target.
ohair@286 851 // but in some other cases, such as when ID is used as a child element
ohair@286 852 // or a value of JAXBElement, it's current.prev.target.
ohair@286 853 // I don't know if this detection logic is complete
ohair@286 854 Object o = current.target;
ohair@286 855 if(o==null)
ohair@286 856 o = current.prev.target;
ohair@286 857 idResolver.bind(id,o);
ohair@286 858 return id;
ohair@286 859 }
ohair@286 860
ohair@286 861 /**
ohair@286 862 * Looks up the ID table and gets associated object.
ohair@286 863 *
ohair@286 864 * <p>
ohair@286 865 * The exception thrown from {@link Callable#call()} means the unmarshaller should abort
ohair@286 866 * right away.
ohair@286 867 *
ohair@286 868 * @see IDResolver#resolve(String, Class)
ohair@286 869 */
ohair@286 870 public Callable getObjectFromId( String id, Class targetType ) throws SAXException {
ohair@286 871 return idResolver.resolve(id,targetType);
ohair@286 872 }
ohair@286 873
ohair@286 874 //
ohair@286 875 //
ohair@286 876 // namespace binding maintainance
ohair@286 877 //
ohair@286 878 //
ohair@286 879 private String[] nsBind = new String[16];
ohair@286 880 private int nsLen=0;
ohair@286 881
mkos@397 882 @Override
ohair@286 883 public void startPrefixMapping( String prefix, String uri ) {
ohair@286 884 if(nsBind.length==nsLen) {
ohair@286 885 // expand the buffer
ohair@286 886 String[] n = new String[nsLen*2];
ohair@286 887 System.arraycopy(nsBind,0,n,0,nsLen);
ohair@286 888 nsBind=n;
ohair@286 889 }
ohair@286 890 nsBind[nsLen++] = prefix;
ohair@286 891 nsBind[nsLen++] = uri;
ohair@286 892 }
mkos@397 893 @Override
ohair@286 894 public void endPrefixMapping( String prefix ) {
ohair@286 895 nsLen-=2;
ohair@286 896 }
ohair@286 897 private String resolveNamespacePrefix( String prefix ) {
ohair@286 898 if(prefix.equals("xml"))
ohair@286 899 return XMLConstants.XML_NS_URI;
ohair@286 900
ohair@286 901 for( int i=nsLen-2; i>=0; i-=2 ) {
ohair@286 902 if(prefix.equals(nsBind[i]))
ohair@286 903 return nsBind[i+1];
ohair@286 904 }
ohair@286 905
ohair@286 906 if(environmentNamespaceContext!=null)
ohair@286 907 // temporary workaround until Zephyr fixes 6337180
ohair@286 908 return environmentNamespaceContext.getNamespaceURI(prefix.intern());
ohair@286 909
ohair@286 910 // by default, the default ns is bound to "".
ohair@286 911 // but allow environmentNamespaceContext to take precedence
ohair@286 912 if(prefix.equals(""))
ohair@286 913 return "";
ohair@286 914
ohair@286 915 // unresolved. error.
ohair@286 916 return null;
ohair@286 917 }
ohair@286 918
ohair@286 919 /**
ohair@286 920 * Returns a list of prefixes newly declared on the current element.
ohair@286 921 *
ohair@286 922 * @return
ohair@286 923 * A possible zero-length array of prefixes. The default prefix
ohair@286 924 * is represented by the empty string.
ohair@286 925 */
ohair@286 926 public String[] getNewlyDeclaredPrefixes() {
ohair@286 927 return getPrefixList( current.prev.numNsDecl );
ohair@286 928 }
ohair@286 929
ohair@286 930 /**
ohair@286 931 * Returns a list of all in-scope prefixes.
ohair@286 932 *
ohair@286 933 * @return
ohair@286 934 * A possible zero-length array of prefixes. The default prefix
ohair@286 935 * is represented by the empty string.
ohair@286 936 */
ohair@286 937 public String[] getAllDeclaredPrefixes() {
ohair@286 938 return getPrefixList(0);
ohair@286 939 }
ohair@286 940
ohair@286 941 private String[] getPrefixList( int startIndex ) {
ohair@286 942 int size = (current.numNsDecl - startIndex)/2;
ohair@286 943 String[] r = new String[size];
ohair@286 944 for( int i=0; i<r.length; i++ )
ohair@286 945 r[i] = nsBind[startIndex+i*2];
ohair@286 946 return r;
ohair@286 947 }
ohair@286 948
ohair@286 949 // NamespaceContext2 implementation
ohair@286 950 //
mkos@397 951 @Override
ohair@286 952 public Iterator<String> getPrefixes(String uri) {
ohair@286 953 // TODO: could be implemented much faster
ohair@286 954 // wrap it into unmodifiable list so that the remove method
ohair@286 955 // will throw UnsupportedOperationException.
ohair@286 956 return Collections.unmodifiableList(
ohair@286 957 getAllPrefixesInList(uri)).iterator();
ohair@286 958 }
ohair@286 959
ohair@286 960 private List<String> getAllPrefixesInList(String uri) {
ohair@286 961 List<String> a = new ArrayList<String>();
ohair@286 962
ohair@286 963 if( uri==null )
ohair@286 964 throw new IllegalArgumentException();
ohair@286 965 if( uri.equals(XMLConstants.XML_NS_URI) ) {
ohair@286 966 a.add(XMLConstants.XML_NS_PREFIX);
ohair@286 967 return a;
ohair@286 968 }
ohair@286 969 if( uri.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI) ) {
ohair@286 970 a.add(XMLConstants.XMLNS_ATTRIBUTE);
ohair@286 971 return a;
ohair@286 972 }
ohair@286 973
ohair@286 974 for( int i=nsLen-2; i>=0; i-=2 )
ohair@286 975 if(uri.equals(nsBind[i+1]))
ohair@286 976 if( getNamespaceURI(nsBind[i]).equals(nsBind[i+1]) )
ohair@286 977 // make sure that this prefix is still effective.
ohair@286 978 a.add(nsBind[i]);
ohair@286 979
ohair@286 980 return a;
ohair@286 981 }
ohair@286 982
mkos@397 983 @Override
ohair@286 984 public String getPrefix(String uri) {
ohair@286 985 if( uri==null )
ohair@286 986 throw new IllegalArgumentException();
ohair@286 987 if( uri.equals(XMLConstants.XML_NS_URI) )
ohair@286 988 return XMLConstants.XML_NS_PREFIX;
ohair@286 989 if( uri.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI) )
ohair@286 990 return XMLConstants.XMLNS_ATTRIBUTE;
ohair@286 991
ohair@286 992 for( int i=nsLen-2; i>=0; i-=2 )
ohair@286 993 if(uri.equals(nsBind[i+1]))
ohair@286 994 if( getNamespaceURI(nsBind[i]).equals(nsBind[i+1]) )
ohair@286 995 // make sure that this prefix is still effective.
ohair@286 996 return nsBind[i];
ohair@286 997
ohair@286 998 if(environmentNamespaceContext!=null)
ohair@286 999 return environmentNamespaceContext.getPrefix(uri);
ohair@286 1000
ohair@286 1001 return null;
ohair@286 1002 }
ohair@286 1003
mkos@397 1004 @Override
ohair@286 1005 public String getNamespaceURI(String prefix) {
ohair@286 1006 if (prefix == null)
ohair@286 1007 throw new IllegalArgumentException();
ohair@286 1008 if (prefix.equals(XMLConstants.XMLNS_ATTRIBUTE))
ohair@286 1009 return XMLConstants.XMLNS_ATTRIBUTE_NS_URI;
ohair@286 1010
ohair@286 1011 return resolveNamespacePrefix(prefix);
ohair@286 1012 }
ohair@286 1013
ohair@286 1014 //
ohair@286 1015 //
ohair@286 1016 //
ohair@286 1017 // scope management
ohair@286 1018 //
ohair@286 1019 //
ohair@286 1020 //
ohair@286 1021 private Scope[] scopes = new Scope[16];
ohair@286 1022 /**
ohair@286 1023 * Points to the top of the scope stack (=size-1).
ohair@286 1024 */
ohair@286 1025 private int scopeTop=0;
ohair@286 1026
ohair@286 1027 {
ohair@286 1028 for( int i=0; i<scopes.length; i++ )
ohair@286 1029 scopes[i] = new Scope(this);
ohair@286 1030 }
ohair@286 1031
ohair@286 1032 /**
ohair@286 1033 * Starts a new packing scope.
ohair@286 1034 *
ohair@286 1035 * <p>
ohair@286 1036 * This method allocates a specified number of fresh {@link Scope} objects.
ohair@286 1037 * They can be accessed by the {@link #getScope} method until the corresponding
ohair@286 1038 * {@link #endScope} method is invoked.
ohair@286 1039 *
ohair@286 1040 * <p>
ohair@286 1041 * A new scope will mask the currently active scope. Only one frame of {@link Scope}s
ohair@286 1042 * can be accessed at any given time.
ohair@286 1043 *
ohair@286 1044 * @param frameSize
ohair@286 1045 * The # of slots to be allocated.
ohair@286 1046 */
ohair@286 1047 public void startScope(int frameSize) {
ohair@286 1048 scopeTop += frameSize;
ohair@286 1049
ohair@286 1050 // reallocation
ohair@286 1051 if(scopeTop>=scopes.length) {
ohair@286 1052 Scope[] s = new Scope[Math.max(scopeTop+1,scopes.length*2)];
ohair@286 1053 System.arraycopy(scopes,0,s,0,scopes.length);
ohair@286 1054 for( int i=scopes.length; i<s.length; i++ )
ohair@286 1055 s[i] = new Scope(this);
ohair@286 1056 scopes = s;
ohair@286 1057 }
ohair@286 1058 }
ohair@286 1059
ohair@286 1060 /**
ohair@286 1061 * Ends the current packing scope.
ohair@286 1062 *
ohair@286 1063 * <p>
ohair@286 1064 * If any packing in progress will be finalized by this method.
ohair@286 1065 *
ohair@286 1066 * @param frameSize
ohair@286 1067 * The same size that gets passed to the {@link #startScope(int)}
ohair@286 1068 * method.
ohair@286 1069 */
ohair@286 1070 public void endScope(int frameSize) throws SAXException {
ohair@286 1071 try {
ohair@286 1072 for( ; frameSize>0; frameSize--, scopeTop-- )
ohair@286 1073 scopes[scopeTop].finish();
ohair@286 1074 } catch (AccessorException e) {
ohair@286 1075 handleError(e);
ohair@286 1076
ohair@286 1077 // the error might have left scopes in inconsistent state,
ohair@286 1078 // so replace them by fresh ones
ohair@286 1079 for( ; frameSize>0; frameSize-- )
ohair@286 1080 scopes[scopeTop--] = new Scope(this);
ohair@286 1081 }
ohair@286 1082 }
ohair@286 1083
ohair@286 1084 /**
ohair@286 1085 * Gets the currently active {@link Scope}.
ohair@286 1086 *
ohair@286 1087 * @param offset
ohair@286 1088 * a number between [0,frameSize)
ohair@286 1089 *
ohair@286 1090 * @return
ohair@286 1091 * always a valid {@link Scope} object.
ohair@286 1092 */
ohair@286 1093 public Scope getScope(int offset) {
ohair@286 1094 return scopes[scopeTop-offset];
ohair@286 1095 }
ohair@286 1096
ohair@286 1097 //
ohair@286 1098 //
ohair@286 1099 //
ohair@286 1100 //
ohair@286 1101 //
ohair@286 1102 //
ohair@286 1103 //
ohair@286 1104
ohair@286 1105 private static final Loader DEFAULT_ROOT_LOADER = new DefaultRootLoader();
ohair@286 1106 private static final Loader EXPECTED_TYPE_ROOT_LOADER = new ExpectedTypeRootLoader();
ohair@286 1107
ohair@286 1108 /**
ohair@286 1109 * Root loader that uses the tag name and possibly its @xsi:type
ohair@286 1110 * to decide how to start unmarshalling.
ohair@286 1111 */
ohair@286 1112 private static final class DefaultRootLoader extends Loader implements Receiver {
ohair@286 1113 /**
ohair@286 1114 * Receives the root element and determines how to start
ohair@286 1115 * unmarshalling.
ohair@286 1116 */
ohair@286 1117 @Override
ohair@286 1118 public void childElement(UnmarshallingContext.State state, TagName ea) throws SAXException {
ohair@286 1119 Loader loader = state.getContext().selectRootLoader(state,ea);
ohair@286 1120 if(loader!=null) {
ohair@286 1121 state.loader = loader;
ohair@286 1122 state.receiver = this;
ohair@286 1123 return;
ohair@286 1124 }
ohair@286 1125
ohair@286 1126 // the registry doesn't know about this element.
ohair@286 1127 // try its xsi:type
ohair@286 1128 JaxBeanInfo beanInfo = XsiTypeLoader.parseXsiType(state, ea, null);
ohair@286 1129 if(beanInfo==null) {
ohair@286 1130 // we don't even know its xsi:type
ohair@286 1131 reportUnexpectedChildElement(ea,false);
ohair@286 1132 return;
ohair@286 1133 }
ohair@286 1134
ohair@286 1135 state.loader = beanInfo.getLoader(null,false);
ohair@286 1136 state.prev.backup = new JAXBElement<Object>(ea.createQName(),Object.class,null);
ohair@286 1137 state.receiver = this;
ohair@286 1138 }
ohair@286 1139
ohair@286 1140 @Override
ohair@286 1141 public Collection<QName> getExpectedChildElements() {
ohair@286 1142 return getInstance().getJAXBContext().getValidRootNames();
ohair@286 1143 }
ohair@286 1144
mkos@397 1145 @Override
ohair@286 1146 public void receive(State state, Object o) {
ohair@286 1147 if(state.backup!=null) {
ohair@286 1148 ((JAXBElement<Object>)state.backup).setValue(o);
ohair@286 1149 o = state.backup;
ohair@286 1150 }
ohair@286 1151 if (state.nil) {
ohair@286 1152 ((JAXBElement<Object>)o).setNil(true);
ohair@286 1153 }
ohair@286 1154 state.getContext().result = o;
ohair@286 1155 }
ohair@286 1156 }
ohair@286 1157
ohair@286 1158 /**
ohair@286 1159 * Root loader that uses {@link UnmarshallingContext#expectedType}
ohair@286 1160 * to decide how to start unmarshalling.
ohair@286 1161 */
ohair@286 1162 private static final class ExpectedTypeRootLoader extends Loader implements Receiver {
ohair@286 1163 /**
ohair@286 1164 * Receives the root element and determines how to start
ohair@286 1165 * unmarshalling.
ohair@286 1166 */
ohair@286 1167 @Override
ohair@286 1168 public void childElement(UnmarshallingContext.State state, TagName ea) {
ohair@286 1169 UnmarshallingContext context = state.getContext();
ohair@286 1170
ohair@286 1171 // unmarshals the specified type
ohair@286 1172 QName qn = new QName(ea.uri,ea.local);
ohair@286 1173 state.prev.target = new JAXBElement(qn,context.expectedType.jaxbType,null,null);
ohair@286 1174 state.receiver = this;
ohair@286 1175 // this is bit wasteful, as in theory we should have each expectedType keep
ohair@286 1176 // nillable version --- but that increases the combination from two to four,
ohair@286 1177 // which adds the resident memory footprint. Since XsiNilLoader is small,
ohair@286 1178 // I intentionally allocate a new instance freshly.
ohair@286 1179 state.loader = new XsiNilLoader(context.expectedType.getLoader(null,true));
ohair@286 1180 }
ohair@286 1181
mkos@397 1182 @Override
ohair@286 1183 public void receive(State state, Object o) {
ohair@286 1184 JAXBElement e = (JAXBElement)state.target;
ohair@286 1185 e.setValue(o);
ohair@286 1186 state.getContext().recordOuterPeer(e);
ohair@286 1187 state.getContext().result = e;
ohair@286 1188 }
ohair@286 1189 }
ohair@286 1190
ohair@286 1191 //
ohair@286 1192 // in-place unmarshalling related capabilities
ohair@286 1193 //
ohair@286 1194 /**
ohair@286 1195 * Notifies the context about the inner peer of the current element.
ohair@286 1196 *
ohair@286 1197 * <p>
ohair@286 1198 * If the unmarshalling is building the association, the context
ohair@286 1199 * will use this information. Otherwise it will be just ignored.
ohair@286 1200 */
ohair@286 1201 public void recordInnerPeer(Object innerPeer) {
ohair@286 1202 if(assoc!=null)
ohair@286 1203 assoc.addInner(currentElement,innerPeer);
ohair@286 1204 }
ohair@286 1205
ohair@286 1206 /**
ohair@286 1207 * Gets the inner peer JAXB object associated with the current element.
ohair@286 1208 *
ohair@286 1209 * @return
ohair@286 1210 * null if the current element doesn't have an inner peer,
ohair@286 1211 * or if we are not doing the in-place unmarshalling.
ohair@286 1212 */
ohair@286 1213 public Object getInnerPeer() {
ohair@286 1214 if(assoc!=null && isInplaceMode)
ohair@286 1215 return assoc.getInnerPeer(currentElement);
ohair@286 1216 else
ohair@286 1217 return null;
ohair@286 1218 }
ohair@286 1219
ohair@286 1220 /**
ohair@286 1221 * Notifies the context about the outer peer of the current element.
ohair@286 1222 *
ohair@286 1223 * <p>
ohair@286 1224 * If the unmarshalling is building the association, the context
ohair@286 1225 * will use this information. Otherwise it will be just ignored.
ohair@286 1226 */
ohair@286 1227 public void recordOuterPeer(Object outerPeer) {
ohair@286 1228 if(assoc!=null)
ohair@286 1229 assoc.addOuter(currentElement,outerPeer);
ohair@286 1230 }
ohair@286 1231
ohair@286 1232 /**
ohair@286 1233 * Gets the outer peer JAXB object associated with the current element.
ohair@286 1234 *
ohair@286 1235 * @return
ohair@286 1236 * null if the current element doesn't have an inner peer,
ohair@286 1237 * or if we are not doing the in-place unmarshalling.
ohair@286 1238 */
ohair@286 1239 public Object getOuterPeer() {
ohair@286 1240 if(assoc!=null && isInplaceMode)
ohair@286 1241 return assoc.getOuterPeer(currentElement);
ohair@286 1242 else
ohair@286 1243 return null;
ohair@286 1244 }
ohair@286 1245
ohair@286 1246 /**
ohair@286 1247 * Gets the xmime:contentType value for the current object.
ohair@286 1248 *
ohair@286 1249 * @see JAXBContextImpl#getXMIMEContentType(Object)
ohair@286 1250 */
ohair@286 1251 public String getXMIMEContentType() {
ohair@286 1252 /*
ohair@286 1253 this won't work when the class is like
ohair@286 1254
ohair@286 1255 class Foo {
ohair@286 1256 @XmlValue Image img;
ohair@286 1257 }
ohair@286 1258
ohair@286 1259 because the target will return Foo, not the class enclosing Foo
ohair@286 1260 which will have xmime:contentType
ohair@286 1261 */
ohair@286 1262 Object t = current.target;
ohair@286 1263 if(t==null) return null;
ohair@286 1264 return getJAXBContext().getXMIMEContentType(t);
ohair@286 1265 }
ohair@286 1266
ohair@286 1267 /**
ohair@286 1268 * When called from within the realm of the unmarshaller, this method
ohair@286 1269 * returns the current {@link UnmarshallingContext} in charge.
ohair@286 1270 */
ohair@286 1271 public static UnmarshallingContext getInstance() {
ohair@286 1272 return (UnmarshallingContext) Coordinator._getInstance();
ohair@286 1273 }
ohair@286 1274
ohair@286 1275 /**
ohair@286 1276 * Allows to access elements which are expected in current state.
ohair@286 1277 * Useful for getting elements for current parent.
ohair@286 1278 *
ohair@286 1279 * @return
ohair@286 1280 */
ohair@286 1281 public Collection<QName> getCurrentExpectedElements() {
ohair@286 1282 pushCoordinator();
ohair@286 1283 try {
ohair@286 1284 State s = getCurrentState();
ohair@286 1285 Loader l = s.loader;
ohair@286 1286 return (l != null) ? l.getExpectedChildElements() : null;
ohair@286 1287 } finally {
ohair@286 1288 popCoordinator();
ohair@286 1289 }
ohair@286 1290 }
ohair@286 1291
ohair@286 1292 /**
ohair@286 1293 * Allows to access attributes which are expected in current state.
ohair@286 1294 * Useful for getting attributes for current parent.
ohair@286 1295 *
ohair@286 1296 * @return
ohair@286 1297 */
ohair@286 1298 public Collection<QName> getCurrentExpectedAttributes() {
ohair@286 1299 pushCoordinator();
ohair@286 1300 try {
ohair@286 1301 State s = getCurrentState();
ohair@286 1302 Loader l = s.loader;
ohair@286 1303 return (l != null) ? l.getExpectedAttributes() : null;
ohair@286 1304 } finally {
ohair@286 1305 popCoordinator();
ohair@286 1306 }
ohair@286 1307 }
ohair@286 1308
ohair@286 1309 /**
ohair@286 1310 * Gets StructureLoader if used as loader.
ohair@286 1311 * Useful when determining if element is mixed or not.
ohair@286 1312 *
ohair@286 1313 */
ohair@286 1314 public StructureLoader getStructureLoader() {
ohair@286 1315 if(current.loader instanceof StructureLoader)
ohair@286 1316 return (StructureLoader)current.loader;
ohair@286 1317
ohair@286 1318 return null;
ohair@286 1319 }
ohair@286 1320
mkos@397 1321 /**
mkos@397 1322 * Based on current {@link Logger} {@link Level} and errorCounter value determines if error should be reported.
mkos@397 1323 *
mkos@397 1324 * If the method called and return true it is expected that error will be reported. And that's why
mkos@397 1325 * errorCounter is automatically decremented during the check.
mkos@397 1326 *
mkos@397 1327 * NOT THREAD SAFE!!! In case of heave concurrency access several additional errors could be reported. It's not expected to be the
mkos@397 1328 * problem. Otherwise add synchronization here.
mkos@397 1329 *
mkos@397 1330 * @return true in case if {@link Level#FINEST} is set OR we haven't exceed errors reporting limit.
mkos@397 1331 */
mkos@397 1332 public boolean shouldErrorBeReported() throws SAXException {
mkos@397 1333 if (logger.isLoggable(Level.FINEST))
mkos@397 1334 return true;
mkos@397 1335
mkos@397 1336 if (errorsCounter >= 0) {
mkos@397 1337 --errorsCounter;
mkos@397 1338 if (errorsCounter == 0) // it's possible to miss this because of concurrency. If required add synchronization here
mkos@397 1339 handleEvent(new ValidationEventImpl(ValidationEvent.WARNING, Messages.ERRORS_LIMIT_EXCEEDED.format(),
mkos@397 1340 getLocator().getLocation(), null), true);
mkos@397 1341 }
mkos@397 1342 return errorsCounter >= 0;
mkos@397 1343 }
ohair@286 1344 }

mercurial