TestCoreJava


I18nUtility.getMediumDisplayDate



package com.steven.junit;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;

import junit.framework.TestCase;
import junit.framework.TestSuite;

import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.comparators.ReverseComparator;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.easymock.EasyMock;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;

import cia.common.base.constants.Constants;
import cia.common.base.util.ApplicationContextUtils;
import cia.common.base.util.StringUtil;
import cia.console.bo.mchntmgmt.MchntInfoMgmt;
import cia.console.struts.action.mchntmgmt.MchntInfoMgmtAction;
import cia.console.test.TestEntity;

import com.steven.easymock.ICalcMethod;
import com.steven.easymock.Position;
import com.steven.templatePattern.DemoAction1;
import com.steven.templatePattern.SafeAction;

public class TestCoreJava extends TestCase {

/**
* switch语句是让i从相应的case开始执行,直到遇到break跳出 所以 结果为 case0 case1 case2。 一般的程序都是要加上break; 的
*/
public void testSwitch() {
int i = 0;
switch (i) {
case 0 :
logger.info("case0");
case 1 :
logger.info("case1");
case 2 :
logger.info("case2");
}
}

/**
* 特殊字符的split需要加上\\来转义
*/
public void testComma() {
String rate = "2.5";
String[] result = rate.split("\\.");
assertEquals("2", result[0]);
assertEquals("5", result[1]);
}

/**
* 去空格
*/
public void testRemoveSpace() {
String result = " ab c".replaceAll("\\s+", "");
assertEquals("abc", result);
}

/**
* Calender 日期测试
*/
synchronized public void testCalendar() {

Calendar c1 = Calendar.getInstance();
printCalendar(c1);

Calendar c2 = Calendar.getInstance();
c2.add(Calendar.YEAR, -1);
printCalendar(c2);

// 比较两日期
assertEquals(1, c1.compareTo(c2));
assertTrue(c1.after(c2));
assertTrue(c2.before(c1));

// 计算相差的天数[用date转成long来比较]
// 解决: 将时间的时分秒设置成0
// c1.set(Calendar.HOUR_OF_DAY, 0);
c1.set(Calendar.HOUR, 0);
c1.set(Calendar.MINUTE, 0);
c1.set(Calendar.SECOND, 0);
c1.set(Calendar.MILLISECOND, 0);

printCalendar(c1);

c2.set(Calendar.HOUR, 0);
c2.set(Calendar.MINUTE, 0);
c2.set(Calendar.SECOND, 0);
c2.set(Calendar.MILLISECOND, 0);

long l1 = c1.getTimeInMillis();
long l2 = c2.getTimeInMillis();
int days = (int) ((l1 - l2) / (24 * 60 * 60 * 1000));
assertEquals(365, days);

// 自定义日期
Calendar c3 = Calendar.getInstance();
c3.set(2012, 12 - 1, 12); // 月份必须要减1, 不然会跑到下个月的

/*
* 功能同上 c3.set(Calendar.YEAR, 2012); c3.set(Calendar.MONTH, 12-1); c3.set(Calendar.DATE,
* 12);
*/
printCalendar(c3);
assertEquals(-1, c1.compareTo(c3));

}

/**
* 打印当前日期, 一定要用SimpleDateFormat, 而不能用Calendar.get(Calendar.YEAR)...
*
* @param c
*/
private void printCalendar(Calendar c) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日-hh时mm分ss秒SSS毫秒 ");
logger.info(sdf.format(c.getTime()));
}

/**
* list1中去掉list2,会有重复的问题。 因为list中的值可以重复 用set包装list后再操作 路由控制用到了该场景
*/
public void testListMinus() {
// 重现问题
List<String> list1 = new ArrayList();
list1.add("a");
list1.add("b");
list1.add("c");
list1.add("a");
list1.add("a");

List<String> list2 = new ArrayList();
list2.add("a");
list2.add("b");

for (String value : list2) {
if (list1.contains(value)) {
list1.remove(value);
}
}

// 结果是3
assertEquals(3, list1.size());

List<String> l1 = new ArrayList<String>();
l1.add("a");
l1.add("b");
l1.add("c");
l1.add("a");
l1.add("a");

// List 和 Set之间的转换
Set<String> set1 = new HashSet<String>(l1);

List<String> l2 = new ArrayList<String>();
l2.add("a");
l2.add("b");
Set<String> set2 = new HashSet<String>(l2);

for (String value : set2) {
if (set1.contains(value)) {
set1.remove(value);
}
}

// 结果是1
assertEquals(1, set1.size());
}

/**
* toString() vs (String)
*/
public void testStringNull() {
Object obj = null;
String a = (String) obj; // 不会有空指针异常
try {
String b = obj.toString(); // 空指针异常
} catch (NullPointerException e) {
}
}

/**
* 金额计算 假设DB中是BigDecimal类型, 计算时用BigDecimal, 显示时用double 加减乘除 都需要用scale来限定输出的位数。 除法时还要确定位数
*/
public void testMoney() {
BigDecimal b1 = new BigDecimal(100.1122);
BigDecimal b2 = new BigDecimal(50.56);
assertEquals(49.55, b1.subtract(b2).setScale(2, RoundingMode.HALF_UP).doubleValue()); // 49.55
assertEquals(5061.67, b1.multiply(b2).setScale(2, RoundingMode.HALF_UP).doubleValue());
assertEquals(1.98, b1.divide(b2, 2).setScale(2, RoundingMode.HALF_UP).doubleValue());
assertEquals(150.67, b1.add(b2).setScale(2, RoundingMode.HALF_UP).doubleValue());
}

/**
* 动态代理: 实现代理类和被代理类的接口分离。 代理类是一个通用类。动态代理用到了反射机制
*/
public void testDynamicProxy() {
HelloWorld hw = new HelloWorldImpl();
InvocationHandler handler = new HelloWorldHandler(hw);
HelloWorld proxy = (HelloWorld) Proxy.newProxyInstance(hw.getClass().getClassLoader(), hw
.getClass().getInterfaces(), handler);
proxy.sayHelloWorld();
}

/**
* 回调函数, 在功能上和动态代理有点类似. 回调函数: 接口上耦合于被回调的代码。 这点和静态代理一致。 回调vs静态代理: 静态代理非常麻烦要实现一个接口的所有方法,
* 而回调只要对一个方法进行封装。 如果需要传参数给回调函数的话,需要定义为final
*/
public void testCallBack() {
// 这里用到了匿名类
calTime(new CallBack() {
// 定义execute方法
public void execute(final String a) {
// 这里可以加放一个或多个要测试运行时间的方法
System.out.println(a);
try {
Thread.sleep(2123);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}

// 参数中传入一个接口, 并在方法体中调用该接口的方法
private void calTime(CallBack callBack) {
long begin = System.currentTimeMillis(); // 测试起始时间
callBack.execute("die for you!"); // /进行回调操作
long end = System.currentTimeMillis(); // 测试结束时间
System.out.println("操作所需时间:" + (end - begin)); // 打印使用时间
}

public void testLoadFile() throws DocumentException {
SAXReader reader = new SAXReader();
Document doc = null;
String file = "E:\\WKP_UNIONPAY\\CIAConsole\\conf\\log\\operlog.xml";
doc = reader.read(new File(file));
logger.info("Load Success");
}

// 优化 TestDefaultRoutInfo。 Fixed

/**
* Bean 排序 Bean实现Comparable接口, 重载compareTo方法
*/
public void testBeanSort() {
List<JavaBean> javaBeanList = new ArrayList<JavaBean>();
javaBeanList.add(new JavaBean("c", 1));
javaBeanList.add(new JavaBean("b", 3));
javaBeanList.add(new JavaBean("a", 2));

// Collections.sort(javaBeanList);

for (int i = 0; i < javaBeanList.size(); i++) {
JavaBean temp = javaBeanList.get(i);
logger.info(temp.getName() + ":" + temp.getValue());
}

Collections.sort(javaBeanList, new BeanComparator("name"));
logger.info("-----------------------------");
for (int i = 0; i < javaBeanList.size(); i++) {
JavaBean temp = javaBeanList.get(i);
logger.info(temp.getName() + ":" + temp.getValue());
}
}

/**
* 深复制是对Bean而言的, 而不是对字符串而言的
*
* @throws Exception
*/
public void testDeepCopyList() throws Exception {
List<String> list1 = new ArrayList<String>();
list1.add("a");
list1.add("b");
list1.add("c");

List<String> list2 = new ArrayList<String>();
list2 = list1;

list1.add("d");
assertEquals(4, list2.size());

List<String> list3 = new ArrayList<String>();
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(list1);
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream in = new ObjectInputStream(byteIn);
list3 = (List<String>) in.readObject();
list1.add("e");
assertEquals(4, list3.size());

List<String> list4 = new ArrayList<String>(list1);
list1.add("f");
list1.add("g");
assertEquals(5, list4.size());

List<String> list5 = new ArrayList<String>(list1);
Collections.copy(list5, list1);
}

public void testDeepCopyList2() throws Exception {
List<JavaBean2> list1 = new ArrayList<JavaBean2>();
JavaBean2 bean1 = new JavaBean2("n1", 1);
JavaBean2 bean2 = new JavaBean2("n2", 2);
JavaBean2 bean3 = new JavaBean2("n3", 3);
list1.add(bean1);
list1.add(bean2);

logger.info("-----------list2【浅复制】-----------");
List<JavaBean2> list2 = new ArrayList<JavaBean2>(list1);
list1.add(bean3);
bean2.setName("list2");

for (JavaBean2 bean : list2) {
logger.info(bean.getName() + " : " + bean.getValue());
}

logger.info("-----------list3【bean需要实现Serializable接口】-----------");
List<JavaBean2> list3 = new ArrayList<JavaBean2>();
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(list1);
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream in = new ObjectInputStream(byteIn);
list3 = (List<JavaBean2>) in.readObject();
bean2.setName("list3");

for (JavaBean2 bean : list3) {
logger.info(bean.getName() + " : " + bean.getValue());
}

logger.info("-----------list5【Collections.copy】也是浅复制-----------");
List<JavaBean2> list5 = new ArrayList<JavaBean2>(list1);
Collections.copy(list5, list1);
bean2.setName("list5");
for (JavaBean2 bean : list5) {
logger.info(bean.getName() + " : " + bean.getValue());
}
}

public void xtestConsoleInput() throws IOException {
BufferedInputStream bs = new BufferedInputStream(System.in);
DataInputStream dis = new DataInputStream(bs);
logger.info("请输入[a]");
String str = dis.readLine();
assertEquals("a", str);

}

public void testDecimalFormat() {
DecimalFormat formatter = new DecimalFormat("###,###,###,###.00");
assertEquals("1,231,123,123.12", formatter.format(1231123123.123123));
}

public void testProperties() throws IOException {
Properties defaultSet = new Properties();
InputStream in = getClass().getResourceAsStream("test.properties");
defaultSet.load(in);
String name = defaultSet.getProperty("name");
assertEquals("steven", name);
}

private static final Logger logger = Logger.getLogger(TestCoreJava.class);

public void testLog4j() {
PropertyConfigurator.configure("E:\\WKP_UNIONPAY\\CIAConsole\\conf\\log4j.xml");
logger.info("info");
logger.warn("warn");
logger.error("error");
}

/**
* Enum的优势, 相较于常量类, 可以指定取值的范围 例如: 国际化是用Lang.ENGLISH 和 Lang.CHINA 来表示两种语音 放入静态类LangCache的Lang
* langType中。 如果用常量文件的话,就可能将其他的常量值放入langType中。
*/
public void testEnum() {
// 名值对【很少用, 还不如用map或是常量文件】
for (Country g : Country.values()) {
logger.info("grade value: '" + g + "' " + g.getValue());
}
logger.info(Country.中国.getValue());

// 用enum来代替int常量 【但是一般我们也很少使用int常量】
for (Grade g : Grade.values()) {
logger.info("Grade: " + g);
}

// enum 最常用的就是和 switch连用。 这样switch中的grade 总是在Grade定义中,而不会像变量i一样
Grade grade = Grade.A;
switch (grade) {
case A :
logger.info("Grade A");
break;
case B :
logger.info("Grade B");
break;
}

}

/**
* 即使有运行时异常,finally还是会执行, 这就是junit为什么tearDown总是会被执行的原因 setUp(); try{ runTest(); }finally{
* tearDown(); }
*/
public void testFinally() {
try {
throw new NullPointerException();
} catch (Exception e) {

} finally {
logger.info("--------Finally----------");
}
}

/**
* 先写test case, 再写代码
*/
public void testTDD() {
MathDemo mathDemo = new MathDemo();
int result = mathDemo.cal(1, 2);
assertEquals(3, result);
}

/**
* LogService的execute方法并不好, 需要将其DB层和业务逻辑层,GlobalData层分开, 这样有利于test case 重构很复杂, 需要将每一步都考虑清楚,
* 不过如果重构好了的话, 可以像Action的valiate方法一样, 一个个调用下面的方法 如果哪个有错,可以抛出特定的错误信息, 而且整体的结构很清楚
*/
public void xtestLogService() {

}

/**
* 看Junit的源代码, 了解其模板模式, 观察者模式等 模板模式非常常见, 网关中就使用了该模式, 定义一个执行的顺序 观察者模式本质就是将两个独立的代码【A并不知道B的接口】 关联起来
* 如果不用JDK的API, AB之间就要有互相引用关系
*/
public void testJunit() {
// 模板模式: 用抽象类来定义模板执行的顺序, 子类来实现
SafeAction action1 = new DemoAction1();
action1.execute();

Subject subject = new Subject();

// 创建两个观察者
Observer mailObserver = new MailObserver();
Observer jmsObserver = new JMSObserver();

// 把两个观察者加到被观察者列表中
subject.addObserver(mailObserver);
subject.addObserver(jmsObserver);

// 执行业务操作
subject.doBusiness();
}

class MailObserver implements Observer {

@Override
public void update(Observable o, Object arg) {
System.out.println(arg.toString() + "发送邮件的观察者已经被执行");
}
}

class JMSObserver implements Observer {

@Override
public void update(Observable o, Object arg) {
System.out.println(arg.toString() + "发送消息给jms服务器的观察者已经被执行");
}
}

class Subject extends Observable {

/**
* 业务方法,一旦执行某个操作,则通知观察者
*/
public void doBusiness() {
if (true) {
super.setChanged();
}
notifyObservers("x");
}

}

/**
* TODO RMI
*/
public void testRMI() {

}

/**
* 参照: socket文件下的。一共有三个版本 1, 普通的通讯 2, 多线程通讯 3, 传递Bean的通讯
*/
public void xtestSocket() {

}

/**
* EasyMock 可以模拟出一个复杂的对象。这样我们就可以专注于我们需要测试的业务逻辑上了 现在的测试目标是Action, 所以假设BO层是ok的
* 用EasyMock.expect录制脚本, 只能针对于有返回值的函数, 而不能是void 参照 IncomeCalculatorTest 需要将ServletActionContext
* 和 数据同步 的删除
*/
public void xtestEasyMock() throws Exception {
MchntInfoMgmtAction action = new MchntInfoMgmtAction();
MchntInfoMgmt mchntInfoMgmt = EasyMock.createMock(MchntInfoMgmt.class);
action.setMchntInfoMgmtBO(mchntInfoMgmt);
assertEquals("success", action.saveAll());
}

public static void xx() {
logger.info("这是静态方法");
}

/**
* 对象的实例也可以访问静态方法
*/
public void testStatic() {
TestCoreJava instance = new TestCoreJava();
instance.xx();
xx();
}

/**
* 参照easymock的源代码, 以现阶段的水平搞不定 如果只是想模拟这个类,并不执行其方法,可以在动态代理中把 method.invoke给注释掉 可以用匿名类的方式来做
*/
public void testReflectByInterface() throws Exception {
Position boss = Position.BOSS;
ICalcMethod instance = new com.steven.easymock.ICalcMethod() {

@Override
public double calc(Position position) {
return 111;
}

@Override
public void calc2(Position position) {

}
};
assertEquals(111.0, instance.calc(boss));
}

public void testSuit() {
TestSuite suit = new TestSuite();
suit.addTestSuite(TestCoreJava.class);
suit.addTestSuite(TestEntity.class);
}

/**
* 测试纳秒
*
* @throws InterruptedException
*/
public void testNanoTime() throws InterruptedException {
long m1 = System.currentTimeMillis();
long n1 = System.nanoTime();
logger.info(m1);
logger.info(n1);

Thread.sleep(1234);

long m2 = System.currentTimeMillis();
long n2 = System.nanoTime();

logger.info(m2 - m1);
logger.info(n2 - n1);
}

/**
* TODO 批量修改文件名
*/
public void testBatchChangeFileName() {

}

private void initSpring() {
String[] locations = StringUtils.tokenizeToStringArray("classpath:spring/*.xml,"
+ "classpath:spring/**/*.xml,", ",");
ApplicationContext context = new ClassPathXmlApplicationContext(locations);
ApplicationContextUtils.setContext(context);
}

/**
* Spring Bean配置默认为单实例
*/
public void xtestSpringBeanScope() {
initSpring();
MchntInfoMgmt bean1 = (MchntInfoMgmt) ApplicationContextUtils.getBean("mchntInfoMgmtBO");
MchntInfoMgmt bean2 = (MchntInfoMgmt) ApplicationContextUtils.getBean("mchntInfoMgmtBO");
if (bean1 == bean2) {
// 默认
System.out.println("单例");
} else {
// scope="prototype"
System.out.println("非单例");
}
}

/**
* 堆:实例 栈:基础数据类型 字符串占用的内存计算方式 X.length()/1024/1024 M 增加内存 -Xmx1024m
* 当String对象的实际占用内存数量与其自身的字节数步相符。 因此应该少用String,特别是+=操作
*/
public void testMemory() {

System.out.println("当前虚拟机最大可用内存为: " + runtime.maxMemory() / 1024 / 1024 + "M");
System.out.println("当前虚拟机已占用内存: " + runtime.totalMemory() / 1024 / 1024 + "M");

String s = "abcdefghijklmnop";

int count = 0;
while (true) {
try {
System.out.println("String实际字节数" + s.length() / 1024 / 1024 + "M");
s += s;
count++;

} catch (Error e) {
System.out.println("循环次数: " + count);
System.out.println("String实际字节数" + s.length() / 1024 / 1024 + "M");
System.out.println("循环后,已占用内存: " + runtime.totalMemory() / 1024 / 1024 + "M");
System.out.println("Catch到错误: " + e);
break;
}
}
}

Runtime runtime = Runtime.getRuntime();

/**
* 测试byte[] 数组的内存使用情况 byte[1024*1024*2] 是2M的数组元素,实际占用内存为:3M byte 里面只能存放 -128 到 127 的数据
*/
public void testArrayMem() {
int len = 1024 * 1024 * 2;
byte[] abc = new byte[len];
System.out.println("已占用内存1: " + runtime.totalMemory() / 1024 / 1024 + "M");

for (int i = 0; i < len; i++) {
abc[i] = (byte) i;
}
System.out.println(String.valueOf(abc[1024]));
System.out.println("已占用内存2: " + runtime.totalMemory() / 1024 / 1024 + "M");
}

/**
* 内存回收标准: 1,当一个方法执行完毕时,这个方法中声明的对象就可以被当做垃圾收集了 2,将对象的引用变量设为null
*
* Finalizer方法的使用 1, 设置Xmx1k 2, 必须将finalize() 写在main函数中 3, 必须新建一个类 4, 当内存被沾满前,JVM会首先去进行内存回收,
* 于是失去活动的test对象被收回, 在回收前调用了finalize()方法 总结: finalize方法很不好用
*/
public void testFinalizer() {
Test t = new Test();
t.callme();
}

class Test {
@Override
protected void finalize() throws Throwable {
System.out.println("---------Finalize--------" + Runtime.getRuntime().totalMemory()
/ 1024 / 1024 + "M");
}

public void callme() {
System.out.println("callme");
}
}

/**
* 内部类中的方法是否需要被实例化?
*/
public void testInnerClass() {

}

/**
* 生成文件
*
* @throws IOException
*/
public void generateFile() throws IOException {
String file4 = "d:\\test4.txt";
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file4)));
out.println("测试文件");
out.close();
}

/**
* 批量更换文件名
*
* @throws Exception
*/
public void batchReplaceFileName() throws Exception {
File file = new File("d:\\test");
File[] files = file.listFiles();
for (File f : files) {
String fileName = f.getAbsolutePath();
if (fileName.contains(".txt")) {
f.renameTo(new File(fileName.replaceAll("\\.txt", ".java")));
}
}

}

/**
* 将【有声读物-人间正道是沧桑034.wma】替换成【034.wma】 用正则表达式将非数字的删除。 不行。正则只能匹配而不能替换 用Character来判断是否是数字 filePath =
* "H:\\RECORD\\暗算\\";
*/
public void batchReplaceFileName2(String filePath) throws Exception {
File file = new File(filePath);
File[] files = file.listFiles();
for (File f : files) {
String fileName = f.getName();
if (fileName.contains(".wma")) {
String f2 = filterChinese(fileName, filePath);
f.renameTo(new File(f2));
}
}
}

private String filterChinese(String name, String filePath) {
String namebk = name;
for (int i = 0; i < name.length(); i++) {
if (!Character.isDigit(name.charAt(i))) {
namebk = namebk.replace(String.valueOf(name.charAt(i)), "");
}
}
return filePath + namebk + ".wma";
}

/**
* hashCode是int类型,任何String都有hashCode的方法,可以转成int
*/
public void testHashCode() {
System.out.println("aaa".hashCode());
System.out.println("bbb".hashCode());
}

/**
* 测试hashCode 和 equals 重写: 父类 -- 子类 override 重载: 相同方法,不同的参数
*/
public void testHashEquals() {
JavaBean3 bean1 = new JavaBean3("王守仁", 1);
JavaBean3 bean2 = new JavaBean3("王守仁", 2);
// 没有重写hashCode方法时,也是好的
assertTrue(bean1.equals(bean2));

// hashCode的作用是体现在集合中的,如果上面判断bean1.equals(bean2)了
// 在Set集合中只能有一个bean,如不加上hashCode就会有两个bean。哈哈
Set<JavaBean3> set = new HashSet<JavaBean3>();
set.add(bean1);
set.add(bean2);
assertEquals(1, set.size());
}

public void testMath() {
}

/**
* 测试基本数据类型 byte 1个字节 8 位 short 2个字节 16位 char 2个字节 16位 int 4个字节 32位 long 8个字节 64位 float 4个字节 32位
* double 8个字节 64位 boolean 占多少少位啊? 应该是1位 0或者1
*/
@SuppressWarnings("unused")
public void testBasicDataType() {
byte b = '1';
char c = '中';
int i = 1231231231; // 负的20亿到正的20亿 10位数字
long l = 123123123123l; // 在数字后要加上l
float f = 12312.123123f;
double d = 11231232312.123123;
boolean flag = true;
}

/**
* bitSet 不好用,尽量别用
*/
public void testBitSet() {
BitSet bitSet = new BitSet(1);
bitSet.set(123);
bitSet.set(444);
System.out.println(bitSet.get(123));
}

/**
* 但是无法绕过session是否为空的检查。如果去掉检查就能使用了 不管是POST还是GET的方法,在Action中都是用getParameter来得到值。
*
* @throws Exception
*/
public void testHttpClient() throws Exception {
HttpPost httpost = new HttpPost("http://localhost:8093/CIAConsole/PAM/2000080004.action");
org.apache.http.client.HttpClient httpclient = new DefaultHttpClient();

List<org.apache.http.NameValuePair> nvps = new ArrayList<org.apache.http.NameValuePair>();
// 需要通过POST提交的参数
nvps.add(new BasicNameValuePair("name", "name111"));
nvps.add(new BasicNameValuePair("location", "location111"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
// 增加COOKIE
httpost.setHeader("Cookie", "TOKEN=1234567890");
HttpResponse response = httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
String temp = "";
int i = 0;
while ((temp = br.readLine()) != null) {
System.out.println(temp);
}
br.close();
}

/**
* 动态重写方法
*/
public void testRewriteMethod() {
HelloWorldImpl impl = new HelloWorldImpl() {
public void sayHelloWorld() {
System.out.println("Rewrite method");
}
};
impl.sayHelloWorld();
}

/**
* 对bean进行排序 1, 该bean需要实现Comparable接口 2, 可以用 new BeanComparator("fieldName") 来排序
*
* Map 和 Set 是用TreeMap 和 TreeSet来排序的 List 是用 Collections.sort() 来排序的
*/
public void testMapSort() {
// JavaBean 是按照value 顺序
JavaBean bean = new JavaBean("王守仁", 333);
JavaBean bean2 = new JavaBean("樱木花道", 55);
JavaBean bean3 = new JavaBean("李斯", 444);

Map<JavaBean, String> map = new TreeMap<JavaBean, String>(new BeanComparator("value"));
map.put(bean, bean.getName());
map.put(bean2, bean2.getName());
map.put(bean3, bean3.getName());

System.out.println("------Map排序-------");
for (JavaBean b : map.keySet()) {
System.out.println(b.getName());
}

Set<JavaBean> set = new TreeSet<JavaBean>(new BeanComparator("value"));
set.add(bean);
set.add(bean2);
set.add(bean3);

System.out.println("------Set排序-------");
for (JavaBean b : set) {
System.out.println(b.getName());
}

List<JavaBean> list = new ArrayList<JavaBean>();
list.add(bean);
list.add(bean2);
list.add(bean3);

// Collections.sort(list);
Collections.sort(list, new BeanComparator("value"));

System.out.println("------List排序-------");
for (JavaBean b : list) {
System.out.println(b.getName());
}

System.out.println("-----------List<JavaBean> 中----------------");

List<JavaBean> list2 = new ArrayList<JavaBean>();
JavaBean bean4 = new JavaBean("王守仁", 333);
JavaBean bean5 = new JavaBean("樱木花道", 55);
list2.add(bean4);
list2.add(bean5);

for (JavaBean x : list) {
if (list2.contains(x)) {
System.out.println(x.getName());
}
}
}

/**
* 两个list如果值顺序都一样,则equals返回为true, 否则返回false
*/
public void testListEquals() {
List list1 = new ArrayList();
list1.add("a");
list1.add("b");
list1.add("c");

List list2 = new ArrayList();
list2.add("a");
list2.add("b");
list2.add("c");

System.out.println(list1.equals(list2));

}

/**
* 逆序 ReverseComparator 汇丰的金额比较是用两个for循环来保证 【审批金额顺序应该从小到大并且不能相等】 如果ABC数量多的话,会很麻烦
* 可以先排序,再对比两个list是否equals
*/
public void testListEquals2() {
List<BigDecimal> list1 = new ArrayList<BigDecimal>();
list1.add(new BigDecimal("100"));
list1.add(new BigDecimal("80"));
list1.add(new BigDecimal("9"));

List<BigDecimal> list2 = new ArrayList<BigDecimal>(list1);

Collections.sort(list1, new ReverseComparator());

System.out.println(list1.equals(list2));

}

/**
* 比较两个数组M个 N个 中相同的元素, 要最少的循环次数完成 Hashtable 是 HashMap 的同步 Vector 是 ArrayList 的同步
*/
public void testArrayHash() {
int[] s1 = {1, 2, 3, 4, 5};
int[] s2 = {2, 4, 6, 8, 10};

// 一般做法 循环M*N
for (int i = 0; i < s1.length; i++) {
for (int j = 0; j < s2.length; j++) {
if (s1[i] == s2[j]) {
System.out.println(s1[i]);
}
}
}

// 用Hash的方法 循环 M+N
Set set = new HashSet();
for (int i = 0; i < s1.length; i++) {
set.add(s1[i]);
}

for (int j = 0; j < s2.length; j++) {
if (set.contains(s2[j])) {
System.out.println(s2[j]);
}
}
}

/**
* 用Spring的DAO来做,顺序为insert, update, delete。 不能用flush来改变其顺序
*/
public void testHibernateExecWay() throws Exception {
String[] locations = StringUtils.tokenizeToStringArray("classpath:spring/*.xml,"
+ "classpath:spring/**/*.xml,", ",");
ApplicationContext context = new ClassPathXmlApplicationContext(locations);
ApplicationContextUtils.setContext(context);
MchntInfoMgmt mchntInfoMgmtBO = (MchntInfoMgmt) ApplicationContextUtils
.getBean("mchntInfoMgmtBO");
// mchntInfoMgmtBO.transTest();
}

public void testRelatedClass() {
/*
* -------1 多线程Callable-------CallableAndFuture Callable 和 Future接口
* Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类都是可被其它线程执行的任务。 Callable和Runnable有几点不同:
* (1)Callable规定的方法是call(),而Runnable规定的方法是run(). (2)Callable的任务执行后可返回值,而Runnable的任务是不能返回值的。
* (3)call()方法可抛出异常,而run()方法是不能抛出异常的。 (4)运行Callable任务可拿到一个Future对象, Future
* 表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。 通过Future对象可了解任务执行情况,可取消任务的执行,还可获取任务执行的结果。
*/
}

// 集合用contains来查看是否有, 而String
public void testIndexOf() {
String url = "abc!def";
System.out.println(url.indexOf("!")); // 3
System.out.println(url.indexOf("%")); // -1
}

/**
* 用来拆分字符串, 可以优化汇丰的首页代码
*/
public void testTokenizer() {
String[] array = spliteStr("aaa,sdfs,sds,ffff,sss,ssss", ",");
for (String value : array) {
System.out.println(value);
}
}

/**
* 用sdf.parse(String) 将String转换为Date类型 sdf.format(Date) 是转成 String类型的 比较日期大小不必转成Calendar后再比较
*/
public void testCompareDate() {
System.out.println(comparaDate("20100808", "20121122")); // TRUE
System.out.println(comparaDate("20100808", "20021122")); // FALSE
System.out.println(comparaDate("20100808", "20100808")); // FALSE
}

/**
* sdf.setLenient(false); 严格检查 在传入的日期格式与format格式不符时抛出异常 默认为true, 即不严格检查, 这样输出的日期会有问题
*/
public void testChechDt() {
System.out.println(checkDt("yyyyMMdd", "20100808")); // TRUE
System.out.println(checkDt("yyyyMMdd", "20100808112233")); // FALSE
System.out.println(checkDt("yyyyMMdd", "20100999")); // FALSE
}

/**
* 在显示账号或是电话时需要隐藏一部分的内容
*/
public void testHiddenString() {
String a = "1238382742293";
System.out.println(hiddenString(a));
}
/**
* 隐藏字符串中间部分
*
* @param string
* @return
*/
public static String hiddenString(String arg0) {
String hid = "";
if (arg0 != null) {
String string = arg0.trim();
if (string.length() == 0 || string.length() == 1) {
return string;
} else if (string.length() == 2) {
return "*" + string.substring(0);
} else {
int index = string.length() / 3;
for (int i = 0; i < index; i++) {
hid += "*";
}
return string.substring(0, index) + hid + string.substring(index * 2);
}
} else {
return Constants.BLANK;
}
}

/**
* 检查日期的有效性
*
* @param format
* 日期格式
* @param date
* 日期
* @return
*/
public static boolean checkDt(String format, String date) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setLenient(false);
Date d = sdf.parse(date);
return true;
} catch (Exception ex) {
logger.info("error date");
}
return false;
}

/**
* 比较日期
*
* @param date1
* @param date2
* @return
* @throws Exception
*/
public static boolean comparaDate(String before_date, String after_date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
try {
Date Date1 = dateFormat.parse(before_date);
Date Date2 = dateFormat.parse(after_date);
return Date1.before(Date2);
} catch (Exception ex) {
return false;
}
}

/**
* 拆分字符串
*
* @param str
* @param code
* @return
*/
public static String[] spliteStr(String str, String code) {
if (str == null || str.equals("")) {
return null;
}
StringTokenizer st = new StringTokenizer(str, code);
String[] ret = new String[st.countTokens()];
int i = 0;
while (st.hasMoreTokens()) {
ret[i] = st.nextToken();
i++;
}
return ret;
}

class TestGen0<K, V> {
public Map<K, V> map = new HashMap<K, V>();
public void put(K k, V v) {
map.put(k, v);
}
public V get(K k) {
return map.get(k);
}
}

private void printCollection(List<?> c) {
for (Object e : c) {
System.out.println(e);
}
}

/**
* 没有多大作用, 挺浮云的
*/
public void testQuestionMark() {
TestGen0<String, String> t = new TestGen0<String, String>();
t.put("key", "value");
String s = t.get("key");
System.out.println(s);

TestGen0<Integer, Integer> t2 = new TestGen0<Integer, Integer>();
t2.put(1, 100);
Integer s2 = t2.get(1);
System.out.println(s2);

List<String> list = new ArrayList<String>();
list.add("aa");
list.add("bb");
list.add("cc");
printCollection(list);

System.out.println("-----------");

List list2 = new ArrayList();
list2.add(1);
list2.add(2);
list2.add(3);
list2.add("sss");
printCollection(list2);

}

/**
* 防止SQL注入的另一种方式 where username='1' or '1'='1' 转化成 where username='1'' or ''1''=''1'
* 这个可以执行,但返回不了任何结果
*/
public void testEscapeSql() {
String username = "1' or '1'='1";
username = StringEscapeUtils.escapeSql(username);

System.out.println(username);

String sql = "select count(userid) from t_user where username='" + username + "'";
System.out.println(sql);

}

/**
* ResourceBundle 可以读取properties文件 properties文件只有用propertiesEditor打开才没有中文乱码问题, 需要安装插件
*
*/
public void testi18n() {
ResourceBundle res = ResourceBundle.getBundle("app", Locale.US);
System.out.println(res.getString("hello"));

ResourceBundle res2 = ResourceBundle.getBundle("app", Locale.CHINA);
System.out.println(res2.getString("hello"));
}

/**
* 不能用java的正则表达式, 只是用来匹配字符串的
*
* @throws Exception
*/
public void testFindChinese() throws Exception {

String fileName = "E:\\WKP_UNIONPAY\\CIAPortal\\WebContent\\page";
// String fileName = "E:\\WKP_UNIONPAY\\CIAPortal\\conf";
// String fileName = "E:\\WKP_UNIONPAY\\CIAPortal\\WebContent\\resources\\js";
File file = new File(fileName);
File[] files = file.listFiles();

testFile(fileName);

}

private void testFile(String fileName) throws Exception {
File file = new File(fileName);
File[] files = file.listFiles();

// 数组也可以用增加型的for 来迭代
for (File fs : files) {
if (fs.isDirectory()) {
testFile(fs.getPath());
}
if (fs.getName().indexOf(".jsp") > 0) {
System.out.println();
System.out.println("----------" + fs.getName() + "----------");
// 解决乱码问题
// File -- FileInputStream -- InputStreamReader -- BufferedReader -- readLine()
InputStreamReader isr = new InputStreamReader(new FileInputStream(fs
.getAbsoluteFile()), "UTF-8");
BufferedReader br = new BufferedReader(isr);

String temp = "";
int i = 0;
while ((temp = br.readLine()) != null) {
filterChinese2(temp);
}
}
}
}

private void filterChinese2(String name) throws Exception {
for (int i = 0; i < name.length(); i++) {
if (i + 1 < name.length()) {
if ((name.charAt(i) == '/' && name.charAt(i + 1) == '/')
|| (name.charAt(i) == '/' && name.charAt(i + 1) == '*')) {
return;
}
}

if (String.valueOf(name.charAt(i)).getBytes("UTF-8").length >= 3) {
System.out.print(name.charAt(i));
if (i + 1 < name.length()
&& String.valueOf(name.charAt(i + 1)).getBytes("UTF-8").length < 3) {
System.out.println();
}
}
}
}

/**
* 安全退出=common.safeBake 版权所有认证与资质=common.allRitQliftAthtct 保存=button.save 放入map中
*/
public Map<String, String> testLoadi18n() throws Exception {
String filePath = "d:/i18n.txt";

Map<String, String> map = new HashMap<String, String>();
File fs = new File(filePath);
InputStreamReader isr = new InputStreamReader(new FileInputStream(fs.getAbsoluteFile()),
"UTF-8");
BufferedReader br = new BufferedReader(isr);

try {
String name;
while ((name = br.readLine()) != null) {
String[] array = name.split("=");
map.put(array[0], "<s:text name=\'" + array[1] + "\'/>");
map.put(array[0] + ":", "<s:text name=\'" + array[1] + "\'/>:");
map.put(array[0] + ":", "<s:text name=\'" + array[1] + "\'/>:");
}
} catch (Exception e) {
e.printStackTrace();
}

/*
* map.put("页,", "<s:text name=\'page.Page,\'/>"); map.put("页", "<s:text
* name=\'page.Page\'/>"); map.put("共","<s:text name=\'page.Total\'/>");
*
* map.put("请选择","<s:text name=\'common.select\'/>");
*
* //银联系统跟踪号 map.put("银联系统跟踪号", "<s:text name=\'common.traceNo\'/>"); //操作成功
*/

/*
* for(String v : map.keySet()){ System.out.println(v + " : " + map.get(v) ); }
*/

return map;
}

/**
* 无法修改只能先删除原来文件, 再新建一个新的文件
*
* @throws Exception
*/
public void testModifyText(String filePath, Map<String, String> map) throws Exception {
// String filePath =
// "E:\\WKP_UNIONPAY\\CIAPortal\\WebContent\\page\\mer\\notify\\YinBulletinMgmtFirst_view.jsp";

File fs = new File(filePath);
File fs2 = new File(filePath + ".1");
InputStreamReader isr = new InputStreamReader(new FileInputStream(fs.getAbsoluteFile()),
"UTF-8");
BufferedReader br = new BufferedReader(isr);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fs2),
"UTF-8"));

String name;
String key = "";

Map<String, String> mapSpace = new HashMap<String, String>();
mapSpace.put("下 载", "<s:text name=\"common.download\"/>");
mapSpace.put("返 回", "<s:text name=\"common.back\"/>");
mapSpace.put("查 询", "<s:text name=\"common.query\"/>");
mapSpace.put("查 询", "<s:text name=\"common.query\"/>");
mapSpace.put("查询", "<s:text name=\"common.query\"/>");
mapSpace.put("重 置", "<s:text name=\"common.reset\"/>");
mapSpace.put("手 机", "<s:text name=\"common.cell\"/>");
mapSpace.put("添 加", "<s:text name=\"common.add\"/>");
mapSpace.put("修 改", "<s:text name=\"common.modify\"/>");
mapSpace.put("删 除", "<s:text name=\"common.delete\"/>");
mapSpace.put("解 锁", "<s:text name=\"common.unlock\"/>");
mapSpace.put("返 回", "<s:text name=\"common.back\"/>");

while ((name = br.readLine()) != null) {

boolean f = true;

for (String k : mapSpace.keySet()) {
if (name.indexOf(k) > 0) {
bw.write(name.replace(k, mapSpace.get(k)));
f = false;
break;
}
}

if (f == false) {
continue;
}

for (int i = 0; i < name.length(); i++) {
if (i + 1 < name.length()) {
if ((name.charAt(i) == '/' && name.charAt(i + 1) == '/')
|| (name.charAt(i) == '/' && name.charAt(i + 1) == '*')
|| (name.charAt(i) == '<' && name.charAt(i + 1) == '!')
|| (name.charAt(i) == '<' && name.charAt(i + 1) == '%')) {
bw.write(name.substring(i));
break;
}
}

if (String.valueOf(name.charAt(i)).getBytes("UTF-8").length >= 3) {
// System.out.print(name.charAt(i));
key += String.valueOf(name.charAt(i));

if (i == name.length() - 1
|| (i + 1 < name.length() && String.valueOf(name.charAt(i + 1))
.getBytes("UTF-8").length < 3)) {
if (key.length() > 0) {
// System.out.println(key);
String value = map.get(key);
if (!StringUtil.isEmpty(value)) {
bw.write(value);
} else {
bw.write(key);
}
key = "";
}
}
} else {
bw.write(name.charAt(i));
}

}

bw.write("\n");
key = "";
}

bw.flush();
bw.close();
br.close();

fs.delete();
fs2.renameTo(new File(fs.getAbsolutePath()));

}

private void replaceChinese() throws Exception {
String fileName = "E:\\WKP_UNIONPAY\\CIAPortal\\WebContent\\page";
testFile2(fileName);
}

private void testFile2(String fileName) throws Exception {
File file = new File(fileName);
File[] files = file.listFiles();

// 将名值对放到map中
Map<String, String> map = testLoadi18n();

// 数组也可以用增加型的for 来迭代
for (File fs : files) {
if (fs.isDirectory()) {
testFile2(fs.getPath());
}
if (fs.getName().indexOf(".jsp") > 0) {
System.out.println();
System.out.println("----------" + fs.getName() + "----------");
// 解决乱码问题
// File -- FileInputStream -- InputStreamReader -- BufferedReader -- readLine()
testModifyText(fs.getAbsolutePath(), map);
}
}
}

/**
* split("\\|", -1)
*/
public void testSplit() {
String s2 = "4001191100000039||123.67||民生银行|6221231212312341|小白|0001121|01|110222197905012315||||";

String[] a2 = s2.split("\\|", -1);// 如果最后一个数组为空的时候不会被截掉

String[] a4 = s2.split("\\|"); // 如果最后一个数组为空的时候就会截掉

for (String v : a2) {
// 001191100000039::123.67::民生银行:6221231212312341:小白:0001121:01:110222197905012315:::::
System.out.print(v + ":");
}
System.out.println();
for (String v : a4) {
// 4001191100000039::123.67::民生银行:6221231212312341:小白:0001121:01:110222197905012315:
System.out.print(v + ":");
}
System.out.println();
System.out.println(a2[11]);
System.out.println(a4[11]);

}

public void testCompareTo() {
String a1 = "aaaaa";
String a2 = "bbbbb";

System.out.println(a1.compareTo(a2));
}

/**
* stack 的5个主要的方法 empty() peek() pop() push() search() 元素可以重复, 和List比较类似
*/
public void testStack() {
Stack<String> stack = new Stack<String>();
stack.push("a");
stack.push("x");
stack.push("a");
stack.push("c");

for (String s : stack) {
System.out.print(s + " : ");
}
System.out.println();

System.out.println(stack.search("a"));
System.out.println(stack.peek());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.empty());
}

/**
* LinkedList 在频繁的add时效率比ArrayList快
* 场景: 代收文件上传 将一个文本文件按照每行转换成List
* @throws IOException
*/
public void testLinkedList() throws IOException{
readLineIgnoreBlankLine("");
}

/**
* 将文件中的数据按行存入list中,空行(包括全空格的行)自动过滤
*
* @param fileName
* @return
* @throws IOException
*/
public List<String> readLineIgnoreBlankLine(String fileName) throws IOException {
InputStreamReader fileReader = new InputStreamReader(new FileInputStream(fileName),
"GBK");
BufferedReader bufferReader = new BufferedReader(fileReader);
List<String> list = new LinkedList<String>();
String str = null;
while ((str = bufferReader.readLine()) != null) {
if (!str.trim().equals(""))
list.add(str);
}
bufferReader = null;
fileReader = null;
return list;
}

/**
* 将一个数组的元素重新存储到Collection中并返回。需考虑方法的通用性。提示,使用泛型
* 不过泛型不适合基本数据类型
* Arrays.asList(xx) 也适用于泛型
*/
public void testParseArrays2Collection(){
String[] s1 = {"a","b","c"};
List<String> l1 = arrayToCollection(s1);
for(String v : l1){
System.out.println(v);
}

Integer[] s2 = {1,2,3};
List<Integer> l2 = Arrays.asList(s2);//arrayToCollection(s2);
for(Integer v : l2){
System.out.println(v);
}

}

public <T> List<T> arrayToCollection(T arr[]){
List<T> list=new ArrayList<T>();
for(int i=0;i<arr.length;i++){
list.add(arr[i]);
}
return list;
}


public static void main(String[] args) throws Exception {
// Runtime runtime = Runtime.getRuntime();
// System.out.println("当前虚拟机最大可用内存为: " + runtime.maxMemory()/1024/1024+"M");
// System.out.println("当前虚拟机已占用内存: " + runtime.totalMemory()/1024/1024+"M");

TestCoreJava java = new TestCoreJava();
java.testComma();

}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值