javax.xml.bind.util.JAXBSource Java Examples

The following examples show how to use javax.xml.bind.util.JAXBSource. 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: JaxbBuilder.java    From xmlunit with Apache License 2.0 6 votes vote down vote up
@Override
public Source build() {
    try {
        if (marshaller == null) {
            createDefaultMarshaller();
        }

        final Object jaxbObject = getPreparedJaxbObject();
        final JAXBSource jaxbSource = new JAXBSource(marshaller, jaxbObject);
        // the fake InputSource cannot be used (the Convert.java
        // will create a working one if it is null)
        jaxbSource.setInputSource(null);
        return jaxbSource;
    } catch (final JAXBException e) {
        throw new DataBindingException(e);
    }
}
 
Example #2
Source File: JDBCSQLXML.java    From evosql with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a Source for reading the XML value designated by this SQLXML
 * instance. <p>
 *
 * @param sourceClass The class of the source, or null.  If null, then a
 *      DOMSource is returned.
 * @return a Source for reading the XML value.
 * @throws SQLException if there is an error processing the XML value
 *   or if the given <tt>sourceClass</tt> is not supported.
 */
protected <T extends Source>T getSourceImpl(
        Class<T> sourceClass) throws SQLException {

    if (JAXBSource.class.isAssignableFrom(sourceClass)) {

        // Must go first presently, since JAXBSource extends SAXSource
        // (purely as an implementation detail) and it's not possible
        // to instantiate a valid JAXBSource with a Zero-Args
        // constructor(or any subclass thereof, due to the finality of
        // its private marshaller and context object attributes)
        // FALL THROUGH... will throw an exception
    } else if (StreamSource.class.isAssignableFrom(sourceClass)) {
        return createStreamSource(sourceClass);
    } else if ((sourceClass == null)
               || DOMSource.class.isAssignableFrom(sourceClass)) {
        return createDOMSource(sourceClass);
    } else if (SAXSource.class.isAssignableFrom(sourceClass)) {
        return createSAXSource(sourceClass);
    } else if (StAXSource.class.isAssignableFrom(sourceClass)) {
        return createStAXSource(sourceClass);
    }

    throw JDBCUtil.invalidArgument("sourceClass: " + sourceClass);
}
 
Example #3
Source File: MCRUserResolver.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Source resolve(String href, String base) throws TransformerException {
    String[] hrefParts = href.split(":");
    String userID = hrefParts[1];
    MCRUser user = null;
    try {
        if ("current".equals(userID)) {
            user = MCRUserManager.getCurrentUser();
        } else if ("getOwnedUsers".equals(userID)) {
            return getOwnedUsers(hrefParts[2]);
        } else {
            user = MCRUserManager.getUser(userID);
        }
        if (user == null) {
            return null;
        }
        return new JAXBSource(MCRUserTransformer.JAXB_CONTEXT, user.getSafeCopy());
    } catch (JAXBException e) {
        throw new TransformerException(e);
    }
}
 
Example #4
Source File: DcStreamEditor.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
@Deprecated
public void write(DigitalObjectHandler handler, ModsDefinition mods, String model, long timestamp, String message) throws DigitalObjectException {
    try {
        JAXBSource jaxbSource = new JAXBSource(ModsUtils.defaultMarshaller(false),
                new cz.cas.lib.proarc.mods.ObjectFactory().createMods(mods));
        // DO NOT include schemaLocation. Fedora validator does not accept it.
        Transformer t = DcUtils.modsTransformer(model);
        EditorResult result = editor.createResult();
        JAXBResult jaxbResult = new JAXBResult(DcUtils.defaultUnmarshaller());
        t.transform(jaxbSource, jaxbResult);
        JAXBElement<OaiDcType> elm = (JAXBElement<OaiDcType>) jaxbResult.getResult();
        OaiDcType dc = elm.getValue();
        addDigitalObjectMetadata(handler, dc);
        DcUtils.marshal(result, dc, false);
        editor.write(result, timestamp, message);
    } catch (TransformerException | JAXBException ex) {
        throw new DigitalObjectException(object.getPid(), ex);
    }
}
 
Example #5
Source File: ValidatorHelper.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void validate(Object jaxbObj, Class xmlClass, String rootSchemaFileLocation) throws TechnicalConnectorException {
   if (jaxbObj == null) {
      LOG.error("Message is null");
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_XML_INVALID, new Object[]{"Message is null"});
   } else {
      ConnectorXmlUtils.dump(jaxbObj);
      LOG.debug("Validating with schema [" + rootSchemaFileLocation + "]");

      try {
         JAXBContext jaxbContext = JaxbContextFactory.getJaxbContextForClass(xmlClass);
         JAXBSource payload = new JAXBSource(jaxbContext, jaxbObj);
         validate((Source)payload, (String[])(rootSchemaFileLocation));
      } catch (Exception var5) {
         throw handleException(var5);
      }

      LOG.debug("Message is valid.");
   }
}
 
Example #6
Source File: ValidatorHelper.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void validate(Object jaxbObj, Class xmlClass, String rootSchemaFileLocation) throws TechnicalConnectorException {
   if (jaxbObj == null) {
      LOG.error("Message is null");
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_XML_INVALID, new Object[]{"Message is null"});
   } else {
      ConnectorXmlUtils.dump(jaxbObj);
      LOG.debug("Validating with schema [" + rootSchemaFileLocation + "]");

      try {
         JAXBContext jaxbContext = JaxbContextFactory.getJaxbContextForClass(xmlClass);
         JAXBSource payload = new JAXBSource(jaxbContext, jaxbObj);
         validate((Source)payload, (String[])(rootSchemaFileLocation));
      } catch (Exception var5) {
         throw handleException(var5);
      }

      LOG.debug("Message is valid.");
   }
}
 
Example #7
Source File: ValidatorHelper.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void validate(Object jaxbObj, Class xmlClass, String rootSchemaFileLocation) throws TechnicalConnectorException {
   if (jaxbObj == null) {
      LOG.error("Message is null");
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_XML_INVALID, new Object[]{"Message is null"});
   } else {
      ConnectorXmlUtils.dump(jaxbObj);
      LOG.debug("Validating with schema [" + rootSchemaFileLocation + "]");

      try {
         JAXBContext jaxbContext = JaxbContextFactory.getJaxbContextForClass(xmlClass);
         JAXBSource payload = new JAXBSource(jaxbContext, jaxbObj);
         validate((Source)payload, (String[])(rootSchemaFileLocation));
      } catch (Exception var5) {
         throw handleException(var5);
      }

      LOG.debug("Message is valid.");
   }
}
 
Example #8
Source File: ValidatorHelper.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void validate(Object jaxbObj, Class xmlClass, String rootSchemaFileLocation) throws TechnicalConnectorException {
   if (jaxbObj == null) {
      LOG.error("Message is null");
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_XML_INVALID, new Object[]{"Message is null"});
   } else {
      ConnectorXmlUtils.dump(jaxbObj);
      LOG.debug("Validating with schema [" + rootSchemaFileLocation + "]");

      try {
         JAXBContext jaxbContext = JaxbContextFactory.getJaxbContextForClass(xmlClass);
         JAXBSource payload = new JAXBSource(jaxbContext, jaxbObj);
         validate((Source)payload, (String[])(rootSchemaFileLocation));
      } catch (Exception var5) {
         throw handleException(var5);
      }

      LOG.debug("Message is valid.");
   }
}
 
Example #9
Source File: GraphMlTest.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void validate() throws Exception {
  GraphMl graphMl = creategraphml();
  JAXBContext jc = new GraphMlContext().getJaxbContext();
  JAXBSource source = new JAXBSource(jc, graphMl);

  SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  Schema schema = sf.newSchema(new URL("http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd"));

  Validator validator = schema.newValidator();
  validator.setErrorHandler(new GraphErrorHandler());
  validator.validate(source);
}
 
Example #10
Source File: CuentasContablesv11.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
public void validar(ErrorHandler handler) throws Exception {
	SchemaFactory sf =
			SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
	Source[] schemas = new Source[XSD.length];
	for (int i = 0; i < XSD.length; i++) {
		schemas[i] = new StreamSource(getClass().getResourceAsStream(XSD[i]));
	}
	Schema schema = sf.newSchema(schemas);
	Validator validator = schema.newValidator();
	if (handler != null) {
		validator.setErrorHandler(handler);
	}
	validator.validate(new JAXBSource(context, document));
}
 
Example #11
Source File: CuentasContablesv11.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
byte[] getOriginalBytes() throws Exception {
	JAXBSource in = new JAXBSource(context, document);
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	Result out = new StreamResult(baos);
	TransformerFactory factory = tf;
	if (factory == null) {
		factory = TransformerFactory.newInstance();
		factory.setURIResolver(new URIResolverImpl());
	}     
	Transformer transformer = factory.newTransformer(new StreamSource(getClass().getResourceAsStream(XSLT)));
	transformer.transform(in, out);
	return baos.toByteArray();
}
 
Example #12
Source File: BalanzaComprobacionv11.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
byte[] getOriginalBytes() throws Exception {
	JAXBSource in = new JAXBSource(context, document);
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	Result out = new StreamResult(baos);
	TransformerFactory factory = tf;
	if (factory == null) {
		factory = TransformerFactory.newInstance();
		factory.setURIResolver(new URIResolverImpl());
	}     
	Transformer transformer = factory.newTransformer(new StreamSource(getClass().getResourceAsStream(XSLT)));
	transformer.transform(in, out);
	return baos.toByteArray();
}
 
Example #13
Source File: PolizasPeriodov11.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
public void validar(ErrorHandler handler) throws Exception {
	SchemaFactory sf =
			SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
	Source[] schemas = new Source[XSD.length];
	for (int i = 0; i < XSD.length; i++) {
		schemas[i] = new StreamSource(getClass().getResourceAsStream(XSD[i]));
	}
	Schema schema = sf.newSchema(schemas);
	Validator validator = schema.newValidator();
	if (handler != null) {
		validator.setErrorHandler(handler);
	}
	validator.validate(new JAXBSource(context, document));
}
 
Example #14
Source File: PolizasPeriodov11.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
byte[] getOriginalBytes() throws Exception {
	JAXBSource in = new JAXBSource(context, document);
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	Result out = new StreamResult(baos);
	TransformerFactory factory = tf;
	if (factory == null) {
		factory = TransformerFactory.newInstance();
		factory.setURIResolver(new URIResolverImpl());
	}     
	Transformer transformer = factory.newTransformer(new StreamSource(getClass().getResourceAsStream(XSLT)));
	transformer.transform(in, out);
	return baos.toByteArray();
}
 
Example #15
Source File: LogicalMessageImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Source getPayload() {
    JAXBContext context = ctxt;
    if (context == null) {
        context = defaultJaxbContext.getJAXBContext();
    }
    try {
        return new JAXBSource(context, o);
    } catch (JAXBException e) {
        throw new WebServiceException(e);
    }
}
 
Example #16
Source File: LogicalMessageImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Source getPayload() {
    JAXBContext context = ctxt;
    if (context == null) {
        context = defaultJaxbContext.getJAXBContext();
    }
    try {
        return new JAXBSource(context, o);
    } catch (JAXBException e) {
        throw new WebServiceException(e);
    }
}
 
Example #17
Source File: LogicalMessageImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Source getPayload() {
    JAXBContext context = ctxt;
    if (context == null) {
        context = defaultJaxbContext.getJAXBContext();
    }
    try {
        return new JAXBSource(context, o);
    } catch (JAXBException e) {
        throw new WebServiceException(e);
    }
}
 
Example #18
Source File: LogicalMessageImpl.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Source getPayload() {
    JAXBContext context = ctxt;
    if (context == null) {
        context = defaultJaxbContext.getJAXBContext();
    }
    try {
        return new JAXBSource(context, o);
    } catch (JAXBException e) {
        throw new WebServiceException(e);
    }
}
 
Example #19
Source File: LogicalMessageImpl.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Source getPayload() {
    JAXBContext context = ctxt;
    if (context == null) {
        context = defaultJaxbContext.getJAXBContext();
    }
    try {
        return new JAXBSource(context, o);
    } catch (JAXBException e) {
        throw new WebServiceException(e);
    }
}
 
Example #20
Source File: MCRUserResolver.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
private Source getOwnedUsers(String userName) throws JAXBException {
    MCRUser owner = MCRUserManager.getUser(userName);
    List<MCRUser> listUsers = MCRUserManager.listUsers(owner);
    MCROwns mcrOwns = new MCROwns();
    int userCount = listUsers.size();
    mcrOwns.users = new MCRUser[userCount];
    for (int i = 0; i < userCount; i++) {
        mcrOwns.users[i] = listUsers.get(i).getBasicCopy();
    }
    return new JAXBSource(MCRUserTransformer.JAXB_CONTEXT, mcrOwns);
}
 
Example #21
Source File: MCRJAXBContent.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Source getSource() throws IOException {
    try {
        Marshaller marshaller = getMarshaller();
        return new JAXBSource(marshaller, jaxbObject);
    } catch (JAXBException e) {
        throw new IOException(e);
    }
}
 
Example #22
Source File: LogicalMessageImpl.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Source getPayload() {
    JAXBContext context = ctxt;
    if (context == null) {
        context = defaultJaxbContext.getJAXBContext();
    }
    try {
        return new JAXBSource(context, o);
    } catch (JAXBException e) {
        throw new WebServiceException(e);
    }
}
 
Example #23
Source File: DcStreamEditorTest.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testTransformation() throws Exception {
    ModsDefinition mods = ModsUtils.unmarshalModsType(new StreamSource(DcStreamEditorTest.class.getResource("periodical.xml").toExternalForm()));
    Transformer t = DcUtils.modsTransformer("model:periodical");
    JAXBSource jaxbSource = new JAXBSource(ModsUtils.defaultMarshaller(false),
            new ObjectFactory().createMods(mods));
    StringWriter dump = new StringWriter();
    t.transform(jaxbSource, new StreamResult(dump));
    String toXml = dump.toString();
    System.out.println(toXml);

    HashMap<String, String> namespaces = new HashMap<String, String>();
    namespaces.put("oai_dc", DcStreamEditor.DATASTREAM_FORMAT_URI);
    namespaces.put("dc", "http://purl.org/dc/elements/1.1/");
    XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(namespaces));
    XMLAssert.assertXpathExists("/oai_dc:dc/dc:title[text()='main']", toXml);
    XMLAssert.assertXpathExists("/oai_dc:dc/dc:title[text()='key']", toXml);
    XMLAssert.assertXpathExists("/oai_dc:dc/dc:title[text()='alternative']", toXml);
    XMLAssert.assertXpathEvaluatesTo("3", "count(/oai_dc:dc/dc:title)", toXml);
    XMLAssert.assertXpathExists("/oai_dc:dc/dc:creator[text()='Boleslav']", toXml);
    XMLAssert.assertXpathExists("/oai_dc:dc/dc:description[text()='poznámka']", toXml);
    XMLAssert.assertXpathExists("/oai_dc:dc/dc:identifier[text()='uuid:40d13cb2-811f-468c-a6d3-1ad6b01f06f7']", toXml);
    XMLAssert.assertXpathExists("/oai_dc:dc/dc:identifier[text()='isbn:0eaa6730']", toXml);
    XMLAssert.assertXpathExists("/oai_dc:dc/dc:identifier[text()='issn-l:idIssn-l']", toXml);
    XMLAssert.assertXpathExists("/oai_dc:dc/dc:identifier[text()='idWitEmptyType']", toXml);
    XMLAssert.assertXpathExists("/oai_dc:dc/dc:identifier[text()='idWithoutType']", toXml);
    // XXX needs more test
}
 
Example #24
Source File: XACMLObjectCopy.java    From XACML with MIT License 5 votes vote down vote up
static public <T> T deepCopy(T object) {
	if (object == null) return null;
	
	try {
		@SuppressWarnings("unchecked")
		Class<T> clazz = (Class<T>)object.getClass();
		JAXBContext context = JAXBContext.newInstance(clazz);
		JAXBElement<T> contentObject = new JAXBElement<T>(new QName(clazz.getSimpleName()), clazz, object);
		JAXBSource source = new JAXBSource(context, contentObject);
		return context.createUnmarshaller().unmarshal(source, clazz).getValue();
	} catch (JAXBException e) {
		throw new RuntimeException(e);
	}
}
 
Example #25
Source File: XmlCopyUtils.java    From yarg with Apache License 2.0 5 votes vote down vote up
public static Cell copyCell(Cell cell, Unmarshaller unmarshaller, Marshaller marshaller) {
    try {
        JAXBElement<Cell> contentObject = new JAXBElement<>(new QName(cellName), Cell.class, cell);
        JAXBSource source = new JAXBSource(marshaller, contentObject);
        source.setXMLReader(new PseudoXMLReader(marshaller, contentObject));
        JAXBElement<Cell> elem = unmarshaller.unmarshal(source, Cell.class);
        return elem.getValue();
    } catch (JAXBException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #26
Source File: TransformerUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void transform(JAXBContext context, JAXBElement<?> jaxb, Result result) throws ParsingException {
    try {
        Transformer transformer = getTransformer();
        JAXBSource jaxbSource = new JAXBSource(context, jaxb);

        transformer.transform(jaxbSource, result);
    } catch (Exception e) {
        throw logger.parserError(e);
    }
}
 
Example #27
Source File: LogicalMessageImpl.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Source getPayload() {
    JAXBContext context = ctxt;
    if (context == null) {
        context = defaultJaxbContext.getJAXBContext();
    }
    try {
        return new JAXBSource(context, o);
    } catch (JAXBException e) {
        throw new WebServiceException(e);
    }
}
 
Example #28
Source File: CFDv2.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
byte[] getOriginalBytes() throws Exception {
    JAXBSource in = new JAXBSource(context, document);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Result out = new StreamResult(baos);
    TransformerFactory factory = tf;
    if (factory == null) {
        factory = TransformerFactory.newInstance();
        factory.setURIResolver(new URIResolverImpl());
    }
    Transformer transformer = factory.newTransformer(new StreamSource(getClass().getResourceAsStream(XSLT)));
    transformer.transform(in, out);
    return baos.toByteArray();
}
 
Example #29
Source File: LogicalMessageImpl.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Source getPayload() {
    JAXBContext context = ctxt;
    if (context == null) {
        context = defaultJaxbContext.getJAXBContext();
    }
    try {
        return new JAXBSource(context, o);
    } catch (JAXBException e) {
        throw new WebServiceException(e);
    }
}
 
Example #30
Source File: RuleToXmlConverterTest.java    From yare with MIT License 5 votes vote down vote up
@Test
void shouldCheckValidRuleAgainstSchema() throws Exception {
    // given
    RuleSer ruleObject = TestRuleFactory.constructValidRuleWithBuildInObjectTypes();

    JAXBContext jc = JAXBContext.newInstance(RuleSer.class, TestRuleFactory.Isbn.class);
    JAXBSource source = new JAXBSource(jc, objectFactory.createRule(ruleObject));
    Validator validator = getSchema().newValidator();
    validator.setErrorHandler(new ThrowingErrorHandler());

    // when / then
    validator.validate(source);
}