CGlib动态代理范例

1、ProxyFactory.java

package com.ats.proxy;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class ProxyFactory implements MethodInterceptor{
	//private Object invoker;
	private List<Object> interceptors;
	
	private ProxyFactory(Object invoker,List<Object> interceptors)
	{
		//this.invoker = invoker;
		if(interceptors==null)
		{
			this.interceptors = new ArrayList<Object>();
		}
		else
		{
			this.interceptors = interceptors;
		}
	}
	
	 public static final Object newInstance(Object invoker,List<Object> interceptors)
	 {
		 Enhancer enhancer = new Enhancer();
		 enhancer.setSuperclass(invoker.getClass());
		 enhancer.setCallback(new ProxyFactory(invoker,interceptors));
		 return enhancer.create();
	 }
	
	@Override
	public Object intercept(Object invoker, Method method, Object[] args,
			MethodProxy proxy) throws Throwable {
		
		Object result = null;
		
		for(Object o : interceptors)
		{
			if(o instanceof IProxyBefore)
			{
				((IProxyBefore)o).BeforeInvoke();
			}
		}
		
		try
		{
			result = proxy.invokeSuper(invoker, args);
		}
		catch(Exception ex)
		{
			for(Object o : interceptors)
			{
				if(o instanceof IProxyThrow)
				{
					((IProxyThrow)o).ThrowInvoke();
				}
			}
		}
		
		for(Object o : interceptors)
		{
			if(o instanceof IProxyAfter)
			{
				((IProxyAfter)o).AfterInvoke();
			}
		}
		
		return result;
	}
}

2、IProxyBefore.java

package com.ats.proxy;

public interface IProxyBefore {
	public void BeforeInvoke();
}

3、IProxyAfter.java

package com.ats.proxy;

public interface IProxyAfter {
	public void AfterInvoke();
}

4、IProxyAround.java

package com.ats.proxy;

public interface IProxyAround extends IProxyBefore,IProxyAfter{
}

5、IProxyThrow.java

[code lang="java"]
package com.ats.proxy;

public interface IProxyThrow {
	public void ThrowInvoke();
}

6、Car.java

package com.ats.test;

public class Car {
	public Car()
	{
		System.out.println("This is a new Car");
	}
}

7、CarFactoryBefore.java

package com.ats.test;

import com.ats.proxy.IProxyBefore;

public class CarFactoryBefore implements IProxyBefore{

	@Override
	public void BeforeInvoke() {
		System.out.println("CarFactoryBefore BeforeInvoke");
	}

}

8、CarFactoryAfter.java

package com.ats.test;

import com.ats.proxy.IProxyAfter;

public class CarFactoryAfter implements IProxyAfter {

	@Override
	public void AfterInvoke() {
		System.out.println("CarFactoryAfter AfterInvoke");
	}

}

9、CarFactoryAround.java

package com.ats.test;

import com.ats.proxy.IProxyAround;

public class CarFactoryAround implements IProxyAround{
	@Override
	public void AfterInvoke() {
		System.out.println("CarFactoryAround AfterInvoke");
	}
	
	@Override
	public void BeforeInvoke() {
		System.out.println("CarFactoryAround BeforeInvoke");
	}
}

10、CarFactoryThrow.java

package com.ats.test;

import com.ats.proxy.IProxyThrow;

public class CarFactoryThrow implements IProxyThrow {
	@Override
	public void ThrowInvoke() {
		System.out.println("CarFactory ThrowInvoke");
	}
}

11、ProxyFactory.java

package com.ats.test;

import java.util.ArrayList;
import java.util.List;

import com.ats.proxy.ProxyFactory;

public class CarFactory{
	public Car NewCar()
	{
		return new Car();
	}
	
	public static void main(String[] args)
	{
		CarFactory fac = new CarFactory();
		CarFactoryAfter after = new CarFactoryAfter();
		CarFactoryBefore before = new CarFactoryBefore();
		CarFactoryAround around = new CarFactoryAround();
		CarFactoryThrow _throw = new CarFactoryThrow();
		List<Object> l = new ArrayList<Object>();
		l.add(after);
		l.add(before);
		l.add(around);
		l.add(_throw);
		
		CarFactory fac1=(CarFactory)ProxyFactory.newInstance(fac, l);
		fac1.NewCar();
	}
}

JDK动态代理范例

1、ProxyFactory.java

package com.ats.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class ProxyFactory implements InvocationHandler{
	private Object invoker;
	private List<Object> interceptors;
	
	private ProxyFactory(Object invoker,List<Object> interceptors)
	{
		this.invoker = invoker;
		if(interceptors==null)
		{
			this.interceptors = new ArrayList<Object>();
		}
		else
		{
			this.interceptors = interceptors;
		}
	}
	
    public static final Object newInstance(Object invoker,List<Object> interceptors)
    {
        return java.lang.reflect.Proxy.newProxyInstance(invoker.getClass().getClassLoader(),
        		invoker.getClass().getInterfaces(), new ProxyFactory(invoker,interceptors));
    }
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		Object result = null;
		
		for(Object o : interceptors)
		{
			if(o instanceof IProxyBefore)
			{
				((IProxyBefore)o).BeforeInvoke();
			}
		}
		
		try
		{
			result = method.invoke(invoker, args);
		}
		catch(Exception ex)
		{
			for(Object o : interceptors)
			{
				if(o instanceof IProxyThrow)
				{
					((IProxyThrow)o).ThrowInvoke();
				}
			}
		}
		
		for(Object o : interceptors)
		{
			if(o instanceof IProxyAfter)
			{
				((IProxyAfter)o).AfterInvoke();
			}
		}
		return result;
	}
}

2、IProxyBefore.java

package com.ats.proxy;

public interface IProxyBefore {
	public void BeforeInvoke();
}

3、IProxyAfter.java

package com.ats.proxy;

public interface IProxyAfter {
	public void AfterInvoke();
}

4、IProxyAround.java

package com.ats.proxy;

public interface IProxyAround extends IProxyBefore,IProxyAfter{
}

5、IProxyThrow.java

package com.ats.proxy;

public interface IProxyThrow {
	public void ThrowInvoke();
}

6、ICarFactory.java

package com.ats.test;

public interface ICarFactory {
	public Car NewCar();
}

7、Car.java

package com.ats.test;

public class Car {
	public Car()
	{
		System.out.println("This is a new Car");
	}
}

8、IProxyBefore.java

package com.ats.test;

import com.ats.proxy.IProxyBefore;

public class CarFactoryBefore implements IProxyBefore{

	@Override
	public void BeforeInvoke() {
		System.out.println("CarFactoryBefore BeforeInvoke");
	}

}

9、CarFactoryAfter.java

package com.ats.test;

import com.ats.proxy.IProxyAfter;

public class CarFactoryAfter implements IProxyAfter {

	@Override
	public void AfterInvoke() {
		System.out.println("CarFactoryAfter AfterInvoke");
	}

}

10、CarFactoryAround .java

package com.ats.test;

import com.ats.proxy.IProxyAround;

public class CarFactoryAround implements IProxyAround{
	@Override
	public void AfterInvoke() {
		System.out.println("CarFactoryAround AfterInvoke");
	}
	
	@Override
	public void BeforeInvoke() {
		System.out.println("CarFactoryAround BeforeInvoke");
	}
}

11、CarFactoryThrow.java

package com.ats.test;

import com.ats.proxy.IProxyThrow;

public class CarFactoryThrow implements IProxyThrow {
	@Override
	public void ThrowInvoke() {
		System.out.println("CarFactory ThrowInvoke");
	}
}

12、CarFactory.java

package com.ats.test;

import java.util.ArrayList;
import java.util.List;

import com.ats.proxy.IProxyAround;
import com.ats.proxy.IProxyThrow;
import com.ats.proxy.ProxyFactory;

public class CarFactory implements ICarFactory {
	public Car NewCar()
	{
		return new Car();
	}
	
	public static void main(String[] args)
	{
		CarFactory fac = new CarFactory();
		CarFactoryAfter after = new CarFactoryAfter();
		CarFactoryBefore before = new CarFactoryBefore();
		CarFactoryAround around = new CarFactoryAround();
		CarFactoryThrow _throw = new CarFactoryThrow();
		List<Object> l = new ArrayList<Object>();
		l.add(after);
		l.add(before);
		l.add(around);
		l.add(_throw);
		
		ICarFactory factory = (ICarFactory)ProxyFactory.newInstance(fac,l);
		factory.NewCar();
	}
}

自定义Java注解Annotation

1、CopyRight.java

package com.ats.annotation;

public @interface CopyRight {
	String value();
}

2、UnitTest.java

package com.ats.annotation;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface UnitTest { }

3、Foo.java

package com.ats.test;

import com.ats.annotation.UnitTest;

public class Foo {
	@UnitTest
	public static void m1() {
	}

	@UnitTest
	public static void m2() {
		throw new RuntimeException("Crash");
	}

	@UnitTest
	public static void m3() {
	}

	public static void m4() {
	}
	
	public static void m5() {
		throw new RuntimeException("Crash");
	}
}

4、RunTests.java

package com.ats.test;

import java.lang.reflect.Method;

import com.ats.annotation.CopyRight;
import com.ats.annotation.UnitTest;

@CopyRight("2012 NEOHOPE")
public class RunTests {
	public static void main(String[] args) throws Exception {
		
		int passed = 0, failed = 0;
		
		for (Method m : Class.forName("com.ats.test.Foo").getMethods()) {
			if (m.isAnnotationPresent(UnitTest.class)) {
				try {
					m.invoke(null);
					passed++;
				} catch (Throwable ex) {
					System.out.printf("Test %s failed: %s %n", m, ex.getCause());
					failed++;
				}
			}
		}
		
		System.out.printf("Passed: %d, Failed %d%n", passed, failed);
	}
}

自定义JSP标签Taglib

1、AuthorTag.java

package com.ats.taglib;

import java.io.IOException;

import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class AuthorTag extends TagSupport{
	private static final long serialVersionUID = 1L;
	private String version="v1.0";

	@Override
	public int doStartTag(){
		JspWriter out=pageContext.getOut();
		try {
			out.print("<div>AuthorTag "+version+" by NEOHOPE</div>");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return EVAL_BODY_INCLUDE;
	}
	
	@Override
	public int doEndTag(){
		return EVAL_PAGE;
	}
	
	public String getVersion()
	{
		return version;
	}
	
	public void setVersion(String version)
	{
		this.version=version;
	}
}

2、IterateTag.java

package com.ats.taglib;

import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class IterateTag extends BodyTagSupport {
	private static final long serialVersionUID = 1L;

	private Iterator it;
	private String type;
	private String name;
	public void setCollection(Collection collection) {
		if (collection.size() > 0)
			it = collection.iterator();
	}
	
	public void setType(String type)
	{
		this.type=type;
	}
	
	public void setName(String name)
	{
		this.name=name;
	}

	@Override
	public int doStartTag() {
		
		JspWriter out=pageContext.getOut();
		try {
			out.print("<table>");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		if (it == null)
			return SKIP_BODY;
		else
			return continueNext(it);
	}

	@Override
	public int doAfterBody() {
		return continueNext(it);
	}

	@Override
	public int doEndTag() {
		try {
			if (bodyContent != null)
				bodyContent.writeOut(bodyContent.getEnclosingWriter());
		} catch (Exception e) {
			System.out.println(e);
		}
		
		JspWriter out=pageContext.getOut();
		try {
			out.print("</table>");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return EVAL_PAGE;
	}

	protected int continueNext(Iterator it) {
		if (it.hasNext()) {
			pageContext.setAttribute(name, "<tr><td>"+it.next()+"</td></tr>", pageContext.PAGE_SCOPE);
			return EVAL_BODY_TAG;
		} else {
			return SKIP_BODY;
		}
	}
}

3、IterateTagTEI.java

package com.ats.taglib;

import javax.servlet.jsp.tagext.TagData;
import javax.servlet.jsp.tagext.TagExtraInfo;
import javax.servlet.jsp.tagext.VariableInfo;

public class IterateTagTEI extends TagExtraInfo {
	public IterateTagTEI() {
		super();
	}

	@Override
	public VariableInfo[] getVariableInfo(TagData data) {
		return new VariableInfo[] { new VariableInfo(
				data.getAttributeString("name"),
				data.getAttributeString("type"), true, VariableInfo.NESTED) };
	}
}

4、LoopTag.java

package com.ats.taglib;

import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class LoopTag extends BodyTagSupport {
	private static final long serialVersionUID = 1L;

	private int total = 0;
	private int count = 0;

	@Override
	public int doStartTag() {
		try {
			if (total > 0)
				return EVAL_BODY_TAG;
			else
				return SKIP_BODY;
		} catch (Exception e) {
			e.printStackTrace();
			return SKIP_BODY;
		}
	}

	@Override
	public int doAfterBody() {
		try {
			if (total - count>1) {
				count++;
				return EVAL_BODY_TAG;
			} 
			else
			{
				count=0;
				return SKIP_BODY;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return SKIP_BODY;
		}
	}

	@Override
	public int doEndTag() {
		try {
			bodyContent.writeOut(bodyContent.getEnclosingWriter());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return EVAL_PAGE;
	}
	
	public void setTotal(int total)
	{
		this.total = total;
	}
	
	public int getTotal()
	{
		return total;
	}
}

5、Taglib.tld

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"&#93;
<taglib>
	<tlibversion>1.0</tlibversion>
	<jspversion>1.1</jspversion>
	<shortname>at</shortname>
	<tag>
		<name>AuthorTag</name>
		<tagclass>com.ats.taglib.AuthorTag</tagclass>
		<bodycontent>empty</bodycontent>

		<attribute>
			<name>version</name>
			<required>false</required>
		</attribute>
	</tag>
	<tag>
		<name>LoopTag</name>
		<tagclass>com.ats.taglib.LoopTag</tagclass>
		<bodycontent>jsp</bodycontent>
		<attribute>
			<name>total</name>
			<required>true</required>
			<rtexprvalue>true</rtexprvalue>
		</attribute>
	</tag>
	<tag>
		<name>IterateTag</name>
		<tagclass>com.ats.taglib.IterateTag</tagclass>
		<teiclass>com.ats.taglib.IterateTagTEI</teiclass>
		<bodycontent>jsp</bodycontent>
		<attribute>
			<name>collection</name>
			<required>true</required>
			<rtexprvalue>true</rtexprvalue>
		</attribute>
		<attribute>
			<name>name</name>
			<required>true</required>
		</attribute>
		<attribute>
			<name>type</name>
			<required>true</required>
		</attribute>
	</tag>
</taglib>

6、web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"&#93;
  <display-name>TaglibTest</display-name>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <jsp-config>
    <taglib>
      <taglib-uri>
        http://www.ats.com/Taglib
      </taglib-uri>
      <taglib-location>
        /WEB-INF/tags/Taglib.tld
      </taglib-location>
	</taglib>
  </jsp-config>
</web-app>

7、index.jsp

<%@ taglib prefix="ats" uri="http://www.ats.com/Taglib" %>

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ page import="java.util.Date"%> 
<%@ page import="java.util.ArrayList"%> 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>TaglibTest</title>
</head>

<body>
<ats:AuthorTag version="v1.01"/>
<ats:LoopTag total="3">
<div><%=new Date()%></div>
</ats:LoopTag>

<%
ArrayList<String> t=new ArrayList<String>();
t.add("A");
t.add("B");
t.add("C");
%>

<div>
<ats:IterateTag name="row" type="String" collection="<%=t%>">
<%=row%>
</ats:IterateTag>
</div>

</body>
</html>

CMD常用命令12切换网络

1、切换为DHCP

@netsh interface ip set address name="本地连接" source=dhcp

@netsh interface ip set dns name="本地连接" source=dhcp

2、切换为静态IP

@netsh interface ip set address name="本地连接" source=static addr=xxx.xxx.xxx.xxx mask=255.255.255.0 gateway=xxx.xxx.xxx.xxx

@netsh interface ip set dns name="本地连接" source=static addr=xxx.xxx.xxx.xxx

JKS密码验证

下面的程序用来验证JKS的文件及密码是否正确

public static URL getStoreURL(String storePath) throws IOException
{
	URL url = null;
	// First see if this is a URL
	try
	{
		url = new URL(storePath);
	}
	catch (MalformedURLException e)
	{
		// Not a URL or a protocol without a handler so...
		// next try to locate this as file path
		File tst = new File(storePath);
		if (tst.exists() == true)
		{
			url = tst.toURL();
		} else
		{
			// not a file either, lastly try to locate this as a classpath
			// resource
			if (url == null)
			{
				ClassLoader loader = Thread.currentThread().getContextClassLoader();
				url = loader.getResource(storePath);
			}
		}
	}
	// Fail if no valid key store was located
	if (url == null)
	{
		String msg = "Failed to find url=" + storePath + " as a URL, file or resource";
		throw new MalformedURLException(msg);
	}
	return url;
}

public static KeyStore loadKeyStore(String storeType, URL storePathURL, String storePassword) throws Exception
{
	KeyStore keyStore = null;
	String provider = null;
	String providerName = null;

	if (provider != null)
	{
		keyStore = KeyStore.getInstance(storeType, provider);
	} else
		if (providerName != null)
		{
			keyStore = KeyStore.getInstance(storeType, providerName);
		} else
		{
			keyStore = KeyStore.getInstance(storeType);
		}
	if (storePathURL == null) { throw new Exception("Can not find store file for url because store url is null."); }
	// now that keystore instance created, need to load data from file
	InputStream keyStoreInputStream = null;
	try
	{
		keyStoreInputStream = storePathURL.openStream();
		// is ok for password to be null, as will just be used to check
		// integrity of store
		char[] password = storePassword != null ? storePassword.toCharArray() : null;
		keyStore.load(keyStoreInputStream, password);
	}
	finally
	{
		if (keyStoreInputStream != null)
		{
			try
			{
				keyStoreInputStream.close();
			}
			catch (IOException e)
			{
				// no op
			}
			keyStoreInputStream = null;
		}
	}
	return keyStore;
}

public static String verifyP12(String p12Path,String p12Pwd)
{
            String ret = "验证成功";
            try
            {
	URL ksURL = getStoreURL(p12Path);
                if(ksURL==null)throw new Exception(p12Path+"文件未找到");
                    
	loadKeyStore("PKCS12",ksURL,p12Pwd);
            }
            catch(Exception ex)
            {
                ret = ex.getMessage();
                ex.printStackTrace();
            }
            return ret;
}

public static String verifyJks(String jksPath,String jksPwd)
{
            String ret = "验证成功";
            try
            {
	URL ksURL = getStoreURL(jksPath);
	loadKeyStore("JKS",ksURL,jksPwd);
                
                if(ksURL==null)throw new Exception(jksPath+"文件未找到");
            }
            catch(Exception ex)
            {
                ret = ex.getMessage();
                ex.printStackTrace();
            }
            
            return ret;
}

AXIS2客户端支持TLS

只要设置下面几个环境变量就好啦;)

public static final String TRUST_STORE_PASSWORD = "javax.net.ssl.trustStorePassword";
public static final String TRUST_STORE = "javax.net.ssl.trustStore";
public static final String TRUST_STORE_TYPE = "javax.net.ssl.trustStoreType";
public static final String KEY_STORE_TYPE = "javax.net.ssl.keyStoreType";
public static final String KEY_STORE_PASSWORD = "javax.net.ssl.keyStorePassword";
public static final String KEY_STORE = "javax.net.ssl.keyStore";

keytool生成key

生成keystore及cert

#生成私钥
keytool -genkey -validity 10000 -keyalg RSA -dname "CN=neohope OU=neohope O=neohope L=Shanghai C=CN" -keystore node1.jks -alias node1 -keypass password -storepass password 
#导出证书
keytool -export -file node1.crt -keystore node1.jks -alias node1 -keypass password -storepass password 
#生成truststore
keytool -import -trustcacerts -file node1.crt -keystore trust.jks -alias node1 -keypass password -storepass password 
#查看
keytool -list -keystore node1.jks
keytool -list -keystore trust.jks

jks转p12

keytool -importkeystore -srckeystore node1.jks -srcstoretype JKS -deststoretype PKCS12 -destkeystore node1.p12 -srcstorepass password -deststorepass password

JBoss配置TLS

文件%JBOSS_HOME%\server\default\deploy\jboss-web.deployer\server.xml
增加下面陪孩子

<Connector port="8443" address="${jboss.bind.address}"
          protocol="HTTP/1.1" SSLEnabled="true" 
          maxThreads="100" strategy="ms" maxHttpHeaderSize="8192"
      	  emptySessionPath="true"
      	  scheme="https" secure="true" clientAuth="false" 
      	  disableUploadTimeout="true" 
      	  keystoreFile="${jboss.server.home.dir}/conf/node1.jks"
      	  keystorePass="passward"
      	  keyAlias="node1"
      	  sslProtocol = "TLS" />