少年阿宾

那些青春的岁月

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  500 Posts :: 0 Stories :: 135 Comments :: 0 Trackbacks

#

package com.abin.lee.junit.httpasyncclient.service;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HttpAsyncClientService extends HttpServlet{
 private static final long serialVersionUID = 807336917776643578L;

 @SuppressWarnings("rawtypes")
 public void service(HttpServletRequest request,HttpServletResponse response) throws IOException{
  Map map=request.getParameterMap();
  String id=(String)((Object[])map.get("id"))[0].toString();
  if(null!=id&&!"".equals(id)){
   String result=id+" is response";
   System.out.println("result="+result);
   ServletOutputStream out=response.getOutputStream();
   BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));
   writer.write(result);
   writer.flush();
   writer.close();
  }else{
   String result=id+" is null";
   System.out.println("result="+result);
   ServletOutputStream out=response.getOutputStream();
   BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));
   writer.write(result);
   writer.flush();
   writer.close();
  }
 }
}








<servlet>
  <servlet-name>HttpAsyncClientService</servlet-name>
  <servlet-class>com.abin.lee.junit.httpasyncclient.service.HttpAsyncClientService</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>HttpAsyncClientService</servlet-name>
  <url-pattern>/HttpAsyncClientService</url-pattern>
 </servlet-mapping>





package com.abin.lee.junit.httpasyncclient.example;

import java.util.concurrent.Future;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.nio.client.DefaultHttpAsyncClient;
import org.apache.http.nio.client.HttpAsyncClient;
import org.apache.http.util.EntityUtils;

public class CreateHttpAsyncClient {
 public static void main(String[] args) throws Exception {
        HttpAsyncClient httpclient = new DefaultHttpAsyncClient();
        httpclient.start();
        try {
            HttpGet request = new HttpGet("http://localhost:7000/global/HttpAsyncClientService?id=5");
            Future<HttpResponse> future = httpclient.execute(request, null);
            HttpResponse response = future.get();
            System.out.println("Response: " + response.getStatusLine());
            System.out.println("Response1: " + EntityUtils.toString(response.getEntity()));
            System.out.println("Shutting down");
        } finally {
            httpclient.shutdown();
        }
        System.out.println("Done");
    }

}

posted @ 2013-01-08 23:15 abin 阅读(5110) | 评论 (0)编辑 收藏

//这个适用于oracle10,11,以前oracle9操作CLOB字段相当的繁琐,记着导入驱动包 
package com.abin.wto.dbs.oracle; 

import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 

public class OperateOracle { 
public static void main(String[] args) { 
Connection conn=null; 
PreparedStatement ps=null; 
ResultSet rs=null; 
try { 
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); 
String url="jdbc:oracle:thin:@localhost:1521:XE"; 
conn=DriverManager.getConnection(url,"abin","abin"); 
String sql="insert into bignumber values(?,?)"; 
ps=conn.prepareStatement(sql); 
ps.setInt(1, 1); 
oracle.sql.CLOB clob=oracle.sql.CLOB.createTemporary(conn, false, oracle.sql.CLOB.DURATION_SESSION); 
clob.open(oracle.sql.CLOB.MODE_READWRITE); 
clob.setString(3, "llll"); 
ps.setClob(2, clob); 
int result=ps.executeUpdate(); 
System.out.println("result="+result); 
} catch (Exception e) { 
e.printStackTrace(); 
} 
} 

} 











package com.abin.wto.dbs.oracle;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import oracle.sql.CLOB;

public class OperateOracle {
 public static void main(String[] args) {
  Connection conn=null;
  PreparedStatement ps=null;
  ResultSet rs=null;
  try {
   Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
   String url="jdbc:oracle:thin:@localhost:1521:XE";
   conn=DriverManager.getConnection(url,"abin","abin");
   String sql="insert into bignumber values(?,?)";
   ps=conn.prepareStatement(sql);
   ps.setInt(1, 8888);
   java.sql.Clob  clob=oracle.sql.CLOB.createTemporary(conn, false, oracle.sql.CLOB.DURATION_SESSION);
   clob.setString(1, "55555555555555");
   ps.setClob(2, clob);
   int result=ps.executeUpdate();
   System.out.println("result="+result);
  } catch (Exception e) {
   e.printStackTrace();
  }finally{
   if(ps!=null){
    try {
     ps.close();
    } catch (SQLException e) {
     e.printStackTrace();
    }
   }
   try {
    CLOB.freeTemporary(null);
   } catch (SQLException e) {
    e.printStackTrace();
   }
  }
 }

}

 

posted @ 2013-01-08 22:00 abin 阅读(1777) | 评论 (0)编辑 收藏

     摘要: 1、sed使用手册(转载)  sed使用手册(转载) 发信站: BBS 水木清华站 (Wed Sep 25 21:06:36 2002), 站内信件      Sed 命令列可分成编辑指令与文件档部份。其中 , 编辑指令负责控制所有的编 辑工作 ; 文件档表示所处理的档案。    ...  阅读全文
posted @ 2013-01-08 12:37 abin 阅读(1674) | 评论 (0)编辑 收藏

public class CyclicBarrier
extends Object
一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point)。在涉及一组固定大小的线程的程序中,这些线程必须不时地互相等待,此时 CyclicBarrier 很有用。因为该 barrier 在释放等待线程后可以重用,所以称它为循环 的 barrier。
CyclicBarrier 支持一个可选的 Runnable 命令,在一组线程中的最后一个线程到达之后(但在释放所有线程之前),该命令只在每个屏障点运行一次。若在继续所有参与线程之前更新共享状态,此屏障操作 很有用。
以上是jdk文档的说明

     *  现在说说我们今天活动的内容、首先我们要在公司大厅集合、然后参观陈云故居
     *  参观完后集合、准备去淀水湖参观。(有3辆车、对应3个线程)
     * 
     *  我们必须等大家都到齐了才能去下个地方、比如说 、在公司集合、3辆车子都到了才能出发
     *  要不然人装不下啊。这是我们可以用到java线程并发库的CyclicBarrier类
 
public class CyclicBarrierTest {

    public static void main(String[] args) {

        final CyclicBarrier cb = new CyclicBarrier(3);
        //final Semaphore semaphore=new Semaphore(1);

        for (int i = 1; i <= 3; i++) {
      
            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                       
                        //semaphore.acquire();
                        System.out.println(Thread.currentThread().getName()
                                + "公司大厅集合");
                        System.out.println(Thread.currentThread().getName()
                                + "公司大厅等待....");
                        //semaphore.release();
                        cb.await();
                        Thread.sleep(2000);
                       
                       
                        //semaphore.acquire();
                        System.out.println(Thread.currentThread().getName()
                                + "陈云故居集合");
                        System.out.println(Thread.currentThread().getName()
                                + "陈云故居等待....");
                        //semaphore.release();
                        cb.await();
                        Thread.sleep(2000);
                       
                       
                        //semaphore.acquire();
                        System.out.println(Thread.currentThread().getName()
                                + "淀水湖集合");
                        System.out.println(Thread.currentThread().getName()
                                + "淀水湖等待....准备回家了");
                        //semaphore.release();
                        cb.await();
                        Thread.sleep(2000);
                       
                       
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }

            }).start();
        }
    }
}
以下是输出结果:
Thread-0公司大厅集合
Thread-0公司大厅等待....
Thread-2公司大厅集合
Thread-1公司大厅集合
Thread-1公司大厅等待....
Thread-2公司大厅等待....
Thread-0陈云故居集合
Thread-1陈云故居集合
Thread-2陈云故居集合
Thread-1陈云故居等待....
Thread-0陈云故居等待....
Thread-2陈云故居等待....
Thread-0淀水湖集合
Thread-2淀水湖集合
Thread-1淀水湖集合
Thread-2淀水湖等待....准备回家了
Thread-0淀水湖等待....准备回家了
Thread-1淀水湖等待....准备回家了

***注意上述代码中的Semaphore类、它也是java线程并发库中的一个类、更多具体作用我们以后再探讨。
以下是使用Semaphore后的输出结果:(相信你已经知道不同的地方了)
Thread-0公司大厅集合
Thread-0公司大厅等待....
Thread-1公司大厅集合
Thread-1公司大厅等待....
Thread-2公司大厅集合
Thread-2公司大厅等待....
Thread-2陈云故居集合
Thread-2陈云故居等待....
Thread-1陈云故居集合
Thread-1陈云故居等待....
Thread-0陈云故居集合
Thread-0陈云故居等待....
Thread-2淀水湖集合
Thread-2淀水湖等待....准备回家了
Thread-1淀水湖集合
Thread-1淀水湖等待....准备回家了
Thread-0淀水湖集合
Thread-0淀水湖等待....准备回家了

http://blog.sina.com.cn/s/blog_7f448c520101219g.html
posted @ 2013-01-08 00:39 abin 阅读(419) | 评论 (0)编辑 收藏

public class Exchanger<V>
extends Object
可以在对中对元素进行配对和交换的线程的同步点。每个线程将条目上的某个方法呈现给 exchange 方法,与伙伴线程进行匹配,并且在返回时接收其伙伴的对象。Exchanger 可能被视为 SynchronousQueue 的双向形式。Exchanger 可能在应用程序(比如遗传算法和管道设计)中很有用。

以上是jdk文档的说明。

  * 今天公司党委组织活动、12点半call我电话、我以80码的速度狂奔过去、上了一个车子(A车)、
  * 戴着眼镜四处瞄了下,没发现什么美女啊。假寐了一会儿,司机说另外一个车子(B车)上要换过来
  * 一个人、让车子上的人下去一个去B车。由于地势原因、我就下去了。
  *
  * 一路上突然想到了java线程并发库中的Exchanger类。A车我们可以看作是一个线程、B车我们也可以
  * 看作是一个线程,我和B车上的一位美女换位子,就可以用到Exchanger类的exchange方法。
  *
  * 代码如下:

public class ExchangerTest {

    public static void main(String[] args) {

        final Exchanger<String> exchange=new Exchanger<String>();
        //final String a="yupan";
        //final String b="a girl";
        final String[] carA=new String[]{"zhangsan","lisi","yupan"};
        final String[] carB=new String[]{"meinv_a","meinv_b","meinv_c"};
        
        //A车线程
        new Thread(new Runnable(){

            String[] carA_copy=carA;
            @Override
            public void run() {
                try {
                    System.out.println("交换前:A车上的第三位乘客:"+carA[2]);
                    carA_copy[2]=exchange.exchange(carA_copy[2]);
                    System.out.println("交换后:A车上的第三位乘客:"+carA[2]);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            
        }).start();
        
        //B车线程
        new Thread(new Runnable(){
            
            String[] carB_copy=carB;
            @Override
            public void run() {
                try {
                    System.out.println("交换前:B车上的第三位乘客:"+carB[2]);
                    carB_copy[2]=exchange.exchange(carB_copy[2]);
                    System.out.println("交换后:B车上的第三位乘客:"+carB[2]);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            
        }).start();
        
    }
}

输出结果:

交换前:A车上的第三位乘客:yupan
交换前:B车上的第三位乘客:meinv_c
交换后:B车上的第三位乘客:yupan
交换后:A车上的第三位乘客:meinv_c

http://blog.sina.com.cn/s/blog_7f448c5201012183.html
posted @ 2013-01-08 00:35 abin 阅读(353) | 评论 (0)编辑 收藏

Semaphore当前在多线程环境下被扩放使用,操作系统的信号量是个很重要的概念,在进程控制方面都有应用。Java 并发库 的Semaphore 可以很轻松完成信号量控制,Semaphore可以控制某个资源可被同时访问的个数,通过 acquire() 获取一个许可,如果没有就等待,而 release() 释放一个许可。比如在Windows下可以设置共享文件的最大客户端访问个数。 

Semaphore实现的功能就类似厕所有5个坑,假如有10个人要上厕所,那么同时只能有多少个人去上厕所呢?同时只能有5个人能够占用,当5个人中 的任何一个人让开后,其中等待的另外5个人中又有一个人可以占用了。另外等待的5个人中可以是随机获得优先机会,也可以是按照先来后到的顺序获得机会,这取决于构造Semaphore对象时传入的参数选项。单个信号量的Semaphore对象可以实现互斥锁的功能,并且可以是由一个线程获得了“锁”,再由另一个线程释放“锁”,这可应用于死锁恢复的一些场合。

Semaphore维护了当前访问的个数,提供同步机制,控制同时访问的个数。在数据结构中链表可以保存“无限”的节点,用Semaphore可以实现有限大小的链表。另外重入锁 ReentrantLock 也可以实现该功能,但实现上要复杂些。 

下面的Demo中申明了一个只有5个许可的Semaphore,而有20个线程要访问这个资源,通过acquire()和release()获取和释放访问许可。

package com.test;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Semaphore;

public class TestSemaphore {

                public static void main(String[] args) {

                // 线程池

                ExecutorService exec = Executors.newCachedThreadPool();

                // 只能5个线程同时访问

                final Semaphore semp = new Semaphore(5);

                 // 模拟20个客户端访问

                 for (int index = 0; index < 20; index++) {

                              final int NO = index;

                              Runnable run = new Runnable() {

                                                 public void run() {

                                                            try {

                                                                    // 获取许可

                                                                    semp.acquire();

                                                                    System.out.println("Accessing: " + NO);

                                                                    Thread.sleep((long) (Math.random() * 10000));

                                                                    // 访问完后,释放

                                                                    semp.release();

                                                                    System.out.println("-----------------"+semp.availablePermits());

                                                            } catch (InterruptedException e) {

                                                                    e.printStackTrace();

                                                            }

                                                  }

                                      };

                      exec.execute(run);

             }

             // 退出线程池

             exec.shutdown();

       }

执行结果如下:

Accessing: 0

Accessing: 1

Accessing: 3

Accessing: 4

Accessing: 2

-----------------0

Accessing: 6

-----------------1

Accessing: 7

-----------------1

Accessing: 8

-----------------1

Accessing: 10

-----------------1

Accessing: 9

-----------------1

Accessing: 5

-----------------1

Accessing: 12

-----------------1

Accessing: 11

-----------------1

Accessing: 13

-----------------1

Accessing: 14

-----------------1

Accessing: 15

-----------------1

Accessing: 16

-----------------1

Accessing: 17

-----------------1

Accessing: 18

-----------------1

Accessing: 19




http://www.cnblogs.com/whgw/archive/2011/09/29/2195555.html
posted @ 2013-01-08 00:11 abin 阅读(364) | 评论 (0)编辑 收藏

View Code
 package generate.httpclient;
 
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.CountDownLatch;
 
 import org.apache.http.HttpResponse;
 import org.apache.http.client.methods.HttpGet;
 import org.apache.http.concurrent.FutureCallback;
 import org.apache.http.impl.nio.client.DefaultHttpAsyncClient;
 import org.apache.http.nio.client.HttpAsyncClient;
 import org.apache.http.nio.reactor.IOReactorException;
 
 public class AsynClient{
     /**
      * @param args
      * @throws IOReactorException
      * @throws InterruptedException
      */
     private List<String> urls;
     private HandlerFailThread failHandler;
     public AsynClient(List<String> list){
         failHandler=new HandlerFailThread();
         urls=list;
     }
     public Map<String,String> asynGet() throws IOReactorException,
             InterruptedException {
         final HttpAsyncClient httpclient = new DefaultHttpAsyncClient();
         httpclient.start();
         int urlLength=urls.size();
         HttpGet[] requests = new HttpGet[urlLength];
         int i=0;
         for(String url : urls){
             requests[i]=new HttpGet(url);
             i++;
         }
         final CountDownLatch latch = new CountDownLatch(requests.length);
         final Map<String, String> responseMap=new HashMap<String, String>();
         try {
             for (final HttpGet request : requests) {
                 httpclient.execute(request, new FutureCallback<HttpResponse>() {
 
                     public void completed(final HttpResponse response) {
                         latch.countDown();
                         responseMap.put(request.getURI().toString(), response.getStatusLine().toString());
                         try {
                             System.out.println(request.getRequestLine() + "->"
                                     + response.getStatusLine()+"->");
                             //+readInputStream(response.getEntity().getContent())
                            
                         } catch (IllegalStateException e) {
                             failHandler.putFailUrl(request.getURI().toString(),
                                     response.getStatusLine().toString());
                             e.printStackTrace();
                         } catch (Exception e) {
                             failHandler.putFailUrl(request.getURI().toString(),
                                     response.getStatusLine().toString());
                             e.printStackTrace();
                         }
                     }
 
                     public void failed(final Exception ex) {
                         latch.countDown();
                         ex.printStackTrace();
                         failHandler.putFailUrl(request.getURI().toString(),
                                 ex.getMessage());
                     }
 
                     public void cancelled() {
                         latch.countDown();
                     }
 
                 });
             }
             System.out.println("Doing...");
         } finally {
             latch.await();
             httpclient.shutdown();
         }
         System.out.println("Done");
         failHandler.printFailUrl();
         return responseMap;
     }
     private String readInputStream(InputStream input) throws IOException{
         byte[] buffer = new byte[128];
         int len = 0;
         ByteArrayOutputStream bytes = new ByteArrayOutputStream();
         while((len = input.read(buffer)) >= 0) {
             bytes.write(buffer, 0, len);
         }
         return bytes.toString();
     }
     /**
      * Test
      * @param args
      */
     public static void main(String[] args) {
         List<String> urls=new ArrayList<String>();
         urls.add("http://127.0.0.1/examples/servlets/");
         urls.add("http://127.0.0.1/examples/servlets/");
         urls.add("http://127.0.0.1/examples/servlets/");
         for(int i=0;i<10;i++){
             urls.addAll(urls);
         }
         System.out.println(urls.size());
         AsynClient client=new AsynClient(urls);
         try {
             client.asynGet();
         } catch (IOReactorException e) {
             e.printStackTrace();
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
         System.out.println("done");
     }
 }
posted @ 2013-01-07 21:14 abin 阅读(912) | 评论 (0)编辑 收藏

package com.abin.lii.han.limei;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.junit.Test;

public class ImediaRegisterTest {
 @Test
 public void testImediaRegister(){
  String LIMEI_HTTP="http://192.168.3.15:1000/release/mybe";
  String appId="fk000";
  String udid="3A5S4D6F8G9K_3596140444464123";
  String requestUrl=LIMEI_HTTP+"?app="+appId+"&udid="+udid+"&source="+"where"";
  System.out.println(requestUrl);
  String result="";
  try {
   URL url=new URL(requestUrl);
   HttpURLConnection connection=(HttpURLConnection)url.openConnection();
   connection.setDoOutput(true);
   connection.setDoInput(true);
   connection.setRequestMethod("GET");
   connection.setUseCaches(false);
   // URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
   connection.setInstanceFollowRedirects(false);
   connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
   connection.connect();
   //发送执行请求
   
   //接收返回请求
   BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream(),"GBK"));
   String line="";
   StringBuffer buffer=new StringBuffer();
   while((line=reader.readLine())!=null){
    buffer.append(line);
   }
   result=buffer.toString();
   System.out.println("result="+result);
   connection.disconnect();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}

posted @ 2013-01-06 21:36 abin 阅读(2655) | 评论 (1)编辑 收藏

1.tomcat下所有应用都强制https访问

在tomcat\conf\web.xml中的</welcome-file-list>后面加上以下配置:


  <login-config>
      <!-- Authorization setting for SSL -->
      <auth-method>CLIENT-CERT</auth-method>
      <realm-name>Client Cert Users-only Area</realm-name>
  </login-config>
  <security-constraint>
      <!-- Authorization setting for SSL -->
      <web-resource-collection >
          <web-resource-name >SSL</web-resource-name>
          <url-pattern>/*</url-pattern>
      </web-resource-collection>
      <user-data-constraint>
          <transport-guarantee>CONFIDENTIAL</transport-guarantee>
      </user-data-constraint>
  </security-constraint>





2.单个应用强制https访问

WEB-INF/web.xml的</welcome-file-list>后面加上以下配置:

  <login-config>
      <!-- Authorization setting for SSL -->
      <auth-method>CLIENT-CERT</auth-method>
      <realm-name>Client Cert Users-only Area</realm-name>
  </login-config>
  <security-constraint>
      <!-- Authorization setting for SSL -->
      <web-resource-collection >
          <web-resource-name >SSL</web-resource-name>
          <url-pattern>/*</url-pattern>
      </web-resource-collection>
      <user-data-constraint>
          <transport-guarantee>CONFIDENTIAL</transport-guarantee>
      </user-data-constraint>
  </security-constraint>




posted @ 2013-01-06 21:28 abin 阅读(1349) | 评论 (0)编辑 收藏

select t.*,t.rowid from abin1 t;
删除重复的记录,只保留一条:
delete from abin1 t where rowid not in (select max(rowid) from abin1 s group by s.id1  );
delete from abin1 t where t.rowid not in (select min(s.rowid) from abin1 s where t.id1=s.id1 group by s.id1)
删除全部重复记录:
delete from abin1 t where t.id1 in (select s.id1 from abin1 s group by s.id1 having count(s.id1)>1 );
delete from abin1 t where exists (select * from abin1 s where t.id1=s.id1 group by s.id1 having count(s.id1)>1)
取出有重复的记录,没有重复的单条记录不取:
select * from abin1 t where t.id1 in (select s.id1 from abin1 s group by s.id1 having(count(s.id1))>1 );
select * from abin1 t where exists (select * from abin1 s where s.id1=t.id1 group by s.id1 having(count(s.id1))>1);
删除重复记录(保留一条):
delete from abin1 t where t.id1 not in(select max(s.id1) from abin1 s group by s.name1 having count(s.name1)>0);

posted @ 2013-01-04 22:51 abin 阅读(1187) | 评论 (0)编辑 收藏

仅列出标题
共50页: First 上一页 17 18 19 20 21 22 23 24 25 下一页 Last