9910

          單飛

             :: 首頁 :: 聯系 :: 聚合  :: 管理

          #

          private Label doneLabel;
          private Timer timer;

              public class ATask extends TimerTask {
                  @Override
                  public void run() {
                      showScrollText(doneLabel);
                     

                  }
              }

              /**
               * 滾動顯示字幕
               *
               * @param toDoLabel
               */
              private void showScrollText(final Label toDoLabel) {
                  if (toDoLabel != null) {
                      if (toDoLabel.isDisposed()) {
                          timer.cancel();
                          return;
                      }
                      shell.getDisplay().asyncExec(new Runnable() {
                          // @Override
                          public void run() {
                              String txt = toDoLabel.getText();
                              if (txt != null && txt.length() > 50) {
                                  txt = txt.substring(1, txt.length())
                                          + txt.substring(0, 1);
                                  toDoLabel.setText(txt);
                              }
                          }

                      });

                  }
              }
          構造的時候
          // 滾動顯示字幕
                  timer = new Timer();
                  timer.schedule(new ATask(), 0, 500);

                  //
              }

              // @Override
              public void dispose() {
                  timer.cancel();
                  super.dispose();
              }
          private Timer timer;

              public class ATask extends TimerTask {
                  @Override
                  public void run() {
                      showScrollText(doneLabel);
                     

                  }
              }


              /**
               * 滾動顯示字幕
               *
               * @param toDoLabel
               */
              private void showScrollText(final Label toDoLabel) {
                  if (toDoLabel != null) {
                      if (toDoLabel.isDisposed()) {
                          timer.cancel();
                          return;
                      }
                      shell.getDisplay().asyncExec(new Runnable() {
                          // @Override
                          public void run() {
                              String txt = toDoLabel.getText();
                              if (txt != null && txt.length() > 50) {
                                  txt = txt.substring(1, txt.length())
                                          + txt.substring(0, 1);
                                  toDoLabel.setText(txt);
                              }
                          }

                      });

                  }
              }


          構造的時候
          // 滾動顯示字幕
                  timer = new Timer();
                  timer.schedule(new ATask(), 0, 500);

          // @Override
              public void dispose() {
                  timer.cancel();
                  super.dispose();
              }



          posted @ 2010-08-06 16:47 單飛 閱讀(959) | 評論 (1)編輯 收藏

          What the Job Post Says What it Really Means
          Standard work hours are 40-50 hours a week We expect developers to live in their tiny tiny cubes 24-7
          我們希望程序員7*24小時工作在自己的小隔間里面
          This is a support position We don’t allow our developers to have a life outside of work
          我們不希望員工有工作之外的生活
          You will work closely with the PM, DBA and QA Our environment is highly political, riddled with ridiculous rules made by people who don’t understand software, and we get very little done
          我們的環境是高政治的,由很多不懂軟件的人制定了很多荒謬的制度。我們還有很多沒有達標。
          This position involves working with our real-time application I don’t know what real-time means but it sounds good
          Great opportunity for growth Only a desperate person would deal with this shit
          只有絕望的人才會做這種狗屎的工作。
          Job candidate must be resourceful, responsible and able to work well under pressure. Our corporate culture is basically the ‘Lord of the Flies
          我們的管理方式就是“蟻王和工蟻”的方式。
          posted @ 2010-05-12 10:35 單飛 閱讀(195) | 評論 (0)編輯 收藏

          http://blog.csdn.net/xiaxiaorui2003/archive/2009/07/29/4390401.aspx

          我現在在編寫一個JAVA工程,是提供給客戶調用的API,但是我的API中大約需要依賴10個.JAR,

          以前我都是使用ECLIPSE 的 EXPORT  JAR file功能導出 JAR,這樣的JAR可以使用,但是我的API種依賴的包客戶還是需要導入,這樣一共就需要導入11個包了,太麻煩了,現在就是想包括API和依賴的JAR打成一個JAR,這樣子就方便多了,

          現在找到了,使用ECLIPSE3.4的EXPORT Runnable JAR file功能導出的JAR就是包含了依賴的JAR,導入這一個JAR就可以了,具體操作如下,

          1. 先找到你的工程中提供接口的類(要包含MAIN方法),

          2. 在該類中右鍵選擇 RUN as

          3. 選擇 Run configurations

          4. 在main窗口中選擇main class為本類

          5. 點擊RUN

          6. 選擇你的工程,右鍵選擇 EXPORT

          7. 在彈出的窗口中選擇 runnable jar file

          8. 在彈出的 runnable jar file export窗口中第一個launch configuration 中選擇你剛才配置的類,

               第二個窗口中選擇你要導出的路徑

          9. 然后選擇下一步就OK了


          posted @ 2010-02-04 13:58 單飛 閱讀(1309) | 評論 (0)編輯 收藏

          http://extjs2.javaeye.com/blog/394128

          正則表達式在字符串處理中經常使用,關于正則簡單的用法相信有一點程序基礎的人都懂得一些,這里就不介紹簡單基礎了。這里主要講解一下在JAVA中實現了的正則的高級用法-分組與捕獲。

              對于要重復單個字符,非常簡單,直接在字符后賣弄加上限定符即可,例如 a+ 表示匹配1個或一個以上的a,a?表示匹配0個或1個a。這些限定符如下所示:

            X? X,一次或一次也沒有
          X* X,零次或多次
          X+ X,一次或多次
          X{n} X,恰好 n 次
          X{n,} X,至少 n 次
          X{n,m} X,至少 n 次,但是不超過 m 次





          但是我們如果要對多個字符進行重復怎么辦呢?此時我們就要用到分組,我們可以使用小括號"()"來指定要重復的子表達式,然后對這個子表達式進行重復,例如:(abc)? 表示0個或1個abc 這里一個括號的表達式就表示一個分組。



             分組可以分為兩種形式,捕獲組和非捕獲組。



          捕獲組

          捕獲組可以通過從左到右計算其開括號來編號。例如,在表達式 ((A)(B(C))) 中,存在四個這樣的組:

          1     ((A)(B(C)))
          2     "A
          3     (B(C))
          4     (C)

          組零始終代表整個表達式

          之所以這樣命名捕獲組是因為在匹配中,保存了與這些組匹配的輸入序列的每個子序列。捕獲的子序列稍后可以通過 Back 引用在表達式中使用,也可以在匹配操作完成后從匹配器檢索。



          Back 引用 是說在后面的表達式中我們可以使用組的編號來引用前面的表達式所捕獲到的文本序列(是文本不是正則)。



          例如 ([" ']).* "1   其中使用了分組,"1就是對引號這個分組的引用,它匹配包含在兩個引號或者兩個單引號中的所有字符串,如,"abc" 或 " ' " 或 ' " '  ,但是請注意,它并不會對" a'或者 'a"匹配。原因上面已經說明,Back引用只是引用文本而不是表達式。



          非捕獲組

                以 (?) 開頭的組是純的非捕獲 組,它不捕獲文本,也不針對組合計進行計數。就是說,如果小括號中以?號開頭,那么這個分組就不會捕獲文本,當然也不會有組的編號,因此也不存在Back 引用。

                在Java中,支持的非捕獲組,有如下幾種:

           
             
            
          (?=X)     X,通過零寬度的正 lookahead
          (?!X)     X,通過零寬度的負 lookahead
          (?<=X)     X,通過零寬度的正 lookbehind
          (?<!X)     X,通過零寬度的負 lookbehind
           




          這四個非捕獲組用于匹配表達式X,但是不包含表達式的文本。

          (?=X ) 零寬度正先行斷言。僅當子表達式 X 在 此位置的右側匹配時才繼續匹配。例如,"w+(?="d) 與后跟數字的單詞匹配,而不與該數字匹配。此構造不會回溯。
          (?!X) 零寬度負先行斷言。僅當子表達式 X 不在 此位置的右側匹配時才繼續匹配。例如,例如,"w+(?!"d) 與后不跟數字的單詞匹配,而不與該數字匹配。
          (?<=X) 零寬度正后發斷言。僅當子表達式 X 在 此位置的左側匹配時才繼續匹配。例如,(?<=19)99 與跟在 19 后面的 99 的實例匹配。此構造不會回溯。
          (?<!X) 零寬度負后發斷言。僅當子表達式 X 不在此位置的左側匹配時才繼續匹配。例如,(?<!19)99 與不跟在 19 后面的 99 的實例匹配






          舉例:



          上面都是理論性的介紹,這里就使用一些例子來說明一下問題:

             1、測試匹配性   (?<!4)56(?=9) 這里的含義就是匹配后面的文本56前面不能是4,后面必須是9組成。因此,可以匹配如下文本 5569  ,與4569不匹配。



            2 、提取字符串   提取 da12bka3434bdca4343bdca234bm   提取包含在字符a和b之間的數字,但是這個a之前的字符不能是c,b后面的字符必須是d才能提取。



                  例如這里就只有3434這個數字滿足要求。那么我們怎么提取呢?

                 首先我們寫出提取這個字符串的表達式: (?<!c)a("d+)bd  這里就只有一個捕獲組("d+)

                 JAVA代碼片段如下:

          Pattern p = Pattern.compile("(?<!c)a(""d+)bd");
          Matcher m = p.matcher("da12bca3434bdca4343bdca234bm");
          while(m.find()){
             System.out.println(m.group(1)); //我們只要捕獲組1的數字即可。結果 3434
             System.out.println(m.group(0)); // 0組是整個表達式,看這里,并沒有提煉出(?<!c)的字符 。結果 a3434bd
          }
              可以看到,非捕獲組,最后是不會返回結果的,因為它本身并不捕獲文本。



          正則表達式功能其實非常強大,這里只是對高級用法的簡單探討。有興趣的朋友和本人共同討論。
          posted @ 2010-01-06 10:14 單飛 閱讀(1132) | 評論 (0)編輯 收藏

           眾所周知,在程序開發中,難免會遇到需要匹配、查找、替換、判斷字符串的情況發生,而這些情況有時又比較復雜,如果用純編碼方式解決,往往會浪費程序員的時間及精力。因此,學習及使用正則表達式,便成了解決這一矛盾的主要手段。
           大 家都知道,正則表達式是一種可以用于模式匹配和替換的規范,一個正則表達式就是由普通的字符(例如字符a到z)以及特殊字符(元字符)組成的文字模式,它 用以描述在查找文字主體時待匹配的一個或多個字符串。正則表達式作為一個模板,將某個字符模式與所搜索的字符串進行匹配。
            自從jdk1.4推出java.util.regex包,就為我們提供了很好的JAVA正則表達式應用平臺。
           
           因為正則表達式是一個很龐雜的體系,所以我僅例舉些入門的概念,更多的請參閱相關書籍及自行摸索。

          \\ 反斜杠
          \t 間隔 ('\u0009')
          \n 換行 ('\u000A')
          \r 回車 ('\u000D')
          \d 數字 等價于[0-9]
          \D 非數字 等價于[^0-9]
          \s 空白符號 [\t\n\x0B\f\r]
          \S 非空白符號 [^\t\n\x0B\f\r]
          \w 單獨字符 [a-zA-Z_0-9]
          \W 非單獨字符 [^a-zA-Z_0-9]
          \f 換頁符
          \e Escape
          \b 一個單詞的邊界
          \B 一個非單詞的邊界
          \G 前一個匹配的結束

          ^為限制開頭
          ^java     條件限制為以Java為開頭字符
          $為限制結尾
          java$     條件限制為以java為結尾字符
          .  條件限制除\n以外任意一個單獨字符
          java..     條件限制為java后除換行外任意兩個字符


          加入特定限制條件「[]」
          [a-z]     條件限制在小寫a to z范圍中一個字符
          [A-Z]     條件限制在大寫A to Z范圍中一個字符
          [a-zA-Z] 條件限制在小寫a to z或大寫A to Z范圍中一個字符
          [0-9]     條件限制在小寫0 to 9范圍中一個字符
          [0-9a-z] 條件限制在小寫0 to 9或a to z范圍中一個字符
          [0-9[a-z]] 條件限制在小寫0 to 9或a to z范圍中一個字符(交集)

          []中加入^后加再次限制條件「[^]」
          [^a-z]     條件限制在非小寫a to z范圍中一個字符
          [^A-Z]     條件限制在非大寫A to Z范圍中一個字符
          [^a-zA-Z] 條件限制在非小寫a to z或大寫A to Z范圍中一個字符
          [^0-9]     條件限制在非小寫0 to 9范圍中一個字符
          [^0-9a-z] 條件限制在非小寫0 to 9或a to z范圍中一個字符
          [^0-9[a-z]] 條件限制在非小寫0 to 9或a to z范圍中一個字符(交集)

          在限制條件為特定字符出現0次以上時,可以使用「*」
          J*     0個以上J
          .*     0個以上任意字符
          J.*D     J與D之間0個以上任意字符

          在限制條件為特定字符出現1次以上時,可以使用「+」
          J+     1個以上J
          .+     1個以上任意字符
          J.+D     J與D之間1個以上任意字符

          在限制條件為特定字符出現有0或1次以上時,可以使用「?」
          JA?     J或者JA出現

          限制為連續出現指定次數字符「{a}」
          J{2}     JJ
          J{3}     JJJ
          文字a個以上,并且「{a,}」
          J{3,}     JJJ,JJJJ,JJJJJ,???(3次以上J并存)
          文字個以上,b個以下「{a,b}」
          J{3,5}     JJJ或JJJJ或JJJJJ
          兩者取一「|」
          J|A     J或A
          Java|Hello     Java或Hello
           
          「()」中規定一個組合類型
          比如,我查詢<a href=\"index.html\">index</a>中<a href></a>間的數據,可寫作<a.*href=\".*\">(.+?)</a>

          在使用Pattern.compile函數時,可以加入控制正則表達式的匹配行為的參數:
          Pattern Pattern.compile(String regex, int flag)

          flag的取值范圍如下:
          Pattern.CANON_EQ     當且僅當兩個字符的"正規分解(canonical decomposition)"都完全相同的情況下,才認定匹配。比如用了這個標志之后,表達式"a\u030A"會匹配"?"。默認情況下,不考慮"規 范相等性(canonical equivalence)"。
          Pattern.CASE_INSENSITIVE(?i)     默認情況下,大小寫不明感的匹配只適用于US-ASCII字符集。這個標志能讓表達式忽略大小寫進行匹配。要想對Unicode字符進行大小不明感的匹 配,只要將UNICODE_CASE與這個標志合起來就行了。
          Pattern.COMMENTS(?x)     在這種模式下,匹配時會忽略(正則表達式里的)空格字符(譯者注:不是指表達式里的"\\s",而是指表達式里的空格,tab,回車之類)。注釋從#開始,一直到這行結束??梢酝ㄟ^嵌入式的標志來啟用Unix行模式。
          Pattern.DOTALL(?s)     在這種模式下,表達式'.'可以匹配任意字符,包括表示一行的結束符。默認情況下,表達式'.'不匹配行的結束符。
          Pattern.MULTILINE
          (?m)     在這種模式下,'^'和'$'分別匹配一行的開始和結束。此外,'^'仍然匹配字符串的開始,'$'也匹配字符串的結束。默認情況下,這兩個表達式僅僅匹配字符串的開始和結束。
          Pattern.UNICODE_CASE
          (?u)     在這個模式下,如果你還啟用了CASE_INSENSITIVE標志,那么它會對Unicode字符進行大小寫不明感的匹配。默認情況下,大小寫不敏感的匹配只適用于US-ASCII字符集。
          Pattern.UNIX_LINES(?d)     在這個模式下,只有'\n'才被認作一行的中止,并且與'.','^',以及'$'進行匹配。


          拋開空泛的概念,下面寫出幾個簡單的Java正則用例:

          ◆比如,在字符串包含驗證時

          //查找以Java開頭,任意結尾的字符串
            Pattern pattern = Pattern.compile("^Java.*");
            Matcher matcher = pattern.matcher("Java不是人");
            boolean b= matcher.matches();
            //當條件滿足時,將返回true,否則返回false
            System.out.println(b);


          ◆以多條件分割字符串時
          Pattern pattern = Pattern.compile("[, |]+");
          String[] strs = pattern.split("Java Hello World  Java,Hello,,World|Sun");
          for (int i=0;i<strs.length;i++) {
              System.out.println(strs[i]);
          }

          ◆文字替換(首次出現字符)
          Pattern pattern = Pattern.compile("正則表達式");
          Matcher matcher = pattern.matcher("正則表達式 Hello World,正則表達式 Hello World");
          //替換第一個符合正則的數據
          System.out.println(matcher.replaceFirst("Java"));

          ◆文字替換(全部)
          Pattern pattern = Pattern.compile("正則表達式");
          Matcher matcher = pattern.matcher("正則表達式 Hello World,正則表達式 Hello World");
          //替換第一個符合正則的數據
          System.out.println(matcher.replaceAll("Java"));


          ◆文字替換(置換字符)
          Pattern pattern = Pattern.compile("正則表達式");
          Matcher matcher = pattern.matcher("正則表達式 Hello World,正則表達式 Hello World ");
          StringBuffer sbr = new StringBuffer();
          while (matcher.find()) {
              matcher.appendReplacement(sbr, "Java");
          }
          matcher.appendTail(sbr);
          System.out.println(sbr.toString());

          ◆驗證是否為郵箱地址

          String str="ceponline@yahoo.com.cn";
          Pattern pattern = Pattern.compile("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+",Pattern.CASE_INSENSITIVE);
          Matcher matcher = pattern.matcher(str);
          System.out.println(matcher.matches());

          ◆去除html標記
          Pattern pattern = Pattern.compile("<.+?>", Pattern.DOTALL);
          Matcher matcher = pattern.matcher("<a href=\"index.html\">主頁</a>");
          String string = matcher.replaceAll("");
          System.out.println(string);

          ◆查找html中對應條件字符串
          Pattern pattern = Pattern.compile("href=\"(.+?)\"");
          Matcher matcher = pattern.matcher("<a href=\"index.html\">主頁</a>");
          if(matcher.find())
            System.out.println(matcher.group(1));
          }

          ◆截取http://地址
          //截取url
          Pattern pattern = Pattern.compile("(http://|https://){1}[\\w\\.\\-/:]+");
          Matcher matcher = pattern.matcher("dsdsds<http://dsds//gfgffdfd>fdf");
          StringBuffer buffer = new StringBuffer();
          while(matcher.find()){             
              buffer.append(matcher.group());       
              buffer.append("\r\n");             
          System.out.println(buffer.toString());
          }
                 
          ◆替換指定{}中文字

          String str = "Java目前的發展史是由{0}年-{1}年";
          String[][] object={new String[]{"\\{0\\}","1995"},new String[]{"\\{1\\}","2007"}};
          System.out.println(replace(str,object));

          public static String replace(final String sourceString,Object[] object) {
                      String temp=sourceString;   
                      for(int i=0;i<object.length;i++){
                                String[] result=(String[])object[i];
                         Pattern    pattern = Pattern.compile(result[0]);
                         Matcher matcher = pattern.matcher(temp);
                         temp=matcher.replaceAll(result[1]);
                      }
                      return temp;
          }


          ◆以正則條件查詢指定目錄下文件

           //用于緩存文件列表
                  private ArrayList files = new ArrayList();
                  //用于承載文件路徑
                  private String _path;
                  //用于承載未合并的正則公式
                  private String _regexp;
                 
                  class MyFileFilter implements FileFilter {

                        /**
                         * 匹配文件名稱
                         */
                        public boolean accept(File file) {
                          try {
                            Pattern pattern = Pattern.compile(_regexp);
                            Matcher match = pattern.matcher(file.getName());               
                            return match.matches();
                          } catch (Exception e) {
                            return true;
                          }
                        }
                      }
                 
                  /**
                   * 解析輸入流
                   * @param inputs
                   */
                  FilesAnalyze (String path,String regexp){
                      getFileName(path,regexp);
                  }
                 
                  /**
                   * 分析文件名并加入files
                   * @param input
                   */
                  private void getFileName(String path,String regexp) {
                      //目錄
                        _path=path;
                        _regexp=regexp;
                        File directory = new File(_path);
                        File[] filesFile = directory.listFiles(new MyFileFilter());
                        if (filesFile == null) return;
                        for (int j = 0; j < filesFile.length; j++) {
                          files.add(filesFile[j]);
                        }
                        return;
                      }
             
                  /**
                   * 顯示輸出信息
                   * @param out
                   */
                  public void print (PrintStream out) {
                      Iterator elements = files.iterator();
                      while (elements.hasNext()) {
                          File file=(File) elements.next();
                              out.println(file.getPath());   
                      }
                  }

                  public static void output(String path,String regexp) {

                      FilesAnalyze fileGroup1 = new FilesAnalyze(path,regexp);
                      fileGroup1.print(System.out);
                  }
             
                  public static void main (String[] args) {
                      output("C:\\","[A-z|.]*");
                  }

          Java正則的功用還有很多,事實上只要是字符處理,就沒有正則做不到的事情存在。(當然,正則解釋時較耗時間就是了|||……)
          posted @ 2009-12-29 10:34 單飛 閱讀(215) | 評論 (0)編輯 收藏

          1byte = 8 bit

          一比特 bit

          4

          低四位

          R

          G

          B

          R

          G

          B

          posted @ 2009-11-27 10:07 單飛 閱讀(190) | 評論 (0)編輯 收藏

          1.jhttp
          2.javanetlib

          在看源代碼的時候,看到一個設計簡單的線程池
          package cs519.proxy.tpool;

          import java.util.*;

          /**
           * Thread Pool Manager.
           *
           * Use a fixed number of threads and process requests.
           */
          public class ThreadPool
          {
              /**
               * @param    nThread
               *        number of threads to create.
               */
              public ThreadPool( int nThread ) {
                  for( int i=0; i<nThread; i++ )
                      new WorkerThread().start();
              }
              
              /** list of tasks waiting for execution */
              private final List tasks = new LinkedList();
              
              /** list of lower-priority tasks waiting for execution */
              private final List backgroundTasks = new LinkedList();
              
              /**
               * Adds a new 'task' to the pool.
               * Assigned task will be eventually processed by one of the threads
               * in the pool.
               */
              public synchronized void addTask( Runnable task ) {
                  tasks.add(task);
                  notify();   // notify any thread waiting for a task
              }
              
              /**
               * Adds a new low-priority 'task' to the pool.
               * Assigned task will be eventually processed by one of the threads
               * in the pool.
               */
              public synchronized void addBackgroundTask( Runnable task ) {
                  backgroundTasks.add(task);
              }
              
              /**
               * Obtains a task from the queue.
               */
              private synchronized Runnable getTask() {
                  while(true) {
                      if(!tasks.isEmpty())
                          return (Runnable)tasks.remove(0);
                      
                      if(!backgroundTasks.isEmpty())
                          return (Runnable)backgroundTasks.remove(0);
                      
                      try {
                          wait(); // wait for a new task
                      } catch( InterruptedException e ) {
                          System.err.println("thread interrupted");
                          throw new InternalError();
                      }
                  }
              }

              
              /** destructs the pool. */
              public void dispose() {
                  suicideSignal = true;
              }
              private boolean suicideSignal = false;
              
              private class WorkerThread extends Thread {
                  public void run() {
                      while(!suicideSignal)
                          getTask().run();
                  }
              }
          }

          并且提供了緩存管理
          package cs519.proxy.cache;

          import java.io.*;
          import java.util.*;
          import java.text.ParseException;
          import cs519.proxy.http.*;

          public class CacheManagerImpl implements CacheManager
          {
              /**
               * Set to non-null to see debug traces.
               */
              private PrintStream debug = System.out;

              /**
               * The number of bytes in the cache.
               * This field is accessed by the Janitor.
               */
              long usedCacheSize = 0;
              
              private Object usedCacheSizeLock = new Object();
                  
              /** Atomically modify the value of usedCacheSize. */
              private void modifyUsedCacheSize( long offset ) {
                  synchronized(usedCacheSizeLock) {
                      usedCacheSize += offset;
                  }
              }
                  
              private final long cacheLimit;
              protected final TreeMap map=new TreeMap();
              protected final TreeSet fileSet=new TreeSet();
              
              /** The directory in which all cached objects are placed. */
              private final File dir = new File("cache");
              public final File getCacheDir() { return dir; }
              
                
              private final CachePolicy policy;

              /**
               * Constructor:
               *   Load cache file information into CacheFileInfo objects.
               *   Include: filename, lastModified time, file length in byte.
               *   Add these objects to a TreeSet object, make them ordered
               *   by lastModified time.
               *   get current used cache size (in Bytes)
               */
              public CacheManagerImpl(long limit, CachePolicy _policy) throws IOException
              {
                  this.policy = _policy;
                  this.cacheLimit=limit;  //in bytes

                  if(!dir.exists())
                      dir.mkdir();
                            
                  String[] files=dir.list();

                  for(int i=0;i<files.length;i++)
                  {
                      //System.out.println(files[i].getName());
                      File f=new File(dir,files[i]);
                      CacheFileInfo cfi = new CacheFileInfo(f);
                      fileSet.add(cfi);
                      
                      map.put( files[i], cfi );
                      
                      modifyUsedCacheSize(cfi.fsize);
                  }
                  
                  // launch the janitor
                  new Thread(new CacheJanitor(this)).start();
              }

            /**
             * Put HttpResponse object into proxy cache.
             * Write HttpResponse to a cache file if it is "toBeCached":
             * 1. use request URL as a base of filename
             * 2. the structure of the cache file contains two parts
             *   a. Request URL (String)
             *   b. HttpResponse object
             */
              public void put( HttpRequest request, HttpResponse response ) {

                  long reservedSize;
                  
                  try {
                      
          //            if(debug!=null)
          //                debug.println("trying to store:"+request.getPath());

                      if(policy.toBeCached(request,response))
                      {
                          
                          reservedSize = response.getBodySize()+2000;
                          
                          // TODO: check if this object fits into the memory
          //                if(...)
          //                    return;
                          
                          
                          // allocate the space before we actually use it
                          modifyUsedCacheSize(reservedSize);
                          
                          // allocate physical space if it's necessary
                          if(!compactCache()) {
                      
                              if(debug!=null)
                                  debug.println("cache compacting failure:"+request.getPath());
                              
                              // we can't store this object.
                              // cancel this reservation
                              modifyUsedCacheSize(-reservedSize);
                              return;
                          }
                          
          //                if(debug!=null)
          //                    debug.println("storing "+request.getPath());

                          File f = getCacheFileName(request);
                          ObjectOutputStream fileOut=new ObjectOutputStream(
                                  new FileOutputStream(f));
                          fileOut.writeObject(request.getPath());
                          try {
                              fileOut.writeObject(response.getHeaderAsDate("Expires"));
                          } catch( java.text.ParseException e ) {
                              fileOut.writeObject(null);  // write a dummy
                          }
                          fileOut.writeObject(response);
                          fileOut.close();
                          
                          long actualSize = f.length();
                          
                          synchronized(fileSet) { // use one lock for both objects
                              CacheFileInfo cfi = new CacheFileInfo(f);
                              fileSet.add( cfi );
                              map.put( cfi.fname, cfi );
                          }
                          
                          modifyUsedCacheSize(actualSize-reservedSize);

                          if(debug!=null)
                              debug.println("stored  :"+request.getPath());
                      }
                  } catch( IOException e ) {
                      // TODO: possibly return the reservedSize.
                      reservedSize=-0;
                      modifyUsedCacheSize(reservedSize);
                      e.printStackTrace();
                      // TODO: remove any corrupted file

                  }
              }

              /**
               * Get requested object from proxy cache.
               * if (URL in file)==(request URL), and object not expired, then
               * return object to callee. else return null
               */
              public HttpResponse get( HttpRequest request )
              {
                  try {
                      File f = getCacheFileName(request);
              
                      if(f.exists()) {
                          ObjectInputStream oi=new ObjectInputStream(
                                                    new FileInputStream(f));
                          String fURL=(String)oi.readObject();
                          
                          if(fURL.equals(request.getPath())) {
                              Date now = new Date();
                              
                              // we won't use it, but we need to read this object
                              // to get to the body
                              Date expires = (Date)oi.readObject();
                          
                              // parse the body
                              HttpResponse resp=(HttpResponse)oi.readObject();
                              oi.close();
                              
                              if(debug!=null)
                                  debug.println("hit     :"+request.getPath());
                              
                              //check if the object expired
                              try {
                                  Date d = resp.getHeaderAsDate("Expires");

                                  if(d==null || d.after(now)) {
                                      // not expired. use this object.
                                      
                                      // touch this file for LRU purpose, and
                                      // modify fileSet and map content
                                      Util.setLastModified(f,now.getTime());
                              
                                      // maintain the control data structure
                                      synchronized(fileSet) {
                                          //remove this object first
                                          fileSet.remove(map.get(f.getName()));
                                          map.remove(f.getName());
                                          
                                          //add this object with current attributes
                                          CacheFileInfo new_cfi=new CacheFileInfo(f);
                                          fileSet.add(new_cfi);
                                          map.put(f.getName(),new_cfi);
                                      }
                                      
                                      return resp;
                                  }
                              } catch( ParseException e ) { ; }
                              
                              // we'll return null, so the caller will go ahead
                              // and fetch a new one, then store that new object
                              // into the cache.
                              // so we don't need to remove the old item now.
                          }
                          oi.close();
                      }
                  } catch( IOException e ) {
                      e.printStackTrace();
                  } catch( ClassNotFoundException e ) {
                      e.printStackTrace();
                  }
                  if(debug!=null)
                      debug.println("miss    :"+request.getPath());
                  return null;
              }
              
              public boolean contains( HttpRequest request ) {
                  try {
                      File f = getCacheFileName(request);
              
                      if(!f.exists()) return false;
                      
                      ObjectInputStream oi=new ObjectInputStream(
                                                new FileInputStream(f));
                      String fURL=(String)oi.readObject();
                      boolean r = fURL.equals(request.getPath());
                      oi.close();
                      return r;
                  } catch( Exception e ) {
                      return false;
                  }
              }
              
           
              private File getCacheFileName( HttpRequest msg ) {
                  return new File( dir, Integer.toHexString( msg.getPath().hashCode() ) );
              }
           

              /**
               * Compacts the cache so that the total size fell below the limit.
               *
               * @return
               *      true if the operation is successful and our used size is
               *      now lower then the limit.
               */
              public boolean compactCache() {
                  synchronized(fileSet) {
                      /**
                      * Remove LRU cache file until get enough free space
                      * LRU strategy
                      */
                      CacheFileInfo cFile;

                      while(cacheLimit<usedCacheSize && !fileSet.isEmpty()) {
                          cFile=(CacheFileInfo)fileSet.first();   //the LRU cache file
                          
                          removeCacheItem(cFile);
                      }
                      
                      return cacheLimit>=usedCacheSize;
                  }
              }

              /**
               * Deletes the object represented by a given CacheFileInfo.
               *
               * To remove something from the cache, you need to call this method
               * so that the cache manager can maintain the proper data structure.
               */
              protected void removeCacheItem( CacheFileInfo cfi ) {
                  
                  synchronized(fileSet) {
                      fileSet.remove(cfi);
                      map.remove(cfi.fname);
                  }
                  
                  File tmp = new File(dir,"_"+cfi.fname);
                  new File(dir,cfi.fname).renameTo(tmp);
                  
                  if(debug!=null) {
                      try {
                          // open the file just to print the name of URL
                          ObjectInputStream ois = new ObjectInputStream(new FileInputStream(tmp));
                          debug.println("delete  :"+ois.readObject());
                          ois.close();
                      } catch( Exception e ) {
                          // it's OK if we fail to print the debug message.
                          // so just ignore the error
                      }
                  }
                  
                  tmp.delete();
                                  
                  modifyUsedCacheSize(-cfi.fsize);
              }
          }



          posted @ 2009-11-25 14:09 單飛 閱讀(953) | 評論 (0)編輯 收藏

               摘要: rfc2616 對于返回是chunked格式的字節流的處理 Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --> import java.io.IOException; import java.io.In...  閱讀全文
          posted @ 2009-11-05 14:45 單飛 閱讀(374) | 評論 (0)編輯 收藏

          String cmd = "ping 127.0.0.1 -t";
                  Runtime rt 
          = Runtime.getRuntime();
                  System.out.println(
          ""+cmd );
                  Process process 
          = rt.exec(cmd );
                  InputStream stdin 
          = process.getInputStream();
                  InputStreamReader isr 
          = new InputStreamReader(stdin);
                  BufferedReader br 
          = new BufferedReader(isr);
                  String line;
                  StringBuffer buf 
          = new StringBuffer();
                  
          while ((line = br.readLine()) != null) {
                      buf.append(line);
                      System.out.println(line);
                  }
                  
          int exitVal = process.waitFor();
                  System.out.println(
          "Process exitValue: " + exitVal);
          posted @ 2009-10-30 17:24 單飛 閱讀(319) | 評論 (0)編輯 收藏

          <extension
                   
          id="product"
                   point
          ="org.eclipse.core.runtime.products">
                
          <product
                      
          application="org.test.a.application"
                      name
          ="%productName">
                   
          <property
                         
          name="windowImages"
                         value
          ="icons/a.16.gif"/>
                   
          <property
                         
          name="appName"
                         value
          ="Test">
                   
          </property>
                   
          <property
                         
          name="preferenceCustomization"
                         value
          ="plugin_customization.ini">
                   
          </property>


          plugin_customization.ini
          # new-style tabs by default
          org.eclipse.ui/SHOW_TRADITIONAL_STYLE_TABS=false

          # put the perspective switcher on the top right
          org.eclipse.ui/DOCK_PERSPECTIVE_BAR=topRight

          # show progress on startup
          org.eclipse.ui/SHOW_PROGRESS_ON_STARTUP=false
          org.eclipse.ui/SHOW_TEXT_ON_PERSPECTIVE_BAR=true

             1public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor {  
             
          2.     /* (non-Javadoc) 
             3.      * @see org.eclipse.ui.application.WorkbenchAdvisor#initialize(org.eclipse.ui.application.IWorkbenchConfigurer) 
             4.      
          */  
             
          5.     public void initialize(IWorkbenchConfigurer configurer) {  
             
          6.         PlatformUI.getPreferenceStore().setDefault(  
             
          7.             IWorkbenchPreferenceConstants.SHOW_PROGRESS_ON_STARTUP, true);  
             
          8.         PlatformUI.getPreferenceStore().setDefault(  
             
          9.             IWorkbenchPreferenceConstants.SHOW_TRADITIONAL_STYLE_TABS, false);  
            
          10.     }  
            
          11. } 

          1. SHOW_PROGRESS_ON_STARTUP           在splash的畫面中, 是否顯示進度條
          2. DISABLE_NEW_FAST_VIEW                   是否禁止左下角的Show View As a Fast View按鈕
          3. SHOW_MEMORY_MONITOR                    是否顯示內存情況, 并可進行GC操作, 這個比較有意思
          4. SHOW_OPEN_ON_PERSPECTIVE_BAR    在PerspectiveBar上,是否顯示New Perspective按鈕
          5. SHOW_TEXT_ON_PERSPECTIVE_BAR     在PerspectiveBar上,是否顯示Perspective的名稱
          6. SHOW_TRADITIONAL_STYLE_TABS         Editor或ViewPart是否使用傳統的Tab的樣式. 這個肯定用true, false的太老土了.
          7. DOCK_PERSPECTIVE_BAR                      PerspectiveBar的顯示位置, 左上 還是 右上.



          posted @ 2009-10-14 15:13 單飛 閱讀(417) | 評論 (0)編輯 收藏

          僅列出標題
          共12頁: 上一頁 1 2 3 4 5 6 7 8 9 下一頁 Last 
          主站蜘蛛池模板: 青岛市| 定南县| 宜章县| 南投县| 海安县| 扶余县| 广平县| 阿瓦提县| 巧家县| 迁安市| 靖远县| 墨脱县| 三明市| 克拉玛依市| 柏乡县| 营山县| 蛟河市| 犍为县| 闸北区| 南漳县| 双辽市| 陆丰市| 张掖市| 郓城县| 吴堡县| 望都县| 徐汇区| 苏州市| 铜陵市| 桂东县| 清新县| 义马市| 银川市| 隆德县| 观塘区| 五华县| 高唐县| 库伦旗| 陵水| 永川市| 永春县|