`
收藏列表
标题 标签 来源
单例加载多个资源文件
package com.baofeng.common.config;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.net.URL;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * User: weichun.zhan
 * Date: 12-7-7
 * Time: 下午12:23
 */
public class AppConfigs {
    private final static Logger log = LoggerFactory.getLogger(AppConfigs.class);
    private static volatile AppConfigs instance; //volatile avoid dcl bug.
    private Map<String, String> configs;
    public static String configFile = "configs.properties";
    private final static Set<String> configFileSet = new HashSet<String>();
    private static final Object lock = new Object();
    private static volatile boolean initDone = false;

    private AppConfigs() {
    }

    public static AppConfigs getInstance() {
        if (instance == null) {
            synchronized (lock) {
                if (instance == null) {
                    instance = new AppConfigs();
                }
            }
        }
        return instance;
    }

    public AppConfigs getByName(String name){
        if(!configFileSet.contains(name)){
            initDone = false;
            configFileSet.add(name);
        }
        this.configFile = name;
        instance.init();
        initDone = true;
        return this;
    }

    public synchronized void reload() {
        Map<String, String> configsTemp = new ConcurrentHashMap<String, String>();
        log.debug("reload AppConfigs");
        Properties props = new Properties();
        try {
            URL url = this.getClass().getClassLoader().getResource(configFile);
            InputStream in = url.openStream();
            props.load(in);
            Enumeration en = props.propertyNames();
            while (en.hasMoreElements()) {
                String key = (String) en.nextElement();
                String value = props.getProperty(key);
                configsTemp.put(key, value);
            }
        } catch (Exception e) {
            log.error("reload AppConfigs error:" + e.getMessage());
            return;
        }
        configs = configsTemp;
    }

    public void init() {
        if (initDone) {
            return;
        }
        log.debug("init AppConfigs");
        Properties props = new Properties();
        try {
            URL url = this.getClass().getClassLoader().getResource(configFile);
            InputStream in = url.openStream();
            props.load(in);
            Enumeration en = props.propertyNames();
            if(configs == null){
                configs = new ConcurrentHashMap<String, String>();
            }
            while (en.hasMoreElements()) {
                String key = (String) en.nextElement();
                String value = props.getProperty(key);
                configs.put(key, value);
            }
        } catch (Exception e) {
            log.error("init AppConfigs error:" + e.getMessage());
        }
    }

    public Map<String, String> getConfigs() {
        return configs;
    }

    public String getString(String key) {
        return configs.get(key);
    }

    public Integer getInt(String key){
        return  Integer.valueOf(configs.get(key));
    }

    public String get(String key,String defaultStr) {
        String result = configs.get(key);
        if(result == null){
            result =  defaultStr;
        }
        return result;
    }
}
Object和二进制数组的转换
package com.baofeng.common.jedis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * 对象工具类
 * User: weichun.zhan
 * Date: 12-7-30
 * Time: 下午4:37
 */
public class ObjectUtils {

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

    public static byte[] convertToByteArray(Object obj) {
        if(obj == null){
            return null;
        }
        ByteArrayOutputStream byteArrayOutputStream = null;
        ObjectOutputStream objectOutputStream = null;
        try {
            byteArrayOutputStream = new ByteArrayOutputStream(3000);
            objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(obj);
            objectOutputStream.flush();
            byte buf[] = byteArrayOutputStream.toByteArray();

            return buf;
        } catch (Exception e) {
            logger.error("{}", e);

        } finally {
            if (objectOutputStream != null) {
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    logger.error("{}", e);
                }
            }
            if (byteArrayOutputStream != null) {
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    logger.error("{}", e);
                }

            }
        }
        return null;
    }

    public static Object converteToObject(byte[] buf) {
        if(buf == null){
            return null;
        }
        ByteArrayInputStream byteArrayInputStream = null;
        ObjectInputStream objectInputStream = null;
        Object obj = null;
        try {
            byteArrayInputStream = new ByteArrayInputStream(buf);
            objectInputStream = new ObjectInputStream(byteArrayInputStream);
            obj = objectInputStream.readObject();
        } catch (Exception e) {
            logger.error("{}", e);
        } finally {
            if(objectInputStream != null){
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    logger.error("{}", e);
                }
            }
            if(byteArrayInputStream != null){
                try {
                    byteArrayInputStream.close();
                } catch (IOException e) {
                    logger.error("{}", e);
                }
            }
        }
        return obj;
    }
}
JQuery鼠标滑过表格变色 jquery http://hdycfm.blog.51cto.com/3937463/863220
 </script>
   <style>
    .over { background-color:#77DDFF;}  //定义鼠标滑过的颜色
 </style>
 <script type="text/javascript">
   $(function(){
          $("#table1 tr").hover(function(){  //table1  指的是一个table的ID
           $(this).addClass("over");
           },function(){
            $(this).removeClass("over");
            });
         });
   </script>
redis队列 redis
package com.test;

import org.junit.Test;
import redis.clients.jedis.Jedis;

import java.util.Iterator;
import java.util.Set;

/**
 * User: weichun.zhan
 * Date: 12-7-30
 * Time: 下午12:17
 */
public class TestRedisQueue {

    @Test
    public void testQeuePriority1(){
        JedisManager manager = JedisManager.getInstance();
        Jedis jedis = manager.getResource();
        //方式一:把队列值放入队列头
        long r = jedis.lpush("derekzhan","1");
        System.out.println(" result1:" + r);
        jedis.lpush("derekzhan","2");
        jedis.lpush("derekzhan","3");

        long r4 = jedis.rpush("derekzhan", "4");
        System.out.println(" result2:" + r4);
        long l = jedis.lpush("derekzhan","5");
        System.out.println(" result3:" + l);

        String value = null;
        while( null != (value = jedis.rpop("derekzhan"))){
            System.out.println(value);
        }
        manager.returnResource(jedis);
    }
    @Test
    public void testQeuePriority2(){
        JedisManager manager = JedisManager.getInstance();
        Jedis jedis = manager.getResource();
        long start = System.currentTimeMillis();
        //方式二:移动队列中指定的值到对列头
        System.out.println("--------------------------");

        for(int i = 0 ;i < 10000;i++){
            jedis.lpush("derekzhan", "" + i);
        }

        String val = null;
        String find = "3000";
        while(true)
        {
            val =  jedis.rpoplpush("derekzhan", "derekzhan");
            //System.out.println("val = " + val);
            if(find.equals(val)){
                val =  jedis.lpop("derekzhan");
                jedis.rpush("derekzhan",val);
                break;
            }
        }



        String value = null;
        while( null != (value = jedis.rpop("derekzhan"))){
            //System.out.println(value);
        }
        System.out.println("took time:" + (System.currentTimeMillis() - start));
        manager.returnResource(jedis);
    }
    @Test
    public void testQeuePriority3(){
        JedisManager manager = JedisManager.getInstance();
        Jedis jedis = manager.getResource();
        long start = System.currentTimeMillis();
        //方式二:移动队列中指定的值到对列头
        for(int i = 0 ;i < 10000;i++){
            jedis.lpush("derekzhan", "" + i);
        }

        String val = null;
        int i = 0;
        String find = "3000";
        while(true)
        {
            val =  jedis.lindex("derekzhan", i);
            //System.out.println("val = " + val);
            i++;
            if(find.equals(val)){
                jedis.lrem("derekzhan",0,find);
                jedis.rpush("derekzhan",val);
                break;
            }
        }



        String value = null;
        while( null != (value = jedis.rpop("derekzhan"))){
            //System.out.println(value);
        }
        System.out.println("took time:" + (System.currentTimeMillis() - start));
        manager.returnResource(jedis);
    }

    /**
     * redis优先级队列
     */
    @Test
    public void TestQueuePriority(){
        JedisManager manager = JedisManager.getInstance();
        Jedis jedis = manager.getResource();
        long start = System.currentTimeMillis();
        //重新调整队列的score值让此值处于队列的头  此种方式比上面的2种方式都要好,效率最高,
        //但可能要维护多个score值,还有个问题是如果score一样,则按照默认的倒叙排列,值越大在队列头
        String _name = "derekzhan";
        jedis.zadd(_name,1,"2");
        jedis.zadd(_name,1,"4");
        jedis.zadd(_name,1,"3");
        jedis.zadd(_name,3,"40");
        jedis.zadd(_name,3,"10");

        for(int i = 0 ;i < 5000;i++){
            jedis.zadd(_name,1,""+i);
        }
        for(int i = 5000 ;i < 10000;i++){
            jedis.zadd(_name,2,""+i);
        }

        String find = "3000";
        jedis.zadd(_name,3,find);



        //System.out.println(jedis.zrevrange(_name,0,-1));

        while (true){
            boolean hasValue = false;
            Set val = jedis.zrevrange(_name,0,0);//从队列中获取一个数据.
            for (Iterator iterator = val.iterator(); iterator.hasNext();) {
                Object next =  iterator.next();
                System.out.println(next);

                //proccess operation........
                jedis.zrem(_name,next.toString());
                if(!next.equals(find)){
                    hasValue = true;
                }else {
                    hasValue = false;
                    System.out.println(next);
                }
            }
            if(!hasValue){
                break;
            }
        }
        System.out.println("took time:" + (System.currentTimeMillis() - start));
        manager.returnResource(jedis);
    }
}
平时用的
public class Test extends TestCase {

    private volatile int i = 0;
    private long count = 0;

    private long countDown = 0 ;

    private CountDownLatch countDownLatch = null;

    public static void main(String[] args) throws InterruptedException {

        Test t = new Test();
        t.testVolatile();
        System.out.println("last in value:" + t.i);

        t.testJoin();
        System.out.println(t.count);

        t.testCountDown();
        if (t.countDownLatch != null) {
            t.countDownLatch.await();
            System.out.println(t.countDown);
        }

        t.testThreadPool();

        //正则截取字符串
        Pattern p = Pattern.compile("^[_a-z0-9\\.\\-]+@([\\._a-z0-9\\-]+\\.)+[a-z0-9]{2,4}$");
        //  中括号之前的内容.*\] , [^]]  不包含中括号
        Pattern p = Pattern.compile(".+form1\\.(.+),\\s(['\"])(\\d+)\\2\\)");
        //Pattern p = Pattern.compile("<(.+)>");
        Matcher m = p.matcher("<htmlasdfd.>");
        if(m.find()){
            System.out.println(m.group());
            System.out.println(m.group(1));

        }else{
            System.out.println("No found");
        }

        Date d = new Date();
        System.out.println(d.getYear());

    }


    //测试volatile
    public void testVolatile() {
        Thread t = new Thread(new Test.Thread1());
        Thread t2 = new Thread(new Test.Thread1());
        t.start();
        t2.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
/**
     * volatile 不是原子级别的,只能保持读的时候是从共享变量中获取,但写入到内存中时覆盖到原来的值
     * http://www.cnblogs.com/aigongsi/archive/2012/04/01/2429166.html
     * http://developer.51cto.com/art/200906/132344.htm
     */
    class Thread1 implements Runnable {
        public void run() {
            Test.this.i++;
            System.out.println(Test.this.i);
        }


    }


    public void testJoin() throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread t = new Thread(new TestJoinThread());
        t.start();
        t.join();
        Thread t2 = new Thread(new TestJoinThread());
        t2.start();
        t2.join();
        System.out.println(" all took time : " +  (System.currentTimeMillis() - start));

    }

    class TestJoinThread implements Runnable {
        @Override
        public void run() {
            for(int i = 0; i <100000000;i ++){
                count++;
            }

        }
    }

    public void testCountDown() {
        long start = System.currentTimeMillis();
        countDownLatch = new CountDownLatch(2);
        CountDownThread tjt = new CountDownThread();
        Thread t = new Thread(tjt);
        t.start();
        Thread t2 = new Thread(tjt);
        t2.start();
        System.out.println("testCountDown= " + (System.currentTimeMillis() - start));
    }

    class CountDownThread implements Runnable{

        @Override
        public void run() {
            for(int i = 0; i <100000000;i ++){
               countDown++;
            }
            if(countDownLatch != null)
                countDownLatch.countDown();
        }
    }


    public void testThreadPool() {
        ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
        exec.scheduleAtFixedRate(new Runnable() {//每隔一段时间就触发异常
                    @Override
                    public void run() {
                        System.out.println(System.currentTimeMillis());
                    }
                }, 1000, 5000, TimeUnit.MILLISECONDS);

        exec.scheduleAtFixedRate(new Runnable() {//每隔一段时间打印系统时间,证明两者是互不影响的
                    @Override
                    public void run() {
                        System.out.println(System.nanoTime());
                    }
                }, 1000, 2000, TimeUnit.MILLISECONDS);

    }

public void testThreadPool() throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(30);
        CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(executorService);

        for (int i = 0; i < 20; i++) {
            Future f = completionService.submit(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    int i = 0;
                    while (true) {
                        System.out.println("Thread " + i + " =[" + Thread.currentThread().getName() + "] " + System.currentTimeMillis());
                        //Thread.sleep(1000);
                        if (i++ > 5) break;
                    }
                    return 1;
                }
            });
            /*if(f != null){
                logger.info(" fff = ",f.get());//调用会阻塞线程,导致线程会挨个执行,不能达到多线程的效果
            }*/
        }
        for (int i = 0; i < 20; i++) {
            logger.info("ffffuture",completionService.take().get());//使用这样的方法可以达到多线程效果
        }


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

    }

    public void testaaYear(){
        Date d = new Date();
        System.out.println(d.getYear());
    }
}
NIO写文件 nio写文件
public static void savefileNIO(String content, String filename) {
        FileOutputStream fos = null;
        FileChannel fc_out = null;
        try {
            fos = new FileOutputStream(filename);
            fc_out = fos.getChannel();
            ByteBuffer buf = ByteBuffer.wrap(content.getBytes());
            buf.put(content.getBytes());
            buf.flip();
            fc_out.write(buf);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != fc_out) {
                try {
                    fc_out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
NIO读取文件 按行处理 nio读取文件 按行处理
//NIO读取文件 按行处理
    public static void testMapped() throws IOException {
        long strat = System.currentTimeMillis();
        String filename = "H:\\wokspace\\job\\core\\src\\test\\java\\com\\dajie\\interview\\dao\\SMSDaoTest.java";
        FileInputStream fis = new FileInputStream(filename);
        FileChannel channel = fis.getChannel();
        int length = (int) channel.size();
        MappedByteBuffer byteBuffer =
                channel.map(FileChannel.MapMode.READ_ONLY, 0, length);
        byte [] buffer = new byte[length];
        byteBuffer.get(buffer);
        String str = new String(buffer);
        String[] strArray = str.split("\r\n");
        int i=0;
        while(i != strArray.length){
            System.out.println(strArray[i]);
            i++;
        }

        System.out.println(System.currentTimeMillis() - strat);
    }
获取几天前的代码 java日期
public static String get5DaysAgo(){
        Calendar now = Calendar.getInstance();
        now.setTime(new Date());
        //now.set(Calendar.DATE,now.get(Calendar.DATE) - 5);
        now.add(Calendar.DATE,-5);//几天后把-5改成正数即可
        return DateUtil.formatDate(now.getTime(),"yyyy-MM-dd hh:mm:ss");


}
Global site tag (gtag.js) - Google Analytics