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 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()); } }
/** * 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() ) ); }
@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; }
static UserCredentialsList loadCredentialsList(File credentialsFile, ValidationEventHandler validationEventHandler) throws Exception { if (credentialsFile.exists()) { final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); final Schema schema = schemaFactory.newSchema(UserCredentialsList.class.getResource(CREDENTIALS_XSD)); final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller(); unmarshaller.setSchema(schema); unmarshaller.setEventHandler(validationEventHandler); final JAXBElement<UserCredentialsList> element = unmarshaller.unmarshal(new StreamSource(credentialsFile), UserCredentialsList.class); UserCredentialsList credentialsList = element.getValue(); return credentialsList; } else { final String notFoundMessage = "The credentials configuration file was not found at: " + credentialsFile.getAbsolutePath(); throw new FileNotFoundException(notFoundMessage); } }
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; }
/** * creates a unmarshaller on pooled JAXBContext instances. * @param jaxbContext the context on which to create a unmarshaller. * @param validationEventHandler validation event handler. * @return the unmarshaller. * @throws JAXBException when unable to create the unmarshaller. */ private static Unmarshaller getUnmarshaller(String jaxbContext, ValidationEventHandler validationEventHandler) throws JAXBException { JAXBContext context = null; synchronized (s_context) { context = s_context.get(jaxbContext); if (null == context) { context = JAXBContext.newInstance(jaxbContext); s_context.put(jaxbContext, context); } } Unmarshaller unmarshaller = null; synchronized (context) { unmarshaller = context.createUnmarshaller(); } unmarshaller.setEventHandler(validationEventHandler); return unmarshaller; }
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(); } }
public ProcessModel unmarshalProcessModel(File procSchmInFile) throws JAXBException, PropertyException, FileNotFoundException, IOException { String pkgName = ProcessModel.class.getCanonicalName().toString(); pkgName = pkgName.substring(0, pkgName.lastIndexOf('.')); JAXBContext jaxbCtx = JAXBContext.newInstance(pkgName); Unmarshaller unmarsh = jaxbCtx.createUnmarshaller(); unmarsh.setEventHandler( new ValidationEventHandler() { public boolean handleEvent(ValidationEvent event) { throw new RuntimeException(event.getMessage(), event.getLinkedException()); } }); ProcessModel proMod = (ProcessModel) unmarsh.unmarshal(procSchmInFile); MetaConstraintUtils.createHierarchicalLinks(proMod.getAllConstraints()); return proMod; }
/** * Converts the given xml into the corresponding T object. * * @param xml * @param context * @param validationSchema * @param validationEventHandler * @return */ @SuppressWarnings("unchecked") public static <T> T convertTo(byte[] xml, JAXBContext context, Schema validationSchema, ValidationEventHandler validationEventHandler) { try (ByteArrayInputStream bis = new ByteArrayInputStream(xml);) { Unmarshaller unmarshaller = context.createUnmarshaller(); if (validationSchema != null) unmarshaller.setSchema(validationSchema); if (validationEventHandler != null) unmarshaller.setEventHandler(validationEventHandler); return (T) unmarshaller.unmarshal(bis); } catch (JAXBException | IOException e) { LOG.error("Failed to unmarshall ", e); return null; } }
/** * Converts the given xml object into the corresponding a string * representation. * * @param xmlObject * @param context * @param validationSchema * @param validationEventHandler * @return */ public static <T> String convertToString(T xmlObject, JAXBContext context, Schema validationSchema, ValidationEventHandler validationEventHandler) { try (ByteArrayOutputStream baos = new ByteArrayOutputStream(1024)) { Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); if (validationSchema != null) marshaller.setSchema(validationSchema); if (validationEventHandler != null) marshaller.setEventHandler(validationEventHandler); marshaller.marshal(xmlObject, baos); return baos.toString().replaceAll(XMLNS_REGEXP, "");// FIXME remove // xmlns attr } catch (JAXBException | IOException e) { LOG.error("Failed to unmarshall ", e); return null; } }
public void setProperty(String prop, Object value) { if (prop.equals(JAXBDataBinding.UNWRAP_JAXB_ELEMENT)) { unwrapJAXBElement = Boolean.TRUE.equals(value); } else if (prop.equals(org.apache.cxf.message.Message.class.getName())) { org.apache.cxf.message.Message m = (org.apache.cxf.message.Message)value; veventHandler = (ValidationEventHandler)m.getContextualProperty("jaxb-validation-event-handler"); if (veventHandler == null) { veventHandler = databinding.getValidationEventHandler(); } setEventHandler = MessageUtils.getContextualBoolean(m, "set-jaxb-validation-event-handler", true); Object unwrapProperty = m.get(JAXBDataBinding.UNWRAP_JAXB_ELEMENT); if (unwrapProperty == null) { unwrapProperty = m.getExchange().get(JAXBDataBinding.UNWRAP_JAXB_ELEMENT); } if (unwrapProperty != null) { unwrapJAXBElement = Boolean.TRUE.equals(unwrapProperty); } } }
/** * Create an instance of {@link IValidationEventHandler} that invokes both * passed event handlers. * * @param aOne * The first event handler. May be <code>null</code>. * @param aOther * The second event handler. May be <code>null</code>. * @return Never <code>null</code>. * @since 8.6.0 */ @Nonnull static IValidationEventHandler and (@Nullable final ValidationEventHandler aOne, @Nullable final ValidationEventHandler aOther) { if (aOne != null) { if (aOther != null) return x -> { if (!aOne.handleEvent (x)) { // We should not continue return false; } return aOther.handleEvent (x); }; return x -> aOne.handleEvent (x); } if (aOther != null) return x -> aOther.handleEvent (x); return x -> true; }
/** * @param aClassLoader * The class loader to be used for XML schema resolving. May be * <code>null</code>. * @return The JAXB unmarshaller to use. Never <code>null</code>. * @throws JAXBException * In case the creation fails. */ @Nonnull private Unmarshaller _createUnmarshaller (@Nullable final ClassLoader aClassLoader) throws JAXBException { final Package aPackage = m_aType.getPackage (); final JAXBContext aJAXBContext = m_bUseContextCache ? JAXBContextCache.getInstance ().getFromCache (aPackage, aClassLoader) : JAXBContext.newInstance (aPackage.getName (), aClassLoader); // create an Unmarshaller final Unmarshaller aUnmarshaller = aJAXBContext.createUnmarshaller (); if (m_aVEHFactory != null) { // Create and set a new event handler final ValidationEventHandler aEvHdl = m_aVEHFactory.apply (aUnmarshaller.getEventHandler ()); if (aEvHdl != null) aUnmarshaller.setEventHandler (aEvHdl); } // Set XSD (if any) final Schema aValidationSchema = createValidationSchema (); if (aValidationSchema != null) aUnmarshaller.setSchema (aValidationSchema); return aUnmarshaller; }
@Test(expected=Exception.class) @Ignore("I can't find a way to get JAXB to set minOccurs=1 with annotations...") public void testRequireLinkTag() throws Exception { ValidationEventHandler handler = new DefaultValidationEventHandler(); m_unmarshaller.setEventHandler(handler); String testXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + "<link-adapter-configuration xmlns=\"http://xmlns.opennms.org/xsd/config/map-link-adapter\">\n" + " <for match=\"foo-(.*?)-baz\">\n" + " </for>\n" + " <for match=\"before-(.*?)-after\">\n" + " <link>middle-was-$1</link>\n" + " </for>\n" + "</link-adapter-configuration>"; StringReader xmlReader = new StringReader(testXml); LinkAdapterConfiguration lac = (LinkAdapterConfiguration)m_unmarshaller.unmarshal(xmlReader); System.err.println("sequence = " + lac); }
public static <T> Object unmarshal(final Class<T> type, final InputStream in) throws ParserConfigurationException, SAXException, JAXBException { final InputSource inputSource = new InputSource(in); final SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); final JAXBContext ctx = JAXBContextFactory.newInstance(type); final Unmarshaller unmarshaller = ctx.createUnmarshaller(); unmarshaller.setEventHandler(new ValidationEventHandler() { public boolean handleEvent(final ValidationEvent validationEvent) { System.out.println(validationEvent); return false; } }); return unmarshaller.unmarshal(inputSource); }
public void reportError( ValidationEvent ve ) throws AbortSerializationException { ValidationEventHandler handler; try { handler = owner.getEventHandler(); } catch( JAXBException e ) { throw new AbortSerializationException(e); } if(!handler.handleEvent(ve)) { if(ve.getLinkedException() instanceof Exception) throw new AbortSerializationException((Exception)ve.getLinkedException()); else throw new AbortSerializationException(ve.getMessage()); } }
public void handleEvent(ValidationEvent event, boolean canRecover ) throws SAXException { ValidationEventHandler eventHandler; try { eventHandler = parent.getEventHandler(); } catch( JAXBException e ) { // impossible. throw new JAXBAssertionError(); } 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 SAXException( new UnmarshalException( event.getMessage(), event.getLinkedException() ) ); }
/** * XsdEventHandler throws exception on every event. * @throws Exception If something goes wrong */ @Test public void throwsExceptionOnEveryEvent() throws Exception { final ValidationEventLocator locator = Mockito.mock(ValidationEventLocator.class); Mockito.doReturn(1).when(locator).getLineNumber(); Mockito.doReturn(1).when(locator).getColumnNumber(); Mockito.doReturn(new URL("http://localhost")).when(locator).getURL(); final ValidationEvent event = Mockito.mock(ValidationEvent.class); Mockito.doReturn("msg").when(event).getMessage(); Mockito.doReturn(locator).when(event).getLocator(); final ValidationEventHandler handler = new XsdEventHandler(); MatcherAssert.assertThat( handler.handleEvent(event), Matchers.is(false) ); }
public FFprobeJAXB() throws JAXBException, ParserConfigurationException { /** * Load JAXB classes */ JAXBContext jc = JAXBContext.newInstance("org.ffmpeg.ffprobe"); unmarshaller = jc.createUnmarshaller(); /** * Prepare an error catcher if trouble are catched during import. */ unmarshaller.setEventHandler((ValidationEventHandler) e -> { ValidationEventLocator localtor = e.getLocator(); Loggers.Transcode.warn("FFprobe XML validation: " + e.getMessage() + " [s" + e.getSeverity() + "] at line " + localtor.getLineNumber() + ", column " + localtor.getColumnNumber() + " offset " + localtor.getOffset() + " node: " + localtor.getNode() + ", object " + localtor.getObject()); return true; }); /** * Load XML engine */ DocumentBuilderFactory xmlDocumentBuilderFactory = DocumentBuilderFactory.newInstance(); xml_document_builder = xmlDocumentBuilderFactory.newDocumentBuilder(); xml_document_builder.setErrorHandler(null); }