Java Code Examples for javax.xml.bind.JAXBContext#createUnmarshaller()

The following examples show how to use javax.xml.bind.JAXBContext#createUnmarshaller() . 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: CodeGuardIssuesParser.java    From sonar-tsql-plugin with GNU General Public License v3.0 6 votes vote down vote up
@Override
public TsqlIssue[] parse(final File file) {
	final List<TsqlIssue> list = new ArrayList<TsqlIssue>();
	try {
		final JAXBContext jaxbContext = JAXBContext.newInstance(CodeGuardIssues.class);
		final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
		final CodeGuardIssues issues = (CodeGuardIssues) jaxbUnmarshaller.unmarshal(file);
		for (final org.sonar.plugins.tsql.rules.issues.CodeGuardIssues.File f : issues.getFile()) {
			for (final Issue is : f.getIssue()) {
				final TsqlIssue issue = new TsqlIssue();
				issue.setDescription(is.getText());
				issue.setFilePath(f.getFullname());
				issue.setLine(is.getLine());
				issue.setType(is.getCode());
				list.add(issue);
			}

		}
		return list.toArray(new TsqlIssue[0]);

	} catch (final Throwable e) {
		LOGGER.warn("Unexpected error occured redading file "+file, e);
	}
	return new TsqlIssue[0];
}
 
Example 2
Source File: PayComponent.java    From weixin4j with Apache License 2.0 6 votes vote down vote up
/**
 * 查询订单
 *
 * @param orderQuery 订单查询对象
 * @return 订单查询结果
 * @throws org.weixin4j.WeixinException 微信操作异常
 */
public OrderQueryResult payOrderQuery(OrderQuery orderQuery) throws WeixinException {
    //将统一下单对象转成XML
    String xmlPost = orderQuery.toXML();
    if (Configuration.isDebug()) {
        System.out.println("调试模式_查询订单接口 提交XML数据:" + xmlPost);
    }
    //创建请求对象
    HttpsClient http = new HttpsClient();
    //提交xml格式数据
    Response res = http.postXml("https://api.mch.weixin.qq.com/pay/orderquery", xmlPost);
    //获取微信平台查询订单接口返回数据
    String xmlResult = res.asString();
    try {
        if (Configuration.isDebug()) {
            System.out.println("调试模式_查询订单接口 接收XML数据:" + xmlResult);
        }
        JAXBContext context = JAXBContext.newInstance(OrderQueryResult.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        OrderQueryResult result = (OrderQueryResult) unmarshaller.unmarshal(new StringReader(xmlResult));
        return result;
    } catch (JAXBException ex) {
        return null;
    }
}
 
Example 3
Source File: ConverterImpl.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public T fromXML(String xml) {

    try {
        JAXBContext context = JAXBContext.newInstance(type);
        Unmarshaller u = context.createUnmarshaller();

        if(schemaLocation != null) {
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

            StreamSource source = new StreamSource(getClass().getResourceAsStream(schemaLocation));
            Schema schema = schemaFactory.newSchema(source);
            u.setSchema(schema);
        }

        StringReader reader = new StringReader(xml);
        T obj = (T) u.unmarshal(reader);

        return obj;
    } catch (Exception e) {
        System.out.println("ERROR: "+e.toString());
        return null;
    }
}
 
Example 4
Source File: JDBCSourceIT.java    From enhydrator with Apache License 2.0 6 votes vote down vote up
@Test
public void jaxbSerialization() throws JAXBException, UnsupportedEncodingException {
    JAXBContext context = JAXBContext.newInstance(JDBCSource.class);
    Marshaller marshaller = context.createMarshaller();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final JDBCSource origin = getSource();
    marshaller.marshal(origin, baos);

    byte[] content = baos.toByteArray();
    System.out.println("Serialized: " + new String(content, "UTF-8"));
    ByteArrayInputStream bais = new ByteArrayInputStream(content);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    JDBCSource deserialized = (JDBCSource) unmarshaller.unmarshal(bais);
    assertNotNull(deserialized);

    assertNotSame(deserialized, origin);
    assertThat(deserialized, is(origin));

}
 
Example 5
Source File: TransportOrdersDocument.java    From openAGV with Apache License 2.0 6 votes vote down vote up
/**
 * Reads a list of <code>TransportOrderXMLStructure</code>s from an XML file.
 *
 * @param xmlData The XML data
 * @return The list of data
 */
@SuppressWarnings("unchecked")
public static TransportOrdersDocument fromXml(String xmlData) {
  requireNonNull(xmlData, "xmlData");

  StringReader stringReader = new StringReader(xmlData);
  try {
    JAXBContext jc = JAXBContext.newInstance(TransportOrdersDocument.class);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    Object o = unmarshaller.unmarshal(stringReader);
    return (TransportOrdersDocument) o;
  }
  catch (JAXBException exc) {
    LOG.warn("Exception unmarshalling data", exc);
    throw new IllegalStateException("Exception unmarshalling data", exc);
  }
}
 
Example 6
Source File: AbstractBinder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected <T> T jaxb(XMLEventReader reader, Schema xsd, JAXBContext jaxbContext, Origin origin) {
	final ContextProvidingValidationEventHandler handler = new ContextProvidingValidationEventHandler();

	try {
		final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
		if ( isValidationEnabled() ) {
			unmarshaller.setSchema( xsd );
		}
		else {
			unmarshaller.setSchema( null );
		}
		unmarshaller.setEventHandler( handler );

		return (T) unmarshaller.unmarshal( reader );
	}
	catch ( JAXBException e ) {
		throw new MappingException(
				"Unable to perform unmarshalling at line number " + handler.getLineNumber()
						+ " and column " + handler.getColumnNumber()
						+ ". Message: " + handler.getMessage(),
				e,
				origin
		);
	}
}
 
Example 7
Source File: ApplicationManagementServiceImpl.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Convert xml file of service provider to object.
 *
 * @param spFileContent xml string of the SP and file name
 * @param tenantDomain  tenant domain name
 * @return Service Provider
 * @throws IdentityApplicationManagementException Identity Application Management Exception
 */
private ServiceProvider unmarshalSP(SpFileContent spFileContent, String tenantDomain)
        throws IdentityApplicationManagementException {

    if (StringUtils.isEmpty(spFileContent.getContent())) {
        throw new IdentityApplicationManagementException(String.format("Empty Service Provider configuration file" +
                " %s uploaded by tenant: %s", spFileContent.getFileName(), tenantDomain));
    }
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(ServiceProvider.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        return (ServiceProvider) unmarshaller.unmarshal(new ByteArrayInputStream(
                spFileContent.getContent().getBytes(StandardCharsets.UTF_8)));

    } catch (JAXBException e) {
        throw new IdentityApplicationManagementException(String.format("Error in reading Service Provider " +
                "configuration file %s uploaded by tenant: %s", spFileContent.getFileName(), tenantDomain), e);
    }
}
 
Example 8
Source File: NaturalLanguageUsageGenTest.java    From rice with Educational Community License v2.0 6 votes vote down vote up
public void assertXmlMarshaling(Object naturalLanguageUsage, String expectedXml)
        throws Exception
    {
        JAXBContext jc = JAXBContext.newInstance(NaturalLanguageUsage.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(naturalLanguageUsage, 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 9
Source File: UndertowSpringTypesFactory.java    From cxf with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <V> List<V> parseListElement(Element parent,
                                       QName name,
                                       Class<?> c,
                                       JAXBContext context) throws JAXBException {
    List<V> list = new ArrayList<>();
    Node data = null;

    Unmarshaller u = context.createUnmarshaller();
    Node node = parent.getFirstChild();
    while (node != null) {
        if (node.getNodeType() == Node.ELEMENT_NODE && name.getLocalPart().equals(node.getLocalName())
            && name.getNamespaceURI().equals(node.getNamespaceURI())) {
            data = node;
            Object obj = unmarshal(u, data, c);
            if (obj != null) {
                list.add((V) obj);
            }
        }
        node = node.getNextSibling();
    }
    return list;
}
 
Example 10
Source File: UnmarshalTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void unmarshalUnexpectedNsTest() throws Exception {
    JAXBContext context;
    Unmarshaller unm;
    // Create JAXB context from testTypes package
    context = JAXBContext.newInstance("testTypes");
    // Create unmarshaller from JAXB context
    unm = context.createUnmarshaller();
    // Unmarshall xml document with unqualified dtime element
    Root r = (Root) unm.unmarshal(new InputSource(new StringReader(DOC)));
    // Print dtime value and check if it is null
    System.out.println("dtime is:"+r.getWhen().getDtime());
    assertNull(r.getWhen().getDtime());
}
 
Example 11
Source File: JaxbParser.java    From sword-lang with Apache License 2.0 5 votes vote down vote up
/**
 * 转为对象
 * @param is
 * @return
 */
public Object toObj(InputStream is){
	JAXBContext context;
	try {
		context = JAXBContext.newInstance(clazz);
		Unmarshaller um = context.createUnmarshaller();
		Object obj = um.unmarshal(is);
		return obj;
	} catch (Exception e) {
		logger.error("post data parse error");
		e.printStackTrace();
	}
	return null;
}
 
Example 12
Source File: MDXFormulaHandler.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private static MDXFormulas getFormulasFromXML() throws JAXBException {
	formulas = new MDXFormulas();

	if (loadFile()) {
		JAXBContext jc = JAXBContext.newInstance(MDXFormulas.class);
		Unmarshaller unmarshaller = jc.createUnmarshaller();
		formulas = (MDXFormulas) unmarshaller.unmarshal(xmlFile);
	}
	return formulas;

}
 
Example 13
Source File: LogicalMessageImpl.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
        public Object getPayload(JAXBContext context) {
//            if(context == ctxt) {
//                return o;
//            }
            try {
                Source payloadSrc = getPayload();
                if (payloadSrc == null)
                    return null;
                Unmarshaller unmarshaller = context.createUnmarshaller();
                return unmarshaller.unmarshal(payloadSrc);
            } catch (JAXBException e) {
                throw new WebServiceException(e);
            }
        }
 
Example 14
Source File: LogicalMessageImpl.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
        public Object getPayload(JAXBContext context) {
//            if(context == ctxt) {
//                return o;
//            }
            try {
                Source payloadSrc = getPayload();
                if (payloadSrc == null)
                    return null;
                Unmarshaller unmarshaller = context.createUnmarshaller();
                return unmarshaller.unmarshal(payloadSrc);
            } catch (JAXBException e) {
                throw new WebServiceException(e);
            }
        }
 
Example 15
Source File: TransformationGraphXMLReaderWriter.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
private EndpointSettings instantiateEndpointSettings(org.w3c.dom.Node element) throws GraphConfigurationException {
	try {
		JAXBContext ctx = JAXBContextProvider.getInstance().getContext(EndpointSettings.class);
		Unmarshaller unmarshaller = ctx.createUnmarshaller();
		return (EndpointSettings)unmarshaller.unmarshal(element);
	} catch (Exception e) {
		throw new GraphConfigurationException("Could not parse endpoint settings: " + e.getMessage());
	}
}
 
Example 16
Source File: XmlUtils.java    From AlipayWechatPlatform with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T xml2Object(String xmlStr, Class<T> clazz) {
    try {
        JAXBContext context = JAXBContext.newInstance(clazz);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        T t = (T) unmarshaller.unmarshal(new StringReader(xmlStr));
        return t;
    } catch (JAXBException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 17
Source File: UnmarshalRSSProcess.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private Feed getFeed() {
    try {
        JAXBContext jc = JAXBContext.newInstance(CODEGEN_PACKAGE);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        return (Feed) unmarshaller.unmarshal(new StringReader(FEED));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 18
Source File: PresetGeometries.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unused")
public void init(InputStream is) throws XMLStreamException, JAXBException {
    // StAX:
    EventFilter startElementFilter = new EventFilter() {
        @Override
        public boolean accept(XMLEvent event) {
            return event.isStartElement();
        }
    };
    
    XMLInputFactory staxFactory = StaxHelper.newXMLInputFactory();
    XMLEventReader staxReader = staxFactory.createXMLEventReader(is);
    XMLEventReader staxFiltRd = staxFactory.createFilteredReader(staxReader, startElementFilter);
    // ignore StartElement:
    /* XMLEvent evDoc = */ staxFiltRd.nextEvent();
    // JAXB:
    JAXBContext jaxbContext = JAXBContext.newInstance(BINDING_PACKAGE);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

    long cntElem = 0;
    while (staxFiltRd.peek() != null) {
        StartElement evRoot = (StartElement)staxFiltRd.peek();
        String name = evRoot.getName().getLocalPart();
        JAXBElement<CTCustomGeometry2D> el = unmarshaller.unmarshal(staxReader, CTCustomGeometry2D.class);
        CTCustomGeometry2D cus = el.getValue();
        cntElem++;
        
        if(containsKey(name)) {
            LOG.log(POILogger.WARN, "Duplicate definition of " + name);
        }
        put(name, new CustomGeometry(cus));
    }       
}
 
Example 19
Source File: TSQLQualityProfile.java    From sonar-tsql-plugin with GNU General Public License v3.0 5 votes vote down vote up
private void activeRules(final RulesProfile profile, final String key, final InputStream file) {
	try {

		final JAXBContext jaxbContext = JAXBContext.newInstance(TSQLRules.class);
		final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
		final TSQLRules issues = (TSQLRules) jaxbUnmarshaller.unmarshal(file);
		for (final org.sonar.plugins.tsql.languages.TSQLRules.Rule rule : issues.rule) {
			profile.activateRule(Rule.create(key, rule.getKey()), null);
		}
	}

	catch (final Throwable e) {
		LOGGER.warn("Unexpected error occured while reading rules for " + key, e);
	}
}
 
Example 20
Source File: XmlHelper.java    From herd with Apache License 2.0 3 votes vote down vote up
/**
 * Unmarshalls the xml into JAXB object.
 *
 * @param classType the class type of JAXB element
 * @param xmlString the xml string
 * @param <T> the class type.
 *
 * @return the JAXB object
 * @throws javax.xml.bind.JAXBException if there is an error in unmarshalling
 */
@SuppressWarnings("unchecked")
public <T> T unmarshallXmlToObject(Class<T> classType, String xmlString) throws JAXBException
{
    JAXBContext context = JAXBContext.newInstance(classType);
    Unmarshaller un = context.createUnmarshaller();
    return (T) un.unmarshal(IOUtils.toInputStream(xmlString));
}