当前位置: 首页 > 知识库问答 >
问题:

如何将wsdl内部模式设置为Jaxb2Marshaller,以验证我所做的每个帖子?

梁丘经艺
2023-03-14

我正在使用一个SOAP webservice,在调用之前必须验证每个xml post。

所以我在使用:

  • 生成POJO树结构的cxf-codegen-plugin。
  • 第三部分wsdl(xxxx-soap-service.wsdl)
  • 实现WebServiceGatewaySupport spring接口进行调用的类。
  • jaxb2marshallerspring marshaller/unmarshaller转换pojo<··>XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
                        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
                        http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd">

    <mybatis:scan base-package="com.company.integration.xxxx.domain.mybatis.mapper" />

    <context:component-scan base-package="com.company.integration.remo" />

    <bean id="xxxxMarshallerProperties" class="com.company.integration.xxxx.domain.properties.XxxxMarshallerProperties"/>

    <bean id="xxxxMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller" depends-on="xxxxMarshallerProperties">
        <property name="contextPath" value="#{xxxxMarshallerProperties.contextPath}"/>
        <property name="validationEventHandler" value="#{xxxxMarshallerProperties.validationEventHandler}"/>
        <property name="schema" value="#{xxxxMarshallerProperties.schema}"/>
    </bean>

    <bean id="xxxxService" class="com.company.integration.xxxx.domain.client.XxxxServiceImpl">
        <property name="defaultUri" value="#{'${xxxx.baseUrl}' + '${xxxx.url.sufix}'}" />
        <property name="marshaller" ref="xxxxMarshaller" />
        <property name="unmarshaller" ref="xxxxMarshaller" />
    </bean>

    <bean id="xxxxObjectFactory" class="com.company.integration.xxxx.domain.model.ObjectFactory" />


</beans>
public Resource getSchema() throws IOException, SAXException {
    WebServiceClient wscAnnotation = Service.class.getAnnotation(WebServiceClient.class);
    String wsdlLocationPath = wscAnnotation.wsdlLocation();
    Resource wsdlResource = resourceLoader.getResource(wsdlLocationPath);
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URI wsdlUri = wsdlResource.getURI();
    Source[] streamSources = new Source[] { new StreamSource(wsdlUri.toString()) };
    final Schema wsdlSchema = schemaFactory.newSchema(streamSources);
    return wsdlSchema;
}

public DefaultValidationEventHandler getValidationEventHandler() {
    return new DefaultValidationEventHandler();
}

public String getContextPath() {
    return XXXXX.class.getPackage().getName();
}

}

用于调用WebService的xxxxService bean类:

公共类XxxxServiceImpl扩展WebServiceGatewaySupport实现ServiceSoap{

@Autowired
XxxxProperties xxxxProperties;

@Autowired
private ObjectFactory xxxxObjectFactory;

@Autowired
private ResourceLoader resourceLoader;

private String getActionUrl(String actionName) {
    return xxxxProperties.getActionNamespace() + actionName;
}

public CXXXX callXXXX(CallXXXX request) {
    Jaxb2Marshaller marshaller = (Jaxb2Marshaller) getMarshaller();
    Result result = new StringResult();

    CallXXXXResponse response = (CallXXXXResponse) getWebServiceTemplate().marshalSendAndReceive(request,
        new WebServiceMessageCallback() {

            public void doWithMessage(WebServiceMessage message) {
                ((SoapMessage) message).setSoapAction(getActionUrl(xxxxProperties.getSoapActionCallXXXX()));
            }
        });
    return response.getCallXXXXResult();
}

你能用那种方式帮我吗?

我愿意探索其他方法或更好的解决方案。

共有1个答案

巫马越彬
2023-03-14

最后,我找到了一个适合我的实现。

这个想法是:

  • 从wsdl中提取嵌入的模式,
  • 配置每个架构命名空间,
  • 在其中添加所有尚未定义但在 标记上定义的实名空间,
  • 配置每个架构导入和位置,
  • 将每个模式存储到Spring资源接口的实现类中,
  • 将它们全部存储到资源数组中
  • 并通过setSchema[s]而不是setSchema(正如我所做的那样)将该数组传递给Jaxb2Marshaller。
@Component
public class XxxxMarshallerProperties {
    @Autowired
    private ResourceLoader resourceLoader;

    /**
     * @return A new transformer.
     * @throws TransformerFactoryConfigurationError
     * @throws TransformerConfigurationException
     */
    private Transformer newTransformer()
        throws TransformerFactoryConfigurationError, TransformerConfigurationException {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        return transformer;
    }

    /**
     * Load the wsdl into a dom Document. Used at:<br/>
     * &nbsp;&nbsp;&nbsp;&nbsp;<b>getSchemas</b>
     *
     * @param wsdlUrl
     *            url where the WSDL is located at
     * @param transformer
     *            used to load the document
     * @return The wsdl dom Document
     * @throws ParserConfigurationException
     * @throws IOException
     * @throws TransformerException
     */
    private Document loadWsdlDoc(URL wsdlUrl, Transformer transformer)
        throws ParserConfigurationException, IOException, TransformerException {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder schemaBuilder = docFactory.newDocumentBuilder();
        Document wsdlDoc = schemaBuilder.newDocument();
        BufferedReader wsdlReader = new BufferedReader(new InputStreamReader(wsdlUrl.openStream()));
        Source source = new StreamSource(wsdlReader);
        transformer.transform(source, new DOMResult(wsdlDoc));
        return wsdlDoc;
    }

    /**
     * Store into a map all namespaces defined on the wsdl. Used at:<br/>
     * &nbsp;&nbsp;&nbsp;&nbsp;<b>getSchemas</b>
     *
     * @param defNode
     *            &lt;<b><i>wsdl:definitions</i></b>&gt; dom node where to look
     *            up.
     * @return A map of namespace definition attributes. Format: [(nodeName,
     *         node)....]
     */
    private Map<String, Node> getWsdlDefinedNamespaces(Element defNode) {
        Map<String, Node> namespaces = new TreeMap<>();
        NamedNodeMap defNodeAtt = defNode.getAttributes();
        int defNodeAttSz = defNodeAtt.getLength();
        for (int attIndex = 0; attIndex < defNodeAttSz; attIndex++) {
            String ns = defNodeAtt.item(attIndex).getPrefix();
            if ("xmlns".equals(ns)) {
                namespaces.put(//
                    defNodeAtt.item(attIndex).getNodeName(), //
                    defNodeAtt.item(attIndex));
            }
        }

        return namespaces;
    }

    /**
     * Store into a map all the atributes present in a xsd schema node. Used at:
     * <br/>
     * &nbsp;&nbsp;&nbsp;&nbsp;<b>addDefinitionNamespaces</b>
     *
     * @param wsdlSchemaNode
     *            &lt;<b><i>s:schema</i></b>&gt; dom node where to look up.
     * @return A map of attributes. Format: [(nodeName, node)....]
     */
    private Map<String, Node> getCurrentSchemaAtt(Node wsdlSchemaNode) {
        Map<String, Node> schemaXmlnss = new HashMap<>();

        NamedNodeMap schemaNodeAtt = wsdlSchemaNode.getAttributes();
        int schemaNodeAttSz = schemaNodeAtt.getLength();
        for (int attIndex = 0; attIndex < schemaNodeAttSz; attIndex++) {
            String nodeAttName = schemaNodeAtt.item(attIndex).getNodeName();
            Node nodeAtt = ((NamedNodeMap) schemaNodeAtt).item(attIndex);
            schemaXmlnss.put(nodeAttName, nodeAtt);
        }
        return schemaXmlnss;
    }

    /**
     * Adds all non existing namespace definition attributes to a schema node in
     * that schema node. If a namespace definition attribute name is found into
     * schema node, it's not added to the current schema node attributes. Used
     * at: <br/>
     * &nbsp;&nbsp;&nbsp;&nbsp;<b>getSchemas</b>
     *
     * @param schemaNode
     *            &lt;<b><i>s:schema</i></b>&gt; dom node where to add the
     *            namespace definition attributes.
     * @param namespaces
     *            map storing all namespace definition attributes.
     */
    private void addDefinitionNamespaces(Node schemaNode, Map<String, Node> namespaces) {
        Map<String, Node> currSchemaAttMap = getCurrentSchemaAtt(schemaNode);
        for (Node xmlns : namespaces.values()) {
            String nodeName = xmlns.getNodeName();
            if (!currSchemaAttMap.containsKey(nodeName)) {
                String namespaceURI = xmlns.getNamespaceURI();
                String nodeValue = xmlns.getNodeValue();
                ((Element) schemaNode).setAttributeNS(namespaceURI, nodeName, nodeValue);
            }
        }
    }

    /**
     * Update schema location by adding path. Used at: <br/>
     * &nbsp;&nbsp;&nbsp;&nbsp;<b>getSchemas</b>
     *
     * @param schemaNode
     *            &lt;<b><i>s:schema</i></b>&gt; dom node to update its
     *            location.
     * @return The updated schema.
     */
    private DOMSource updateSchemaLocationByAddingPath(Node schemaNode) {
        DOMSource schemaDomSource = new DOMSource(schemaNode);
        NodeList noteList = schemaDomSource.getNode().getChildNodes();
        for (int j = 0; j < noteList.getLength(); j++) {
            if ("xsd:import".equals(noteList.item(j).getNodeName())) {
                NamedNodeMap nodeMap = noteList.item(j).getAttributes();
                for (int attIndex = 0; attIndex < nodeMap.getLength(); attIndex++) {
                    if ("schemaLocation".equals(nodeMap.item(attIndex).getNodeName())) {
                        nodeMap.item(attIndex).setNodeValue(nodeMap.item(attIndex).getNodeValue());
                    }
                }
            }
        }
        return schemaDomSource;
    }

    /**
     * Transform a DOMSource schema into a spring's {@link Resource} to be
     * attached to a {@link Jaxb2Marshaller}.
     *
     * @param schemaDomSource
     *            The schema to be transformed.
     * @param transformer
     *            The transformer used.
     * @return A spring's {@link Resource} interface.
     * @throws TransformerException
     */
    private Resource transformToResource(DOMSource schemaDomSource, Transformer transformer)
        throws TransformerException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        Result result = new StreamResult(outStream);
        transformer.transform(schemaDomSource, result);
        ByteArrayResource schemaResource = new ByteArrayResource(outStream.toByteArray());
        return schemaResource;
    }

    /**
     * Generate and retrieves all schemas contained into a wsdl file stored in
     * the classpath, in an {@link Resource} array, to be attached to a
     * {@link Jaxb2Marshaller} .
     *
     * @return An {@link Resource} array.
     * @throws IOException
     * @throws SAXException
     * @throws ParserConfigurationException
     * @throws TransformerException
     */
    public Resource[] getSchemas()
        throws IOException, SAXException, ParserConfigurationException, TransformerException {
        Resource[] schemaResources = null;

        WebServiceClient wscAnnotation = Service.class.getAnnotation(WebServiceClient.class);
        String wsdlLocationPath = wscAnnotation.wsdlLocation();
        Resource wsdlResource = resourceLoader.getResource(wsdlLocationPath);
        URL wsdlUri = wsdlResource.getURL();

        Transformer transformer = newTransformer();
        Document wsdlDoc = loadWsdlDoc(wsdlUri, transformer);
        NodeList schemaNodes = wsdlDoc.getElementsByTagNameNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "schema");
        int nrSchemas = schemaNodes.getLength();
        if (nrSchemas > 0) {
            Element defNode = wsdlDoc.getDocumentElement();
            Map<String, Node> namespaces = getWsdlDefinedNamespaces(defNode);

            schemaResources = new Resource[nrSchemas];

            for (int i = 0; i < nrSchemas; i++) {
                Node schemaNode = schemaNodes.item(i);
                addDefinitionNamespaces(schemaNode, namespaces);
                DOMSource schemaDomSource = updateSchemaLocationByAddingPath(schemaNode);
                schemaResources[i] = transformToResource(schemaDomSource, transformer);
            }
        }

        return schemaResources;
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
                        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
                        http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd">

    <mybatis:scan base-package="com.company.integration.xxxx.domain.mybatis.mapper" />

    <context:component-scan base-package="com.company.integration.remo" />

    <bean id="xxxxMarshallerProperties" class="com.company.integration.xxxx.domain.properties.XxxxMarshallerProperties"/>

    <bean id="xxxxMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller" depends-on="xxxxMarshallerProperties">
        <property name="contextPath" value="#{xxxxMarshallerProperties.contextPath}"/>
        <property name="validationEventHandler" value="#{xxxxMarshallerProperties.validationEventHandler}"/>
        <property name="schemas" value="#{xxxxMarshallerProperties.schemas}"/>
    </bean>

    <bean id="xxxxService" class="com.company.integration.xxxx.domain.client.XxxxServiceImpl">
        <property name="defaultUri" value="#{'${xxxx.baseUrl}' + '${xxxx.url.sufix}'}" />
        <property name="marshaller" ref="xxxxMarshaller" />
        <property name="unmarshaller" ref="xxxxMarshaller" />
    </bean>

    <bean id="xxxxObjectFactory" class="com.company.integration.xxxx.domain.model.ObjectFactory" />


</beans>
 类似资料:
  • 我想使用模式验证JSON(目前草案6,但如果需要,我们可以升级)。我的案例是一个具有属性的对象,其值都具有相同的结构,例如: 是否有办法为一般属性值设置验证模式?类似的东西: 谢谢你。

  • 考虑到此XML: 我只想验证“祖父”及其属性,而忽略XML的其余部分。为此,我在模式中添加了这一行:type=“xs:anyType” 正在使用的XSD如下所示: 我怎能无视“父亲”下面的一切?

  • 我有一个textarea在一个角ui模式,需要设置焦点时,模式是可见的,不能在文档加载,因为它只工作在第一次打开模式。 更多信息:在某种程度上解决了始终保持对textarea的关注的问题。 但是由于我的模式在动画中有一个淡入淡出,在IE中焦点显示在文本框上方,在外部,我不得不使用timeout到IE来正确设置焦点。那可不太好。更好的办法?

  • > 应用程序A在Q1中发布消息。 应用程序B使用来自Q1的消息,进行一些处理,并在Q2中发布其他消息。B仅在Q2中成功发布消息后才对来自Q1的消息进行ACK。 应用程序C使用来自Q2的消息,进行一些处理,并将一些内容写入数据库。 如果我能限制每个队列的内存和磁盘使用量,而不是限制整个RabbitMQ的内存和磁盘使用量,我想这是可以解决的。有没有办法做到这一点,或者另一种方法来解决我的问题? 如果需

  • 每年,我都希望我的Firebase用户再次验证他们的帐户电子邮件,检查他们的电子邮件地址是否还在使用。 为了测试这一点,我向我(已验证)帐户发送了一封新的验证电子邮件。邮件已发送,但这并没有将我的,这也是在重新加载和应用程序之后。 有人知道是否可以将设置为false,一旦它完全为true,如果是这样,如何做到这一点?

  • 问题内容: 我在詹金斯(Jenkins)有大约10个项目,每个项目针对10个不同的客户。因此,我需要为所有项目创建凭据,以便每个客户端只能访问其项目。 有任何插件可以满足我的要求吗? 请帮忙 !!! 问题答案: 在“全局安全性”下选择“基于项目的矩阵授权策略” 定义普通用户,但不能访问此级别的项目。 然后在每个项目上选择“启用基于项目的安全性”,在这里您可以为单个用户授予其他权限,例如查看和执行作