private Unmarshaller createUnmarshaller() throws JAXBException { JAXBContext jc = JAXBContext.newInstance(_portfolioDocumentClass); Unmarshaller unmarshaller = jc.createUnmarshaller(); unmarshaller.setSchema(_schema); // Output parsing info to System.out unmarshaller.setEventHandler(new DefaultValidationEventHandler()); // The resolver allows us to differentiate between trades and positions // that have the same id. With this a trade and position can both have // id = 1 in the xml file, yet be resolved correctly based on context. // TODO can this be done without using a sun.internal class? //unmarshaller.setProperty(IDResolver.class.getName(), _idRefResolverFactory.create()); return unmarshaller; }
@Test public void unmarshalBean() throws JAXBException { Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); unmarshaller.setEventHandler(new DefaultValidationEventHandler()); Bean bean = (Bean) unmarshaller.unmarshal(getClass().getResourceAsStream("/bean.xml")); assertNotNull(bean); assertThat(bean.duration, equalTo(Duration.parse("P2DT3H4M"))); assertThat(bean.period, equalTo(Period.parse("P1Y2M3W4D"))); assertThat(bean.instant, equalTo(Instant.parse("2007-12-03T10:15:30.00Z"))); assertThat(bean.zonedDateTime, equalTo(ZonedDateTime.parse("2007-12-03T10:15:30+01:00[Europe/Paris]"))); assertThat(bean.localDate, equalTo(LocalDate.parse("2014-12-31+01:00",DateTimeFormatter.ISO_DATE))); assertThat(bean.localDate2, equalTo(LocalDate.parse("2014-12-31"))); assertThat(bean.localDateTime, equalTo(LocalDateTime.parse("2007-12-03T10:15:30"))); assertThat(bean.localTime, equalTo(LocalTime.parse("10:15:30"))); assertThat(bean.offsetDateTime, equalTo(OffsetDateTime.parse("2007-12-03T10:15:30+01:00"))); assertThat(bean.offsetTime, equalTo(OffsetTime.parse("10:15:30+01:00"))); assertThat(bean.month, equalTo(Month.FEBRUARY)); assertThat(bean.dayOfWeek, equalTo(DayOfWeek.WEDNESDAY)); assertThat(bean.year, equalTo(Year.of(-2014))); assertThat(bean.yearMonth, equalTo(YearMonth.of(2014, 12))); assertThat(bean.monthDay, equalTo(MonthDay.of(Month.DECEMBER, 3))); assertThat(bean.zoneOffset, equalTo(ZoneOffset.ofHoursMinutes(-12, 0))); assertThat(bean.zoneId, equalTo(ZoneId.of("America/New_York"))); }
/** * This method deserializes tm ec specification from an input stream. * * @author limg00n * @param inputStream to deserialize * @return tm specification * @throws Exception if deserialization fails */ public static TMFixedFieldListSpec deserializeTMFixedFieldListSpec(InputStream inputStream) throws Exception { TMFixedFieldListSpec spec = null; try { String JAXB_CONTEXT = "org.fosstrak.ale.xsd.ale.epcglobal"; // initialize jaxb context and unmarshaller JAXBContext context = JAXBContext.newInstance(JAXB_CONTEXT); Unmarshaller unmarshaller = context.createUnmarshaller(); unmarshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler()); spec = ((JAXBElement<TMFixedFieldListSpec>) unmarshaller.unmarshal(inputStream)).getValue(); } catch (JAXBException e) { e.printStackTrace(); } return spec; }
/** * This method deserializes tm ec specification from an input stream. * * @author limg00n * @param inputStream to deserialize * @return tm specification * @throws Exception if deserialization fails */ public static TMVariableFieldListSpec deserializeTMVariableFieldListSpec(InputStream inputStream) throws Exception { TMVariableFieldListSpec spec = null; try { String JAXB_CONTEXT = "org.fosstrak.ale.xsd.ale.epcglobal"; // initialize jaxb context and unmarshaller JAXBContext context = JAXBContext.newInstance(JAXB_CONTEXT); Unmarshaller unmarshaller = context.createUnmarshaller(); unmarshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler()); spec = ((JAXBElement<TMVariableFieldListSpec>) unmarshaller.unmarshal(inputStream)).getValue(); } catch (JAXBException e) { e.printStackTrace(); } return spec; }
@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); }
/** {@inheritDoc} */ @Override public void afterPropertiesSet() { try { m_context = JAXBContext.newInstance(LinkAdapterConfiguration.class, LinkPattern.class); m_marshaller = m_context.createMarshaller(); m_marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); m_marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new DefaultNamespacePrefixMapper("http://xmlns.opennms.org/xsd/config/map-link-adapter")); m_unmarshaller = m_context.createUnmarshaller(); m_unmarshaller.setSchema(null); ValidationEventHandler handler = new DefaultValidationEventHandler(); m_unmarshaller.setEventHandler(handler); } catch (Throwable e) { throw new IllegalStateException("Unable to create JAXB context.", e); } super.afterPropertiesSet(); }
@BeforeTest public void setup() throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(MutableObjectMetadata.class); marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); unmarshaller = jaxbContext.createUnmarshaller(); unmarshaller.setEventHandler(new DefaultValidationEventHandler()); }
/** Get a {@link Unmarshaller} instance with the default configuration. */ private Unmarshaller getUnmarshaller() throws JAXBException { Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); unmarshaller.setSchema(schema); // This handler was the default in JAXB 1.0. It fails on any exception thrown while // unmarshalling. In JAXB 2.0 some errors are considered recoverable and are ignored, which is // not what we want, so we have to set this explicitly. unmarshaller.setEventHandler(new DefaultValidationEventHandler()); return unmarshaller; }
public void loadConnector( InputStream is ) throws JAXBException { Unmarshaller unmarshaller = JAXBContext.newInstance(ConnectorWrapper.class).createUnmarshaller(); unmarshaller.setEventHandler(new DefaultValidationEventHandler()); Object obj = unmarshaller.unmarshal(is); ConnectorWrapper connectorWrapper = (ConnectorWrapper) obj; getConnectors().add(connectorWrapper.convert()); }
/** {@inheritDoc} */ @Override public void afterPropertiesSet() { try { m_context = JAXBContext.newInstance( EndPointTypeValidator.class, EndPointType.class, AndEndPointValidationExpression.class, OrEndPointValidationExpression.class, MatchingSnmpEndPointValidationExpression.class, PingEndPointValidationExpression.class ); m_marshaller = m_context.createMarshaller(); m_marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); m_marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new DefaultNamespacePrefixMapper("http://xmlns.opennms.org/xsd/config/endpoint-types")); m_unmarshaller = m_context.createUnmarshaller(); m_unmarshaller.setSchema(null); ValidationEventHandler handler = new DefaultValidationEventHandler(); m_unmarshaller.setEventHandler(handler); } catch (Throwable e) { throw new IllegalStateException("Unable to create JAXB context.", e); } super.afterPropertiesSet(); }
@Test(expected=UnmarshalException.class) public void readInvalidXML() throws Exception { File exampleFile = new File(ClassLoader.getSystemResource("invalid-sequence.xml").getFile()); ValidationEventHandler handler = new DefaultValidationEventHandler(); m_unmarshaller.setEventHandler(handler); MobileSequenceConfig s = (MobileSequenceConfig)m_unmarshaller.unmarshal(exampleFile); System.err.println("sequence = " + s); assertTransactionParentsSet(s); }
@Test(expected=UnmarshalException.class) public void readPoorlyFormedXML() throws Exception { File exampleFile = new File(ClassLoader.getSystemResource("poorly-formed-sequence.xml").getFile()); ValidationEventHandler handler = new DefaultValidationEventHandler(); m_unmarshaller.setEventHandler(handler); MobileSequenceConfig s = (MobileSequenceConfig)m_unmarshaller.unmarshal(exampleFile); System.err.println("sequence = " + s); assertTransactionParentsSet(s); }
@Test public void readAnotherSampleXML() throws Exception { File exampleFile = new File(ClassLoader.getSystemResource("alternate-ping-sequence.xml").getFile()); ValidationEventHandler handler = new DefaultValidationEventHandler(); m_unmarshaller.setEventHandler(handler); MobileSequenceConfig s = (MobileSequenceConfig)m_unmarshaller.unmarshal(exampleFile); System.err.println("sequence = " + s); assertTransactionParentsSet(s); }
@Test public void readXML() throws Exception { File exampleFile = new File(ClassLoader.getSystemResource("ussd-balance-sequence.xml").getFile()); ValidationEventHandler handler = new DefaultValidationEventHandler(); m_unmarshaller.setEventHandler(handler); MobileSequenceConfig s = (MobileSequenceConfig)m_unmarshaller.unmarshal(exampleFile); System.err.println("sequence = " + s); assertTransactionParentsSet(s); }
public void setEventHandler( ValidationEventHandler handler ) { if( handler == null ) { eventHandler = new DefaultValidationEventHandler(); } else { eventHandler = handler; } }
/** * Imports an OrganisationContainers form an XML file. * @throws JAXBException * @throws JAXBException */ private OrganisationContainers _import(InputStream is) throws JAXBException { OrganisationContainers orgCs = null; //Retrieving the JAXBContext JAXBContext context = JAXBUtils.getInstance().getJAXBContextForExport(); //Creating the Unmarshaller Unmarshaller um = context.createUnmarshaller(); um.setEventHandler(new DefaultValidationEventHandler()); orgCs = (OrganisationContainers) um.unmarshal(is); return orgCs; }
private static ProbeDescriptor load(File file) { try { JAXBContext jc = JAXBContext.newInstance("com.sun.btrace.annotations:com.sun.btrace.runtime"); if (Main.isDebug()) Main.debugPrint("reading " + file); Unmarshaller u = jc.createUnmarshaller(); u.setEventHandler(new DefaultValidationEventHandler()); return (ProbeDescriptor)u.unmarshal(file); } catch (JAXBException exp) { if (Main.isDebug()) Main.debugPrint(exp); return null; } }
protected T unmarshall(File filename, InputSource xml, HashMap<String,String> extra_overrides) throws Exception { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setXIncludeAware(true); spf.setNamespaceAware(true); spf.setFeature("http://apache.org/xml/features/xinclude/fixup-base-uris", false); StreamSource schemaSource = new StreamSource(this.getClass().getResourceAsStream("/sdrun.xsd")); SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(schemaSource); spf.setSchema(schema); NamespaceFiller filter = new NamespaceFiller(this.propertyOverrides(), extra_overrides); XMLReader xr = spf.newSAXParser().getXMLReader(); filter.setParent(xr); Unmarshaller u = jc.createUnmarshaller(); UnmarshallerHandler uh = u.getUnmarshallerHandler(); u.setSchema(schema); u.setEventHandler(new DefaultValidationEventHandler()); filter.setContentHandler(uh); try { filter.parse(xml); } catch(SAXParseException e) { filter.log_error(e); throw new XMLUnmarshallingFailure(); } T result = (T) uh.getResult(); if (result == null || filter.failed()) throw new XMLUnmarshallingFailure(); if (filter.conversion_hint) log.log(Logging.NOTICE, "Use the following command to convert old style files to the new format:\n" + "sed '1d; 2i <?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\\n<SDRun xmlns:xi=\"http://www.w3.org/2001/XInclude\" xmlns=\"{}\">\n" + "s#<(reactionScheme|morphology|stimulation|initialConditions|outputScheme)File>\\s*(\\w+)\\s*</.*>#<xi:include href=\"\\2.xml\" />#' -r -i.bak \"{}\"", NEURORD_NS, filename != null ? filename : "..."); return result; }