Solo  当前访客:3 登录 注册

喧哗博客-http://blog.xuahua.com

繁华过后的沉寂--技术经验分享
浏览次数: 95,037    文章总数: 91    评论总数: 3
标签:

visual VM 监听远程内存 提示无法使用 service:jmx:rmi:///jndi/rmi:///jmxrmi

1,启动参数

  

java -Djava.rmi.server.hostname=xxx -Djava.security.policy=jstatd.all.policy -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote=true -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.port=8888
-Xmx256m -Xms=256m -jar xxx.jar

 

2,需要开启监听的二个随机端口,如果这两个端口访问不了,会提示 

VisualVM 无法使用 service:jmx:rmi:///jndi/rmi:///jmxrmi 连接到XX.xx.xx.xx 

 

如何查看,如下命令

netstat -tupln |grep {要监听java进程id}

3,命令查看内存占用情况分布

jstat -gcutil xxx 200 3

 

 

java并发编程之栅栏(CyclicBarrier)与闭锁(Latch) 有更新!

如果想实现所有的线程一起等待某个事件的发生,当某个事件发生时,所有线程一起开始往下执行的话,有什么好的办法吗?

方法1,栅栏CyclicBarrier

方法2 ,闭锁 Latch


栅栏与闭锁(Latch)的差异在于:


    闭锁   Latch 


一种同步方法,可以延迟线程的进度直到线程到达某个终点状态。通俗的讲就是,一个闭锁相当于一扇大门,在大门打开之前所有线程都被阻断,一旦大门打开所有线程都将通过,

但是一旦大门打开,所有线程都通过了,那么这个闭锁的状态就失效了,门的状态也就不能变了,只能是打开状态。

也就是说闭锁的状态是一次性的,它确保在闭锁打开之前所有特定的活动都需要在闭锁打开之后才能完成。


   应用场景:


  • 确保某个计算在其需要的所有资源都被初始化之后才继续执行。二元闭锁(包括两个状态)可以用来表示“资源R已经被初始化”,而所有需要R的操作都必须先在这个闭锁上等待。
  • 确保某个服务在其依赖的所有其他服务都已经启动之后才启动。
  • 等待直到某个操作的所有参与者都就绪在继续执行。(例如:多人游戏中需要所有玩家准备才能开始)


            CountDownLatch是JDK 5+里面闭锁的一个实现,允许一个或者多个线程等待某个事件的发生。CountDownLatch有一个正数计数器,countDown方法对计数器做减操作,await方法等待计数器达到0。

         所有await的线程都会阻塞直到计数器为0或者等待线程中断或者超时。


         代码例子: 

                   

    栅栏  CyclicBarrier


 栅栏类似于闭锁,它能阻塞一组线程直到某个事件发生。栅栏与闭锁的关键区别在于,所有的线程必须同时到达栅栏位置,才能继续执行。闭锁用于等待事件,而栅栏用于等待其他线程。


     场景:

 应用一些协议,比如几个家庭成员决定在某个地方集合,所有人在6:00在某地集合,到了以后要等待其他人,之后才能讨论去哪里吃饭。

 并行迭代,将一个问题分成很多子问题,当一系列的子问题都解决之后(所有子问题线程都已经await()),此时将栅栏打开,所有子问题线程被释放,而栅栏位置可以留着下次使用。



  例子:两个分别关于CountDownlatch和CyclicBarrier的例子

1、CountDownLatch


    有三个工人在为老板干活,这个老板有一个习惯,就是当三个工人把一天的活都干完了的时候,他就来检查所有工人所干的活。记住这个条件:三个工人先全部干完活,老板才检查。所以在这里用Java代码设计两个类,Worker代表工人,Boss代表老板,具体的代码实现如下:


    工人:


              

package LatchAndCyclicBarrier;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class Work implements Runnable{


        private CountDownLatch downLatch;
        private String name;

        public Work(CountDownLatch downLatch, String name){
            this.downLatch = downLatch;
            this.name = name;
        }

        public void run() {
            this.doWork();
            try{
                TimeUnit.SECONDS.sleep(new Random().nextInt(10));
            }catch(InterruptedException ie){
            }
            System.out.println(this.name + "活干完了!");
            this.downLatch.countDown();

        }

        private void doWork(){
            System.out.println(this.name + "正在干活!");
        }

    }


老板:

 

package LatchAndCyclicBarrier;

import java.util.concurrent.CountDownLatch;

public class Boss implements Runnable{

        private CountDownLatch downLatch;

        public Boss(CountDownLatch downLatch){
            this.downLatch = downLatch;
        }

        public void run() {
            System.out.println("老板正在等所有的工人干完活......");
            try {
                this.downLatch.await();
            } catch (InterruptedException e) {
            }
            System.out.println("工人活都干完了,老板开始检查了!");
        }

    }

测试代码: 




package LatchAndCyclicBarrier;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestLatch {

    public static void main(String[] args) {
            ExecutorService executor = Executors.newCachedThreadPool();

            CountDownLatch latch = new CountDownLatch(3);

            Work w1 = new Work(latch,"张三");
            Work w2 = new Work(latch,"李四");
            Work w3 = new Work(latch,"王二");

            Boss boss = new Boss(latch);

            executor.execute(w3);
            executor.execute(w2);
            executor.execute(w1);
            executor.execute(boss);

            executor.shutdown();
        }

    }
执行结果:
李四正在干活!
老板正在等所有的工人干完活......
王二正在干活!
张三正在干活!
李四活干完了!
王二活干完了!
张三活干完了!
工人活都干完了,老板开始检查了!

2、CyclicBarrier


接着上面的例子,还是这三个工人,不过这一次,这三个工人自由了,老板不用检查他们任务了,他们三个合作建桥,有三个桩,每人打一个,同时打完之后才能一起搭桥(搭桥需要三人一起合作)。也就是说三个人都打完桩之后才能继续工作。

   








package LatchAndCyclicBarrier;

import java.util.concurrent.CyclicBarrier;

public class CycWork implements Runnable {


        private CyclicBarrier cyclicBarrier ;
        private String name ;

        public CycWork(CyclicBarrier cyclicBarrier,String name)
       {
               this .name =name;
               this .cyclicBarrier =cyclicBarrier;
       }

        @Override
        public void run() {
               // TODO Auto-generated method stub

              System. out .println(name +"正在打桩,毕竟不轻松。。。。。" );

               try {
                     Thread. sleep(5000);
                     System. out .println(name +"不容易,终于把桩打完了。。。。" );
                      cyclicBarrier .await();

              } catch (Exception e) {
                      // TODO: handle exception
                     e.printStackTrace();
              }

              System. out .println(name +":其他逗b把桩都打完了,又得忙活了。。。" );


       }

}
测试程序:
 
package LatchAndCyclicBarrier;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CycTest {

        public static void main(String[] args)
       {
              ExecutorService executorpool=Executors. newFixedThreadPool(3);
              CyclicBarrier cyclicBarrier= new CyclicBarrier(3);

              CycWork work1= new CycWork(cyclicBarrier, "张三" );
              CycWork work2= new CycWork(cyclicBarrier, "李四" );
              CycWork work3= new CycWork(cyclicBarrier, "王五" );

              executorpool.execute(work1);
              executorpool.execute(work2);
              executorpool.execute(work3);

              executorpool.shutdown();

       }

}
运行结果:
 
李四正在打桩,毕竟不轻松。。。。。
张三正在打桩,毕竟不轻松。。。。。
王五正在打桩,毕竟不轻松。。。。。
李四不容易,终于把桩打完了。。。。
张三不容易,终于把桩打完了。。。。
王五不容易,终于把桩打完了。。。。
王五:其他逗b把桩都打完了,又得忙活了。。。
李四:其他逗b把桩都打完了,又得忙活了。。。
张三:其他逗b把桩都打完了,又得忙活了。。。 
 

CountDownlatch和CyclicBarrierde 源码部分

1、CountDownLatch中的两个关键方法

 public void countDown() {    //对计数器减一 表示有一个事件已经发生了
        sync.releaseShared(1); 
    }
public void await() throws InterruptedException { //等到计数器为0
        sync.acquireSharedInterruptibly(1);
    }
await方法调用了AbstractQueuedSynchronizer中的acquireSharedInterruptibly
 
public final void acquireSharedInterruptibly (int arg)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        if (tryAcquireShared(arg) < 0)
            doAcquireSharedInterruptibly(arg);
    }
public final boolean releaseShared (int arg) {
        if (tryReleaseShared(arg)) {   
            doReleaseShared();
            return true ;
        }
        return false ;
    }
protected boolean tryReleaseShared (int arg) {
        throw new UnsupportedOperationException();
    }
2、CyclicBarrier中的await()方法
 
public int await() throws InterruptedException, BrokenBarrierException {
        try {
            return dowait(false, 0L);
        } catch (TimeoutException toe) {
            throw new Error(toe); // cannot happen;
        }
    }
 private int dowait(boolean timed, long nanos)
        throws InterruptedException, BrokenBarrierException,
               TimeoutException {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            final Generation g = generation;

            if (g.broken)
                throw new BrokenBarrierException();

            if (Thread.interrupted()) {
                breakBarrier();
                throw new InterruptedException();
            }

           int index = --count;
           if (index == 0) {  // tripped
               boolean ranAction = false;
               try {
                   final Runnable command = barrierCommand;
                   if (command != null)
                       command.run();
                   ranAction = true;
                   nextGeneration();
                   return 0;
               } finally {
                   if (!ranAction)
                       breakBarrier();
               }
           }

            // loop until tripped, broken, interrupted, or timed out
            for (;;) {
                try {
                    if (!timed)
                        trip.await();
                    else if (nanos > 0L)
                        nanos = trip.awaitNanos(nanos);
                } catch (InterruptedException ie) {
                    if (g == generation && ! g.broken) {
                        breakBarrier();
                        throw ie;
                    } else {
                        // We‘re about to finish waiting even if we had not
                        // been interrupted, so this interrupt is deemed to
                        // "belong" to subsequent execution.
                        Thread.currentThread().interrupt();
                    }
                }

                if (g.broken)
                    throw new BrokenBarrierException();

                if (g != generation)
                    return index;

                if (timed && nanos <= 0L) {
                    breakBarrier();
                    throw new TimeoutException();
                }
            }
        } finally {
            lock.unlock();
        }
    }
上面dowait方法中有一个index,index=--count而count的值在源码中来自

count = parties;
提到 parties就不得不看看构造函数了 

public CyclicBarrier(int parties) {
        this(parties, null);
    }
如上例子,我们构造了CyclicBarrier(3)那么此时的 count值为3,接着dowait源码,当index==0时,后面执行的

final Runnable command = barrierCommand;
其实是可以设置的,这个Runnable可以传进来,当我们希望所有线程都达到某一时刻之后,用什么线程执行接下来的工作,
当没有传Runnable进来时,就继续执行(唤醒其他线程),否则就runnable.run()(唤醒其他线程之前执行) 
原文:http://blog.csdn.net/yujin753/article/details/46125283


java进阶之一生成二维码

生成二维码图片,指定内容,生成图片提供下载。


/**
	 * 生成二维码并返回图片路径
	 * @param domain
	 * @param SERVER_PATH
	 * @param filepath
	 * @param content
	 * @param imgPath
	 * @param filename
	 * @param needCompress
	 * @return
	 * @throws Exception
	 * 
	 * String path_ = QRCodeUtil.buildcodeurl(Constants.getConfigkey("upload.image.base64.domain"),
					Constants.getConfigkey("common.file.path"),"/qrcode/user/",
					Constants.getConfigkey("h5.cus.url")+"/reg?cid="+o.getId()
					, null,o.getId()+".jpg");
	 */
	public static String buildcodeurl(String domain,String SERVER_PATH,String filepath,String content, String imgPath,String filename) throws Exception{
		String path = SERVER_PATH+filepath;
		QRCodeUtil.encode(content, imgPath, path,filename, true);
		String path_ = domain+filepath+filename;
		return path_;
		
	}

/**
	 * 生成二维码(内嵌LOGO)
	 * 
	 * @param content
	 *            内容
	 * @param imgPath
	 *            LOGO地址
	 * @param destPath
	 *            存放目录
	 * @param needCompress
	 *            是否压缩LOGO
	 * @throws Exception
	 */
	public static void encode(String content, String imgPath, String destPath,String filename,
			boolean needCompress) throws Exception {
		BufferedImage image = QRCodeUtil.createImage(content, imgPath,
				needCompress);
		mkdirs(destPath);
		String file = filename;
		File f = new File(destPath+"/"+file);
		if(!f.getParentFile().exists()){
			f.getParentFile().mkdirs();
		}
		ImageIO.write(image, FORMAT_NAME,f);
	}

整个源文件下载  http://file.xuahua.com/blog/2016/0806/QRCodeUtil.java


j2ee开发之druid联接池配置,监控 有更新!

数据库联接池有很多种,除了c3p0,dbcp,还有druid,而且现在用的也比较火。

今天把配置过程记录下来。

1,pom.xml 配置

  <dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.23</version>
</dependency>


2,jndi配置

  jndi配置-喧哗博客


3,web.xml 配置


 <servlet>  
        <servlet-name>DruidStatView</servlet-name>  
        <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>  
    </servlet>    
    <servlet-mapping>  
        <servlet-name>DruidStatView</servlet-name>  
        <url-pattern>/druid/*</url-pattern>  
    </servlet-mapping> 
4,启动服务,在浏览器输入 http://localhost:8080/druid/index.html 就会展示默认的html页面


druid监控-喧哗博客


如果还需要使用Web应用、URI监控、Session监控、Spring监控等则还需要继续增加配置。

5、Wen应用配置

WebStatFilter用于采集web-jdbc关联监控的数据

在Web.xml中增加配置,就可以使用Web应用、URI监控、Session监控等功能

 <filter>
    <filter-name>DruidWebStatFilter</filter-name>
    <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
    <init-param>
        <param-name>exclusions</param-name>
        <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/console/*</param-value>
    </init-param>
    <init-param>
    	<param-name>profileEnable</param-name>
    	<param-value>true</param-value>
	</init-param>
	<init-param>
        <param-name>principalCookieName</param-name>
        <param-value>USER_COOKIE</param-value>
    </init-param>
    <init-param>
        <param-name>principalSessionName</param-name>
        <param-value>USER_SESSION</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>DruidWebStatFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

6,spring配置
<bean id="druid-stat-interceptor"
		class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
	</bean>
	<bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut"
		scope="prototype">
		<property name="patterns">
			<list>
				<value>com.bdbvip.*.service.*</value>
				<value>com.bdbvip.*.dao.*</value>
			</list>
		</property>
	</bean>

	<aop:config proxy-target-class="true">
		<aop:advisor advice-ref="druid-stat-interceptor"
			pointcut-ref="druid-stat-pointcut" />
	</aop:config>

至此已经全部配置完毕。


spring--secrutiy--控制到按钮 有更新!

使用spring security taglib: 
Java代码 
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> 
... 
<security:authorize ifAnyGranted="ROLE_ADMIN"> 
<a href="user/input/id/${nuId}.html">编辑</a> 
</security:authorize>

java提高篇-导出execl(具体使用篇) 有更新!

现在这篇文章,讲的是如何使用前一篇文章导出通用工具类

具体如下:

ackage com.xuahua.utils.export;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jxl.CellView;
import jxl.write.Label;
import jxl.write.Number;

import com.xuahua.pojo.TMemCashTradeRecordVo;
import com.xuahua.utils.ExportExcelUtils;

public class TradeExportUtils extends ExportExcelUtils {
	
	@Override
	public List<Map<String, Object>> getHeaders() {
		List<Map<String, Object>> headers = new ArrayList<Map<String, Object>>();

		Map<String, Object> header = new HashMap<String, Object>();
		header.put("value", "序");
		headers.add(header);

		header = new HashMap<String, Object>();
		header.put("value", "用户名");
		headers.add(header);

		header = new HashMap<String, Object>();
		header.put("value", "交易号");
		headers.add(header);

		header = new HashMap<String, Object>();
		header.put("value", "交易前余额");
		headers.add(header);

		header = new HashMap<String, Object>();
		header.put("value", "交易金额");
		headers.add(header);

		header = new HashMap<String, Object>();
		header.put("value", "交易后余额");
		headers.add(header);

		header = new HashMap<String, Object>();
		header.put("value", "交易类型");
		headers.add(header);

		header = new HashMap<String, Object>();
		header.put("value", "收入支出");
		headers.add(header);
		
		header = new HashMap<String, Object>();
		header.put("value", "交易支出");
		headers.add(header);
		
		header = new HashMap<String, Object>();
		header.put("value", "订单号");
		headers.add(header);
		
		header = new HashMap<String, Object>();
		header.put("value", "摘要");
		headers.add(header);
		return headers;
	}

	@Override
	public void writeContent(List list) throws Exception{
		List<TMemCashTradeRecordVo> currencyCardList = list;
		CellView cellView = new CellView();  
	    cellView.setAutosize(true); //设置自动大小
		for (int i = 0; i < currencyCardList.size(); i++) {
			TMemCashTradeRecordVo vo = currencyCardList.get(i);

			number = new jxl.write.Number(0, rowIndex, (i + 1), cellFormat1);
			ws.addCell(number);
			
			label = new jxl.write.Label(1, rowIndex, vo.getUsername(),cellFormat1); // 用户名
			ws.addCell(label);

			label = new jxl.write.Label(2, rowIndex, vo.getTradeno(),cellFormat1); // 交易流水号
			ws.addCell(label);
			
			number = new Number(3, rowIndex, vo.getAccountcashmoney().add(vo.getAccountfrzoenmoney()).doubleValue(),cellFormat1); // 交易前金额
			ws.addCell(number);
			
			number = new Number(4, rowIndex, vo.getTradetotalmoney().doubleValue(),cellFormat1); // 交易金额
			ws.addCell(number);
			
			number = new Number(5, rowIndex, vo.getCashmoney().add(vo.getFrzoenmoney()).doubleValue(),cellFormat1); // 交易后金额
			ws.addCell(number);
			
			label = new jxl.write.Label(6, rowIndex,vo.getTradetype(), cellFormat1); // 交易类型
			ws.addCell(label);
			
			label = new jxl.write.Label(7, rowIndex,vo.getInorout(), cellFormat1); // 收入支出类型
			ws.addCell(label);

			label = new Label(8, rowIndex, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(vo.getCreatetime()),cellFormat1);
			ws.addCell(label);
			
			label = new Label(9, rowIndex, vo.getGeneralno(),cellFormat1); // 订单号
			ws.addCell(label);

			label = new Label(10, rowIndex, vo.getRemark(),cellFormat1); // 备注
			
			ws.setColumnView(i, cellView);
			ws.addCell(label);

			rowIndex++;
		}

	}
	
}

看了上面的代码以后,怎么样?会使用了么?

java提高篇-导出execl(通用工具类) 有更新!

在web开发中,经常会遇到需要把数据导出到EXCEL中,并提供下载。

那么本文将提供一个通用的导出EXCEL的工具类。。。具体的实现或自定义的样式,可以自己定义。

请看下文代码

package com.xuahua.utils;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import org.apache.log4j.Logger;

/**
 * @author wyong 提供公用方法,来生成xls。 具体的数据对象由writeContent实现,标签页的头由getHeaders实现。
 * 
 */
public class ExportExcelUtils {

	protected Label label;
	protected Number number;

	protected WritableWorkbook wwb;
	protected WritableSheet ws;
	protected int rowIndex = 0;
	protected int MAXRECORD = 60000;// 每个工作空间最大记录条数。

	protected WritableCellFormat titleFormat1;
	protected WritableCellFormat headerFormat1;
	protected WritableCellFormat cellFormat1;
	protected WritableCellFormat dateCellFormat;

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

	public ExportExcelUtils() {
		try {
			headerFormat1 = initHeaderFormat();
			cellFormat1 = initCellFormat();
			dateCellFormat = initDateFormat();
			titleFormat1 = initTitleFormate();
		} catch (WriteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void xls(OutputStream os, String sheetName, List contentList)
			throws Exception {
		wwb = Workbook.createWorkbook(os);
		try {
			int maxsize = contentList.size();
			if (maxsize > MAXRECORD) {
				int s = maxsize % MAXRECORD == 0 ? maxsize / MAXRECORD
						: maxsize / MAXRECORD + 1;
				List tmpList = new ArrayList(MAXRECORD);
				for (int i = 0; i < s; i++) {
					rowIndex = 0;
					tmpList = contentList.subList(i * MAXRECORD, (i + 1)
							* MAXRECORD > maxsize ? maxsize : (i + 1)
							* MAXRECORD);
					ws = wwb.createSheet(sheetName + "-" + i, i);
					this.writeHeaders();
					this.writeContent(tmpList);
				}
			} else {
				ws = wwb.createSheet(sheetName, 0);
				this.writeHeaders();
				this.writeContent(contentList);
			}
		} finally {
			wwb.write();
			wwb.close();

			os.flush();
			os.close();
		}
	}

	/**
	 * @param objlist
	 *            需要写入xls文件中的对象。做过处理的一个标签页最多60000条。
	 * @throws Exception
	 */
	public void writeContent(List objlist) throws Exception {
		throw new Exception("u` must implements this method.");
	};

	/**
	 * xls文件中的标题头。
	 * 
	 * @return
	 * @throws Exception
	 */
	public List<Map<String, Object>> getHeaders() throws Exception {
		throw new Exception("u` must implements this method.");
	};

	// 写表头
	public void writeHeaders() throws Exception {
		List<Map<String, Object>> headers = this.getHeaders();

		for (int i = 0; i < headers.size(); i++) {
			Map<String, Object> map = headers.get(i);

			Label label = new Label(i, rowIndex, map.get("value").toString(),
					headerFormat1);
			ws.addCell(label);

		}
		rowIndex++;
	}

	/**
	 * 格式化日期单元格
	 * 
	 * @return
	 * @throws WriteException
	 */
	protected WritableCellFormat initDateFormat() throws WriteException {
		jxl.write.DateFormat df = new jxl.write.DateFormat("yyyy-MM-dd HH:mm:ss");
		WritableCellFormat dateCellFormat = new jxl.write.WritableCellFormat(df);
		dateCellFormat.setAlignment(Alignment.LEFT);
		dateCellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
		dateCellFormat.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
		dateCellFormat.setAlignment(Alignment.CENTRE); //设置水平对齐
		dateCellFormat.setWrap(false); //设置自动换行
		return dateCellFormat;
	}

	/**
	 * 格式化单元格样式
	 * 
	 * @return
	 * @throws WriteException
	 */
	protected WritableCellFormat initCellFormat() throws WriteException {
		WritableFont cellFont1 = new WritableFont(WritableFont.TIMES, 12);
		WritableCellFormat cellFormat1 = new WritableCellFormat(cellFont1);
		cellFormat1.setAlignment(Alignment.LEFT);
		cellFormat1.setVerticalAlignment(VerticalAlignment.CENTRE);
		cellFormat1.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
		cellFormat1.setAlignment(Alignment.CENTRE); //设置水平对齐
		cellFormat1.setWrap(false); //设置自动换行
		return cellFormat1;

	}

	/**
	 * @return 格式化headerformate
	 * @throws WriteException
	 */
	protected WritableCellFormat initHeaderFormat() throws WriteException {
		WritableFont headerFont1 = new WritableFont(WritableFont.TIMES, 14,
				WritableFont.BOLD);
		headerFont1.setColour(Colour.BLUE);
		WritableCellFormat headerFormat1 = new WritableCellFormat(headerFont1);
		headerFormat1.setAlignment(Alignment.CENTRE);
		headerFormat1.setVerticalAlignment(VerticalAlignment.CENTRE);
		headerFormat1.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
		headerFormat1.setBackground(Colour.YELLOW);
		headerFormat1.setAlignment(Alignment.CENTRE); //设置水平对齐
		headerFormat1.setWrap(false); //设置自动换行
		return headerFormat1;
	}

	/**
	 * 格式化initTitleFormate1
	 * 
	 * @return
	 * @throws WriteException
	 */
	protected WritableCellFormat initTitleFormate() throws WriteException {
		WritableFont titleFont1 = new WritableFont(WritableFont.TIMES, 24,
				WritableFont.BOLD);
		titleFont1.setColour(Colour.BLUE);
		WritableCellFormat titleFormat1 = new WritableCellFormat(titleFont1);
		titleFormat1.setAlignment(Alignment.CENTRE);
		titleFormat1.setVerticalAlignment(VerticalAlignment.CENTRE);
		titleFormat1.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
		titleFormat1.setBackground(Colour.YELLOW);
		titleFormat1.setAlignment(Alignment.CENTRE); //设置水平对齐
		titleFormat1.setWrap(false); //设置自动换行
		return titleFormat1;
	}
}

java基础篇--生成指定长度的随机字符串 有更新!

public static Random random = new Random();
	/**
	 * 生成len 位随机整数
	 *  包括数字字母
	  * @Title: getSexRandom
	  * @return int    
	  * @throws
	 */
	public static String getRandomStr(int len){
		StringBuilder ret = new StringBuilder();
		for (int i = 0; i < len; i++) {
			boolean isChar = (random.nextInt(2) % 2 == 0);// 输出字母还是数字
			if (isChar) { // 字符串
				int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; // 取得大写字母还是小写字母
				ret.append((char) (choice + random.nextInt(26)));
			} else { // 数字
				ret.append(Integer.toString(random.nextInt(10)));
			}
		}
		return ret.toString();
	}

java基础篇-模拟浏览器请求(post,get) 有更新!

public static String postRequest(String url, Map<String, String> data) {
		// 响应内容
		String result = "";

		// 定义http客户端对象--httpClient
		HttpClient httpClient = new HttpClient();

		// 定义并实例化客户端链接对象-postMethod
		PostMethod postMethod = new PostMethod(url);

		try {
			// 设置http的头
			postMethod.getParams().setParameter(
					HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
			postMethod.setRequestHeader("ContentType",
					"application/x-www-form-urlencoded;charset=UTF-8");
			if (data != null) {
				NameValuePair[] data1 = new NameValuePair[data.size()];
				int i = 0;
				for (String mapKey : data.keySet()) {
					// 填入各个表单域的值
					String vString = data.get(mapKey) == null ? "" : data.get(
							mapKey).toString();
					// vString = new String(vString.getBytes("utf-8"),"GBK");
					data1[i++] = new NameValuePair(mapKey, vString);
				}

				// 将表单的值放入postMethod中
				postMethod.setRequestBody(data1);
			}
			// 定义访问地址的链接状态
			int statusCode = 0;
			try {
				// 客户端请求url数据
				statusCode = httpClient.executeMethod(postMethod);
			} catch (Exception e) {
				e.printStackTrace();
			}

			// 请求成功状态-200
			if (statusCode == HttpStatus.SC_OK) {
				try {
					result = postMethod.getResponseBodyAsString();
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				System.out.println("请求返回状态:" + statusCode);
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			// 释放链接
			postMethod.releaseConnection();
			httpClient.getHttpConnectionManager().closeIdleConnections(0);
		}
		return result;
	}

	public static String postRequest(String url, String xmlstring,
			String contentType, String charset) {
		if (StringUtils.isBlank(charset)) {
			charset = "UTF-8";
		}
		if (StringUtils.isBlank(contentType)) {
			contentType = "text/html;charset=" + charset;
		}
		PostMethod post = new PostMethod(url);
		// 设置请求的内容直接从文件中读取
		HttpClient httpclient = new HttpClient();
		httpclient.getParams().setContentCharset("UTF-8");
		String resultstring = "";
		try {
			post.setRequestEntity(new StringRequestEntity(xmlstring,
					contentType, charset));
			int result = httpclient.executeMethod(post);
			resultstring = post.getResponseBodyAsString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		post.releaseConnection();
		return resultstring;
	}

	public static String postRequest(String url, Map<String, Object> data,
			Map<String, String> cookie, String domain) {
		// 响应内容
		String result = "";

		// 定义http客户端对象--httpClient
		HttpClient httpClient = new HttpClient();

		// 定义并实例化客户端链接对象-postMethod
		PostMethod postMethod = new PostMethod(url);

		try {
			// 设置http的头
			postMethod.getParams().setParameter(
					HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
			postMethod.setRequestHeader("ContentType",
					"application/x-www-form-urlencoded;charset=UTF-8");
			if (cookie != null) {
				if (domain == null) {
					domain = "";
				}
				HttpState initialState = new HttpState();
				for (String cookieName : cookie.keySet()) {
					Cookie c = new Cookie(domain, cookieName,
							cookie.get(cookieName), "/", -1, true);
					initialState.addCookie(c);
				}
				httpClient.setState(initialState);
			}
			if (data != null) {
				NameValuePair[] data1 = new NameValuePair[data.size()];
				int i = 0;
				for (String mapKey : data.keySet()) {
					// 填入各个表单域的值
					String vString = data.get(mapKey) == null ? "" : data.get(
							mapKey).toString();
					// vString = new String(vString.getBytes("utf-8"),"GBK");
					data1[i++] = new NameValuePair(mapKey, vString);
				}

				// 将表单的值放入postMethod中
				postMethod.setRequestBody(data1);
			}

			// 定义访问地址的链接状态
			int statusCode = 0;
			try {
				// 客户端请求url数据
				statusCode = httpClient.executeMethod(postMethod);
			} catch (Exception e) {
				e.printStackTrace();
			}

			// 请求成功状态-200
			if (statusCode == HttpStatus.SC_OK) {
				try {
					result = postMethod.getResponseBodyAsString();
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				System.out.println("请求返回状态:" + statusCode);
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			// 释放链接
			postMethod.releaseConnection();
			httpClient.getHttpConnectionManager().closeIdleConnections(0);
		}
		return result;
	}

java基础篇--模拟浏览器请求https--安全协议https请求 有更新!

https 协议,因为安全,所以在处理上,也有些不同。现在给出示例

 

/**
	 * @param url
	 * @param xmlstring
	 * @param match_id 密钥-- .p12的密钥
	 * @param file "apiclient_cert.p12" .p12的文件路径
	 * @return
	 */
	public static String httpsGetRequest(String url, String xmlstring, String match_id,String file){
		    KeyStore keyStore;
		    StringBuilder result = new StringBuilder();
			try {
				keyStore = KeyStore.getInstance("PKCS12");
				FileInputStream instream = new FileInputStream(new File(file));
	            keyStore.load(instream, match_id.toCharArray());

		        // Trust own CA and all self-signed certs
		        SSLContext sslcontext = SSLContexts.custom()
		                .loadKeyMaterial(keyStore, match_id.toCharArray())
		                .build();
		        // Allow TLSv1 protocol only
		        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
		                sslcontext,
		                new String[] { "TLSv1" },
		                null,
		                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
		        CloseableHttpClient httpclient = HttpClients.custom()
		                .setSSLSocketFactory(sslsf)
		                .build();
		        try {

	            HttpGet httpget = new HttpGet(url);
	            System.out.println("executing request" + httpget.getRequestLine());
	            CloseableHttpResponse response = httpclient.execute(httpget);
	            try {
	                HttpEntity entity = response.getEntity();
	                System.out.println("----------------------------------------");
	                System.out.println(response.getStatusLine());
	                if (entity != null) {
	                    System.out.println("Response content length: " + entity.getContentLength());
	                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
	                    String text="";
	                    while ((text = bufferedReader.readLine()) != null) {
	                    	result.append(text);
	                    }
	                }
	                EntityUtils.consume(entity);
	            } finally {
	                response.close();
	            }
	        } finally {
	            httpclient.close();
	        }
			} catch (Exception e) {
				e.printStackTrace();
			}
		return result.toString();
	}
	

java基础篇-日期格式处理 有更新!

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 日期工具类,提供常用的静态方法
 * 
 * @author Administrator
 * 
 */
public class DateUtils extends org.apache.commons.lang.time.DateUtils {

	protected final static Log log = LogFactory.getLog(DateUtils.class);
	public final static String[] ChineseWeek = { "日", "一", "二", "三", "四", "五",
			"六" };

	/**
	 * yyyy-MM-dd HH:mm:ss
	 */
	public static final String YYYYMMDDHHMMSS = "yyyy-MM-dd HH:mm:ss";
	/**
	 * new SimpleDateFormat("yyyy-MM-dd");
	 * */
	public final static SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat(
			"yyyy-MM-dd");;
	/**
	 * new SimpleDateFormat("yyyy-MM-dd HH:mm");
	 * */
	public final static SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm");;
	/**
	 * new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	 * */
	public final static SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");;
	/**
	 * new SimpleDateFormat("yyyyMMdd");
	 * */
	public final static SimpleDateFormat simpleDateFormat4 = new SimpleDateFormat(
			"yyyyMMdd");;
	/**
	 * new SimpleDateFormat("yyyyMMddHHmmss")
	 * */
	public final static SimpleDateFormat simpleDateFormat5 = new SimpleDateFormat(
			"yyyyMMddHHmmss");;

	/**
	 * new SimpleDateFormat("yyyyMMddHHmm")
	 * */
	public final static SimpleDateFormat simpleDateFormat6 = new SimpleDateFormat(
			"yyyyMMddHHmm");

	/**
	 * 将日期转换为字符串时间
	 * 
	 * @param date
	 *            //日期
	 * @param dateFormat
	 *            //格式
	 * @return
	 */
	public static String date2String(Date date, SimpleDateFormat dateFormat) {
		return dateFormat.format(date);
	}

	public static String date2String(Date date, String format) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(format);
		return dateFormat.format(date);
	}

	public static Date string2Date(String source, SimpleDateFormat dateFormat) {
		try {
			return dateFormat.parse(source);
		} catch (ParseException e) {
			log.error(e.getMessage(), e);
		}

		return null;
	}

	public static Date string2Date(String source, String format) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(format);
		try {
			return dateFormat.parse(source);
		} catch (ParseException e) {
			log.error(e.getMessage(), e);
		}

		return null;
	}

	public static Date format(Date date, SimpleDateFormat dateFormat) {
		try {
			return dateFormat.parse(dateFormat.format(date));
		} catch (ParseException e) {
			log.error(e.getMessage(), e);
		}

		return date;
	}

	public static Date format(Date date, String f) {
		try {
			SimpleDateFormat dateFormat = new SimpleDateFormat(f);
			return dateFormat.parse(dateFormat.format(date));
		} catch (ParseException e) {
			log.error(e.getMessage(), e);
		}

		return date;
	}

	public static boolean isSameMinute(Date d1, Date d2) {
		return simpleDateFormat2.format(d1)
				.equals(simpleDateFormat2.format(d2));
	}

	/**
	 * 英文操作系统下 强制得到中文yyyy-MM-dd 星期 以上午10点为分界
	 * */
	public static String getChineseYMDWeek(Date d) {
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		int hour = c.get(Calendar.HOUR_OF_DAY);
		if (hour < 10)
			c.add(Calendar.DAY_OF_MONTH, -1);
		return simpleDateFormat1.format(c.getTime()) + " 星期"
				+ ChineseWeek[c.get(Calendar.DAY_OF_WEEK) - 1];
	}

	/**
	 * 英文操作系统下 强制得到中文yyyy-MM-dd 星期 标准
	 * */
	public static String getChineseYMDWeek_(Date d) {
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		return simpleDateFormat1.format(c.getTime()) + " 星期"
				+ ChineseWeek[c.get(Calendar.DAY_OF_WEEK) - 1];
	}

	public static String dateadd(Date d, int field, int num, String format) {
		SimpleDateFormat dateFormat = null;
		if (format == null)
			dateFormat = simpleDateFormat1;
		else
			dateFormat = new SimpleDateFormat(format);
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		c.add(field, num);
		return dateFormat.format(c.getTime());
	}

	/**
	 * @author wyong
	 * @version 1.0
	 * @2011-5-17
	 * @description 计算二个时间相差天数 同一天算做 0 .
	 * @path 
	 * @param othertime
	 * @return int
	 */
	public static int deduction(long othertime) {
		long nowtime = System.currentTimeMillis();
		long d = Math.abs(nowtime - othertime);
		int day = (int) (d / 1000 / 60 / 60 / 24);
		return day;
	}

	/**
	 * 得到最近一个月的日期时间数组串,前面小时间,后面大时间
	 * 
	 * @return ['2011-06-06 12:10:10','2011-07-06 12:10:10']
	 */
	public static String[] getNearMonthDateTimeStr() {
		Calendar cal = Calendar.getInstance();
		String begin = simpleDateFormat3.format(cal.getTime());
		cal.add(Calendar.MONTH, -1);
		String end = simpleDateFormat3.format(cal.getTime());
		return new String[] { end, begin };
	}

	/**
	 * 得到最近一个月的日期数组串,前面小时间,后面大时间
	 * 
	 * @return ['2011-06-06','2011-07-06']
	 */
	public static String[] getNearMonthDateStr() {
		Calendar cal = Calendar.getInstance();
		String begin = simpleDateFormat1.format(cal.getTime());
		cal.add(Calendar.MONTH, -1);
		String end = simpleDateFormat1.format(cal.getTime());
		return new String[] { end, begin };
	}

	/**
	 * 得到最近一周的日期时间数组串,前面小时间,后面大时间
	 * 
	 * @return ['2011-06-29 09:33:12','2011-07-06 09:33:12']
	 */
	public static String[] getNearWeekDateTimeStr() {
		Calendar cal = Calendar.getInstance();
		String begin = simpleDateFormat3.format(cal.getTime());
		cal.add(Calendar.DAY_OF_WEEK_IN_MONTH, -1);
		String end = simpleDateFormat3.format(cal.getTime());
		return new String[] { end, begin };
	}

	/**
	 * 得到最近三天的日期时间数组串,前面小时间,后面大时间
	 * 
	 * @return ['2011-07-03 09:33:12','2011-07-06 09:33:12']
	 */
	public static String[] getNearThreeDayDateTimeStr() {
		Calendar cal = Calendar.getInstance();
		String begin = simpleDateFormat3.format(cal.getTime());
		cal.add(Calendar.DAY_OF_MONTH, -3);
		String end = simpleDateFormat3.format(cal.getTime());
		return new String[] { end, begin };
	}

	/**
	 * 得到今明后天
	 * 
	 * @param format
	 * @return
	 */
	public static String[] getThreeday(String format) {
		String[] theDate = new String[3];
		try {
			DateFormat dateFormat = new SimpleDateFormat(format);
			Date inputDate = new Date();
			Calendar cal = Calendar.getInstance();
			cal.setTime(inputDate);
			int inputDayOfYear = cal.get(Calendar.DAY_OF_YEAR);

			cal.set(Calendar.DAY_OF_YEAR, inputDayOfYear + 0);
			theDate[0] = dateFormat.format(cal.getTime());

			cal.set(Calendar.DAY_OF_YEAR, inputDayOfYear + 1);
			theDate[1] = dateFormat.format(cal.getTime());

			cal.set(Calendar.DAY_OF_YEAR, inputDayOfYear + 2);
			theDate[2] = dateFormat.format(cal.getTime());

		} catch (Exception e) {
		}
		return theDate;
	}

	public static void main(String[] args) {
		String[] a = DateUtils.getThreeday("yyyyMMdd");
		for (String s : a) {
			System.out.println(s);
		}

	}

	/**
	 * 得到今天的日期时间数组串,前面小时间,后面大时间
	 * 
	 * @return ['2011-07-03 00:00:00','2011-07-03 23:59:59']
	 */
	public static String[] getNearTodayDateTimeStr() {
		Calendar cal = Calendar.getInstance();
		String today = simpleDateFormat1.format(cal.getTime());
		return new String[] { today + " 00:00:00", today + " 23:59:59" };
	}

	/**
	 * 得到昨天的日期时间数组串,前面小时间,后面大时间
	 * 
	 * @return ['2011-07-03 00:00:00','2011-07-03 23:59:59']
	 */
	public static String[] getNearYesterdayDateTimeStr() {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DAY_OF_MONTH, -1);
		String today = simpleDateFormat1.format(cal.getTime());
		return new String[] { today + " 00:00:00", today + " 23:59:59" };
	}

	/**
	 * 取得该月的第一天
	 * 
	 * @param date
	 *            传入null时,默认取当前时间
	 * @return
	 * @author
	 */
	public static Date getCurrentMonthFirstDay(Date date) {
		Calendar cal = Calendar.getInstance();

		if (null != date) {
			cal.setTime(date);
		}
		cal.set(Calendar.DATE, 1);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);

		return cal.getTime();
	}

	/**
	 * 取得下月的第一天
	 * 
	 * @param date
	 *            传入null时,默认取当前时间
	 * @return
	 * @author feng.li 2011-07-05
	 */
	public static Date getNextMonthFirstDay(Date date) {
		Calendar cal = Calendar.getInstance();

		if (null != date) {
			cal.setTime(date);
		}
		cal.set(Calendar.DATE, 1);
		cal.roll(Calendar.MONTH, 1);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);

		return cal.getTime();
	}

	/**
	 * 取得在当天0时0分0秒的基础增加或减少N天的时间
	 * 
	 * @param add
	 *            增加或减少的偏移量
	 * @return
	 */
	public static Date getSetTime(int add) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);

		calendar.add(Calendar.DAY_OF_MONTH, add);

		return calendar.getTime();
	}

	public static Timestamp stringToTimestamp(String date) {
		Timestamp ts = null;
		try {
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			ts = new Timestamp(format.parse(date).getTime());
		} catch (ParseException e) {
			log.error(e.getMessage(), e);
		}
		return ts;
	}

	/**
	 * Date转化为字符串
	 * 
	 * @param Date
	 *            日期
	 * @return String yyyy-MM-dd HH:mm:ss
	 */
	public static String getDateToStr(Date date) {
		if (date == null) {
			return null;
		} else {
			SimpleDateFormat sdf = new SimpleDateFormat(YYYYMMDDHHMMSS);
			return sdf.format(date);
		}
	}

	/**
	 * Date转化为字符串
	 * 
	 * @param Date
	 *            日期
	 * @param format
	 *            格式
	 * @return String
	 */
	public static String getDateToStr(Date date, String format) {
		if (date == null) {
			return null;
		} else {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			return sdf.format(date);
		}
	}
	
	/**String 转化date 验证
	 * <pre>
	 * @param date
	 *         时间
	 * @return
	 * </pre>
	 */
	public static boolean isDateMatch(String date) {
        String regex = "^((((1[6-9]|[2-9]\\d)\\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\\d|3[01]))|(((1[6-9]|[2-9]\\d)\\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\\d|30))|(((1[6-9]|[2-9]\\d)\\d{2})-0?2-(0?[1-9]|1\\d|2[0-8]))|(((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-)) (20|21|22|23|[0-1]?\\d):[0-5]?\\d:[0-5]?\\d$";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(date);
        return m.matches();
    }
	
}

java基础篇-字符串编码转化 有更新!

原文 http://blog.xuahua.com/articles/2016/03/09/1457510183958.html

	/**
	 * GBK格式转换成utf-8编码
	 * @param str
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String gbToUtf8(String str)
			throws UnsupportedEncodingException {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < str.length(); i++) {
			String s = str.substring(i, i + 1);
			if (s.charAt(0) > 0x80) {
				byte[] bytes = s.getBytes("Unicode");
				String binaryStr = "";
				for (int j = 2; j < bytes.length; j += 2) {
					// the first byte
					String hexStr = getHexString(bytes[j + 1]);
					String binStr = getBinaryString(Integer.valueOf(hexStr, 16));
					binaryStr += binStr;
					// the second byte
					hexStr = getHexString(bytes[j]);
					binStr = getBinaryString(Integer.valueOf(hexStr, 16));
					binaryStr += binStr;
				}
				// convert unicode to utf-8
				String s1 = "1110" + binaryStr.substring(0, 4);
				String s2 = "10" + binaryStr.substring(4, 10);
				String s3 = "10" + binaryStr.substring(10, 16);
				byte[] bs = new byte[3];
				bs[0] = Integer.valueOf(s1, 2).byteValue();
				bs[1] = Integer.valueOf(s2, 2).byteValue();
				bs[2] = Integer.valueOf(s3, 2).byteValue();
				String ss = new String(bs, "UTF-8");
				sb.append(ss);
			} else {
				sb.append(s);
			}
		}
		return sb.toString();
	}

	private static String getHexString(byte b) {
		String hexStr = Integer.toHexString(b);
		int m = hexStr.length();
		if (m < 2) {
			hexStr = "0" + hexStr;
		} else {
			hexStr = hexStr.substring(m - 2);
		}
		return hexStr;
	}

	private static String getBinaryString(int i) {
		String binaryStr = Integer.toBinaryString(i);
		int length = binaryStr.length();
		for (int l = 0; l < 8 - length; l++) {
			binaryStr = "0" + binaryStr;
		}
		return binaryStr;
	}

	/**
	 * UTF-8格式的字符串,转换成GB2312
	 * 
	 * @param str
	 * @return
	 */
	public static String utf8Togb2312(String str) {
		String utf8 = "";
		String unicode = "";
		String gbk = "";
		try {
			utf8 = new String(str.getBytes("UTF-8"));
			// System.out.println(utf8);
			unicode = new String(utf8.getBytes(), "UTF-8");
			// System.out.println(unicode);
			gbk = new String(unicode.getBytes("GBK"));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return gbk;
	}

	/**
	 * 将 GB2312 编码格式的字符串转换为 UTF-8 格式的字符串:
	 * 
	 * @param str
	 * @return
	 */
	public static String gb2312ToUtf8(String str) {
		String urlEncode = "";
		try {
			urlEncode = URLEncoder.encode(str, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return urlEncode;
	}

tomcat7+自带的jdbc连接池 有更新!

原文 :/articles/2016/03/09/1457487972614.html

官方文档资料:https://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html

一,优点

Tomcat jdbc pool的优点:

(1)    tomcat jdbc pool 近乎兼容 dbcp ,性能更高

(2)    异步方式获取连接

(3)    tomcat jdbc pool 是 tomcat 的一个模块,基于 tomcat JULI,使用 Tomcat 的日志框架

(4)    使用 javax.sql.PooledConnection 接口获取连接

(5)    支持高并发应用环境

(6)    超简单,核心文件只有8个,比 c3p0 还

(7)    更好的空闲连接处理机制

(8)    支持 JMX

(9)    支持 XA Connection

Tomcat jdbc pool的使用仅需2个jar包,分别为tomcat-jdbc.jar和tomcat-juli.jar,这两个jar包都可以在tomcat7中找到,tomcat-jdbc.jar在tomcat的lib目录下,tomcat-juli.jar在bin目录下。

二,配置代码

<Resource name="jdbc/bdbvip" auth="Container"
type="javax.sql.DataSource"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
testWhileIdle="true"
testOnBorrow="true"
testOnReturn="false"
validationQuery="SELECT 1"
validationInterval="30000"
timeBetweenEvictionRunsMillis="30000"
maxActive="100"
minIdle="10"
maxWait="10000"
initialSize="10"
removeAbandonedTimeout="60"
removeAbandoned="true"
logAbandoned="true"
minEvictableIdleTimeMillis="30000"
jmxEnabled="true"
jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"
username="user"
password="pwd"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://192.168.0.105:3306/abc?sendStringParametersAsUnicode=false"/>

 

java基础篇-字符串首字母大写 有更新!

1,需求

  字符串首字母大写

2,代码

 

public static String toUpFirstChar(String str) {
		if (StringUtils.isNotEmpty(str)) {
			return str.substring(0, 1).toUpperCase() + str.substring(1);
		}
		return null;
}

java基础篇-字符串隐藏2 有更新!

1,需求

   

* 名称格式化,名称隐藏 <s:property
* value="@com.ecp.common.helper.StringUtil@formatStr(name)"/>
*
* @param name
* @param myname
* 没有传null
* @return 若:中文名称 (name为空:*** name为一位:name+*** name为两位或者以下:张***
* name为两位以上:张***三 )
*
* 若:英文名称 (name为空:*** name为一位:name+***
* name为四位或者以下:长度减一+***+最后一位 name为四位以上:前四位+***+最后一位 )
*/

2,代码

public static String formatStr(String name, String myname) {

		if (StringUtils.isBlank(name)) {
			return "***";
		}
		if (name.equals(myname)) {
			return name;
		}
		if (name.length() < 2) {
			return name + "***";
		}
		String lastname  = name.substring(name.length()-1);
		String regEx = "[\u4e00-\u9fa5]";
		Matcher matcher = Pattern.compile(regEx).matcher(name);
		if (matcher.find())
			name = name.length() <= 2 ? name.substring(0, name.length() - 1)
					: name.substring(0, 2);
		else
			name = name.length() <= 4 ? name.substring(0, name.length() - 1)
					: name.substring(0, 4);
		return name + "***"+lastname;
	}

java基础篇-字符串隐藏1 有更新!

一,字符串隐藏替换

     1,需求

         长度为二位以下者,还回原串
         长度为二位以上到四位者,保留前前一位与最后一位中间以***替换
         长度为四位以上者到八位者,保留前二位与最最后二位,中间以***替换
         长度为八位以上者,保留以前三位与后三位,中间以***替换。

     2,适用场景

         针对用户名,姓名等敏感信息,做隐藏处理。

    3,代码实现 

   

/**
	 * 长度为二位以下者,还回原串
	 * 长度为二位以上到四位者,保留前前一位与最后一位中间以***替换
	 * 长度为四位以上者到八位者,保留前二位与最最后二位,中间以***替换
	 * 长度为八位以上者,保留以前三位与后三位,中间以***替换。
	 * @param number
	 * @return
	 */
	public static String formatNumber(String number){
		if(StringUtils.isBlank(number)) return "";
		if(number.length()<=2) return number;
		if(number.length()<=4) return number.substring(0,1)+"***"+number.substring(number.length()-1);
		if(number.length()<8) return number.substring(0,2)+"***"+number.substring(number.length()-2);
		return number.substring(0,3)+"***"+number.substring(number.length()-3);
	}

公告

喧哗博客--繁华过后的沉寂--技术经验分享^-^
Copyright (c) 2009-2019, b3log.org & hacpai.com