[3.1.0]使用自定义处理程序发布API时出错

如何解决[3.1.0]使用自定义处理程序发布API时出错

说明: 我正在使用pattern-2。 我只添加了体积,将jar和Velocity_template.xml添加到pubStore pod 这是我的配置:

instance1:

        volumeMounts:
        - name: wso2am-pattern-2-ext-jar-1
          mountPath: /home/wso2carbon/wso2am-3.1.0/repository/components/dropins/org.wso2.carbon.test-1.0-SNAPSHOT.jar
          subPath: org.wso2.carbon.test-1.0-SNAPSHOT.jar
        - name: wso2am-pattern-2-velocity-template-1
          mountPath: /home/wso2carbon/wso2am-3.1.0/repository/resources/api_templates/velocity_template.xml
          subPath: velocity_template.xml
      volumes:
      - name: wso2am-pattern-2-ext-jar-1
        hostPath: 
          path: /mnt/jar/
      - name: wso2am-pattern-2-velocity-template-1
        hostPath:
          path: /mnt/jar/

instance2:

        volumeMounts:
        - name: wso2am-pattern-2-ext-jar-2
          mountPath: /home/wso2carbon/wso2am-3.1.0/repository/components/dropins/org.wso2.carbon.test-1.0-SNAPSHOT.jar
          subPath: org.wso2.carbon.test-1.0-SNAPSHOT.jar
        - name: wso2am-pattern-2-velocity-template-2
          mountPath: /home/wso2carbon/wso2am-3.1.0/repository/resources/api_templates/velocity_template.xml
          subPath: velocity_template.xml
      volumes:
      - name: wso2am-pattern-2-ext-jar-2
        hostPath: 
          path: /mnt/jar/
      - name: wso2am-pattern-2-velocity-template-2
        hostPath:
          path: /mnt/jar/

自定义处理程序代码:

package org.wso2.carbon.test;
import org.apache.synapse.MessageContext;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.rest.AbstractHandler;


import java.util.Map;

public class CustomAPIResponseHandler extends AbstractHandler {

    public boolean handleRequest(MessageContext messageContext) {
        return true;
    }

    public boolean handleResponse(MessageContext messageContext) {
        if(doit(messageContext).equals("virus"))
        {
            Map headers=add(messageContext);
            setTransportHeaders( messageContext,headers);
        }
        return true;
    }

    public String doit(MessageContext synCtx) {
        Map headers = getTransportHeaders(synCtx);
        String aString = getHeader(headers);
        return aString;
    }
    public Map add(MessageContext synCtx) {
        Map headers = getTransportHeaders(synCtx);
        setHeader(headers);
        return headers;
    }

    private void setHeader(Map headers) {
        headers.put("handlers","activited");
    }
    private String getHeader(Map headers) {
        return (String) headers.get("safety");
    }
    private void setTransportHeaders(MessageContext messageContext,Map headers) {
        messageContext.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS,headers);
    }
    private Map getTransportHeaders(MessageContext messageContext) {
        return (Map) ((Axis2MessageContext) messageContext).getAxis2MessageContext().
                getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    }
}

velocity_template.xml:

<!--
 ~ Copyright (c) 2005-2010,WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 ~
 ~ WSO2 Inc. licenses this file to you under the Apache License,~ Version 2.0 (the "License"); you may not use this file except
 ~ in compliance with the License.
 ~ You may obtain a copy of the License at
 ~
 ~    http://www.apache.org/licenses/LICENSE-2.0
 ~
 ~ Unless required by applicable law or agreed to in writing,~ software distributed under the License is distributed on an
 ~ "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY
 ~ KIND,either express or implied.  See the License for the
 ~ specific language governing permissions and limitations
 ~ under the License.
 -->

        #####################  Define the macros ######################

        #macro ( print_string_if_exist $field $default)
        #if($field && "$field" !="")
        "$field"
        #else
        "$default"
        #end
        #end

        #macro ( draw_endpoint $type $endpoint_config )

        #set( $endpointClass = $endpoint_config.get("endpoint_type") )
        #set( $endpoints = $endpoint_config.get("${type}_endpoints"))
        #set( $ep_key = "${endpointKey}_API${type}Endpoint")
        #set( $endpointsecurity = $endpoint_security.get("${type}"))

        ## IF endpoint secured
        #if($endpointsecurity.enabled)
        #if($isSecureVaultEnabled)
<property xmlns="http://ws.apache.org/ns/synapse" name="password" expression="wso2:vault-lookup('$endpointsecurity.alias')"/>
<property xmlns="http://ws.apache.org/ns/synapse" name="unpw" expression="fn:concat('$username',':',get-property('password'))"/>
<property xmlns="http://ws.apache.org/ns/synapse" name="Authorization" expression="fn:concat('Basic ',base64Encode(get-property('unpw')))" scope="transport"/>
        #else
        #if($endpointsecurity.type == "digest" || $endpointsecurity.type == "DIGEST")
<property xmlns="http://ws.apache.org/ns/synapse" name="UNAMEPASSWORD" value="$util.escapeXml($endpointsecurity.base64EncodedPassword)" type="STRING"/>
<property name="BACKEND_URL" value="$util.escapeXml($endpoints.get("url"))"/>
<property name="POSTFIX" expression="get-property('axis2','REST_URL_POSTFIX')"/>
<property name="HTTP_METHOD" expression="get-property('axis2','HTTP_METHOD')"/>
<property name="POST_TO_URI" value="true" scope="axis2"/>
<property name="MessageType" expression="get-property('axis2','messageType')"/>

<enrich>
<source type="body" clone="true"/>
<target type="property" property="MessageBody"/>
</enrich>

<call>
<endpoint key="$ep_key"/>
</call>

<class name="org.wso2.carbon.apimgt.gateway.mediators.DigestAuthMediator"/>

<property name="Authorization" expression="get-property('AuthHeader')" scope="transport"/>
<property name="messageType" expression="get-property('MessageType')" scope="axis2"/>
<property name="HTTP_METHOD" expression="get-property('HTTP_METHOD')" scope="axis2"/>
<property name="REST_URL_POSTFIX" expression="$ctx:POSTFIX" scope="axis2"/>
<property name="POST_TO_URI" value="true" scope="axis2"/>

<enrich>
<source type="property" property="MessageBody" clone="true"/>
<target type="body"/>
</enrich>

        #else
<property xmlns="http://ws.apache.org/ns/synapse" name="Authorization" expression="fn:concat('Basic ','$endpointsecurity.base64EncodedPassword')" scope="transport"/>
        #end
        #end
        #end
<send>

## If endpoint is http
#if ($endpointClass == "http")
<endpoint xmlns="http://ws.apache.org/ns/synapse" key="$ep_key"/>
#elseif ($endpointClass == "address")
<endpoint xmlns="http://ws.apache.org/ns/synapse" key="$ep_key"/>
#elseif ($endpointClass == "wsdl")
<endpoint xmlns="http://ws.apache.org/ns/synapse" name="$ep_name">
    #if (${type} == "production")
    <wsdl uri="$util.escapeXml($endpoints.get("url"))" service="$!endpoint_config.get("wsdlendpointService")" port="$!endpoint_config.get("wsdlendpointPort")">
    #timeout()
</wsdl>
#else
<wsdl uri="$util.escapeXml($endpoints.get("url"))" service="$!endpoint_config.get("wsdlendpointServiceSandbox")" port="$!endpoint_config.get("wsdlendpointPortSandbox")">
#timeout()
</wsdl>
        #end
<property name="ENDPOINT_ADDRESS" value="$util.escapeXml($endpoints.get("url"))"/>
        </endpoint>
        #elseif ($endpointClass == "failover")
        #set( $failover_endpoints = $endpoint_config.get("${type}_failovers"))
<endpoint xmlns="http://ws.apache.org/ns/synapse" key="$ep_key"/>
        #elseif ($endpointClass == "load_balance")
<endpoint xmlns="http://ws.apache.org/ns/synapse" key="$ep_key"/>
        #elseif ($endpointClass == "default")
<endpoint key="$ep_key"/>
        #end
        </send>
        #end

        ######################## End of Macros ######################################


<api xmlns="http://ws.apache.org/ns/synapse"  name="$!apiName" context="$!apiContext" version="$!apiVersion" transports="$!transport" version-type="context">
#if($apiIsBlocked)
## if API is blocked send the API Block message
<resource methods="GET POST PUT DELETE PATCH" url-mapping="/*" faultSequence=#print_string_if_exist($faultSequence "fault")>
<inSequence>
    <payloadFactory>
        <format>
            <am:fault xmlns:am="http://wso2.org/apimanager">
                <am:code>700700</am:code>
                <am:message>API blocked</am:message>
                <am:description>This API has been blocked temporarily. Please try again later or contact the system administrators.</am:description>
            </am:fault>
        </format>
    </payloadFactory>
    <property name="HTTP_SC" value="503" scope="axis2"/>
    <property name="RESPONSE" value="true"/>
    <property name="NO_ENTITY_BODY" scope="axis2" action="remove"/>
    <header name="To" action="remove"/>
    <send/>
</inSequence>
</resource>
        #else
        ## api not blocked
        #set ($resourceNo = 0)
        #foreach($resource in $resources)

<resource xmlns="http://ws.apache.org/ns/synapse"
        #if($resource.getUriTemplate().contains("{") ||
        ($resource.getUriTemplate().contains("*") && !$resource.getUriTemplate().endsWith("/*")))
        uri-template="$util.escapeXml($resource.getUriTemplate())"
        #else
        url-mapping="$resource.getUriTemplate()"
        #end
        methods="$resource.getMethodsAsString()" faultSequence=#print_string_if_exist($faultSequence "fault")>
<inSequence>
## check and set response caching
#if($responseCacheEnabled)
<cache scope="per-host" collector="false" hashGenerator="org.wso2.carbon.mediator.cache.digest.REQUESTHASHGenerator" timeout="$!responseCacheTimeOut">
    <implementation type="memory" maxSize="500"/>
</cache>
#end
<property name="api.ut.backendRequestTime" expression="get-property('SYSTEM_TIME')"/>
#if($isSoapToRestMode)
<property name="HTTP_METHOD" value="POST" scope="axis2" type="STRING"/>
#foreach($uri in $in_sequences.get("$resource.getUriTemplate()").keySet())
$in_sequences.get("$resource.getUriTemplate()").get($uri)
#end
#end
##############  define the filter based on environment type production only,sandbox only,hybrid ############

#if(($environmentType == 'sandbox') || ($environmentType =='hybrid' && !$endpoint_config.get("production_endpoints") ))
#set( $filterRegex = "SANDBOX" )
#else
#set( $filterRegex = "PRODUCTION" )
#end
## AWS Lambda: start
#if($endpoint_config.get("endpoint_type") == 'awslambda')
#set( $accessKey = $!{endpoint_config.get("amznAccessKey")} )
#set( $secretKey = $!{endpoint_config.get("amznSecretKey")} )
#set( $resourceName = $!{resource.getAmznResourceName()} )
<class name="org.wso2.carbon.apimgt.gateway.mediators.AWSLambdaMediator">
    #if($accessKey != '')
    <property name="accessKey" value="$accessKey"/>
    #end
    #if($secretKey != '')
    <property name="secretKey" value="$secretKey"/>
    #end
    #if($resourceName != '')
    <property name="resourceName" value="$resourceName"/>
    #end
</class>
<loopback />
## AWS Lambda: end
#else
#if($apiStatus != 'PROTOTYPED' && $apiIsOauthProtected)
<filter source="$ctx:AM_KEY_TYPE" regex="$filterRegex">
    <then>
        #end
        #if(($environmentType == 'sandbox') || ($environmentType =='hybrid' && ! $endpoint_config.get("production_endpoints") ))
        #draw_endpoint( "sandbox" $endpoint_config )
        #else
        #draw_endpoint( "production" $endpoint_config )
        #end
        #if($apiStatus != 'PROTOTYPED' && $apiIsOauthProtected)
    </then>
    <else>
        #if($environmentType !='hybrid')
        <payloadFactory>
            <format>
                <error xmlns="">
                    #if($environmentType == 'production')
                    <message>Sandbox Key Provided for Production Gateway</message>
                    #elseif($environmentType == 'sandbox')
                    <message>Production Key Provided for Sandbox Gateway</message>
                    #end
                </error>
            </format>
        </payloadFactory>
        <property name="ContentType" value="application/xml" scope="axis2"/>
        <property name="RESPONSE" value="true"/>
        <header name="To" action="remove"/>
        <property name="HTTP_SC" value="401" scope="axis2"/>
        <property name="NO_ENTITY_BODY" scope="axis2" action="remove"/>
        <send/>
        #else
        #if($endpoint_config.get("production_endpoints") && $endpoint_config.get("sandbox_endpoints"))
        #draw_endpoint( "sandbox" $endpoint_config )
        #elseif($endpoint_config.get("production_endpoints"))
        <sequence key="_sandbox_key_error_"/>
        #elseif($endpoint_config.get("sandbox_endpoints"))
        <sequence key="_production_key_error_"/>
        #end
        #end
    </else>
</filter>
#end
#end
</inSequence>
<outSequence>
#if($isSoapToRestMode)
#foreach($uri in $out_sequences.get("$resource.getUriTemplate()").keySet())
$out_sequences.get("$resource.getUriTemplate()").get($uri)
#end
#end
#if($apiStatus != 'PROTOTYPED')
<class name="org.wso2.carbon.apimgt.gateway.handlers.analytics.APIMgtResponseHandler"/>
#end
## check and set response caching
#if($responseCacheEnabled)
<cache scope="per-host" collector="true"/>
#end
<send/>
</outSequence>
        </resource>
        #set ($resourceNo = $resourceNo + 1)
        #end  ## end of resource iterator
        ## print the handlers
        #if($handlers.size() > 0)
<handlers xmlns="http://ws.apache.org/ns/synapse">
<handler class="org.wso2.carbon.test.CustomAPIResponseHandler"/>
#foreach($handler in $handlers)
<handler xmlns="http://ws.apache.org/ns/synapse" class="$handler.className">
    #if($handler.hasProperties())
    #set ($map = $handler.getProperties() )
    #foreach($property in $map.entrySet())
    <property name="$!property.key" value="$!property.value"/>
    #end
    #end
</handler>
#end
## check and set enable schema validation
#if($enableSchemaValidation)
<handler class="org.wso2.carbon.apimgt.gateway.handlers.security.SchemaValidator"/>
#end
</handlers>
        #end
        #end
        #if($apiStatus == 'PROTOTYPED')
        #end
        ## end of apiIsBlocked check
</api>
        <!--$endpoint_security-->

**受影响的产品版本:3.1.0

** OS,DB,其他环境详细信息和版本:CentOS,Kubernetes,JAVA11,mysql

**我正在使用kubernetes-apim。https://github.com/wso2/kubernetes-apim 日志太大,无法发布,请参阅https://github.com/wso2/kubernetes-apim/issues/441

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-