@Override public JAXBIntrospector createJAXBIntrospector() { return new JAXBIntrospector() { public boolean isElement(Object object) { return getElementName(object)!=null; } public QName getElementName(Object jaxbElement) { try { return JAXBContextImpl.this.getElementName(jaxbElement); } catch (JAXBException e) { return null; } } }; }
@Override protected void execute(ExecutionContext ec) { try { // import object graph from XML // create and persist equivalent objects via menus. InputStream is = this.getClass().getResourceAsStream("/au/com/scds/agric/fixture/dom/producer.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); jaxbUnmarshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler()); Producer pr = (Producer) JAXBIntrospector.getValue(jaxbUnmarshaller.unmarshal(is)); producer = wrap(producerMenu).create(pr.getName()); wrap(producer).setName(pr.getName()); for(ProductLine _line : pr.getProductLines()){ ProductType type = wrap(productTypeMenu).createProductType(_line.getProductType().getName()); ProductLine line = wrap(productLineMenu).createProductLine(_line.getName(), type); } } catch (JAXBException e) { e.printStackTrace(); } }
/** * Unmarshal a given SOAP xml stream and return the content of the SOAP body * @throws IOException,SAXException */ public Object unmarshal(Exchange exchange, InputStream stream) throws IOException, SAXException { checkElementNameStrategy(exchange); String soapAction = getSoapActionFromExchange(exchange); // Determine the method name for an eventual BeanProcessor in the route if (soapAction != null && elementNameStrategy instanceof ServiceInterfaceStrategy) { ServiceInterfaceStrategy strategy = (ServiceInterfaceStrategy) elementNameStrategy; String methodName = strategy.getMethodForSoapAction(soapAction); exchange.getOut().setHeader(Exchange.BEAN_METHOD_NAME, methodName); } // Store soap action for an eventual later marshal step. // This is necessary as the soap action in the message may get lost on the way if (soapAction != null) { exchange.setProperty(Exchange.SOAP_ACTION, soapAction); } Object unmarshalledObject = super.unmarshal(exchange, stream); Object rootObject = JAXBIntrospector.getValue(unmarshalledObject); return adapter.doUnmarshal(exchange, stream, rootObject); }
@Test @SuppressWarnings("unchecked") public void test() throws JAXBException { File euLOTL = new File("src/test/resources/tl-mp.xml"); JAXBContext jc = JAXBContext.newInstance("eu.europa.esig.jaxb.tsl"); Unmarshaller unmarshaller = jc.createUnmarshaller(); JAXBElement<TrustStatusListType> unmarshalled = (JAXBElement<TrustStatusListType>) unmarshaller.unmarshal(euLOTL); assertNotNull(unmarshalled); TrustStatusListType euLOTLObj = unmarshalled.getValue(); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); JAXBIntrospector introspector = jc.createJAXBIntrospector(); if (null == introspector.getElementName(euLOTLObj)) { JAXBElement jaxbElement = new JAXBElement(new QName("ROOT"), Object.class, euLOTLObj); ByteArrayOutputStream os = new ByteArrayOutputStream(); marshaller.marshal(jaxbElement, os); assertTrue(os.toByteArray() != null && os.toByteArray().length > 0); } }
/** * get JAXB Introspector * * @param context JAXBContext * @return JAXBIntrospector * @throws JAXBException */ public static JAXBIntrospector getJAXBIntrospector(final JAXBContext context) throws JAXBException { JAXBIntrospector i = null; if (!ENABLE_INTROSPECTION_POOLING) { if (log.isDebugEnabled()) { log.debug("JAXBIntrospector created [no pooling]"); } i = internalCreateIntrospector(context); } else { i = ipool.get(context); if (i == null) { if (log.isDebugEnabled()) { log.debug("JAXBIntrospector created [not in pool]"); } i = internalCreateIntrospector(context); } else { if (log.isDebugEnabled()) { log.debug("JAXBIntrospector obtained [from pool]"); } } } return i; }
private QName discoverQNameFromJaxb(Class<?> classType) { QName qName = null; try { final JAXBIntrospector jaxbIntrospector = JAXBContext.newInstance(classType).createJAXBIntrospector(); qName = jaxbIntrospector.getElementName(classType.getConstructor().newInstance()); } catch (Exception e) { // Add e to the logger message because JAXB Exceptions has a lot of information in the toString(). // and some loggers implementations just print the getMessage(); logger.warn("Cannot discover QName from JAXB annotations for class: " + classType.getName() + ". Preparing generic QName." + e, e); } if (qName == null) { // Could be null if getElementName returned null, or a exception was thrown. return EMPTY_Q_NAME; } return qName; }
@Override protected void execute(ExecutionContext ec) { try { // import object graph from XML // create and persist equivalent objects via menus. InputStream is = this.getClass().getResourceAsStream("/au/com/scds/agric/fixture/dom/formulations.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); jaxbUnmarshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler()); Formulations _formulations = (Formulations) JAXBIntrospector.getValue(jaxbUnmarshaller.unmarshal(is)); for (Formulation _f : _formulations.getFormulation()) { formulation = wrap(formulationMenu).createFormulation(_f.getName()); formulation.setDescription(_f.getDescription()); FormulationMethod _m = _f.getMethod(); FormulationMethod formulationMethod = wrap(formulationMenu).createFormulationMethod(_m.getName()); formulationMethod.setDescription(_m.getDescription()); formulation.setMethod(formulationMethod); FormulationMixins.FormulationMethod_addStep addStep = mixin( FormulationMixins.FormulationMethod_addStep.class, formulationMethod); for (FormulationStep _s : _m.getSteps()) { wrap(addStep).$$(_s.getDescription(), _s.getOrder()); } FormulationMixins.Formulation_addComponentIngredient addComponentIngredient = mixin( FormulationMixins.Formulation_addComponentIngredient.class, formulation); for (FormulationComponent _c : _f.getComponents()) { Ingredient _i = _c.getIngredient(); Ingredient ingredient = wrap(ingredientMenu).createIngredient(_i.getName(), _i.getDescription()); // ingredient supply covered in batches fixture SiUnit u = wrap(unitRepo).createSiUnit(_c.getUnit().getName()); wrap(addComponentIngredient).$$(ingredient, _c.getQuantity(), u); } } } catch (JAXBException e) { e.printStackTrace(); } }
private void parsePayload(XMLStreamReader streamReader, ModelBuilder builder) throws JAXBException { final Unmarshaller unmarshaller = context.createUnmarshaller(); final Object result = unmarshaller.unmarshal(streamReader); final Object value = JAXBIntrospector.getValue(result); builder.add(value); }
/** * @param pomFile * @return * @throws JAXBException */ public static Model unmarshallPomFile(File pomFile) throws JAXBException { JAXBContext context = JAXBContext.newInstance(Model.class); Unmarshaller unmarshaller = context.createUnmarshaller(); return (Model) JAXBIntrospector.getValue(unmarshaller.unmarshal(pomFile)); }
@Override public Object doUnmarshal(Exchange exchange, InputStream stream, Object rootObject) throws IOException { if (rootObject.getClass() != Envelope.class) { throw new RuntimeCamelException("Expected Soap Envelope but got " + rootObject.getClass()); } Envelope envelope = (Envelope) rootObject; Header header = envelope.getHeader(); if (header != null) { List<Object> returnHeaders; List<Object> anyHeaderElements = envelope.getHeader().getAny(); if (null != anyHeaderElements && !(getDataFormat().isIgnoreUnmarshalledHeaders())) { if (getDataFormat().isIgnoreJAXBElement()) { returnHeaders = new ArrayList<Object>(); for (Object headerEl : anyHeaderElements) { returnHeaders.add(JAXBIntrospector.getValue(headerEl)); } } else { returnHeaders = anyHeaderElements; } exchange.getOut().setHeader(SoapJaxbDataFormat.SOAP_UNMARSHALLED_HEADER_LIST, returnHeaders); } } List<Object> anyElement = envelope.getBody().getAny(); if (anyElement.size() == 0) { // No parameter so return null return null; } Object payloadEl = anyElement.get(0); Object payload = JAXBIntrospector.getValue(payloadEl); if (payload instanceof Fault) { Exception exception = createExceptionFromFault((Fault) payload); exchange.setException(exception); return null; } else { return getDataFormat().isIgnoreJAXBElement() ? payload : payloadEl; } }
protected <V> V getElemValueByName(List<?> list, String name, Class<V> clazz) { JAXBIntrospector introspector = context.createJAXBIntrospector(); return list.stream() .filter(introspector::isElement) .filter(obj -> Objects.equals(introspector.getElementName(obj).getLocalPart(), name)) .map(JAXBIntrospector::getValue) .filter(clazz::isInstance) .map(clazz::cast) .findFirst() .orElse(null); }
/** * Parses the given XML to a Java model (JAXB unmarshalling). * Performs XSD validation. * * @param xml an input XML content * @param xmlPath a path to the input xml * @param xsds a full path to all XSDs corresponding to the given XML * @param pkg a package containing the corresponding Java model classes. * @param resultClass a corresponding Java model class. * @param <T> a corresponding Java model class. * @return a corresponding Java model instance. * @throws XmlParsingException if input is not a valid XML or it doesn't pass XSD validation */ public static <T> T parse(InputStream xml, String xmlPath, String[] xsds, String pkg, Class<T> resultClass) throws XmlParsingException { try { // 1. create JAXB unmarshaller JAXBContext jaxbContext = JAXBContext.newInstance(pkg); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); UnmarshallerHandler unmarshallerHandler = unmarshaller.getUnmarshallerHandler(); // 2. create a an error and content handler (which is also a bridge between a sax parser and unmarshaller) XmlParsingHandler contentErrorHandler = new XmlParsingHandlerWrapper(unmarshallerHandler, xmlPath); // 3. do parse doParse(xml, xsds, contentErrorHandler); // 4. get unmarshall result Object result = JAXBIntrospector.getValue(unmarshallerHandler.getResult()); if (!resultClass.isInstance(result)) { throw new RuntimeException(String.format("A root element in '%s' must be an instance of %s type.", xmlPath, resultClass.getSimpleName())); } //noinspection unchecked return (T) result; } catch (JAXBException e) { throw new RuntimeException(e); } }
@Test public void testSchemaCompleteness() throws JAXBException, DatatypeConfigurationException { JAXBIntrospector info = JAXBContext.newInstance(JobUsageRecord.class).createJAXBIntrospector(); Assert.assertTrue(info.isElement(new Charge())); Assert.assertTrue(info.isElement(new CpuDuration())); Assert.assertTrue(info.isElement(new Disk())); Assert.assertTrue(info.isElement(new EndTime())); Assert.assertTrue(info.isElement(new Host())); Assert.assertTrue(info.isElement(new JobIdentity())); Assert.assertTrue(info.isElement(new JobName())); Assert.assertTrue(info.isElement(new JobUsageRecord())); Assert.assertTrue(info.isElement(new MachineName())); Assert.assertTrue(info.isElement(new Memory())); Assert.assertTrue(info.isElement(new Network())); Assert.assertTrue(info.isElement(new NodeCount())); Assert.assertTrue(info.isElement(new PhaseResource())); Assert.assertTrue(info.isElement(new Processors())); Assert.assertTrue(info.isElement(new ProjectName())); Assert.assertTrue(info.isElement(new Queue())); Assert.assertTrue(info.isElement(new RecordIdentity())); Assert.assertTrue(info.isElement(new ServiceLevel())); Assert.assertTrue(info.isElement(new StartTime())); Assert.assertTrue(info.isElement(new Status())); Assert.assertTrue(info.isElement(new SubmitHost())); Assert.assertTrue(info.isElement(new Swap())); Assert.assertTrue(info.isElement(new TimeDuration())); Assert.assertTrue(info.isElement(new TimeInstant())); Assert.assertTrue(info.isElement(new UserIdentity())); Assert.assertTrue(info.isElement(new VolumeResource())); Assert.assertTrue(info.isElement(new WallDuration())); }
public XmlBinder(final Class<?>[] supportedClasses) { JAXBContext context2 = null; JAXBIntrospector introspector2 = null; try { // context context2 = newInstance(supportedClasses, new HashMap<>()); // introspector introspector2 = context2.createJAXBIntrospector(); } catch (Exception e) { LOGGER.error("Failed to configure XML binding", e); } context = context2; introspector = introspector2; }
/** * TODO verify {@link ResourceType} * * @return the {@link InputStream} unmarshalled using the specified * {@link XmlContext} into an object of the specified * {@code resultType} * @throws JAXBException */ @SuppressWarnings("unchecked") public <T> T toXML(final XmlContext<?> context, final Class<T> resultType) { try { return (T) JAXBIntrospector.getValue(context.getUnmarshaller() .unmarshal(new StreamSource(getStream()), resultType)); } catch (final JAXBException e) { throw CoalaExceptionFactory.UNMARSHAL_FAILED.createRuntime(e, "<stream>", resultType); } }
/** * Release JAXBIntrospector Do not call this method if an exception occurred while using the * JAXBIntrospector. We object my be in an invalid state. * * @param context JAXBContext * @param introspector JAXBIntrospector */ public static void releaseJAXBIntrospector(JAXBContext context, JAXBIntrospector introspector) { if (log.isDebugEnabled()) { log.debug("JAXBIntrospector placed back into pool"); } if (ENABLE_INTROSPECTION_POOLING) { ipool.put(context, introspector); } }
@Override protected void execute(ExecutionContext ec) { try { // import object graph from XML // create and persist equivalent objects via menus. InputStream is = this.getClass().getResourceAsStream("/au/com/scds/agric/fixture/dom/sales.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); jaxbUnmarshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler()); Sales _sales = (Sales) JAXBIntrospector.getValue(jaxbUnmarshaller.unmarshal(is)); for(Sale _sale : _sales.getSale()){ Client client = wrap(clientMenu).createClient("Client with Sales"); sale = wrap(salesMenu).createSale(client); SalesMixins.Sale_addSaleLine sale_addSaleLine = mixin(SalesMixins.Sale_addSaleLine.class, sale); for(SaleLine _line : _sale.getLines()){ ProductType productType = wrap(productTypeMenu).createProductType(_line.getProductLine().getProductType().getName()); ProductLine productLine = wrap(productLineMenu).createProductLine(_line.getProductLine().getName(), productType); SaleLine line = wrap(sale_addSaleLine).$$(productLine); for(ProductPack _pack : _line.getProductPacks()){ ProductPack pack = wrap(productPackRepo).createProductPack(productLine); for(ProductItem _item : _pack.getProductItems()){ ProductItem item = wrap(productItemRepo).createProductItem(productLine, _item.getSerialNumber()); pack.getProductItems().add(item); } line.getProductPacks().add(pack); } } if(_sale.getInvoice() != null){ Invoice invoice = wrap(invoicesMenu).createInvoice(client); sale.setInvoice(invoice); } if(_sale.getReceipt() != null){ Receipt receipt = wrap(receiptsMenu).createReceipt(client); sale.setReceipt(receipt); } } ec.addResult(this, sale); } catch (JAXBException e) { e.printStackTrace(); } }
public static CPluginCustomization marshal(final JAXBContext context, final QName name, final Object object) { try { final JAXBIntrospector introspector = context.createJAXBIntrospector(); final Object value; { if (introspector.isElement(object)) { value = object; } else { @SuppressWarnings("unchecked") final JAXBElement jaxbElement = new JAXBElement(name, object.getClass(), object); value = jaxbElement; } } final Marshaller marshaller = context.createMarshaller(); final DOMResult result = new DOMResult(); marshaller.marshal(value, result); final Node node = result.getNode(); final Element element; if (node instanceof Element) { element = (Element) node; } else if (node instanceof Document) { element = ((Document) node).getDocumentElement(); } else { element = null; throw new IllegalArgumentException("Could not marhsall object into an element."); } return new CPluginCustomization(element, null); } catch (JAXBException jaxbex) { throw new IllegalArgumentException("Could not marhsall object into an element.", jaxbex); } }
/** * Create a Block representing an JAXB and simulate a * normal Dispatch<JAXB> flow * @throws Exception */ public void testJAXBOutflow() throws Exception { // Get the BlockFactory JAXBBlockFactory f = (JAXBBlockFactory) FactoryRegistry.getFactory(JAXBBlockFactory.class); // Create a jaxb object ObjectFactory factory = new ObjectFactory(); EchoString jaxb = factory.createEchoString(); jaxb.setInput("Hello World"); JAXBBlockContext context = new JAXBBlockContext(EchoString.class.getPackage().getName()); JAXBIntrospector jbi = JAXBUtils.getJAXBIntrospector(context.getJAXBContext()); QName expectedQName = jbi.getElementName(jaxb); // Create a Block using the sample string as the content. This simulates // what occurs on the outbound JAX-WS dispatch<JAXB> client Block block = f.createFrom(jaxb, context, null); // JAXB objects set the qname from their internal data assertTrue(block.isQNameAvailable()); // Assume that we need to find the QName (perhaps to identify the operation and // determine if handlers are installed). This is not very perfomant since // it causes an underlying parse of the String...but we need to support this. QName qName = block.getQName(); assertTrue("Expected: " + expectedQName + " but found: " + qName, expectedQName.equals(qName)); // Assuming no handlers are installed, the next thing that will happen // is a XMLStreamReader will be requested...to go to OM. At this point the // block should be consumed. XMLStreamReader reader = block.getXMLStreamReader(true); // The block should be consumed assertTrue(block.isConsumed()); // To check that the output is correct, get the String contents of the // reader Reader2Writer r2w = new Reader2Writer(reader); String newText = r2w.getAsString(); assertTrue(newText.contains("Hello World")); assertTrue(newText.contains("echoString")); }
/** * Create a Block representing an JAXB and simulate a * slightly more complicated Dispatch<JAXB> flow * @throws Exception */ public void testJAXBOutflow2() throws Exception { // Get the BlockFactory JAXBBlockFactory f = (JAXBBlockFactory) FactoryRegistry.getFactory(JAXBBlockFactory.class); // Create a jaxb object ObjectFactory factory = new ObjectFactory(); EchoString jaxb = factory.createEchoString(); jaxb.setInput("Hello World"); JAXBBlockContext context = new JAXBBlockContext(EchoString.class.getPackage().getName()); JAXBIntrospector jbi = JAXBUtils.getJAXBIntrospector(context.getJAXBContext()); QName expectedQName = jbi.getElementName(jaxb); // Create a Block using the sample string as the content. This simulates // what occurs with an outbound JAX-WS JAXB parameter Block block = f.createFrom(jaxb, context, expectedQName); // We did pass in a qname, so the following should return false assertTrue(block.isQNameAvailable()); // Assume that we need to find the QName (perhaps to identify the operation and // determine if handlers are installed). This is not very perfomant since // it causes an underlying parse of the String...but we need to support this. QName qName = block.getQName(); assertTrue("Expected: " + expectedQName + " but found: " + qName, expectedQName.equals(qName)); // Assuming no handlers are installed, the next thing that will happen // is a XMLStreamReader will be requested...to go to OM. At this point the // block should be consumed. XMLStreamReader reader = block.getXMLStreamReader(true); // The block should be consumed assertTrue(block.isConsumed()); // To check that the output is correct, get the String contents of the // reader Reader2Writer r2w = new Reader2Writer(reader); String newText = r2w.getAsString(); assertTrue(newText.contains("Hello World")); assertTrue(newText.contains("echoString")); }
/** * Create a Block representing an JAXB and simulate a * normal Dispatch<JAXB> input flow * @throws Exception */ public void testJAXBInflow2() throws Exception { // Get the BlockFactory JAXBBlockFactory f = (JAXBBlockFactory) FactoryRegistry.getFactory(JAXBBlockFactory.class); // Create a jaxb object ObjectFactory factory = new ObjectFactory(); EchoString jaxb = factory.createEchoString(); jaxb.setInput("Hello World"); JAXBBlockContext context = new JAXBBlockContext(EchoString.class.getPackage().getName()); JAXBIntrospector jbi = JAXBUtils.getJAXBIntrospector(context.getJAXBContext()); QName expectedQName = jbi.getElementName(jaxb); // On inbound, there will already be a XMLStreamReader (probably from OM) // which represents the message. We will simulate this with inflow. StringWriter sw = new StringWriter(); XMLStreamWriter writer = outputFactory.createXMLStreamWriter(sw); Marshaller marshaller = JAXBUtils.getJAXBMarshaller(context.getJAXBContext()); marshaller.marshal(jaxb, writer); JAXBUtils.releaseJAXBMarshaller(context.getJAXBContext(), marshaller); writer.flush(); sw.flush(); StringReader sr = new StringReader(sw.toString()); XMLStreamReader inflow = inputFactory.createXMLStreamReader(sr); // Create a Block from the inflow. Block block = f.createFrom(inflow, context, null); // Assume that we need to find the QName (perhaps to identify the operation and // determine if handlers are installed). This is not very perfomant since // it causes an underlying parse of the String...but we need to support this. QName qName = block.getQName(); assertTrue("Expected: " + expectedQName + " but found: " + qName, expectedQName.equals(qName)); // Assuming no handlers are installed, the next thing that will happen // is the proxy code will ask for the business object. Object bo = block.getBusinessObject(true); assertTrue(bo instanceof EchoString); // The block should be consumed assertTrue(block.isConsumed()); // Check for accuracy assertTrue("Unexpected:" + ((EchoString)bo).getInput(), ((EchoString)bo).getInput().equals(jaxb.getInput())); }
/** * Create a Block representing an JAXB and simulate a * normal Dispatch<JAXB> input flow * @throws Exception */ public void testJAXBInflow3() throws Exception { // Get the BlockFactory JAXBBlockFactory f = (JAXBBlockFactory) FactoryRegistry.getFactory(JAXBBlockFactory.class); // Create a jaxb object ObjectFactory factory = new ObjectFactory(); EchoString jaxb = factory.createEchoString(); jaxb.setInput("Hello World"); JAXBBlockContext context = new JAXBBlockContext(EchoString.class.getPackage().getName()); JAXBIntrospector jbi = JAXBUtils.getJAXBIntrospector(context.getJAXBContext()); QName expectedQName = jbi.getElementName(jaxb); // On inbound, there will already be a XMLStreamReader (probably from OM) // which represents the message. We will simulate this with inflow. StringWriter sw = new StringWriter(); XMLStreamWriter writer = outputFactory.createXMLStreamWriter(sw); Marshaller marshaller = JAXBUtils.getJAXBMarshaller(context.getJAXBContext()); marshaller.marshal(jaxb, writer); JAXBUtils.releaseJAXBMarshaller(context.getJAXBContext(), marshaller); writer.flush(); sw.flush(); StringReader sr = new StringReader(sw.toString()); XMLStreamReader inflow = inputFactory.createXMLStreamReader(sr); // Create a Block from the inflow. Block block = f.createFrom(inflow, context, expectedQName); // We passed in a qname, so the following should return true assertTrue(block.isQNameAvailable()); // Assume that we need to find the QName (perhaps to identify the operation and // determine if handlers are installed). This is not very perfomant since // it causes an underlying parse of the String...but we need to support this. QName qName = block.getQName(); assertTrue("Expected: " + expectedQName + " but found: " + qName, expectedQName.equals(qName)); // Assuming no handlers are installed, the next thing that will happen // is the proxy code will ask for the business object. Object bo = block.getBusinessObject(true); assertTrue(bo instanceof EchoString); assertTrue(bo != jaxb); // The block should be consumed assertTrue(block.isConsumed()); // Check for accuracy assertTrue("Unexpected:" + ((EchoString)bo).getInput(), ((EchoString)bo).getInput().equals(jaxb.getInput())); }
/** * Create a Block representing an JAXB and simulate a * normal Dispatch<JAXB> input flow * @throws Exception */ public void testJAXBInflow4() throws Exception { // Get the BlockFactory JAXBBlockFactory f = (JAXBBlockFactory) FactoryRegistry.getFactory(JAXBBlockFactory.class); // Create a jaxb object ObjectFactory factory = new ObjectFactory(); EchoString jaxb = factory.createEchoString(); jaxb.setInput("Hello World"); JAXBBlockContext context = new JAXBBlockContext(EchoString.class.getPackage().getName()); JAXBContext jaxbContext = context.getJAXBContext(); JAXBIntrospector jbi = JAXBUtils.getJAXBIntrospector(jaxbContext); QName expectedQName = jbi.getElementName(jaxb); // On inbound, there will already be a probably be an OM // which represents the message. In this scenario, the OM contains // a OMSourcedElement that is backed by EchoString. OMFactory omFactory = OMAbstractFactory.getOMFactory(); JAXBDSContext dsContext = new JAXBDSContext(jaxbContext); JAXBDataSource ds = new JAXBDataSource(jaxb, dsContext); OMNamespace ns = omFactory.createOMNamespace(expectedQName.getNamespaceURI(), "pre"); OMElement om = omFactory.createOMElement(ds, expectedQName.getLocalPart(), ns); // Create a Block from the inflow. Block block = f.createFrom(om, context, expectedQName); // We passed in a qname, so the following should return true assertTrue(block.isQNameAvailable()); // Assume that we need to find the QName (perhaps to identify the operation and // determine if handlers are installed). QName qName = block.getQName(); assertTrue("Expected: " + expectedQName + " but found: " + qName, expectedQName.equals(qName)); // Assuming no handlers are installed, the next thing that will happen // is the proxy code will ask for the business object. Object bo = block.getBusinessObject(true); assertTrue(bo instanceof EchoString); // Since the EchoString was already provided in a data source, this // object should be same as the original echoString assertTrue(bo == jaxb); // The block should be consumed assertTrue(block.isConsumed()); // Check for accuracy assertTrue("Unexpected:" + ((EchoString)bo).getInput(), ((EchoString)bo).getInput().equals(jaxb.getInput())); }
/** * Gets the sbml. * * @param file * the file * @return the sbml * @throws JAXBException * the JAXB exception */ public static Sbml getSbml(File file) throws JAXBException { context = JAXBContext.newInstance(Sbml.class); Unmarshaller unmarshaller = context.createUnmarshaller(); Object schemaObject = JAXBIntrospector.getValue(unmarshaller.unmarshal(file)); sbml = (Sbml) schemaObject; return sbml; }
/** * Gets the sbml. * * @param xml * the xml * @return the sbml * @throws JAXBException * the JAXB exception */ public static Sbml getSbml(String xml) throws JAXBException { StringReader reader = new StringReader(xml); context = JAXBContext.newInstance(Sbml.class); Unmarshaller unmarshaller = context.createUnmarshaller(); Object schemaObject = JAXBIntrospector.getValue(unmarshaller.unmarshal(reader)); sbml = (Sbml) schemaObject; return sbml; }
/** * Returns the {@link QName} of the specified content tree, null if the QName cannot be determined. * This method returns a non-null value iff the specified content tree is annotated with the * {@link XmlRootElement} annotation, or it is an {@link JAXBElement} instance. * * @param content a content tree. * @return the {@link QName} of the specified content tree, null if the QName cannot be determined. */ public QName getElementName( Object content ) { JAXBIntrospector introspector = jaxb.createJAXBIntrospector(); return introspector.getElementName( content ); }