0
votes

I'm trying to develop a custom handler for WSO2 Api Manager v3.2. I used the tutorial provided in official docs of WSO2AM: https://apim.docs.wso2.com/en/latest/develop/extending-api-manager/extending-gateway/writing-custom-handlers/

I'm trying to make the handler to add a 'X-Request-ID' header in requests sent to the sample API (PizzaShack), but not even logs can be found. I'm not sure if it's a problem with my code or in the config. I checked through osgi console that the handler is considered ACTIVE within WSO2AM.

My class:

package com.company.wso2.handlers;

import org.apache.synapse.MessageContext;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.rest.AbstractHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Random;

import static org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS;

public class CustomHeaderHandler extends AbstractHandler {

    private static final String REQUEST_ID_HEADER="X-Request-ID";

    private static final Logger LOG = LoggerFactory.getLogger(CustomHeaderHandler.class);

    public boolean handleRequest(MessageContext messageContext) {
        Map<String, String> headers = (Map<String, String>) ((Axis2MessageContext) messageContext).getAxis2MessageContext().
                getProperty(TRANSPORT_HEADERS);

        if (!headers.containsKey(REQUEST_ID_HEADER)) {
            LOG.info("Request-ID missing, adding new Request-ID");
            System.out.println("Request-ID missing, adding new Request-ID");
            headers.put(REQUEST_ID_HEADER, Integer.toHexString(new Random().nextInt(0x9999999) + 0x9999999));
            ((Axis2MessageContext) messageContext).getAxis2MessageContext().setProperty(TRANSPORT_HEADERS, headers);
            return true;
        }

        LOG.debug("Request-ID header present, continuing");
        System.out.println("Request-ID header present, continuing");

        return true;
    }

    public boolean handleResponse(MessageContext messageContext) {
        Map<String, String> headers = (Map<String, String>) ((Axis2MessageContext) messageContext).getAxis2MessageContext().
                getProperty(TRANSPORT_HEADERS);

        if (!headers.containsKey(REQUEST_ID_HEADER)) {
            LOG.info("Request-ID missing, adding new Request-ID in response");
            System.out.println("Request-ID missing, adding new Request-ID in response");
            headers.put(REQUEST_ID_HEADER, Integer.toHexString(new Random().nextInt(0x9999999) + 0x9999999));
            ((Axis2MessageContext) messageContext).getAxis2MessageContext().setProperty(TRANSPORT_HEADERS, headers);
            return true;
        }

        LOG.debug("Request-ID header present, continuing in response");
        System.out.println("Request-ID header present, continuing in response");

        return true;
    }

}


My pom.xml file responsible for creating a jar with the above shown class:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.company.wso2.handlers</groupId>
    <artifactId>custom-header-handler</artifactId>
    <version>0.1</version>
    <packaging>bundle</packaging>

    <name>custom-header-handler</name>

    <dependencies>
        <dependency>
            <groupId>org.apache.synapse</groupId>
            <artifactId>synapse-core</artifactId>
            <version>2.1.7-wso2v10</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>wso2-nexus</id>
            <name>WSO2 internal Repository</name>
            <url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
            <releases>
                <enabled>true</enabled>
                <updatePolicy>daily</updatePolicy>
                <checksumPolicy>ignore</checksumPolicy>
            </releases>
        </repository>

        <repository>
            <id>wso2.releases</id>
            <name>WSO2 internal Repository</name>
            <url>http://maven.wso2.org/nexus/content/repositories/releases/</url>
            <releases>
                <enabled>true</enabled>
                <updatePolicy>daily</updatePolicy>
                <checksumPolicy>ignore</checksumPolicy>
            </releases>
        </repository>

        <repository>
            <id>wso2.snapshots</id>
            <name>Apache Snapshot Repository</name>
            <url>http://maven.wso2.org/nexus/content/repositories/snapshots/</url>
            <snapshots>
                <enabled>true</enabled>
                <updatePolicy>daily</updatePolicy>
            </snapshots>
            <releases>
                <enabled>false</enabled>
            </releases>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>wso2-nexus</id>
            <name>WSO2 internal Repository</name>
            <url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
            <releases>
                <enabled>true</enabled>
                <updatePolicy>daily</updatePolicy>
                <checksumPolicy>ignore</checksumPolicy>
            </releases>
        </pluginRepository>

        <pluginRepository>
            <id>wso2.releases</id>
            <name>WSO2 internal Repository</name>
            <url>http://maven.wso2.org/nexus/content/repositories/releases/</url>
            <releases>
                <enabled>true</enabled>
                <updatePolicy>daily</updatePolicy>
                <checksumPolicy>ignore</checksumPolicy>
            </releases>
        </pluginRepository>

        <pluginRepository>
            <id>wso2.snapshots</id>
            <name>WSO2 Snapshot Repository</name>
            <url>http://maven.wso2.org/nexus/content/repositories/snapshots/</url>
            <snapshots>
                <enabled>true</enabled>
                <updatePolicy>daily</updatePolicy>
            </snapshots>
            <releases>
                <enabled>false</enabled>
            </releases>
        </pluginRepository>
    </pluginRepositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <version>1.4.0</version>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-SymbolicName>com.company.wso2.handlers</Bundle-SymbolicName>
                        <Bundle-Name>com.company.wso2.handlers</Bundle-Name>
                        <Export-Package>
                             com.company.wso2.handlers.*,
                        </Export-Package>
                        <Import-Package>
                            *; resolution:=optional
                        </Import-Package>
                    </instructions>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

After building the jar, I add it into this folder: [WSO2AM_HOME]/repository/components/dropins/ I also added manually this handler class into synapse-config in file [WSO2AM_HOME]/repository/deployment/server/synapse-configs/default/api/admin--PizzaShackAPI_v1.0.0.xml The 'handlers' section is as follows:

<handlers>
        <handler class="org.wso2.carbon.apimgt.gateway.handlers.common.APIMgtLatencyStatsHandler">
            <property name="apiUUID" value="303aa4cb-fd51-4194-b319-aa0410a853f0"/>
        </handler>
        <handler class="org.wso2.carbon.apimgt.gateway.handlers.security.CORSRequestHandler">
            <property name="apiImplementationType" value="ENDPOINT"/>
            <property name="AuthorizationHeader" value="Authorization"/>
        </handler>
        <handler class="org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler">
            <property name="RemoveOAuthHeadersFromOutMessage" value="true"/>
            <property name="APILevelPolicy" value=""/>
            <property name="AuthorizationHeader" value="Authorization"/>
            <property name="keyManagers" value="all"/>
            <property name="CertificateInformation" value="{}"/>
            <property name="APISecurity" value="oauth2,oauth_basic_auth_api_key_mandatory"/>
            <property name="apiUUID" value="303aa4cb-fd51-4194-b319-aa0410a853f0"/>
        </handler>
        <handler class="org.wso2.carbon.apimgt.gateway.handlers.throttling.ThrottleHandler"/>
        <handler class="org.wso2.carbon.apimgt.gateway.handlers.analytics.APIMgtUsageHandler"/>
        <handler class="org.wso2.carbon.apimgt.gateway.handlers.analytics.APIMgtGoogleAnalyticsTrackingHandler">
            <property name="configKey" value="ga-config-key"/>
        </handler>
        <handler class="org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler"/>
        <!-- logging according to docs -->
        <handler class="org.wso2.carbon.apimgt.gateway.handlers.logging.APILogMessageHandler"/>
        <!-- Custom request ID handler -->
        <handler class="com.company.wso2.handlers.CustomHeaderHandler"/>
    </handlers>

Lastly the config of [WSO2AM_HOME]/repository/conf/log4j2.properties file (cut version):

(...)

loggers = (all the loggers provided by default in config), custom-log-handler

(...)

logger.custom-log-handler.name = com.company.wso2.handlers.CustomHeaderHandler
logger.custom-log-handler.level = DEBUG
logger.custom-log-handler.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE

If there is anything else you would like me to provide, feel free to ask. Thank you for any help with this issue.

1

1 Answers

0
votes

I did a quick check on your custom handler. everything works fine.

[2020-11-10 19:28:05,138]  INFO - CustomHeaderHandler Request-ID missing, adding new Request-ID in response
Request-ID missing, adding new Request-ID in response
[2020-11-10 19:29:24,408]  INFO - CustomHeaderHandler Request-ID missing, adding new Request-ID
Request-ID missing, adding new Request-ID
[2020-11-10 19:29:24,486]  INFO - CustomHeaderHandler Request-ID missing, adding new Request-ID in response
Request-ID missing, adding new Request-ID in response

Can you restore the log4j2.properties file from a fresh pack and check the behavior.

This wont make any difference, but change the dependency as follows since you are using the apim 3.2.0

<dependency>
    <groupId>org.apache.synapse</groupId>
    <artifactId>synapse-core</artifactId>
    <version>2.1.7-wso2v183</version>
</dependency>

Also, can you try using apache commons logging.

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

private static final Log LOG = LogFactory.getLog(CustomHeaderHandler.class);

Try the above and share the feedback.