The osgi combat project (osmp) plays the osgi interceptor step by step (8)

In osmp, osmp-http publishes a unified access interface to the outside world. After accepting request parsing, it obtains services from the osmp-service container, calls and returns the result. In this process, we write custom interceptors to process requests. Interception is mainly used in the following scenarios (security, permissions, data filtering, data formatting, recording input parameters, output parameter logs, calling statistical analysis, full-link logs, etc. AOP behavior).

Below we introduce how to write our first interceptor to intercept requests from illegal IPs under the osmp framework.

 

1. Referring to the development of the first service mentioned above, build a component development environment, and delete the classes and packages that are not available.

2. Added interceptor implementation class OsmpDemoInterceptor.java

 

/*   
 * Project: basic components
 * FileName: SicentTestServiceImpl.java
 * Company: Chengdu Sicent Technology Co.,Ltd
 * version: V1.0
 */
package com.osmp.demo.interceptor;

import org.springframework.stereotype.Component;

import com.osmp.intf.define.config.FrameConst;
import com.osmp.intf.define.interceptor.ServiceInterceptor;
import com.osmp.intf.define.interceptor.ServiceInvocation;
import com.osmp.intf.define.model.ServiceContext;


/**
 * Description: Log interception is used to provide supporting data for statistical log access
 *
 * @author: wangkaiping
 * @date: Sep 26, 2014 3:03:55 PM
 */
@Component
public class OsmpDemoInterceptor implements ServiceInterceptor {


	@Override
	public Object invock(ServiceInvocation invocation) {
		ServiceContext context = invocation.getContext();
		String ip = context.getClientInfo().get(FrameConst.CLIENT_IP);
		String serviceName = context.getServiceName();
		System.out.println("serviceName : " + serviceName);
		System.out.println("IP拦截 : " + ip);
		if ("192.168.1.1".equals(ip)) {
			return "IP illegal!";
		} else {
			return invocation.process();
		}
	}
}

 

 

Implement the interceptor interface ServiceInterceptor.java defined by osmp-intf-define, here we get the ServiceContext context from ServiceInvocation and get client information.

 

Obtain the client IP from the client information to determine whether the client IP is "192.168.1.1" If it is, we return the IP is invalid, if not, execute the request and return!

 

Interceptor interface definition ServiceInterceptor.java

 

/*   
 * Project: OSMP
 * FileName: ServiceInterceptor.java
 * version: V1.0
 */
package com.osmp.intf.define.interceptor;

/**
 * Description:Interceptor
 * All osmp-based interceptors need to implement this interface. The interceptors are divided into three types: global interceptors, BUNDLE interceptors, and SERVICE interceptors according to their scope.
 * Global interceptor (ALL): All BUNDLE and services acting on osmp.
 * BUNDLE interceptor (BUNDLE): Acts on all services under the BUNDLE specified by osmp.
 * SERVICE interceptor (SERVICE): Act on the SERVICE service specified by osmp.
 *
 * The interceptor is suitable for business scenarios such as interface security, permission verification, global log, call chain log Track, and specific service AOP interception
 *
 * When the service is published, you need to specify the type of interceptor (type) and the matching interception strategy (pattern) in service-properties
 *
 * <osgi:service interface="com.osmp.intf.define.interceptor.ServiceInterceptor" ref="osmp.demo.interceptor">
		<osgi:service-properties>
			<entry key="name" value="Interceptor_demo" />
			<entry key="mark" value="拦截器demo"/>
			<entry key="type" value="SERVICE"/> //type:ALL、BUNDLE、SERVICE
			<entry key="pattern" value="This is the published service name"/> //Support regular matching, AAAService* , *AAA* ,   
		</osgi:service-properties>
	</osgi:service>
 *
 * Interceptors are bound to bundles and services in two ways:
 * 1. When the interceptor is installed, when the osmp-service component is monitoring the bundle, it obtains the interface service through the bundle, parses the type and pattern, and injects it into the ServiceContainer.
 * 2. You can bind and unbind interceptors, bundles, and services online through osmp-web.
 *
 * @author: wangkaiping
 *@date: Aug 9, 2016 9:26:32AM 10:51:30AM
 */
public interface ServiceInterceptor {
    Object invock(ServiceInvocation invocation);
}

 

 

ServiceInvocation defines ServiceContext getContext(); Object process(); Two interfaces,

 

The getContext() interface obtains the service context. The context contains the basic information of the requesting client, request parameters, service name, and the requested url string.

 

The process() request execution interface, the default implementation is, first obtain the interceptor corresponding to this service from the interceptor chain, if the interceptor chain is empty, execute the execute() call service of BaseDataService directly, if it is not empty, execute the call interception Chain execution.

 

Defaults to Invocation Implement DefaultServiceInvocation.java

 

/*   
 * Project: OSMP
 * FileName: DefaultServiceInvocation.java
 * version: V1.0
 */
package com.osmp.http.tool;

import java.util.List;

import com.osmp.intf.define.interceptor.ServiceInterceptor;
import com.osmp.intf.define.interceptor.ServiceInvocation;
import com.osmp.intf.define.model.ServiceContext;
import com.osmp.intf.define.service.BaseDataService;

/**
 * Service interceptor call
 * @author heyu
 *
 */
public class DefaultServiceInvocation implements ServiceInvocation {
    private int currentInterceptorIndex = 0;
    private List<ServiceInterceptor> interceptorChain;
    private BaseDataService dataService;
    private ServiceContext context;
    private boolean isError = true;
    
    @Override
    public Object process() {
        if(interceptorChain == null || interceptorChain.isEmpty()){
            isError = false;
            return dataService.execute(context.getParameter());
        }
        if(currentInterceptorIndex == interceptorChain.size()){
            isError =false;
            return dataService.execute(context.getParameter());
        }
        ++currentInterceptorIndex;
        return interceptorChain.get(currentInterceptorIndex-1).invock(this);
    }

    public DefaultServiceInvocation(List<ServiceInterceptor> interceptorChain,
            BaseDataService dataService, ServiceContext context) {
        super();
        this.interceptorChain = interceptorChain;
        this.dataService = dataService;
        this.context = context;
    }

    @Override
    public ServiceContext getContext() {
        return context;
    }

    public boolean isError() {
        return isError;
    }
    

}

 

 

 

 

3. Write the spirng configuration file /src/main/resources/META-INF/spring/spirng-context.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:osgi="http://www.springframework.org/schema/osgi"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
		http://www.springframework.org/schema/osgi http://www.springframework.org/schema/osgi/spring-osgi-1.2.xsd">

	<context:component-scan base-package="com.osmp.demo.interceptor"></context:component-scan>

	<bean id="osmp.demo.interceptor" class="com.osmp.demo.interceptor.OsmpDemoInterceptor" />
	<osgi:service interface="com.osmp.intf.define.interceptor.ServiceInterceptor" ref="osmp.demo.interceptor">
		<osgi:service-properties>
			<entry key="name" value="Interceptor_demo" />
			<entry key="mark" value="拦截器demo"/>
			<entry key="type" value="ALL"/>
			<entry key="pattern" value=""/>
		</osgi:service-properties>
	</osgi:service>
	
</beans>

 

 

  • Publish the interceptor implementation as a service
  • Service attributes include name, mark, type, pattern
  • name: interceptor name
  • mark: Interceptor annotation 
  • type: interceptor type (ALL: global interception BUNDLE: bundle interceptor SERVICE: service interceptor) can be omitted, the default is ALL global interception
  • pattern: interception matching (only type is not valid for ALL, you can omit eg: regular matching, AAAService* , *AAA* )

4. pom.xml configuration

 

<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>
	<parent>
		<groupId>com.osmp.baseweb</groupId>
		<artifactId>osmp-parent</artifactId>
		<version>1.0.0</version>
	</parent>

	<artifactId>osmp-interceptor-demo</artifactId>
	<packaging>bundle</packaging>
	<name>osmp-interceptor-demo</name>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.felix</groupId>
				<artifactId>maven-bundle-plugin</artifactId>
				<extensions>true</extensions>
				<configuration>
					<instructions>
						<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
						<Export-Package></Export-Package>
						<Import-Package>
							*;resolution:=optional
						</Import-Package>
					</instructions>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<dependencies>
		<dependency>
			<groupId>com.osmp.baseweb</groupId>
			<artifactId>osmp-intf-define</artifactId>
			<version>${osmp.version}</version>
		</dependency>
	</dependencies>
</project>

 

5. Package and deploy mvn install, deploy the bundled package (osmp-interceptor-demo-1.0.0.jar) to servicemix

 

 

6. Bind the interceptor in two ways: automatic binding and manual binding:

  • Automatic binding: When deploying the interceptor to servicemix, osmp-service will listen to the interceptor interface service, parse typ and pattern for automatic binding
  • Manual binding: After we deploy the interceptor, if the type and pattern interceptor attributes are not added, we can manually bind by calling the interface provided by osmp-config.

 

 

 

 7. Access request

 

 

 The interceptor has taken effect, let's stop the interceptor



 

visit again



 

 normal return request

 

So far, the development of osmp-based interceptor has been completed.

 

 

 

 

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326450138&siteId=291194637