01: /*
02: * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
03: * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
04: */
05: package javax.xml.bind.util;
06:
07: import javax.xml.bind.ValidationEvent;
08: import javax.xml.bind.ValidationEventHandler;
09: import java.util.ArrayList;
10: import java.util.List;
11:
12: /**
13: * {@link javax.xml.bind.ValidationEventHandler ValidationEventHandler}
14: * implementation that collects all events.
15: *
16: * <p>
17: * To use this class, create a new instance and pass it to the setEventHandler
18: * method of the Validator, Unmarshaller, Marshaller class. After the call to
19: * validate or unmarshal completes, call the getEvents method to retrieve all
20: * the reported errors and warnings.
21: *
22: * @author <ul><li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li><li>Ryan Shoemaker, Sun Microsystems, Inc.</li><li>Joe Fialli, Sun Microsystems, Inc.</li></ul>
23: * @version $Revision: 1.3 $
24: * @see javax.xml.bind.Validator
25: * @see javax.xml.bind.ValidationEventHandler
26: * @see javax.xml.bind.ValidationEvent
27: * @see javax.xml.bind.ValidationEventLocator
28: * @since JAXB1.0
29: */
30: public class ValidationEventCollector implements ValidationEventHandler {
31: private final List<ValidationEvent> events = new ArrayList<ValidationEvent>();
32:
33: /**
34: * Return an array of ValidationEvent objects containing a copy of each of
35: * the collected errors and warnings.
36: *
37: * @return
38: * a copy of all the collected errors and warnings or an empty array
39: * if there weren't any
40: */
41: public ValidationEvent[] getEvents() {
42: return events.toArray(new ValidationEvent[events.size()]);
43: }
44:
45: /**
46: * Clear all collected errors and warnings.
47: */
48: public void reset() {
49: events.clear();
50: }
51:
52: /**
53: * Returns true if this event collector contains at least one
54: * ValidationEvent.
55: *
56: * @return true if this event collector contains at least one
57: * ValidationEvent, false otherwise
58: */
59: public boolean hasEvents() {
60: return !events.isEmpty();
61: }
62:
63: public boolean handleEvent(ValidationEvent event) {
64: events.add(event);
65:
66: boolean retVal = true;
67: switch (event.getSeverity()) {
68: case ValidationEvent.WARNING:
69: retVal = true; // continue validation
70: break;
71: case ValidationEvent.ERROR:
72: retVal = true; // continue validation
73: break;
74: case ValidationEvent.FATAL_ERROR:
75: retVal = false; // halt validation
76: break;
77: default:
78: _assert(false, Messages
79: .format(Messages.UNRECOGNIZED_SEVERITY, event
80: .getSeverity()));
81: break;
82: }
83:
84: return retVal;
85: }
86:
87: private static void _assert(boolean b, String msg) {
88: if (!b) {
89: throw new InternalError(msg);
90: }
91: }
92: }
|