public String marshallToXml(Statistics statistics) { try { Marshaller marshaller = jaxbContext.createMarshaller(); StringWriter stringWriter = new StringWriter(); List<ValidationEvent> validationEvents = new ArrayList<>(); marshaller.setEventHandler(event -> { if (event.getSeverity() == ValidationEvent.ERROR || event.getSeverity() == ValidationEvent.FATAL_ERROR) { validationEvents.add(event); } //let the un-marshalling proceed to find any more problems return true; }); marshaller.marshal(statistics, stringWriter); if (!validationEvents.isEmpty()) { String detail = validationEventsToString(validationEvents); throw new RuntimeException("Errors encountered marshalling xml: " + detail); } return stringWriter.toString(); } catch (JAXBException e) { LOGGER.error("Error marshalling message value"); throw new RuntimeException(String.format("Error marshalling message value"), e); } }
public synchronized void setJaxbContext(Class... classesToBeBound) { try { setJaxbContext(JAXBContext.newInstance(classesToBeBound)); // Every time we set the JAXBContext, we need to also set the marshaller and unmarshaller for EXICodec getExiCodec().setUnmarshaller(getJaxbContext().createUnmarshaller()); getExiCodec().setMarshaller(getJaxbContext().createMarshaller()); /* * JAXB by default silently ignores errors. Adding this code to throw an exception if * something goes wrong. */ getExiCodec().getUnmarshaller().setEventHandler( new ValidationEventHandler() { @Override public boolean handleEvent(ValidationEvent event ) { throw new RuntimeException(event.getMessage(), event.getLinkedException()); } }); } catch (JAXBException e) { getLogger().error("A JAXBException occurred while trying to set JAXB context", e); } }
public String print(XMLGregorianCalendar cal) { XMLSerializer xs = XMLSerializer.getInstance(); QName type = xs.getSchemaType(); if (type != null) { try { checkXmlGregorianCalendarFieldRef(type, cal); String format = xmlGregorianCalendarFormatString.get(type); if (format != null) { return format(format, cal); } } catch (javax.xml.bind.MarshalException e) { // see issue 649 xs.handleEvent(new ValidationEventImpl(ValidationEvent.WARNING, e.getMessage(), xs.getCurrentLocation(null) )); return ""; } } return cal.toXMLFormat(); }
public void serializeRoot(BeanT bean, XMLSerializer target) throws SAXException, IOException, XMLStreamException { if(tagName==null) { Class beanClass = bean.getClass(); String message; if (beanClass.isAnnotationPresent(XmlRootElement.class)) { message = Messages.UNABLE_TO_MARSHAL_UNBOUND_CLASS.format(beanClass.getName()); } else { message = Messages.UNABLE_TO_MARSHAL_NON_ELEMENT.format(beanClass.getName()); } target.reportError(new ValidationEventImpl(ValidationEvent.ERROR,message,null, null)); } else { target.startElement(tagName,bean); target.childAsSoleContent(bean,null); target.endElement(); if (retainPropertyInfo) { target.currentProperty.remove(); } } }
public void reportError( ValidationEvent ve ) throws SAXException { ValidationEventHandler handler; try { handler = marshaller.getEventHandler(); } catch( JAXBException e ) { throw new SAXException2(e); } if(!handler.handleEvent(ve)) { if(ve.getLinkedException() instanceof Exception) throw new SAXException2((Exception)ve.getLinkedException()); else throw new SAXException2(ve.getMessage()); } }
public String onIDREF( Object obj ) throws SAXException { String id; try { id = getIdFromObject(obj); } catch (JAXBException e) { reportError(null,e); return null; // recover by returning null } idReferencedObjects.add(obj); if(id==null) { reportError( new NotIdentifiableEventImpl( ValidationEvent.ERROR, Messages.NOT_IDENTIFIABLE.format(), new ValidationEventLocatorImpl(obj) ) ); } return id; }
void reconcileID() throws SAXException { // find objects that were not a part of the object graph idReferencedObjects.removeAll(objectsWithId); for( Object idObj : idReferencedObjects ) { try { String id = getIdFromObject(idObj); reportError( new NotIdentifiableEventImpl( ValidationEvent.ERROR, Messages.DANGLING_IDREF.format(id), new ValidationEventLocatorImpl(idObj) ) ); } catch (JAXBException e) { // this error should have been reported already. just ignore here. } } // clear the garbage idReferencedObjects.clear(); objectsWithId.clear(); }
/** * Reports an error to the user, and asks if s/he wants * to recover. If the canRecover flag is false, regardless * of the client instruction, an exception will be thrown. * * Only if the flag is true and the user wants to recover from an error, * the method returns normally. * * The thrown exception will be catched by the unmarshaller. */ public void handleEvent(ValidationEvent event, boolean canRecover ) throws SAXException { ValidationEventHandler eventHandler = parent.getEventHandler(); boolean recover = eventHandler.handleEvent(event); // if the handler says "abort", we will not return the object // from the unmarshaller.getResult() if(!recover) aborted = true; if( !canRecover || !recover ) throw new SAXParseException2( event.getMessage(), locator, new UnmarshalException( event.getMessage(), event.getLinkedException() ) ); }
public boolean handleEvent( ValidationEvent event ) { events.add(event); boolean retVal = true; switch( event.getSeverity() ) { case ValidationEvent.WARNING: retVal = true; // continue validation break; case ValidationEvent.ERROR: retVal = true; // continue validation break; case ValidationEvent.FATAL_ERROR: retVal = false; // halt validation break; default: _assert( false, Messages.format( Messages.UNRECOGNIZED_SEVERITY, event.getSeverity() ) ); break; } return retVal; }
@Nonnull private static javax.xml.bind.Marshaller marshallerFor(@Nonnull TestSuites element) { final javax.xml.bind.Marshaller marshaller; try { marshaller = JAXB_CONTEXT.createMarshaller(); marshaller.setProperty(JAXB_FORMATTED_OUTPUT, true); marshaller.setEventHandler(new ValidationEventHandler() { @Override public boolean handleEvent(ValidationEvent event) { return true; } }); } catch (final Exception e) { throw new RuntimeException("Could not create marshaller to marshall " + element + ".", e); } return marshaller; }
private static <T> ValidationEvent[] marshalToStream(T object, OutputStream out, boolean doFormatting, MarshallerType type, Class<?>... nestedClasses) throws JAXBException { ValidationEventCollector vec = new ValidationEventCollector(); final Marshaller marshaller; // switch(type) { // case JSON: // marshaller = createJsonMarshaller(object, doFormatting, nestedClasses); // break; // default: // marshaller = createXmlMarshaller(object, doFormatting, nestedClasses); // break; // } marshaller = createXmlMarshaller(object, doFormatting, nestedClasses); marshaller.setEventHandler(vec); marshaller.marshal(object, out); checkEvents(vec); return vec.getEvents(); }
private boolean validateParameters(ExpressiveDescriptor es, ArrayList<RenderingMethodParameterDescriptor> parameterdesc, List<ExpressiveParameter> parameters) { int errs = 0; for (RenderingMethodParameterDescriptor desc : parameterdesc) { ExpressiveParameter found = null; for (ExpressiveParameter param : parameters) { if (param.getName().equalsIgnoreCase(desc.getName())) { found = param; } } if (found == null & desc.isRequired()) { errs++; ((ValidationEventCollector) this.eventHandler).handleEvent(new SLDValidationEvent(ValidationEvent.ERROR, "Incomplete rendering method : the required expressive parameter " + desc.getName() + " is missing", ll.getLocation(es))); } } return errs == 0; }
public static File write(DynamicVRPREPModel dynamicVRPREPModel, Path outputPath) throws JAXBException, SAXException { outputPath.getParent().toFile().mkdirs(); InputStream stream = Instance.class.getResourceAsStream("/xsd/instance.xsd"); Source schemaSource = new StreamSource(stream); SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = sf.newSchema(schemaSource); JAXBContext jc = JAXBContext.newInstance(DynamicVRPREPModel.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setSchema(schema); marshaller.setEventHandler(new ValidationEventHandler() { public boolean handleEvent(ValidationEvent event) { System.err.println("MESSAGE: " + event.getMessage()); return true; } }); marshaller.marshal(dynamicVRPREPModel, outputPath.toFile()); return outputPath.toFile(); }
public File writeToFile(Path outputPath) throws JAXBException, SAXException { outputPath.getParent().toFile().mkdirs(); InputStream stream = Instance.class.getResourceAsStream("/xsd/instance.xsd"); Source schemaSource = new StreamSource(stream); SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = sf.newSchema(schemaSource); JAXBContext jc = JAXBContext.newInstance(ResultData.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setSchema(schema); marshaller.setEventHandler(new ValidationEventHandler() { public boolean handleEvent(ValidationEvent event) { System.err.println("MESSAGE: " + event.getMessage()); return true; } }); marshaller.marshal(this, outputPath.toFile()); return outputPath.toFile(); }
protected Unmarshaller createUnmarshaller() throws JAXBException, SAXException, FileNotFoundException, MalformedURLException { Unmarshaller unmarshaller = getContext().createUnmarshaller(); if (schema != null) { unmarshaller.setSchema(cachedSchema); unmarshaller.setEventHandler(new ValidationEventHandler() { public boolean handleEvent(ValidationEvent event) { // stop unmarshalling if the event is an ERROR or FATAL // ERROR return event.getSeverity() == ValidationEvent.WARNING; } }); } return unmarshaller; }
@Override public boolean handleEvent(ValidationEvent event) { try { System.out.println("\nEVENT"); System.out.println("SEVERITY: " + event.getSeverity()); System.out.println("MESSAGE: " + event.getMessage()); System.out.println("LINKED EXCEPTION: " + event.getLinkedException()); if (event.getLocator() != null) { System.out.println("LOCATOR"); System.out.println(" LINE NUMBER: " + event.getLocator().getLineNumber()); System.out.println(" COLUMN NUMBER: " + event.getLocator().getColumnNumber()); System.out.println(" OFFSET: " + event.getLocator().getOffset()); System.out.println(" OBJECT: " + event.getLocator().getObject()); System.out.println(" NODE: " + event.getLocator().getNode()); System.out.println(" URL: " + event.getLocator().getURL()); } } catch (Exception e) { e.printStackTrace(); } return true; }
public static void load() throws JAXBException { try { JAXBContext context = JAXBContext.newInstance(Settings.class); Unmarshaller um = context.createUnmarshaller(); um.setEventHandler(new ValidationEventHandler() { public boolean handleEvent(ValidationEvent event) { log.warn("Problem on loading settings.xml: " + event.getMessage()); return true; } }); instance = (Settings) um.unmarshal(FILE); instance.wgsGrid.checkValues(); instance.paperAtlas.checkValues(); SETTINGS_LAST_MODIFIED = FILE.lastModified(); // Settings 重新加载之后,必须更新语言资源 I18nUtils.updateLocalizedStringFormSettings(); } finally { Settings s = getInstance(); s.applyProxySettings(); } }
private Unmarshaller getUnmarshaller() throws JAXBException { JAXBContext jctx = JAXBContext.newInstance(WorkflowDefinition.class); Unmarshaller unmarshaller = jctx.createUnmarshaller(); SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); URL schemaUrl = WorkflowDefinition.class.getResource("workflow.xsd"); Schema schema = null; try { schema = sf.newSchema(new StreamSource(schemaUrl.toExternalForm())); } catch (SAXException ex) { throw new JAXBException("Missing schema workflow.xsd!", ex); } unmarshaller.setSchema(schema); ValidationEventCollector errors = new ValidationEventCollector() { @Override public boolean handleEvent(ValidationEvent event) { super.handleEvent(event); return true; } }; unmarshaller.setEventHandler(errors); return unmarshaller; }