lizongbo at 618119.com 工作,生活,Android,前端,Linode,Ubuntu,nginx,java,apache,tomcat,Resin,mina,Hessian,XMPP,RPC

2008年03月7日

Apache MINA 2.0.0-M1 试用体会

Filed under: Java,SSL — 标签:, , , — lizongbo @ 14:15

Apache MINA 2.0.0-M1 的api比1.x更简单好用了,

新增加了许多filter功能,各个filter 功能在filter包下面以子目录方式存放,例如:

org.apache.mina.filter.executor.ExecutorFilter

org.apache.mina.filter.ssl.SslFilter

org.apache.mina.filter.keepalive.KeepAliveFilter

org.apache.mina.filter.compression.CompressionFilter
org.apache.mina.filter.firewall.BlacklistFilter
org.apache.mina.filter.logging.LoggingFilter

[code]

public static void main(String[] args) throws IOException, Exception {
IoAcceptor acceptor = new NioSocketAcceptor();
DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
//Utils.addServerSSLSupport(chain);
Utils.addThreadPool(chain);
// Utils.addCompress(chain);
Utils.addCodec(chain);
Utils.addLogger(chain);
SMPPServerSessionHandler handlers = new SMPPServerSessionHandler();
handlers.getHandles().put(Integer.valueOf(0x00000001),
new com.lizongbo.smpp.server.handlers.
BindReceiverHandler());
handlers.getHandles().put(Integer.valueOf(0x00000002),
new com.lizongbo.smpp.server.handlers.
BindTransmitterHandler());
handlers.getHandles().put(Integer.valueOf(0x00000004),
new com.lizongbo.smpp.server.handlers.
SubmitSMHandler());
handlers.getHandles().put(Integer.valueOf(0x00000006),
new com.lizongbo.smpp.server.handlers.
UnbindHandler());
InetSocketAddress serverAddr = new InetSocketAddress(Utils.PORT);
acceptor.setHandler(handlers);
acceptor.bind(serverAddr);
System.out.println(“Listening on port ” + Utils.PORT);
}

[/code]

spring配置的bean也有所变动

[code]

<?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:aop=”http://www.springframework.org/schema/aop”
xmlns:util=”http://www.springframework.org/schema/util”
xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd”>
<util:constant id=”ie.omk.smpp.message.BIND_TRANSMITTER”
static-field=”ie.omk.smpp.message.SMPPPacket.BIND_TRANSMITTER” />
<bean id=”com.lizongbo.smpp.server.handlers.BindTransmitterHandler”
class=”com.lizongbo.smpp.server.handlers.BindTransmitterHandler” />
<bean id=”com.lizongbo.smpp.server.handlers.BindReceiverHandler”
class=”com.lizongbo.smpp.server.handlers.BindReceiverHandler” />
<bean id=”com.lizongbo.smpp.server.handlers.SubmitSMHandler”
class=”com.lizongbo.smpp.server.handlers.SubmitSMHandler” />
<bean id=”com.lizongbo.smpp.server.handlers.UnbindHandler”
class=”com.lizongbo.smpp.server.handlers.UnbindHandler” />
<util:map id=”handlers” key-type=”java.lang.Integer”>
<entry key=”0x00000002″>
<ref
local=”com.lizongbo.smpp.server.handlers.BindTransmitterHandler” />
</entry>
<entry key=”0x00000001″>
<ref
local=”com.lizongbo.smpp.server.handlers.BindReceiverHandler” />
</entry>
<entry key=”0x00000004″>
<ref
local=”com.lizongbo.smpp.server.handlers.SubmitSMHandler” />
</entry>
<entry key=”0x00000006″>
<ref
local=”com.lizongbo.smpp.server.handlers.UnbindHandler” />
</entry>
</util:map>
<bean
class=”org.springframework.beans.factory.config.CustomEditorConfigurer”>
<property name=”customEditors”>
<map>
<entry key=”java.net.SocketAddress”>
<bean
class=”org.apache.mina.integration.beans.InetSocketAddressEditor” />
</entry>
</map>
</property>
</bean>
<!– The IoHandler delegate implementation –>
<bean id=”smppHandler”
class=”com.lizongbo.smpp.server.SMPPServerSessionHandler”>
<property name=”handles”>
<ref local=”handlers” />
</property>
<property name=”readerIdleTimeout”>
<value>600</value>
</property>
</bean>
<!– The protocol codec factory for smpp –>
<bean id=”smppProtocolCodecFactory”
class=”com.lizongbo.smpp.server.codec.SMPPProtocolCodecFactory”>
</bean>
<util:map id=”mfilters” key-type=”java.lang.String”
value-type=”org.apache.mina.common.IoFilter”
map-class=”java.util.LinkedHashMap”>
<entry key=”threadpool”>
<bean
class=”org.apache.mina.filter.executor.ExecutorFilter” />
</entry>
<!– entry key=”compress”>
<bean
class=”org.apache.mina.filter.compression.CompressionFilter” />
</entry–>
<entry key=”codec”>
<bean
class=”org.apache.mina.filter.codec.ProtocolCodecFilter”>
<constructor-arg ref=”smppProtocolCodecFactory” />
</bean>
</entry>
<entry key=”logger”>
<bean class=”org.apache.mina.filter.logging.LoggingFilter” />
</entry>
</util:map>
<bean id=”smppFilterChainBuilder”
class=”org.apache.mina.common.DefaultIoFilterChainBuilder”>
<property name=”filters” ref=”mfilters” />
</bean>
<util:list id=”ipaddrs” value-type=”java.net.InetSocketAddress”>
<value>0.0.0.0:5432</value>
<value>0.0.0.0:5433</value>
</util:list>
<bean id=”smppAcceptor”
class=”org.apache.mina.transport.socket.nio.NioSocketAcceptor”>
<property name=”filterChainBuilder”
ref=”smppFilterChainBuilder” />
<property name=”handler” ref=”smppHandler” />
<property name=”defaultLocalAddresses” ref=”ipaddrs” />
</bean>

</beans>
[/code]

在修改代码的时候,发现以前写的smpp server例子里SMPPProtocolDecoder 存在bug,

[code]
public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
throws Exception {

try {

//以前用的if判断,导致有数据包漏了。

while(in.remaining() >= 4
&& (in.remaining() >= in.getInt(in.position()))) {
byte[] b = new byte[in.getInt(in.position())];
in.get(b);
SMPPPacketpak = null;
int id = -1;
id = SMPPIO.bytesToInt(b, 4, 4);
pak = PacketFactory.newInstance(id);
if (pak != null) {
pak.readFrom(b, 0);
System.out.println(“decode:==” + pak);
out.write(pak);
}
}
} catch (BadCommandIDException ex) {
ex.printStackTrace();
}
}

[/code]

在使用AprSocketAcceptor的时候,客户端连接上来时,

服务端就出错,在网上也没搜索到这个错误码具体是什么含义。

[code]

java.io.IOException: (乱码显示) (code: -730054)
at org.apache.mina.transport.socket.apr.AprIoProcessor.throwException(AprIoProcessor.java:365)
at org.apache.mina.transport.socket.apr.AprIoProcessor.write(AprIoProcessor.java:352)
at org.apache.mina.transport.socket.apr.AprIoProcessor.write(AprIoProcessor.java:1)
at org.apache.mina.common.AbstractPollingIoProcessor.writeBuffer(AbstractPollingIoProcessor.java:567)
at org.apache.mina.common.AbstractPollingIoProcessor.flushNow(AbstractPollingIoProcessor.java:528)
at org.apache.mina.common.AbstractPollingIoProcessor.flush(AbstractPollingIoProcessor.java:469)
at org.apache.mina.common.AbstractPollingIoProcessor.access$500(AbstractPollingIoProcessor.java:43)
at org.apache.mina.common.AbstractPollingIoProcessor$Worker.run(AbstractPollingIoProcessor.java:681)
at org.apache.mina.util.NamePreservingRunnable.run(NamePreservingRunnable.java:51)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
at java.lang.Thread.run(Thread.java:619)

[/code]

2007年12月14日

用Spring,smppapi,apache mina, commons ssl快速实现安全的smpp smsc (六)

Filed under: Java,SSL — 标签:, , , , , , , — lizongbo @ 14:37

接上一篇: http://618119.com/archives/2007/12/13/45.html

使用 commons ssl生成 SSLContext :

[code]

package com.lizongbo.smpp.ssl;

import javax.net.ssl.SSLContext;
import java.security.GeneralSecurityException;
import java.io.IOException;
import javax.net.ssl.KeyManager;
import org.apache.commons.ssl.KeyMaterial;

public class SMPPSSLContextFactory {
private static final String PROTOCOL = “TLS”;
private static final String CA_FILE = “ca.crt.properties”;
private static final String CERT_FILE = “server.crt.properties”;
private static final String KEY_FILE = “server.key.properties”;
private static final String CILENT_FILE = “client.crt.properties”;;//”client.p12.properties”;
private static final String CILENT_KEY_FILE = “client.key.properties”;

private static final char[] password =new char[0] ;//”lizongbo”.toCharArray();

private static SSLContext serverInstance = null;

private static SSLContext clientInstance = null;

/**
* Get SSLContext singleton.
*
* @return SSLContext
* @throws java.security.GeneralSecurityException
*
*/
public static SSLContext getInstance(boolean server) throws
GeneralSecurityException, IOException {
SSLContext retInstance = null;
if (server) {
if (serverInstance == null) {
synchronized (SMPPSSLContextFactory.class) {
if (serverInstance == null) {
try {
serverInstance = createSMPPServerSSLContext();
}
catch (Exception ioe) {
throw new GeneralSecurityException(
“Can’t create Server SSLContext:” + ioe);
}
}
}
}
retInstance = serverInstance;
}
else {
if (clientInstance == null) {
synchronized (SMPPSSLContextFactory.class) {
if (clientInstance == null) {
clientInstance = createSMPPClientSSLContext();
}
}
}
retInstance = clientInstance;
}
return retInstance;
}

private static SSLContext createSMPPServerSSLContext() throws
GeneralSecurityException, IOException {
// ssl.setCheckHostname(false); // default setting is “false” for SSLServer
// ssl.setCheckExpiry(true); // default setting is “true” for SSLServer
// ssl.setCheckCRL(true); // default setting is “true” for SSLServer
// ssl.useStrongCiphers();
// return ssl.getSSLContext();
SSLContext sslContext = SSLContext.getInstance(PROTOCOL);
KeyMaterial km = new KeyMaterial(SMPPSSLContextFactory.class
.getResourceAsStream(CERT_FILE),
SMPPSSLContextFactory.class
.getResourceAsStream(KEY_FILE),
password);
sslContext.init( (KeyManager[]) km.getKeyManagers(),
SMPPTrustManagerFactory.X509_MANAGERS, null);
// System.out.println(“getCipherSuites ==” +
// java.util.Arrays.toString(sslContext.getServerSessionContext().
// getSupportedSSLParameters().
// getCipherSuites()));
return sslContext;

}

private static SSLContext createSMPPClientSSLContext() throws
GeneralSecurityException, IOException {
{
SSLContext context = SSLContext.getInstance(PROTOCOL);
KeyMaterial km = new KeyMaterial(SMPPSSLContextFactory.class
.getResourceAsStream(CILENT_FILE),
SMPPSSLContextFactory.class
.getResourceAsStream(CILENT_KEY_FILE),
password);
context.init( (KeyManager[]) km.getKeyManagers(),
SMPPTrustManagerFactory.X509_MANAGERS, null);
return context;
}
}
}
[/code]

实现证书检查认证的代码:

[code]

package com.lizongbo.smpp.ssl;

import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.ManagerFactoryParameters;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactorySpi;
import javax.net.ssl.X509TrustManager;

public class SMPPTrustManagerFactory
extends TrustManagerFactorySpi {

static final X509TrustManager X509 = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] x509Certificates,
String s) throws CertificateException {
if (x509Certificates != null) {
for (X509Certificate elem : x509Certificates) {
elem.checkValidity();
//System.out.println(“checkClientTrusted elem ==” + elem);
}
}
// System.out.println(“checkClientTrusted s ==” + s);
}

public void checkServerTrusted(X509Certificate[] x509Certificates,
String s) throws CertificateException {
if (x509Certificates != null) {
for (X509Certificate elem : x509Certificates) {
// System.out.println(“checkServerTrusted elem ==” + elem);
}
}
// System.out.println(“checkServerTrusted s ==” + s);

}

public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};

static final TrustManager[] X509_MANAGERS = new TrustManager[] {
X509};

public SMPPTrustManagerFactory() {
}

protected TrustManager[] engineGetTrustManagers() {
return X509_MANAGERS;
}

protected void engineInit(KeyStore keystore) throws KeyStoreException {
// noop
}

protected void engineInit(
ManagerFactoryParameters managerFactoryParameters) throws
InvalidAlgorithmParameterException {
// noop
}
}
[/code]

2007年12月13日

用Spring,smppapi,apache mina, commons ssl快速实现安全的smpp smsc (五)

Filed under: Java,SSL — 标签:, , , , , , , , — lizongbo @ 08:43

接上一篇: http://618119.com/archives/2007/12/06/39.html

为 DefaultIoFilterChainBuilder 增加filter:

[code]
import org.apache.mina.filter.LoggingFilter;
import javax.net.ssl.SSLContext;
import org.apache.mina.filter.SSLFilter;
import org.apache.mina.common.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.commons.ssl.*;
import java.io.*;
import java.security.*;
import com.lizongbo.smpp.ssl.SMPPSSLContextFactory;
import com.lizongbo.smpp.server.codec.SMPPProtocolCodecFactory;

public static final int PORT = 5432;
public static final int CONNECT_TIMEOUT = 3; // seconds
private static final boolean USE_SSL = true;
private static final boolean USE_LOG = false;
private static final boolean USE_COMPRESS = false;
private static final boolean USE_THREADPOOL = false;
/**
添加服务端的ssl支持
*/
public static void addServerSSLSupport(DefaultIoFilterChainBuilder chain) throws
Exception {
if (USE_SSL) {
SSLContext sslc = SMPPSSLContextFactory.getInstance(true);
SSLFilter sslFilter = new SSLFilter(sslc);
sslFilter.setNeedClientAuth(true);//
//sslFilter.setWantClientAuth(true);
sslFilter.setEnabledCipherSuites(new String[] {
“TLS_RSA_WITH_AES_256_CBC_SHA”
“SSL_RSA_WITH_RC4_128_MD5″//,
“TLS_RSA_WITH_AES_128_CBC_SHA”,
“TLS_DHE_RSA_WITH_AES_128_CBC_SHA”,
“TLS_DHE_DSS_WITH_AES_128_CBC_SHA”,
“TLS_RSA_WITH_AES_256_CBC_SHA”,
“TLS_DHE_RSA_WITH_AES_256_CBC_SHA”,
“SSL_RSA_WITH_RC4_128_SHA”,
“TLS_DHE_DSS_WITH_AES_256_CBC_SHA”
});
chain.addLast(“sslFilter”, sslFilter);
System.out.println(“Server SSL ON”);
}
}
/**
添加客户端的ssl支持
*/
public static void addCilentSSLSupport(DefaultIoFilterChainBuilder chain) throws
Exception {
if (USE_SSL) {
SSLContext sslc = SMPPSSLContextFactory.getInstance(false);
SSLFilter sslFilter = new SSLFilter(sslc);
sslFilter.setUseClientMode(true);
chain.addLast(“sslFilter”, sslFilter);
System.out.println(“Client SSL ON”);
}
}
/**
添加 logger 过滤器
*/
public static void addLogger(DefaultIoFilterChainBuilder chain) throws
Exception {
if (USE_LOG) {
chain.addLast(“logger”, new LoggingFilter());
System.out.println(“Logging ON”);
}
}
/**
添加压缩 过滤器
*/
public static void addCompress(DefaultIoFilterChainBuilder chain) throws
Exception {
if (USE_COMPRESS) {
chain.addLast(“compress”, new org.apache.mina.filter.CompressionFilter());
System.out.println(“Compress ON”);
}
}
/**
添加编码解码过滤器
*/
public static void addCodec(DefaultIoFilterChainBuilder chain) throws
Exception {
chain.addLast(“codec”,
new ProtocolCodecFilter(new SMPPProtocolCodecFactory()));

}
/**
添加线程池过滤器
*/
public static void addThreadPool(DefaultIoFilterChainBuilder chain) throws
Exception {
if (USE_THREADPOOL) {
chain.addLast(“threadpool”,
new org.apache.mina.filter.executor.ExecutorFilter());
System.out.println(“Threadpool ON”);
}
}

public static void main(String[] args) throws IOException, Exception {
IoAcceptor acceptor = new SocketAcceptor();
IoAcceptorConfig config = new SocketAcceptorConfig();
DefaultIoFilterChainBuilder chain = config.getFilterChain();
//Utils.addServerSSLSupport(chain);
Utils.addThreadPool(chain);
Utils.addCompress(chain);
Utils.addCodec(chain);
Utils.addLogger(chain);
SMPPServerSessionHandler handlers = new SMPPServerSessionHandler();
handlers.getHandles().put(Integer.valueOf(0x00000001),
new com.lizongbo.smpp.server.handlers.
BindReceiverHandler());
handlers.getHandles().put(Integer.valueOf(0x00000002),
new com.lizongbo.smpp.server.handlers.
BindTransmitterHandler());
handlers.getHandles().put(Integer.valueOf(0x00000004),
new com.lizongbo.smpp.server.handlers.
SubmitSMHandler());
handlers.getHandles().put(Integer.valueOf(0x00000006),
new com.lizongbo.smpp.server.handlers.
UnbindHandler());
InetSocketAddress serverAddr = new InetSocketAddress(Utils.PORT);
acceptor.bind(
serverAddr, handlers,
config);

//JMX控制

IoServiceManager serviceManager = new IoServiceManager(acceptor);
serviceManager.startCollectingStats(1000);
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name = new ObjectName(
“com.lizongbo.smpp.server:type=IoServiceManager”);
mbs.registerMBean(serviceManager, name);

System.out.println(“Listening on port ” + Utils.PORT);
}

[/code]

Powered by WordPress