javax.xml.bind.Unmarshaller Java Examples

The following examples show how to use javax.xml.bind.Unmarshaller. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ReferenceObjectBindingGenTest.java    From rice with Educational Community License v2.0 6 votes vote down vote up
public void assertXmlMarshaling(Object referenceObjectBinding, String expectedXml)
        throws Exception
    {
        JAXBContext jc = JAXBContext.newInstance(ReferenceObjectBinding.class);

        Marshaller marshaller = jc.createMarshaller();
        StringWriter stringWriter = new StringWriter();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        // marshaller.setProperty("com.sun.xml.internal.bind.namespacePrefixMapper", new CustomNamespacePrefixMapper());
        marshaller.marshal(referenceObjectBinding, stringWriter);
        String xml = stringWriter.toString();

//        System.out.println(xml); // run test, paste xml output into XML, comment out this line.

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Object actual = unmarshaller.unmarshal(new StringReader(xml));
        Object expected = unmarshaller.unmarshal(new StringReader(expectedXml));
        Assert.assertEquals(expected, actual);
    }
 
Example #2
Source File: XMLConfigurationReader.java    From xframium-java with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean readFile( InputStream inputStream )
{
    try
    {
        
        JAXBContext jc = JAXBContext.newInstance( ObjectFactory.class );
        Unmarshaller u = jc.createUnmarshaller();
        JAXBElement<?> rootElement = (JAXBElement<?>) u.unmarshal( inputStream );

        xRoot = (XFramiumRoot) rootElement.getValue();
        
        for ( XProperty currentProp : xRoot.getDriver().getProperty() )
        {
            configProperties.put( currentProp.getName(), currentProp.getValue() );
        }
        return true;
    }
    catch ( Exception e )
    {
        log.fatal( "Error reading CSV Element File", e );
        return false;
    }
}
 
Example #3
Source File: IntrahubEncryptionUtil.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static <T> T encryptFolder(T request, String hubIdPropKey, String hubAppIdPropKey) throws TechnicalConnectorException {
   if (LOG.isDebugEnabled()) {
      MarshallerHelper<T, T> helper = new MarshallerHelper(request.getClass(), request.getClass());
      LOG.debug("Pre-encrypted request:\n" + helper.toString(request));
   }

   try {
      Marshaller marshaller = JAXBContext.newInstance(request.getClass()).createMarshaller();
      DOMResult res = new DOMResult();
      marshaller.marshal(request, res);
      Document doc = FolderEncryptor.encryptFolder((Document)res.getNode(), SessionUtil.getEncryptionCrypto(), hubIdPropKey, hubAppIdPropKey);
      Unmarshaller unmarshaller = JAXBContext.newInstance(request.getClass()).createUnmarshaller();
      return unmarshaller.unmarshal(doc.getFirstChild());
   } catch (JAXBException var7) {
      LOG.error("JAXBException when (un)marchalling the request", var7);
      return request;
   }
}
 
Example #4
Source File: AppManagementConfigurationManagerTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
private void validateMalformedConfig(File malformedConfig) {
	try {
		JAXBContext ctx = JAXBContext.newInstance(AppManagementConfig.class);
		Unmarshaller um = ctx.createUnmarshaller();
		um.setSchema(this.getSchema());
		um.unmarshal(malformedConfig);
		Assert.assertTrue(false);
	} catch (JAXBException e) {
		Throwable linkedException = e.getLinkedException();
		if (!(linkedException instanceof SAXParseException)) {
			log.error("Unexpected error occurred while unmarshalling app management config", e);
			Assert.assertTrue(false);
		}
		log.error("JAXB parser occurred while unmarsharlling app management config", e);
		Assert.assertTrue(true);
	}
}
 
Example #5
Source File: XmlUtils.java    From rxp-remote-java with MIT License 6 votes vote down vote up
/**
 * Unmarshals XML to request object. 
 * 
 * @param xml
 * @param messageType
 * @return Object
 */
public static Object fromXml(Source xml, MessageType messageType) {
	LOGGER.debug("Unmarshalling XML to domain object.");

	Object response = null;

	try {
		Unmarshaller jaxbUnmarshaller = JAXB_CONTEXT_MAP.get(messageType).createUnmarshaller();
		response = jaxbUnmarshaller.unmarshal(xml);
	} catch (JAXBException ex) {
		LOGGER.error("Error unmarshalling from XML", ex);
		throw new RealexException("Error unmarshalling from XML", ex);
	}

	return response;
}
 
Example #6
Source File: StreamMessage.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public Object readPayloadAsJAXB(Unmarshaller unmarshaller) throws JAXBException {
    if(!hasPayload())
        return null;
    assert unconsumed();
    // TODO: How can the unmarshaller process this as a fragment?
    if(hasAttachments())
        unmarshaller.setAttachmentUnmarshaller(new AttachmentUnmarshallerImpl(getAttachments()));
    try {
        return unmarshaller.unmarshal(reader);
    } finally{
        unmarshaller.setAttachmentUnmarshaller(null);
        XMLStreamReaderUtil.readRest(reader);
        XMLStreamReaderUtil.close(reader);
        XMLStreamReaderFactory.recycle(reader);
    }
}
 
Example #7
Source File: RunTable.java    From audiveris with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Unmarshal a RunTable from a file.
 *
 * @param path path to file
 * @return unmarshalled run table
 */
public static RunTable unmarshal (Path path)
{
    logger.debug("RunTable unmarshalling {}", path);

    try (InputStream is = Files.newInputStream(path, StandardOpenOption.READ)) {
        Unmarshaller um = getJaxbContext().createUnmarshaller();
        RunTable runTable = (RunTable) um.unmarshal(is);
        logger.debug("Unmarshalled {}", runTable);

        return runTable;
    } catch (IOException |
             JAXBException ex) {
        logger.warn("RunTable. Error unmarshalling " + path + " " + ex, ex);

        return null;
    }
}
 
Example #8
Source File: CqlLibraryReader.java    From cql_engine with Apache License 2.0 6 votes vote down vote up
public static Unmarshaller getUnmarshaller() throws JAXBException {
    // This is supposed to work based on this link:
    // https://jaxb.java.net/2.2.11/docs/ch03.html#compiling-xml-schema-adding-behaviors
    // Override the unmarshal to use the XXXEvaluator classes
    // This doesn't work exactly how it's described in the link above, but this is functional
    if (context == null)
    {
        context = JAXBContext.newInstance(ObjectFactory.class);
    }

    if (unmarshaller == null) {
        unmarshaller = context.createUnmarshaller();
        try {
            // https://bugs.eclipse.org/bugs/show_bug.cgi?id=406032
            //https://javaee.github.io/jaxb-v2/doc/user-guide/ch03.html#compiling-xml-schema-adding-behaviors
            // for jre environment
            unmarshaller.setProperty("com.sun.xml.bind.ObjectFactory", new ObjectFactoryEx());
        } catch (javax.xml.bind.PropertyException e) {
            // for jdk environment
            unmarshaller.setProperty("com.sun.xml.internal.bind.ObjectFactory", new ObjectFactoryEx());
        }
    }

    return unmarshaller;
}
 
Example #9
Source File: MapSettings.java    From megamek with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates and returns a new instance of MapSettings with default values
 * loaded from the given input stream.
 * 
 * @param is
 *            the input stream that contains an XML representation of the
 *            map settings
 * @return a MapSettings with the values from XML
 */
public static MapSettings getInstance(final InputStream is) {
    MapSettings ms = null;

    try {
        JAXBContext jc = JAXBContext.newInstance(MapSettings.class);

        Unmarshaller um = jc.createUnmarshaller();
        ms = (MapSettings) um.unmarshal(MegaMekXmlUtil.createSafeXmlSource(is));
    } catch (JAXBException | SAXException | ParserConfigurationException ex) {
        System.err.println("Error loading XML for map settings: " + ex.getMessage()); //$NON-NLS-1$
        ex.printStackTrace();
    }

    return ms;
}
 
Example #10
Source File: ScriptManager.java    From aion-germany with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Loads script contexes from descriptor
 * 
 * @param scriptDescriptor
 *            xml file that describes contexes
 * @throws Exception
 *             if can't load file
 */
public synchronized void load(File scriptDescriptor) throws Exception {
	FileInputStream fin = new FileInputStream(scriptDescriptor);
	JAXBContext c = JAXBContext.newInstance(ScriptInfo.class, ScriptList.class);
	Unmarshaller u = c.createUnmarshaller();

	ScriptList list = null;
	try {
		list = (ScriptList) u.unmarshal(fin);
	} catch (Exception e) {
		throw e;
	} finally {
		fin.close();
	}

	for (ScriptInfo si : list.getScriptInfos()) {
		ScriptContext context = createContext(si, null);
		if (context != null) {
			contexts.add(context);
			context.init();
		}
	}
}
 
Example #11
Source File: WorkflowProfiles.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #12
Source File: ProviderImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Convert from EndpointReference to CXF internal 2005/08 EndpointReferenceType
 *
 * @param external the javax.xml.ws.EndpointReference
 * @return CXF internal 2005/08 EndpointReferenceType
 */
public static EndpointReferenceType convertToInternal(EndpointReference external) {
    if (external instanceof W3CEndpointReference) {

        Unmarshaller um = null;
        try {
            DocumentFragment frag = DOMUtils.getEmptyDocument().createDocumentFragment();
            DOMResult result = new DOMResult(frag);
            external.writeTo(result);
            W3CDOMStreamReader reader = new W3CDOMStreamReader(frag);

            // CXF internal 2005/08 EndpointReferenceType should be
            // compatible with W3CEndpointReference
            //jaxContext = ContextUtils.getJAXBContext();
            JAXBContext context = JAXBContext
                .newInstance(new Class[] {org.apache.cxf.ws.addressing.ObjectFactory.class});
            um = context.createUnmarshaller();
            return um.unmarshal(reader, EndpointReferenceType.class).getValue();
        } catch (JAXBException e) {
            throw new IllegalArgumentException("Could not unmarshal EndpointReference", e);
        } finally {
            JAXBUtils.closeUnmarshaller(um);
        }
    }
    return null;
}
 
Example #13
Source File: BridgeAdapter.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private @NotNull InMemory adaptU(Unmarshaller _u, OnWire v) throws JAXBException {
    UnmarshallerImpl u = (UnmarshallerImpl) _u;
    XmlAdapter<OnWire,InMemory> a = u.coordinator.getAdapter(adapter);
    u.coordinator.pushCoordinator();
    try {
        return a.unmarshal(v);
    } catch (Exception e) {
        throw new UnmarshalException(e);
    } finally {
        u.coordinator.popCoordinator();
    }
}
 
Example #14
Source File: LazyScreenshotZipPersistence.java    From recheck with GNU Affero General Public License v3.0 5 votes vote down vote up
public Unmarshaller.Listener getUnmarshallListener() {
	return new Unmarshaller.Listener() {
		@Override
		public void afterUnmarshal( final Object target, final Object parent ) {
			if ( target instanceof Screenshot ) {
				screenshots.add( (Screenshot) target );
				screenshotParentMap.put( (Screenshot) target, parent );
			}
		}
	};
}
 
Example #15
Source File: JAXBEncoderDecoderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testMarshallWithoutQNameInfo() throws Exception {
    GreetMe obj = new GreetMe();
    obj.setRequestType("Hello");

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLOutputFactory opFactory = XMLOutputFactory.newInstance();
    opFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
    XMLEventWriter writer = opFactory.createXMLEventWriter(baos);

    //STARTDOCUMENT/ENDDOCUMENT is not required
    //writer.add(eFactory.createStartDocument("utf-8", "1.0"));
    JAXBEncoderDecoder.marshall(context.createMarshaller(), obj, null, writer);
    //writer.add(eFactory.createEndDocument());
    writer.flush();
    writer.close();

    //System.out.println(baos.toString());

    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    XMLInputFactory ipFactory = XMLInputFactory.newInstance();
    XMLEventReader reader = ipFactory.createXMLEventReader(bais);

    Unmarshaller um = context.createUnmarshaller();
    Object val = um.unmarshal(reader, GreetMe.class);
    assertTrue(val instanceof JAXBElement);
    val = ((JAXBElement<?>)val).getValue();
    assertTrue(val instanceof GreetMe);
    assertEquals(obj.getRequestType(),
                 ((GreetMe)val).getRequestType());
}
 
Example #16
Source File: WorkflowProfiles.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
private void read() throws JAXBException {
    long currentTime = file.lastModified();
    if (currentTime == lastModified) {
        return ;
    }
    Unmarshaller unmarshaller = getUnmarshaller();
    ValidationEventCollector errors = (ValidationEventCollector) unmarshaller.getEventHandler();
    WorkflowDefinition fetchedWf = null;
    try {
        WorkflowDefinition wf = (WorkflowDefinition) unmarshaller.unmarshal(file);
        if (!errors.hasEvents()) {
            readCaches(wf);
            fetchedWf = wf;
        }
    } catch (UnmarshalException ex) {
        if (!errors.hasEvents()) {
            throw ex;
        }
    } finally {
        setProfiles(fetchedWf, currentTime);
    }
    if (errors.hasEvents()) {
        StringBuilder err = new StringBuilder();
        for (ValidationEvent event : errors.getEvents()) {
            err.append(event).append('\n');
        }
        throw new JAXBException(err.toString());
    }
}
 
Example #17
Source File: Configuration.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T read(URL url, Class<?>... classes) throws Exception {
	try {
		url.openStream();
	} catch (Exception e) {
		throw new IllegalArgumentException(String.format("File path: %s does not exist", url));
	}

	JAXBContext jaxb = JAXBContext.newInstance(classes);
	Unmarshaller unmarshaller = jaxb.createUnmarshaller();
	return (T) unmarshaller.unmarshal(url);
}
 
Example #18
Source File: SAAJMessage.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public <T> T readPayloadAsJAXB(Unmarshaller unmarshaller) throws JAXBException {
    access();
    if (payload != null) {
        if(hasAttachments())
            unmarshaller.setAttachmentUnmarshaller(new AttachmentUnmarshallerImpl(getAttachments()));
        return (T) unmarshaller.unmarshal(payload);

    }
    return null;
}
 
Example #19
Source File: ReadXMLFileUtils.java    From opencps-v2 with GNU Affero General Public License v3.0 5 votes vote down vote up
private static DynamicReportList convertXMLToDynamicReport(String xmlString) throws JAXBException {

			JAXBContext jaxbContext = null;
			jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			StringReader reader = new StringReader(xmlString);
			DynamicReportList objectElement = (DynamicReportList) jaxbUnmarshaller.unmarshal(reader);

			return objectElement;
	}
 
Example #20
Source File: Jaxb2Marshaller.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Return a newly created JAXB unmarshaller.
 * Note: JAXB unmarshallers are not necessarily thread-safe.
 */
protected Unmarshaller createUnmarshaller() {
	try {
		Unmarshaller unmarshaller = getJaxbContext().createUnmarshaller();
		initJaxbUnmarshaller(unmarshaller);
		return unmarshaller;
	}
	catch (JAXBException ex) {
		throw convertJaxbException(ex);
	}
}
 
Example #21
Source File: Loader.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Fires the afterUnmarshal event if necessary.
 *
 * @param state
 *      state of the parent object
 */
protected final void fireAfterUnmarshal(JaxBeanInfo beanInfo, Object child, UnmarshallingContext.State state) throws SAXException {
    // fire the event callback
    if(beanInfo.lookForLifecycleMethods()) {
        UnmarshallingContext context = state.getContext();
        Unmarshaller.Listener listener = context.parent.getListener();
        if(beanInfo.hasAfterUnmarshalMethod()) {
            beanInfo.invokeAfterUnmarshalMethod(context.parent, child, state.getTarget());
        }
        if(listener!=null)
            listener.afterUnmarshal(child, state.getTarget());
    }
}
 
Example #22
Source File: PetFeedData.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
void afterUnmarshal(Unmarshaller u, Object parent) {
	if (flavours == null) {
		return;
	}

	for (PetFlavour flavour : flavours) {
		petFlavoursById.put(flavour.getId(), flavour);
	}

	flavours.clear();
	flavours = null;
}
 
Example #23
Source File: XmlUtils.java    From tutorial-soap-spring-boot-cxf with MIT License 5 votes vote down vote up
public static <T> JAXBElement<T> unmarshallNode(Node node, Class<T> jaxbClassName) throws InternalBusinessException {
	Objects.requireNonNull(node);
	JAXBElement<T> jaxbElement = null;
	try {
		JAXBContext jaxbContext = JAXBContext.newInstance(jaxbClassName);
		Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
		jaxbElement = unmarshaller.unmarshal(new DOMSource(node), jaxbClassName);
	} catch (Exception exception) {
		throw new InternalBusinessException("Problem beim Unmarshalling der Node in das JAXBElement: " + exception.getMessage(), exception);
	}		
	return jaxbElement;
}
 
Example #24
Source File: SpawnTemplates.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
void afterUnmarshal(Unmarshaller u, Object parent) 
{
	for (SpawnMap map : spawnmaps)
	{
		if (!mapsByWorldId.containsKey(map.worldId))
			mapsByWorldId.put(map.worldId, map);
	}
}
 
Example #25
Source File: StateMachine.java    From development with Apache License 2.0 5 votes vote down vote up
private States loadStateMachine(String filename)
        throws StateMachineException {
    logger.debug("filename: " + filename);
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    try (InputStream stream = loader.getResourceAsStream("statemachines/"
            + filename);) {
        JAXBContext jaxbContext = JAXBContext.newInstance(States.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        return (States) jaxbUnmarshaller.unmarshal(stream);
    } catch (Exception e) {
        throw new StateMachineException(
                "Failed to load state machine definition file: " + filename,
                e);
    }
}
 
Example #26
Source File: TestDisabledServiceSettings.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
private Object unmarshall(Unmarshaller unmarshaller, File sourceFile) {
    try {
        return unmarshaller.unmarshal(sourceFile);
    } catch (JAXBException e) {
        Assert.fail(String.format("Could not unmarshall [%s]. [%s]", sourceFile, e));
    }
    return null;
}
 
Example #27
Source File: SysMail.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
void afterUnmarshal(Unmarshaller u, Object parent) {
	for (MailTemplate template : templates) {
		String caseName = template.getName().toLowerCase();
		List<MailTemplate> sysTemplates = mailCaseTemplates.get(caseName);
		if (sysTemplates == null) {
			sysTemplates = new ArrayList<MailTemplate>();
			mailCaseTemplates.put(caseName, sysTemplates);
		}
		sysTemplates.add(template);
	}
	templates.clear();
	templates = null;
}
 
Example #28
Source File: XMLTransmitter.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
   public <T> T unmarshal(Class<T> tclass, File xmlFile) throws JAXBException {
	Unmarshaller unmarshaller;
	try {
		unmarshaller = getContext(tclass).createUnmarshaller();
	} catch (Exception e) {
		throw new EPSCommonException("An unmarshaller instance could not be created for class " + tclass.getCanonicalName(),e);
	}
	return (T)unmarshaller.unmarshal(xmlFile);
}
 
Example #29
Source File: JaxContextCentralizer.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public Unmarshaller getUnmarshaller(Class<?> clazz) throws GFDDPPException {
   try {
      return this.getContext(clazz).createUnmarshaller();
   } catch (JAXBException var4) {
      LOG.error("", var4);
      String message = this.processJAXBException(var4);
      throw new GFDDPPException(StatusCode.COMMON_ERROR_UNMARSHALLER, new String[]{message, clazz.getName()});
   }
}
 
Example #30
Source File: Test.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance("testjaxbcontext");
    Unmarshaller u = jc.createUnmarshaller();
    Object result = u.unmarshal(new File(System.getProperty("test.src", ".") + "/test.xml"));
    StringWriter sw = new StringWriter();
    Marshaller m = jc.createMarshaller();
    m.marshal(result, sw);
    System.out.println("Expected:" + EXPECTED);
    System.out.println("Observed:" + sw.toString());
    if (!EXPECTED.equals(sw.toString())) {
        throw new Exception("Unmarshal/Marshal generates different content");
    }
}