0

我的目标非常简单。我只想将来自 Mule 中 Jersey 模块的 json 响应包装在 JSON 响应中,这样:

{"status": "ok", message:<json-message>}

我尝试使用自定义变压器:

<flow name="sicsRest" doc:name="sicsRest">
    <inbound-endpoint address="http://localhost:65432/RestServices" 
        exchange-pattern="request-response" doc:name="RestEntry" />
    <jersey:resources doc:name="REST">
        <component doc:name="Java">
            <spring-object bean="serviceImpl" />
        </component>
        <custom-transformer returnClass="java.lang.String" 
            class="com.hyperborea.sicsbus.transformer.JsonTransformer" 
            doc:name="JsonTransformer" />
        <jersey:exception-mapper 
            class="com.hyperborea.sicsbus.exception.JsonRestExceptionMapper" />
    </jersey:resources>
</flow>

变压器类:

public class JsonTransformer extends AbstractTransformer {
    @Override 
    protected Object doTransform(Object src, String enc) 
    throws TransformerException {
        return "{\"status\":\"ok\", \"message\":\"" + src + "\"}";
    }
}

不幸的是,它在 Mule 启动期间引发了异常:

org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'custom-transformer'. One of '{"http://www.mulesoft.org/schema/mule/core":abstract-component, "http://www.mulesoft.org/schema/mule/jersey":exception-mapper}' is expected.

有什么建议吗?

4

1 回答 1

2

如果你把你的放在和之间的custom-transformer一个<response> ... </response>块里怎么办?inbound-endpointjersey:resources

编辑

新流程:

<flow name="sicsRest" doc:name="sicsRest">
    <inbound-endpoint ... />
    <response>
        <custom-transformer returnClass="java.lang.String"
            class="com.hyperborea.sicsbus.transformer.JsonTransformer"
            doc:name="JsonTransformer" />
    </response>
    <jersey:resources doc:name="REST">
        <component doc:name="Java">
            <spring-object bean="serviceImpl" />
        </component>
        <jersey:exception-mapper ... />
    </jersey:resources>
</flow>

为了更好地处理输入,必须在 AbstractMessageTransformer 中更改转换器(这对于 AbstractTransformer 几乎是不可能的):

public class JsonTransformer extends AbstractMessageTransformer {
    @Override 
    public Object transformMessage(MuleMessage message, String outputEncoding)
    throws TransformerException {
        try {
            return "{\"status\":\"ok\", \"message.getPayloadAsString()\":\"" 
            + src + "\"}";
        } catch (Exception e) {}
    }
}
于 2012-09-26T22:45:11.033 回答