Sun River
          Topics about Java SE, Servlet/JSP, JDBC, MultiThread, UML, Design Pattern, CSS, JavaScript, Maven, JBoss, Tomcat, ...
          posts - 78,comments - 0,trackbacks - 0
           

          1. How someone can define that a method should be execute inside read-only transaction semantics?

            A

          It is not possible

            B

          No special action should be taken, default transaction semantics is read-only

            C

          It is possible using the following snippet:
          <tx:methodname="some-method"semantics="read-only"/>

          D

          It is possible using the following snippet:
          <tx:methodname="some-method"read-only="true"/>  

          explanation

          Default semantics in Spring is read/write, and someone should use read-only attribute to define read-only semantics for the method.

          2.      What is the correct way to execute some code inside transaction using programmatic transaction management?

           A

          Extend TransactionTemplate class and put all the code inside execute() method.

            B

          Implement class containing business code inside the method. Inject this class into TransactionManager.

          C

          Extend TransactionCallback class. Put all the code inside doInTransaction() method. Pass the object of created class as parameter to transactionTemplate.execute() method. 

            D

          Extend TransactionCallback class. Put all the code inside doInTransaction() method. Create the instance of TransactionCallback, call transactionCallback.doInTransaction method and pass TransactionManager as a parameter.

          3. Select all statements that are correct.

          Spring provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO.

          The Spring Framework supports declarative transaction management.

          Spring provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA.

          The transaction management integrates very well with Spring's various data access abstractions.

          4. Does this method guarantee that all of its invocations will process data with ISOLATION_SERIALIZABLE?
          Assume
          txManager to be valid and only existing PlatformTransactionManager .
          publicvoid query(){
                 DefaultTransactionDefinition txDef =newDefaultTransactionDefinition();
                 txDef.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
                 txDef.setReadOnly(true);
                 txDef.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
                 TransactionStatus txStat = txManager.getTransaction(txDef);
                 // ...
                 txManager.commit(txStat);
          }

          explanation

          If this method executes within an existing transaction context, it's isolation level will reflect the existing isolation level. For example JDBC does not specify what happens when one tries to change isolation level during existing transaction. PROPAGATION_REQUIRES_NEW will assure that transaction isolation is set to serializable.

          5. You would like to implement class with programmatic transaction management.
          How can you get TransactionTemplate instance?

          It is necessary to implement a certain interface in this class and then use getTransactionTemplate() call.

           

          It is possible to declare TransactionTemplate object in configuration file and inject it in this class.

          It is possible to declare PlatformTransactionManager object in configuration file, inject the manager in this class and then create TransactionTemplate like
          TransactionTemplate transactionTemplate =newTransactionTemplate(platformTransactionManager);

          It's possible to inject either PlatformTransactionManager or TransactionTemplate in this class.
          Option one is obviously wrong.

          6. Check the correct default values for the @Transactional annotation.

          PROPAGATION_REQUIRED

          The isolation level defaults to the default level of the underlying transaction system.

          readOnly="true"

           

          Only the Runtime Exceptions will trigger rollback.

          The transaction timeout defaults to the default timeout of the underlying transaction system, or none if timeouts are not supported.

          7. To make a method transactional in a concrete class it's enough to use @Transactional annotation before the method name (in Java >=5.0).

          correct answer

          FALSE

          explanation

          No, @Transactional annotation only marks a method as transactional. To make it transactional it is necessary to include the <tx:annotation-driven/> element in XML configuration file.

          8. The JtaTransactionManager allows us to use distributed transactions. (t)
          posted @ 2007-12-01 15:20 Sun River| 編輯 收藏
          現(xiàn)在JDK1.4里終于有了自己的正則表達式API包,JAVA程序員可以免去找第三方提供的正則表達式庫的周折了,我們現(xiàn)在就馬上來了解一下這個SUN提供的遲來恩物- -對我來說確實如此。
          1.簡介:
          java.util.regex是一個用正則表達式所訂制的模式來對字符串進行匹配工作的類庫包。

          它包括兩個類:Pattern和Matcher Pattern 一個Pattern是一個正則表達式經(jīng)編譯后的表現(xiàn)模式。
          Matcher 一個Matcher對象是一個狀態(tài)機器,它依據(jù)Pattern對象做為匹配模式對字符串展開匹配檢查。


          首先一個Pattern實例訂制了一個所用語法與PERL的類似的正則表達式經(jīng)編譯后的模式,然后一個Matcher實例在這個給定的Pattern實例的模式控制下進行字符串的匹配工作。

          以下我們就分別來看看這兩個類:

          2.Pattern類:
          Pattern的方法如下: static Pattern compile(String regex)
          將給定的正則表達式編譯并賦予給Pattern類
          static Pattern compile(String regex, int flags)
          同上,但增加flag參數(shù)的指定,可選的flag參數(shù)包括:CASE INSENSITIVE,MULTILINE,DOTALL,UNICODE CASE, CANON EQ
          int flags()
          返回當(dāng)前Pattern的匹配flag參數(shù).
          Matcher matcher(CharSequence input)
          生成一個給定命名的Matcher對象
          static boolean matches(String regex, CharSequence input)
          編譯給定的正則表達式并且對輸入的字串以該正則表達式為模開展匹配,該方法適合于該正則表達式只會使用一次的情況,也就是只進行一次匹配工作,因為這種情況下并不需要生成一個Matcher實例。
          String pattern()
          返回該Patter對象所編譯的正則表達式。
          String[] split(CharSequence input)
          將目標(biāo)字符串按照Pattern里所包含的正則表達式為模進行分割。
          String[] split(CharSequence input, int limit)
          作用同上,增加參數(shù)limit目的在于要指定分割的段數(shù),如將limi設(shè)為2,那么目標(biāo)字符串將根據(jù)正則表達式分為割為兩段。


          一個正則表達式,也就是一串有特定意義的字符,必須首先要編譯成為一個Pattern類的實例,這個Pattern對象將會使用matcher()方法來 生成一個Matcher實例,接著便可以使用該 Matcher實例以編譯的正則表達式為基礎(chǔ)對目標(biāo)字符串進行匹配工作,多個Matcher是可以共用一個Pattern對象的。

          現(xiàn)在我們先來看一個簡單的例子,再通過分析它來了解怎樣生成一個Pattern對象并且編譯一個正則表達式,最后根據(jù)這個正則表達式將目標(biāo)字符串進行分割:
          import java.util.regex.*;
          public class Replacement{
          public static void main(String[] args) throws Exception {
          // 生成一個Pattern,同時編譯一個正則表達式
          Pattern p = Pattern.compile("[/]+");
          //用Pattern的split()方法把字符串按"/"分割
          String[] result = p.split(
          "Kevin has seen《LEON》seveal times,because it is a good film."
          +"/ 凱文已經(jīng)看過《這個殺手不太冷》幾次了,因為它是一部"
          +"好電影。/名詞:凱文。");
          for (int i=0; i
          System.out.println(result[i]);
          }
          }



          輸出結(jié)果為:

          Kevin has seen《LEON》seveal times,because it is a good film.
          凱文已經(jīng)看過《這個殺手不太冷》幾次了,因為它是一部好電影。
          名詞:凱文。

          很明顯,該程序?qū)⒆址?/"進行了分段,我們以下再使用 split(CharSequence input, int limit)方法來指定分段的段數(shù),程序改動為:
          tring[] result = p.split("Kevin has seen《LEON》seveal times,because it is a good film./ 凱文已經(jīng)看過《這個殺手不太冷》幾次了,因為它是一部好電影。/名詞:凱文。",2);

          這里面的參數(shù)"2"表明將目標(biāo)語句分為兩段。

          輸出結(jié)果則為:

          Kevin has seen《LEON》seveal times,because it is a good film.
          凱文已經(jīng)看過《這個殺手不太冷》幾次了,因為它是一部好電影。/名詞:凱文。

          由上面的例子,我們可以比較出java.util.regex包在構(gòu)造Pattern對象以及編譯指定的正則表達式的實現(xiàn)手法與我們在上一篇中所介紹的 Jakarta-ORO 包在完成同樣工作時的差別,Jakarta-ORO 包要先構(gòu)造一個PatternCompiler類對象接著生成一個Pattern對象,再將正則表達式用該PatternCompiler類的 compile()方法來將所需的正則表達式編譯賦予Pattern類:

          PatternCompiler orocom=new Perl5Compiler();

          Pattern pattern=orocom.compile("REGULAR EXPRESSIONS");

          PatternMatcher matcher=new Perl5Matcher();

          但是在java.util.regex包里,我們僅需生成一個Pattern類,直接使用它的compile()方法就可以達到同樣的效果:
          Pattern p = Pattern.compile("[/]+");

          因此似乎java.util.regex的構(gòu)造法比Jakarta-ORO更為簡潔并容易理解。

          3.Matcher類:
          Matcher方法如下: Matcher appendReplacement(StringBuffer sb, String replacement)
          將當(dāng)前匹配子串替換為指定字符串,并且將替換后的子串以及其之前到上次匹配子串之后的字符串段添加到一個StringBuffer對象里。
          StringBuffer appendTail(StringBuffer sb)
          將最后一次匹配工作后剩余的字符串添加到一個StringBuffer對象里。
          int end()
          返回當(dāng)前匹配的子串的最后一個字符在原目標(biāo)字符串中的索引位置 。
          int end(int group)
          返回與匹配模式里指定的組相匹配的子串最后一個字符的位置。
          boolean find()
          嘗試在目標(biāo)字符串里查找下一個匹配子串。
          boolean find(int start)
          重設(shè)Matcher對象,并且嘗試在目標(biāo)字符串里從指定的位置開始查找下一個匹配的子串。
          String group()
          返回當(dāng)前查找而獲得的與組匹配的所有子串內(nèi)容
          String group(int group)
          返回當(dāng)前查找而獲得的與指定的組匹配的子串內(nèi)容
          int groupCount()
          返回當(dāng)前查找所獲得的匹配組的數(shù)量。
          boolean lookingAt()
          檢測目標(biāo)字符串是否以匹配的子串起始。
          boolean matches()
          嘗試對整個目標(biāo)字符展開匹配檢測,也就是只有整個目標(biāo)字符串完全匹配時才返回真值。
          Pattern pattern()
          返回該Matcher對象的現(xiàn)有匹配模式,也就是對應(yīng)的Pattern 對象。
          String replaceAll(String replacement)
          將目標(biāo)字符串里與既有模式相匹配的子串全部替換為指定的字符串。
          String replaceFirst(String replacement)
          將目標(biāo)字符串里第一個與既有模式相匹配的子串替換為指定的字符串。
          Matcher reset()
          重設(shè)該Matcher對象。
          Matcher reset(CharSequence input)
          重設(shè)該Matcher對象并且指定一個新的目標(biāo)字符串。
          int start()
          返回當(dāng)前查找所獲子串的開始字符在原目標(biāo)字符串中的位置。
          int start(int group)
          返回當(dāng)前查找所獲得的和指定組匹配的子串的第一個字符在原目標(biāo)字符串中的位置。


          (光看方法的解釋是不是很不好理解?不要急,待會結(jié)合例子就比較容易明白了)

          一個Matcher實例是被用來對目標(biāo)字符串進行基于既有模式(也就是一個給定的Pattern所編譯的正則表達式)進行匹配查找的,所有往 Matcher的輸入都是通過CharSequence接口提供的,這樣做的目的在于可以支持對從多元化的數(shù)據(jù)源所提供的數(shù)據(jù)進行匹配工作。

          我們分別來看看各方法的使用:

          ★matches()/lookingAt ()/find():
          一個Matcher對象是由一個Pattern對象調(diào)用其matcher()方法而生成的,一旦該Matcher對象生成,它就可以進行三種不同的匹配查找操作:

          matches()方法嘗試對整個目標(biāo)字符展開匹配檢測,也就是只有整個目標(biāo)字符串完全匹配時才返回真值。
          lookingAt ()方法將檢測目標(biāo)字符串是否以匹配的子串起始。
          find()方法嘗試在目標(biāo)字符串里查找下一個匹配子串。

          以上三個方法都將返回一個布爾值來表明成功與否。

          ★replaceAll ()/appendReplacement()/appendTail():
          Matcher類同時提供了四個將匹配子串替換成指定字符串的方法:

          replaceAll()
          replaceFirst()
          appendReplacement()
          appendTail()

          replaceAll()與replaceFirst()的用法都比較簡單,請看上面方法的解釋。我們主要重點了解一下appendReplacement()和appendTail()方法。

          appendReplacement(StringBuffer sb, String replacement) 將當(dāng)前匹配子串替換為指定字符串,并且將替換后的子串以及其之前到上次匹配子串之后的字符串段添加到一個StringBuffer對象里,而 appendTail(StringBuffer sb) 方法則將最后一次匹配工作后剩余的字符串添加到一個StringBuffer對象里。

          例如,有字符串fatcatfatcatfat,假設(shè)既有正則表達式模式為"cat",第一次匹配后調(diào)用appendReplacement(sb, "dog"),那么這時StringBuffer sb的內(nèi)容為fatdog,也就是fatcat中的cat被替換為dog并且與匹配子串前的內(nèi)容加到sb里,而第二次匹配后調(diào)用 appendReplacement(sb,"dog"),那么sb的內(nèi)容就變?yōu)閒atdogfatdog,如果最后再調(diào)用一次appendTail (sb),那么sb最終的內(nèi)容將是fatdogfatdogfat。

          還是有點模糊?那么我們來看個簡單的程序:
          //該例將把句子里的"Kelvin"改為"Kevin"
          import java.util.regex.*;
          public class MatcherTest{
          public static void main(String[] args)
          throws Exception {
          //生成Pattern對象并且編譯一個簡單的正則表達式"Kelvin"
          Pattern p = Pattern.compile("Kevin");
          //用Pattern類的matcher()方法生成一個Matcher對象
          Matcher m = p.matcher("Kelvin Li and Kelvin Chan are both working in Kelvin Chens KelvinSoftShop company");
          StringBuffer sb = new StringBuffer();
          int i=0;
          //使用find()方法查找第一個匹配的對象
          boolean result = m.find();
          //使用循環(huán)將句子里所有的kelvin找出并替換再將內(nèi)容加到sb里
          while(result) {
          i++;
          m.appendReplacement(sb, "Kevin");
          System.out.println("第"+i+"次匹配后sb的內(nèi)容是:"+sb);
          //繼續(xù)查找下一個匹配對象
          result = m.find();
          }
          //最后調(diào)用appendTail()方法將最后一次匹配后的剩余字符串加到sb里;
          m.appendTail(sb);
          System.out.println("調(diào)用m.appendTail(sb)后sb的最終內(nèi)容是:"+ sb.toString());
          }
          }


          最終輸出結(jié)果為:
          第1次匹配后sb的內(nèi)容是:Kevin
          第2次匹配后sb的內(nèi)容是:Kevin Li and Kevin
          第3次匹配后sb的內(nèi)容是:Kevin Li and Kevin Chan are both working in Kevin
          第4次匹配后sb的內(nèi)容是:Kevin Li and Kevin Chan are both working in Kevin Chens Kevin
          調(diào)用m.appendTail(sb)后sb的最終內(nèi)容是:Kevin Li and Kevin Chan are both working in Kevin Chens KevinSoftShop company.

          看了上面這個例程是否對appendReplacement(),appendTail()兩個方法的使用更清楚呢,如果還是不太肯定最好自己動手寫幾行代碼測試一下。

          ★group()/group(int group)/groupCount():
          該系列方法與我們在上篇介紹的Jakarta-ORO中的MatchResult .group()方法類似(有關(guān)Jakarta-ORO請參考上篇的內(nèi)容),都是要返回與組匹配的子串內(nèi)容,下面代碼將很好解釋其用法:
          import java.util.regex.*;

          public class GroupTest{
          public static void main(String[] args)
          throws Exception {
          Pattern p = Pattern.compile("(ca)(t)");
          Matcher m = p.matcher("one cat,two cats in the yard");
          StringBuffer sb = new StringBuffer();
          boolean result = m.find();
          System.out.println("該次查找獲得匹配組的數(shù)量為:"+m.groupCount());
          for(int i=1;i<=m
          }
          }


          輸出為:
          該次查找獲得匹配組的數(shù)量為:2
          第1組的子串內(nèi)容為:ca
          第2組的子串內(nèi)容為:t

          Matcher對象的其他方法因比較好理解且由于篇幅有限,請讀者自己編程驗證。

          4.一個檢驗Email地址的小程序:
          最后我們來看一個檢驗Email地址的例程,該程序是用來檢驗一個輸入的EMAIL地址里所包含的字符是否合法,雖然這不是一個完整的EMAIL地址檢驗程序,它不能檢驗所有可能出現(xiàn)的情況,但在必要時您可以在其基礎(chǔ)上增加所需功能。
          import java.util.regex.*;
          public class Email {
          public static void main(String[] args) throws Exception {
          String input = args[0];
          //檢測輸入的EMAIL地址是否以 非法符號"."或"@"作為起始字符
          Pattern p = Pattern.compile("^.|^@");
          Matcher m = p.matcher(input);
          if (m
          //檢測是否以"www."為起始
          p = Pattern.compile("^www.");
          m = p.matcher(input);
          if (m
          //檢測是否包含非法字符
          p = Pattern.compile("[^A-Za-z0-9.@_-~#]+");
          m = p.matcher(input);
          StringBuffer sb = new StringBuffer();
          boolean result = m.find();
          boolean deletedIllegalChars = false;
          while(result) {
          //如果找到了非法字符那么就設(shè)下標(biāo)記
          deletedIllegalChars = true;
          //如果里面包含非法字符如冒號雙引號等,那么就把他們消去,加到SB里面
          m.appendReplacement(sb, "");
          result = m.find();
          }
          m.appendTail(sb);
          input = sb.toString();
          if (deletedIllegalChars) {
          System.out.println("輸入的EMAIL地址里包含有冒號、逗號等非法字符,請修改");
          System.out.println("您現(xiàn)在的輸入為: "+args[0]);
          System.out.println("修改后合法的地址應(yīng)類似: "+input);
          }
          }
          }


          例如,我們在命令行輸入:java Email www.kevin@163.net

          那么輸出結(jié)果將會是:EMAIL地址不能以www.起始

          如果輸入的EMAIL為@kevin@163.net

          則輸出為:EMAIL地址不能以.或@作為起始字符

          當(dāng)輸入為:cgjmail#$%@163.net

          那么輸出就是:

          輸入的EMAIL地址里包含有冒號、逗號等非法字符,請修改
          您現(xiàn)在的輸入為: cgjmail#$%@163.net
          修改后合法的地址應(yīng)類似: cgjmail@163.net

          5.總結(jié):
          本文介紹了jdk1.4.0-beta3里正則表達式庫--java.util.regex中的類以及其方法,如果結(jié)合與上一篇中所介紹的Jakarta -ORO API作比較,讀者會更容易掌握該API的使用,當(dāng)然該庫的性能將在未來的日子里不斷擴展,希望獲得最新信息的讀者最好到及時到SUN的網(wǎng)站去了解。

          6.結(jié)束語:
          本來計劃再多寫一篇介紹一下需付費的正則表達式庫中較具代表性的作品,但覺得既然有了免費且優(yōu)秀的正則表達式庫可以使用,何必還要去找需付費的呢,相信很 多讀者也是這么想的:,所以有興趣了解更多其他的第三方正則表達式庫的朋友可以自己到網(wǎng)上查找或者到我在參考資料里提供的網(wǎng)址去看看。
          posted @ 2007-08-09 12:43 Sun River| 編輯 收藏
          POI
          Example One:創(chuàng)建XLS

          群眾:笑死人了,這還要你教么,別丟人現(xiàn)眼了,用FileOutputStream就可以了,寫個文件,擴展名為xls就可以了,哈哈,都懶得看你的,估計又是個水貨上來瞎喊,下去,喲貨~~

          小筆:無聊的人一邊去,懶得教你,都沒試過,還雞叫雞叫,&^%&**(()&%$#$#@#@


              HSSFWorkbook wb = new HSSFWorkbook();//構(gòu)建新的XLS文檔對象
              FileOutputStream fileOut = new FileOutputStream("workbook.xls");
              wb.write(fileOut);//注意,參數(shù)是文件輸出流對象
              fileOut.close();



          Example Two:創(chuàng)建Sheet

          群眾:有點責(zé)任心好吧,什么是Sheet?欺負我們啊?

          小筆:花300塊去參加Office 培訓(xùn)班去,我不負責(zé)教預(yù)科


             HSSFWorkbook wb = new HSSFWorkbook();//創(chuàng)建文檔對象
              HSSFSheet sheet1 = wb.createSheet("new sheet");//創(chuàng)建Sheet對象,參數(shù)為Sheet的標(biāo)題
              HSSFSheet sheet2 = wb.createSheet("second sheet");//同上,注意,同是wb對象,是一個XLS的兩個Sheet
              FileOutputStream fileOut = new FileOutputStream("workbook.xls");
              wb.write(fileOut);
              fileOut.close();


          Example Three:創(chuàng)建小表格,并為之填上數(shù)據(jù)

          群眾:什么是小表格啊?

          小筆:你用過Excel嗎?人家E哥天天都穿的是網(wǎng)格襯衫~~~~


                            HSSFWorkbook document = new HSSFWorkbook();//創(chuàng)建XLS文檔

          HSSFSheet salary = document.createSheet("薪水");//創(chuàng)建Sheet

          HSSFRow titleRow = salary.createRow(0);//創(chuàng)建本Sheet的第一行



          titleRow.createCell((short) 0).setCellValue("工號");//設(shè)置第一行第一列的值
          titleRow.createCell((short) 1).setCellValue("薪水");//......
          titleRow.createCell((short) 2).setCellValue("金額");//設(shè)置第一行第二列的值


          File filePath = new File(baseDir+"excel/example/");

          if(!filePath.exists())
          filePath.mkdirs();

          FileOutputStream fileSystem = new FileOutputStream(filePath.getAbsolutePath()+"/Three.xls");

          document.write(fileSystem);

          fileSystem.close();

           

          Example Four :帶自定義樣式的數(shù)據(jù)(eg:Date)

          群眾:Date!么搞錯,我昨天已經(jīng)插入成功了~

          小筆:是么?那我如果要你5/7/06 4:23這樣輸出你咋搞?

          群眾:無聊么?能寫進去就行了!

          小筆:一邊涼快去~


                            HSSFWorkbook document = new HSSFWorkbook();

          HSSFSheet sheet = document.createSheet("日期格式");

          HSSFRow row = sheet.createRow(0);


          HSSFCell secondCell = row.createCell((short) 0);

          /**
           * 創(chuàng)建表格樣式對象
           */
          HSSFCellStyle style = document.createCellStyle();

          /**
           * 定義數(shù)據(jù)顯示格式
           */
          style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));

          /**
           * setter
           */
          secondCell.setCellValue(new Date());

          /**
           * 設(shè)置樣式
           */
          secondCell.setCellStyle(style);



          File filePath = new File(baseDir+"excel/example/");

          if(!filePath.exists())
          filePath.mkdirs();

          FileOutputStream fileSystem = new FileOutputStream(filePath.getAbsolutePath()+"/Four.xls");

          document.write(fileSystem);

          fileSystem.close();

          Example Five:讀取XLS文檔


          File filePath = new File(baseDir+"excel/example/");

          if(!filePath.exists())
          throw new Exception("沒有該文件");
          /**
           * 創(chuàng)建對XLS進行讀取的流對象
           */
          POIFSFileSystem reader = new POIFSFileSystem(new FileInputStream(filePath.getAbsolutePath()+"/Three.xls"));
          /**
           * 從流對象中分離出文檔對象
           */
          HSSFWorkbook document = new HSSFWorkbook(reader);
          /**
           * 通過文檔對象獲取Sheet
           */
          HSSFSheet sheet = document.getSheetAt(0);
          /**
           * 通過Sheet獲取指定行對象
           */
          HSSFRow row = sheet.getRow(0);
          /**
           * 通過行、列定位Cell
           */
          HSSFCell cell = row.getCell((short) 0);

          /**
           * 輸出表格數(shù)據(jù)
           */
          log.info(cell.getStringCellValue());


          至此,使用POI操作Excel的介紹告一段落,POI是一個仍然在不斷改善的項目,有很多問題,比如說中文問題,大數(shù)據(jù)量內(nèi)存溢出問題等等,但這個Pure Java的庫的性能仍然是不容質(zhì)疑的,是居家旅行必備良品。

          而且開源軟件有那么一大點好處是,可以根據(jù)自己的需要自己去定制。如果大家有中文、性能等問題沒解決的,可以跟我索要我已經(jīng)改好的庫。當(dāng)然,你要自己看原代碼,我也不攔你。


          posted @ 2007-08-09 12:37 Sun River| 編輯 收藏
               摘要:   如何將JSP中將查詢結(jié)果導(dǎo)出為Excel,其實可以利用jakarta提供的POI接口將查詢結(jié)果導(dǎo)出到excel。POI接口是jakarta組織的一個子項目,它包括POIFS,HSSF,HWSF,HPSF,HSLF,目前比較成熟的是HSSF,它是一組操作微軟的excel文檔的API,現(xiàn)在到達3.0版本,已經(jīng)能夠支持將圖片插入到excel里面。java 代碼 import ...  閱讀全文
          posted @ 2007-08-09 12:26 Sun River| 編輯 收藏

          Populating Value Objects from ActionForms

          Problem

          You don't want to have to write numerous getters and setters to pass data from your action forms to your business objects.

          Solution

          Use the introspection utilities provided by the Jakarta Commons BeanUtils package in your Action.execute( ) method:

          import org.apache.commons.beanutils.*;
          // other imports omitted
          public ActionForward execute(ActionMapping mapping,
          ActionForm form,
          HttpServletRequest request,
          HttpServletResponse response) throws Exception {
          BusinessBean businessBean = new BusinessBean( );
          BeanUtils.copyProperties(businessBean, form);
          // ... rest of the Action

          Discussion

          A significant portion of the development effort for a web application is spent moving data to and from the different system tiers. Along the way, the data may be transformed in one way or another, yet many of these transformations are required because the tier to which the data is moving requires the information to be represented in a different way.

          Data sent in the HTTP request is represented as simple text. For some data types, the value can be represented as a String object throughout the application. However, many data types should be represented in a different format in the business layer than on the view. Date fields provide the classic example. A date field is retrieved from a form's input field as a String. Then it must be converted to a java.util.Date in the model. Furthermore, when the value is persisted, it's usually transformed again, this time to a java.sql.Timestamp. Numeric fields require similar transformations.

          The Jakarta Commons BeanUtils package supplied with the Struts distribution provides some great utilities automating the movement and conversion of data between objects. These utilities use JavaBean property names to match the source property to the destination property for data transfer. To leverage these utilities, ensure you give your properties consistent, meaningful names. For example, to represent an employee ID number, you may decide to use the property name employeeId. In all classes that contain an employee ID, you should use that name. Using empId in one class and employeeIdentifier in another will only lead to confusion among your developers and will render the BeanUtils facilities useless.

          The entire conversion and copying of properties from ActionForm to business object can be performed with one static method call:

          BeanUtils.copyProperties(
          businessBean
          , 
          form
          );

          This copyProperties( ) method attempts to copy each JavaBean property in form to the property with the same name in businessBean. If a property in form doesn't have a matching property in businessBean, that property is silently ignored. If the data types of the matched properties are different, BeanUtils will attempt to convert the value to the type expected. BeanUtils provides converters from Strings to the following types:

          • java.lang.BigDecimal

          • java.lang.BigInteger

          • boolean and java.lang.Boolean

          • byte and java.lang.Byte

          • char and java.lang.Character

          • java.lang.Class

          • double and java.lang.Double

          • float and java.lang.Float

          • int and java.lang.Integer

          • long and java.lang.Long

          • short and java.lang.Short

          • java.lang.String

          • java.sql.Date

          • java.sql.Time

          • java.sql.Timestamp

          While the conversions to character-based and numeric types should cover most of your needs, date type fields (as shown in Recipe 3-13) can be problematic. A good solution suggested by Ted Husted is to implement transformation getter and setter methods in the business object that convert from the native type (e.g. java.util.Date) to a String and back again.

          Because BeanUtils knows how to handle DynaBeans and the DynaActionForm implements DynaBean, the Solution will work unchanged for DynaActionForms and normal ActionForms.


          As an example, suppose you want to collect information about an employee for a human resources application. Data to be gathered includes the employee ID, name, salary, marital status, and hire date. Example 5-9 shows the Employee business object. Most of the methods of this class are getters and setters; for the hireDate property, however, helper methods are provided that get and set the value from a String.

          Example 5-9. Employee business object
          package com.oreilly.strutsckbk.ch05;
          import java.math.BigDecimal;
          import java.text.DateFormat;
          import java.text.ParseException;
          import java.text.SimpleDateFormat;
          import java.util.Date;
          public class Employee {
          private String employeeId;
          private String firstName;
          private String lastName;
          private Date hireDate;
          private boolean married;
          private BigDecimal salary;
          public BigDecimal getSalary( ) {
          return salary;
          }
          public void setSalary(BigDecimal salary) {
          this.salary = salary;
          }
          public String getEmployeeId( ) {
          return employeeId;
          }
          public void setEmployeeId(String employeeId) {
          this.employeeId = employeeId;
          }
          public String getFirstName( ) {
          return firstName;
          }
          public void setFirstName(String firstName) {
          this.firstName = firstName;
          }
          public String getLastName( ) {
          return lastName;
          }
          public void setLastName(String lastName) {
          this.lastName = lastName;
          }
          public boolean isMarried( ) {
          return married;
          }
          public void setMarried(boolean married) {
          this.married = married;
          }
          public Date getHireDate( ) {
          return hireDate;
          }
          public void setHireDate(Date HireDate) {
          this.hireDate = HireDate;
          }
          public String getHireDateDisplay( ) {
          if (hireDate == null)
          return "";
          else
          return dateFormatter.format(hireDate);
          }
          public void setHireDateDisplay(String hireDateDisplay) {
          if (hireDateDisplay == null)
          hireDate = null;
          else {
          try {
          hireDate = dateFormatter.parse(hireDateDisplay);
          } catch (ParseException e) {
          e.printStackTrace( );
          }
          }
          }
          private DateFormat dateFormatter = new SimpleDateFormat("mm/DD/yy");
          }

          Example 5-10 shows the corresponding ActionForm that will retrieve the data from the HTML form. The hire date is represented in the ActionForm as a String property, hireDateDisplay. The salary property is a java.lang.String, not a java.math.BigDecimal, as in the Employee object of Example 5-9.

          Example 5-10. Employee ActionForm
          package com.oreilly.strutsckbk.ch05;
          import java.math.BigDecimal;
          import org.apache.struts.action.ActionForm;
          public class EmployeeForm extends ActionForm {
          private String firstName;
          private String lastName;
          private String hireDateDisplay;
          private String salary;
          private boolean married;
          public String getEmployeeId( ) {
          return employeeId;
          }
          public void setEmployeeId(String employeeId) {
          this.employeeId = employeeId;
          }
          public String getFirstName( ) {
          return firstName;
          }
          public void setFirstName(String firstName) {
          this.firstName = firstName;
          }
          public String getLastName( ) {
          return lastName;
          }
          public void setLastName(String lastName) {
          this.lastName = lastName;
          }
          public boolean isMarried( ) {
          return married;
          }
          public void setMarried(boolean married) {
          this.married = married;
          }
          public String getHireDateDisplay( ) {
          return hireDateDisplay;
          }
          public void setHireDateDisplay(String hireDate) {
          this.hireDateDisplay = hireDate;
          }
          public String getSalary( ) {
          return salary;
          }
          public void setSalary(String salary) {
          this.salary = salary;
          }
          }

          If you wanted to use a DynaActionForm, you would configure it identically as the EmployeeForm class. The form-bean declarations from the struts-config.xml file show the declarations for the EmployeeForm and a functionally identical DynaActionForm:

          <form-bean name="EmployeeForm"
          type="com.oreilly.strutsckbk.ch05.EmployeeForm"/>
          <form-bean name="EmployeeDynaForm"
          type="org.apache.struts.action.DynaActionForm">
          <form-property name="employeeId" type="java.lang.String"/>
          <form-property name="firstName" type="java.lang.String"/>
          <form-property name="lastName" type="java.lang.String"/>
          <form-property name="salary" type="java.lang.String"/>
          <form-property name="married" type="java.lang.Boolean"/>
          <form-property name="hireDateDisplay" type="java.lang.String"/>
          </form-bean>

          The following is the action mapping that processes the form. In this case, the name attribute refers to the handcoded EmployeeForm. You could, however, change this to use the EmployeeDynaForm without requiring any modifications to the SaveEmployeeAction or the view_emp.jsp JSP page:

          <action    path="/SaveEmployee"
          name="EmployeeForm"
          scope="request"
          type="com.oreilly.strutsckbk.ch05.SaveEmployeeAction">
          <forward name="success" path="/view_emp.jsp"/>
          </action>

          The data is converted and copied from the form to the business object in the SaveEmployeeAction shown in Example 5-11.

          Example 5-11. Action to save employee data
          package com.oreilly.strutsckbk.ch05;
          import javax.servlet.http.HttpServletRequest;
          import javax.servlet.http.HttpServletResponse;
          import org.apache.commons.beanutils.BeanUtils;
          import org.apache.struts.action.Action;
          import org.apache.struts.action.ActionForm;
          import org.apache.struts.action.ActionForward;
          import org.apache.struts.action.ActionMapping;
          public class SaveEmployeeAction extends Action {
          public ActionForward execute(ActionMapping mapping,
          ActionForm form,
          HttpServletRequest request,
          HttpServletResponse response)
          throws Exception {
          Employee emp = new Employee( );
          // Copy to business object from ActionForm
          BeanUtils.copyProperties( emp, form );
          request.setAttribute("employee", emp);
          return mapping.findForward("success");
          }
          }

          Finally, two JSP pages complete the example. The JSP of Example 5-12 (edit_emp.jsp) renders the HTML form to retrieve the data.

          Example 5-12. Form for editing employee data
          <%@ page contentType="text/html;charset=UTF-8" language="java" %>
          <%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix=
          "bean" %>
          <%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix=
          "html" %>
          <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
          <html>
          <head>
          <title>Struts Cookbook - Chapter 5 : Add Employee</title>
          </head>
          <body>
          <h2>Edit Employee</h2>
          <html:form action="/SaveEmployee">
          Employee ID: <html:text property="employeeId"/><br />
          First Name: <html:text property="firstName"/><br />
          Last Name: <html:text property="lastName"/><br />
          Married? <html:checkbox property="married"/><br />
          Hired on Date: <html:text property="hireDateDisplay"/><br />
          Salary: <html:text property="salary"/><br />
          <html:submit/>
          </html:form>
          </body>
          </html>

          The JSP in Example 5-13 (view_emp.jsp) displays the results. This page is rendering data from the business object, and not an ActionForm. This is acceptable since the data on this page is for display purposes only. This approach allows for the formatting of data, (salary and hireDate) to be different than the format in which the values were entered.

          Example 5-13. View of submitted employee data
          <%@ page contentType="text/html;charset=UTF-8" language="java" %>
          <%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix=
          "bean" %>
          <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
          <html>
          <head>
          <title>Struts Cookbook - Chapter 5 : View Employee</title>
          </head>
          <body>
          <h2>View Employee</h2>
          Employee ID: <bean:write name="employee" property="employeeId"/><br />
          First Name: <bean:write name="employee" property="firstName"/><br />
          Last Name: <bean:write name="employee" property="lastName"/><br />
          Married? <bean:write name="employee" property="married"/><br />
          Hired on Date: <bean:write name="employee" property="hireDate"
          format="MMMMM dd, yyyy"/><br />
          Salary: <bean:write name="employee" property="salary" format="$##0.00"/
          ><br />
          </body>
          </html>

          When you work with this example, swap out the handcoded form for the DyanActionForm to see how cleanly BeanUtils works. When you consider how many files need to be changed for one additional form input, the use of BeanUtils in conjunction with DynaActionForms becomes obvious.

          posted @ 2007-08-07 18:28 Sun River| 編輯 收藏
           

          2NF and 3NF

          The 2NF and 3NF are very similar--the 2NF deals with composite primary keys and the 3NF deals with single primary keys. In general, if you do an ER diagram, convert many-to-many relationships to entities, and then convert all entities to tables, then your tables will already be in 3NF form.

          Second normal form is violated when a non-key field is a fact about a subset of a key. It is only relevant when the key is composite, i.e., consists of several fields. Consider the following inventory record:

          ---------------------------------------------------
          | PART | WAREHOUSE | QUANTITY | WAREHOUSE-ADDRESS |
          ====================-------------------------------

          The key here consists of the PART and WAREHOUSE fields together, but WAREHOUSE-ADDRESS is a fact about the WAREHOUSE alone. The basic problems with this design are:

          • The warehouse address is repeated in every record that refers to a part stored in that warehouse.
          • If the address of the warehouse changes, every record referring to a part stored in that warehouse must be updated. Because of the redundancy, the data might become inconsistent, with different records showing different addresses for the same warehouse.
          • If at some point in time there are no parts stored in the warehouse, there may be no record in which to keep the warehouse's address.

          To satisfy second normal form, the record shown above should be decomposed into (replaced by) the two records:

          ------------------------------- --------------------------------- 
          | PART | WAREHOUSE | QUANTITY | | WAREHOUSE | WAREHOUSE-ADDRESS |
          ====================----------- =============--------------------
           

          The 3NF differs from the 2NF in that all non-key attributes in 3NF are required to be directly dependent on the primary key of the relation. The 3NF therefore insists that all facts in the relation are about the key (or the thing that the key identifies), the whole key and nothing but the key.

          Third normal form is violated when a non-key field is a fact about another non-key field, as in

          ------------------------------------
          | EMPLOYEE | DEPARTMENT | LOCATION |
          ============------------------------

          The EMPLOYEE field is the key. If each department is located in one place, then the LOCATION field is a fact about the DEPARTMENT -- in addition to being a fact about the EMPLOYEE. The problems with this design are the same as those caused by violations of second normal form:

          • The department's location is repeated in the record of every employee assigned to that department.
          • If the location of the department changes, every such record must be updated.
          • Because of the redundancy, the data might become inconsistent, with different records showing different locations for the same department.
          • If a department has no employees, there may be no record in which to keep the department's location.

          To satisfy third normal form, the record shown above should be decomposed into the two records:

          ------------------------- -------------------------
          | EMPLOYEE | DEPARTMENT | | DEPARTMENT | LOCATION |
          ============-------------  ==============-----------
           
          To summarize, a record is in second and third normal forms if every field is either part of the key or provides a (single-valued) fact about exactly the whole key and nothing else.

           

          posted @ 2007-07-20 00:51 Sun River| 編輯 收藏
          ---How do you submit a form using Javascript?
          Use document.forms[0].submit();
          (0 refers to the index of the form – if you have more than one form in a page, then the first one has the index 0, second has index 1 and so on).
          --

          How do we get JavaScript onto a web page?
          You can use several different methods of placing javascript in you pages.
          You can directly add a script element inside the body of page.
          1. For example, to add the "last updated line" to your pages, In your page text, add the following:
          <p>blah, blah, blah, blah, blah.</p>
          <script type="text/javascript" >
          <!-- Hiding from old browsers
          document.write("Last Updated:" +
          document.lastModified);
          document.close();
          // -->
          </script>
          <p>yada, yada, yada.</p>

          Security Tip

          Use Firefox instead of Internet Explorer and PREVENT Spyware !

          Firefox is free and is considered the best free, safe web browser available today
           
          Get Firefox with Google Toolbar for better browsing

          (Note: the first comment, "<--" hides the content of the script from browsers that don't understand javascript. The "http:// -->" finishes the comment. The "http://" tells javascript that this is a comment so javascript doesn't try to interpret the "-->". If your audience has much older browsers, you should put this comments inside your javascript. If most of your audience has newer browsers, the comments can be omitted. For brevity, in most examples here the comments are not shown. )
          The above code will look like this on Javascript enabled browsers,
          2. Javascript can be placed inside the <head> element
          Functions and global variables typically reside inside the <head> element.
          <head>
          <title>Default Test Page</title>
          <script language="JavaScript" type="text/javascript">
          var myVar = "";
          function timer(){setTimeout('restart()',10);}
          document.onload=timer();
          </script>
          </head>

          Javascript can be referenced from a separate file
          Javascript may also a placed in a separate file on the server and referenced from an HTML page. (Don't use the shorthand ending "<script ... />). These are typically placed in the <head> element.
          <script type="text/javascript" SRC="myStuff.js"></script>

          How to read and write a file using javascript?
          I/O operations like reading or writing a file is not possible with client-side javascript. However , this can be done by coding a Java applet that reads files for the script.

          ---What are JavaScript types?
          Number, String, Boolean, Function, Object, Null, Undefined.

          ---

          How do you convert numbers between different bases in JavaScript?
          Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt ("3F", 16);

          How to create arrays in JavaScript?
          We can declare an array like this
          var scripts = new Array();
          We can add elements to this array like this

          scripts[0] = "PHP";
          scripts[1] = "ASP";
          scripts[2] = "JavaScript";
          scripts[3] = "HTML";

          Now our array scrips has 4 elements inside it and we can print or access them by using their index number. Note that index number starts from 0. To get the third element of the array we have to use the index number 2 . Here is the way to get the third element of an array.
          document.write(scripts[2]);
          We also can create an array like this
          var no_array = new Array(21, 22, 23, 24, 25);

          How do you target a specific frame from a hyperlink?
          Include the name of the frame in the target attribute of the hyperlink. <a href=”mypage.htm” target=”myframe”>>My Page</a>

          What is a fixed-width table and its advantages?

          Security Issue

          Get Norton Security Scan and Spyware Doctor free for your Computer from Google.

          The Pack contains nearly 14 plus software . Pick the one which is suited for you Make your PC more useful. Get the free Google Pack.

          Fixed width tables are rendered by the browser based on the widths of the columns in the first row, resulting in a faster display in case of large tables. Use the CSS style table-layout:fixed to specify a fixed width table.
          If the table is not specified to be of fixed width, the browser has to wait till all data is downloaded and then infer the best width for each of the columns. This process can be very slow for large tables.

          Example of using Regular Expressions for syntax checking in JavaScript


          ...
          var re = new RegExp("^(&[A-Za-z_0-9]{1,}=[A-Za-z_0-9]{1,})*$");
          var text = myWidget.value;
          var OK = re.test(text);
          if( ! OK ) {
          alert("The extra parameters need some work.\r\n Should be something like: \"&a=1&c=4\"");
          }


          ---

          How to add Buttons in JavaScript?
          The most basic and ancient use of buttons are the "submit" and "clear", which appear slightly before the Pleistocene period. Notice when the "GO!" button is pressed it submits itself to itself and appends the name in the URL.
          <form action="" name="buttonsGalore" method="get">
          Your Name: <input type="text" name="mytext" />
          <br />
          <input type="submit" value="GO!" />
          <input type="reset" value="Clear All" />
          </form>

          Another useful approach is to set the "type" to "button" and use the "onclick" event.
          <script type="text/javascript">
          function displayHero(button) {
          alert("Your hero is \""+button.value+"\".");
          }
          </script>

          <form action="" name="buttonsGalore" method="get">
          <fieldset style="margin: 1em; text-align: center;">
          <legend>Select a Hero</legend>
          <input type="button" value="Agamemnon" onclick="displayHero(this)" />
          <input type="button" value="Achilles" onclick="displayHero(this)" />
          <input type="button" value="Hector" onclick="displayHero(this)" />
          <div style="height: 1em;" />
          </fieldset>
          </form>

          What can javascript programs do?
          Generation of HTML pages on-the-fly without accessing the Web server. The user can be given control over the browser like User input validation Simple computations can be performed on the client's machine The user's browser, OS, screen size, etc. can be detected Date and Time Handling

          How to set a HTML document's background color?
          document.bgcolor property can be set to any appropriate color.
          ---

          How to get the contents of an input box using Javascript?
          Use the "value" property.
          var myValue = window.document.getElementById("MyTextBox").value;

          How to determine the state of a checkbox using Javascript?
          var checkedP = window.document.getElementById("myCheckBox").checked;

          How to set the focus in an element using Javascript?
          <script> function setFocus() { if(focusElement != null) { document.forms[0].elements["myelementname"].focus(); } } </script>

          How to access an external javascript file that is stored externally and not embedded?
          This can be achieved by using the following tag between head tags or between body tags.
          <script src="abc.js"></script>How to access an external javascript file that is stored externally and not embedded? where abc.js is the external javscript file to be accessed.

          What is the difference between an alert box and a confirmation box?
          An alert box displays only one button which is the OK button whereas the Confirm box displays two buttons namely OK and cancel.

          What is a prompt box?
          A prompt box allows the user to enter input by providing a text box.

          Can javascript code be broken in different lines?
          Breaking is possible within a string statement by using a backslash \ at the end but not within any other javascript statement.
          that is ,
          document.write("Hello \ world");
          is possible but not document.write \
          ("hello world");

          Taking a developer’s perspective, do you think that that JavaScript is easy to learn and use?
          One of the reasons JavaScript has the word "script" in it is that as a programming language, the vocabulary of the core language is compact compared to full-fledged programming languages. If you already program in Java or C, you actually have to unlearn some concepts that had been beaten into you. For example, JavaScript is a loosely typed language, which means that a variable doesn't care if it's holding a string, a number, or a reference to an object; the same variable can even change what type of data it holds while a script runs.
          The other part of JavaScript implementation in browsers that makes it easier to learn is that most of the objects you script are pre-defined for the author, and they largely represent physical things you can see on a page: a text box, an image, and so on. It's easier to say, "OK, these are the things I'm working with and I'll use scripting to make them do such and such," instead of having to dream up the user interface, conceive of and code objects, and handle the interaction between objects and users. With scripting, you tend to write a _lot_ less code.

          What Web sites do you feel use JavaScript most effectively (i.e., best-in-class examples)? The worst?
          The best sites are the ones that use JavaScript so transparently, that I'm not aware that there is any scripting on the page. The worst sites are those that try to impress me with how much scripting is on the page.

          How about 2+5+"8"?
          Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, it’s concatenation, so 78 is the result.

          What is the difference between SessionState and ViewState?
          ViewState is specific to a page in a session. Session state refers to user specific data that can be accessed across all pages in the web application.

          What does the EnableViewStateMac setting in an aspx page do?
          Setting EnableViewStateMac=true is a security measure that allows ASP.NET to ensure that the viewstate for a page has not been tampered with. If on Postback, the ASP.NET framework detects that there has been a change in the value of viewstate that was sent to the browser, it raises an error - Validation of viewstate MAC failed.
          Use <%@ Page EnableViewStateMac="true"%> to set it to true (the default value, if this attribute is not specified is also true) in an aspx page.


          ---
          posted @ 2007-07-13 05:52 Sun River| 編輯 收藏
          --What is the difference between Session bean and Entity bean ?
          The Session bean and Entity bean are two main parts of EJB container.
          Session Bean
          --represents a workflow on behalf of a client
          --one-to-one logical mapping to a client.
          --created and destroyed by a client
          --not permanent objects
          --lives its EJB container(generally) does not survive system shut down
          --two types: stateless and stateful beans
          Entity Bean
          --represents persistent data and behavior of this data
          --can be shared among multiple clients
          --persists across multiple invocations
          --findable permanent objects
          --outlives its EJB container, survives system shutdown
          --two types: container managed persistence(CMP) and bean managed persistence(BMP)

          --What is reentrant entity bean ?
          An entity bean that can handle multiple simultaneous, interleaved, or nested invocations that will not interfere with each other.
          --What is JMS session ?
          A single-threaded context for sending and receiving JMS messages. A JMS session can be nontransacted, locally transacted, or participating in a distributed transaction.
          ---Can you make use of a ServletOutputStream object from within a JSP page?
          No. You are supposed to make use of only a JSPWriter object (given to you in the form of the implicit object out) for replying to clients.
          A JSPWriter can be viewed as a buffered version of the stream object returned by response.getWriter(), although from an implementational perspective, it is not.

          ---What are the core JMS-related objects required for each JMS-enabled application?
          Each JMS-enabled client must establish the following:
          * A connection object provided by the JMS server (the message broker)
          * Within a connection, one or more sessions, which provide a context for message sending and receiving
          * Within a session, either a queue or topic object representing the destination (the message staging area) within the message broker
          * Within a session, the appropriate sender or publisher or receiver or subscriber object (depending on whether the client is a message producer or consumer and uses a point-to-point or publish/subscribe strategy, respectively). Within a session, a message object (to send or to receive)

          How does the Application server handle the JMS Connection?
          1. App server creates the server session and stores them in a pool.
          2. Connection consumer uses the server session to put messages in the session of the JMS.
          3. Server session is the one that spawns the JMS session.
          4. Applications written by Application programmers creates the message listener.

          What is Stream Message ?
          Stream messages are a group of java primitives. It contains some convenient methods for reading the data. However Stream Message prevents reading a long value as short. This is so because the Stream Message also writes the type information along with the value of the primitive type and enforces a set of strict conversion rules which actually prevents reading of one primitive type as another.
          --

          Why do the JMS dbms_aqadm.add_subscriber and dbms_aqadm.remove_subscriber calls sometimes hang when there are concurrent enqueues or dequeues happening on the same queue to which these calls are issued?
          Add_subscriber and remove_subscriber are administrative operations on a queue. Though AQ does not prevent applications from issuing administrative and operational calls concurrently, they are executed serially. Both add_subscriber and remove_subscriber will block until pending transactions that have enqueued or dequeued messages commit and release the resources they hold. It is expected that adding and removing subscribers will not be a frequent event. It will mostly be part of the setup for the application. The behavior you observe will be acceptable in most cases. The solution is to try to isolate the calls to add_subscriber and remove_subscriber at the setup or cleanup phase when there are no other operations happening on the queue. That will make sure that they will not stay blocked waiting for operational calls to release resources.

          Why do the TopicSession.createDurableSubscriber and TopicSession.unubscribe calls raise JMSException with the message "ORA - 4020 - deadlock detected while trying to lock object"?
          CreateDurableSubscriber and unsubscribe calls require exclusive access to the Topics. If there are pending JMS operations (send/publish/receive) on the same Topic before these calls are issued, the ORA - 4020 exception is raised.
          There are two solutions to the problem:
          1. Try to isolate the calls to createDurableSubscriber and unsubscribe at the setup or cleanup phase when there are no other JMS operations happening on the Topic. That will make sure that the required resources are not held by other JMS operational calls. Hence the error ORA - 4020 will not be raised.
          2. Issue a TopicSession.commit call before calling createDurableSubscriber and unsubscribe call.

          Why doesn't AQ_ADMINISTRATOR_ROLE or AQ_USER_ROLE always work for AQ applications using Java/JMS API?
          In addition to granting the roles, you would also need to grant execute to the user on the following packages:
          * grant execute on sys.dbms_aqin to <userid>
          * grant execute on sys.dbms_aqjms to <userid>

          Why do I get java.security.AccessControlException when using JMS MessageListeners from Java stored procedures inside Oracle8i JServer?
          To use MessageListeners inside Oracle8i JServer, you can do one for the following
          1. GRANT JAVASYSPRIV to <userid>

          Call dbms_java.grant_permission ('JAVASYSPRIV', 'SYS:java.net.SocketPermission', '*', 'accept,connect,listen,resolve');

          What is the use of ObjectMessage?
          ObjectMessage contains a Serializable java object as it's payload. Thus it allows exchange of Java objects between applications. This in itself mandates that both the applications be Java applications. The consumer of the message must typecast the object received to it's appropriate type. Thus the consumer should before hand know the actual type of the object sent by the sender. Wrong type casting would result in ClassCastException. Moreover the class definition of the object set in the payload should be available on both the machine, the sender as well as the consumer. If the class definition is not available in the consumer machine, an attempt to type cast would result in ClassNotFoundException. Some of the MOMs might support dynamic loading of the desired class over the network, but the JMS specification does not mandate this behavior and would be a value added service if provided by your vendor. And relying on any such vendor specific functionality would hamper the portability of your application. Most of the time the class need to be put in the classpath of both, the sender and the consumer, manually by the developer.

          What is the use of MapMessage?
          A MapMessage carries name-value pair as it's payload. Thus it's payload is similar to the java.util.Properties object of Java. The values can be Java primitives or their wrappers.

          What is the difference between BytesMessage and StreamMessage?
          BytesMessage stores the primitive data types by converting them to their byte representation. Thus the message is one contiguous stream of bytes. While the StreamMessage maintains a boundary between the different data types stored because it also stores the type information along with the value of the primitive being stored. BytesMessage allows data to be read using any type. Thus even if your payload contains a long value, you can invoke a method to read a short and it will return you something. It will not give you a semantically correct data but the call will succeed in reading the first two bytes of data. This is strictly prohibited in the StreamMessage. It maintains the type information of the data being stored and enforces strict conversion rules on the data being read.

          What is object message ?
          Object message contains a group of serializeable java object. So it allows exchange of Java objects between applications. sot both the applications must be Java applications.

          What is text message?
          Text messages contains String messages (since being widely used, a separate messaging Type has been supported) . It is useful for exchanging textual data and complex character data like XML.

          What is Map message?
          map message contains name value Pairs. The values can be of type primitives and its wrappers. The name is a string.


          ---Does JMS specification define transactions? Queue
          JMS specification defines a transaction mechanisms allowing clients to send and receive groups of logically bounded messages as a single unit of information. A Session may be marked as transacted. It means that all messages sent in a session are considered as parts of a transaction. A set of messages can be committed (commit() method) or rolled back (rollback() method). If a provider supports distributed transactions, it's recommended to use XAResource API.
          ---

          Does JMS specification define transactions? Queue
          JMS specification defines a transaction mechanisms allowing clients to send and receive groups of logically bounded messages as a single unit of information. A Session may be marked as transacted. It means that all messages sent in a session are considered as parts of a transaction. A set of messages can be committed (commit() method) or rolled back (rollback() method). If a provider supports distributed transactions, it's recommended to use XAResource API.

          posted @ 2007-07-13 04:48 Sun River| 編輯 收藏
          --How are Observer and Observable used?
          Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.
          --Can a top level class be private or protected?
          No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected.
          --How can we make a class Singleton ?
          A) If the class is Serializable
          class Singleton implements Serializable
          {
          private static Singleton instance;
          private Singleton() { }
          public static synchronized Singleton getInstance()
          {
          if (instance == null)
          instance = new Singleton();
          return instance;
          }

          /**
          If the singleton implements Serializable, then this method must be supplied.
          */
          protected Object readResolve() {
          return instance;
          }

          /**
          This method avoids the object fro being cloned
          */
          public Object clone() {
          throws CloneNotSupportedException ;
          //return instance;
          }
          }

          B) If the class is NOT Serializable

          class Singleton
          {
          private static Singleton instance;
          private Singleton() { }

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

          /**
          This method avoids the object from being cloned**/
          public Object clone() {
          throws CloneNotSupportedException ;
          //return instance;
          }
          }
           --

          What is covariant return type?
          A covariant return type lets you override a superclass method with a return type that subtypes the superclass method's return type. So we can use covariant return types to minimize upcasting and downcasting.
          class Parent {
          Parent foo () {
          System.out.println ("Parent foo() called");
          return this;
          }
          }

          class Child extends Parent {
          Child foo () {
          System.out.println ("Child foo() called");
          return this;
          }
          }

          class Covariant {
          public static void main(String[] args) {
          Child c = new Child();
          Child c2 = c.foo(); // c2 is Child
          Parent c3 = c.foo(); // c3 points to Child
          }
          }

          --What an I/O filter?
          An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.
          --What modifiers can be used with a local inner class?
          A local inner class may be final or abstract.
          --What is autoboxing ?
          Automatic conversion between reference and primitive types.

          --How can I investigate the physical structure of a database?
          The JDBC view of a database internal structure can be seen in the image below.

          * Several database objects (tables, views, procedures etc.) are contained within a Schema.
          * Several schema (user namespaces) are contained within a catalog.
          * Several catalogs (database partitions; databases) are contained within a DB server (such as Oracle, MS SQL

          The DatabaseMetaData interface has methods for discovering all the Catalogs, Schemas, Tables and Stored Procedures in the database server. The methods are pretty intuitive, returning a ResultSet with a single String column; use them as indicated in the code below:

          public static void main(String[] args) throws Exception
          {
          // Load the database driver - in this case, we
          // use the Jdbc/Odbc bridge driver.
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

          // Open a connection to the database
          Connection conn = DriverManager.getConnection("[jdbcURL]",
          "[login]", "[passwd]");

          // Get DatabaseMetaData
          DatabaseMetaData dbmd = conn.getMetaData();

          // Get all Catalogs
          System.out.println("\nCatalogs are called '" + dbmd.getCatalogTerm()
          + "' in this RDBMS.");
          processResultSet(dbmd.getCatalogTerm(), dbmd.getCatalogs());

          // Get all Schemas
          System.out.println("\nSchemas are called '" + dbmd.getSchemaTerm()
          + "' in this RDBMS.");
          processResultSet(dbmd.getSchemaTerm(), dbmd.getSchemas());

          // Get all Table-like types
          System.out.println("\nAll table types supported in this RDBMS:");
          processResultSet("Table type", dbmd.getTableTypes());

          // Close the Connection
          conn.close();
          }
          public static void processResultSet(String preamble, ResultSet rs)
          throws SQLException
          {
          // Printout table data
          while(rs.next())
          {
          // Printout
          System.out.println(preamble + ": " + rs.getString(1));
          }

          // Close database resources
          rs.close();
          }
          ---How do I find all database stored procedures in a database?
          Use the getProcedures method of interface java.sql.DatabaseMetaData to probe the database for stored procedures. The exact usage is described in the code below.

          public static void main(String[] args) throws Exception
          {
          // Load the database driver - in this case, we use the Jdbc/Odbc bridge driver.
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

          // Open a connection to the database
          Connection conn = DriverManager.getConnection("[jdbcURL]", "[login]", "[passwd]");

          // Get DatabaseMetaData
          DatabaseMetaData dbmd = conn.getMetaData();

          // Get all procedures.
          System.out.println("Procedures are called '" + dbmd.getProcedureTerm() +"' in the DBMS.");
          ResultSet rs = dbmd.getProcedures(null, null, "%");

          // Printout table data
          while(rs.next())
          {
          // Get procedure metadata
          String dbProcedureCatalog = rs.getString(1);
          String dbProcedureSchema = rs.getString(2);
          String dbProcedureName = rs.getString(3);
          String dbProcedureRemarks = rs.getString(7);
          short dbProcedureType = rs.getShort(8);

          // Make result readable for humans
          String procReturn = (dbProcedureType == DatabaseMetaData.procedureNoResult ? "No Result" : "Result");

          // Printout
          System.out.println("Procedure: " + dbProcedureName + ", returns: " + procReturn);
          System.out.println(" [Catalog | Schema]: [" + dbProcedureCatalog + " | " + dbProcedureSchema + "]");
          System.out.println(" Comments: " + dbProcedureRemarks);
          }

          // Close database resources
          rs.close();
          conn.close();
          }

          ---

          How can I investigate the parameters to send into and receive from a database stored procedure?
          Use the method getProcedureColumns in interface DatabaseMetaData to probe a stored procedure for metadata. The exact usage is described in the code below.

          NOTE! This method can only discover parameter values. For databases where a returning ResultSet is created simply by executing a SELECT statement within a stored procedure (thus not sending the return ResultSet to the java application via a declared parameter), the real return value of the stored procedure cannot be detected. This is a weakness for the JDBC metadata mining which is especially present when handling Transact-SQL databases such as those produced by SyBase and Microsoft.

          public static void main(String[] args) throws Exception
          {
          // Load the database driver - in this case, we
          // use the Jdbc/Odbc bridge driver.
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")
          ;
          // Open a connection to the database
          Connection conn = DriverManager.getConnection("[jdbcURL]",
          "[login]", "[passwd]");

          // Get DatabaseMetaData
          DatabaseMetaData dbmd = conn.getMetaData();

          // Get all column definitions for procedure "getFoodsEaten" in
          // schema "testlogin" and catalog "dbo".
          System.out.println("Procedures are called '" + dbmd.getProcedureTerm() +"' in the DBMS.");
          ResultSet rs = dbmd.getProcedureColumns("test", "dbo", "getFoodsEaten", "%");

          // Printout table data
          while(rs.next())
          {
          // Get procedure metadata
          String dbProcedureCatalog = rs.getString(1);
          String dbProcedureSchema = rs.getString(2);
          String dbProcedureName = rs.getString(3);
          String dbColumnName = rs.getString(4);
          short dbColumnReturn = rs.getShort(5);
          String dbColumnReturnTypeName = rs.getString(7);
          int dbColumnPrecision = rs.getInt(8);
          int dbColumnByteLength = rs.getInt(9);
          short dbColumnScale = rs.getShort(10);
          short dbColumnRadix = rs.getShort(11);
          String dbColumnRemarks = rs.getString(13);


          // Interpret the return type (readable for humans)
          String procReturn = null;

          switch(dbColumnReturn)
          {
          case DatabaseMetaData.procedureColumnIn:
          procReturn = "In";
          break;
          case DatabaseMetaData.procedureColumnOut:
          procReturn = "Out";
          break;
          case DatabaseMetaData.procedureColumnInOut:
          procReturn = "In/Out";
          break;
          case DatabaseMetaData.procedureColumnReturn:
          procReturn = "return value";
          break;
          case DatabaseMetaData.procedureColumnResult:
          procReturn = "return ResultSet";
          default:
          procReturn = "Unknown";
          }

          // Printout
          System.out.println("Procedure: " + dbProcedureCatalog + "." + dbProcedureSchema
          + "." + dbProcedureName);
          System.out.println(" ColumnName [ColumnType(ColumnPrecision)]: " + dbColumnName
          + " [" + dbColumnReturnTypeName + "(" + dbColumnPrecision + ")]");
          System.out.println(" ColumnReturns: " + procReturn + "(" + dbColumnReturnTypeName + ")");
          System.out.println(" Radix: " + dbColumnRadix + ", Scale: " + dbColumnScale);
          System.out.println(" Remarks: " + dbColumnRemarks);
          }

          // Close database resources
          rs.close();
          conn.close();
          }

          How do I check what table-like database objects (table, view, temporary table, alias) are present in a particular database?
          Use java.sql.DatabaseMetaData to probe the database for metadata. Use the getTables method to retrieve information about all database objects (i.e. tables, views, system tables, temporary global or local tables or aliases). The exact usage is described in the code below.

          NOTE! Certain JDBC drivers throw IllegalCursorStateExceptions when you try to access fields in the ResultSet in the wrong order (i.e. not consecutively). Thus, you should not change the order in which you retrieve the metadata from the ResultSet.

          public static void main(String[] args) throws Exception
          {
          // Load the database driver - in this case, we
          // use the Jdbc/Odbc bridge driver.
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

          // Open a connection to the database
          Connection conn = DriverManager.getConnection("[jdbcURL]",
          "[login]", "[passwd]");

          // Get DatabaseMetaData
          DatabaseMetaData dbmd = conn.getMetaData();

          // Get all dbObjects. Replace the last argument in the getTables
          // method with objectCategories below to obtain only database
          // tables. (Sending in null retrievs all dbObjects).
          String[] objectCategories = {"TABLE"};
          ResultSet rs = dbmd.getTables(null, null, "%", null);

          // Printout table data
          while(rs.next())
          {
          // Get dbObject metadata
          String dbObjectCatalog = rs.getString(1);
          String dbObjectSchema = rs.getString(2);
          String dbObjectName = rs.getString(3);
          String dbObjectType = rs.getString(4);

          // Printout
          System.out.println("" + dbObjectType + ": " + dbObjectName);
          System.out.println(" Catalog: " + dbObjectCatalog);
          System.out.println(" Schema: " + dbObjectSchema);
          }

          // Close database resources
          rs.close();
          conn.close();
          }

          --How do I extract SQL table column type information?
          Use the getColumns method of the java.sql.DatabaseMetaData interface to investigate the column type information of a particular table. Note that most arguments to the getColumns method (pinpointing the column in question) may be null, to broaden the search criteria. A code sample can be seen below:

          public static void main(String[] args) throws Exception
          {
          // Load the database driver - in this case, we
          // use the Jdbc/Odbc bridge driver.
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

          // Open a connection to the database
          Connection conn = DriverManager.getConnection("[jdbcURL]",
          "[login]", "[passwd]");

          // Get DatabaseMetaData
          DatabaseMetaData dbmd = conn.getMetaData();

          // Get all column types for the table "sysforeignkeys", in schema
          // "dbo" and catalog "test".
          ResultSet rs = dbmd.getColumns("test", "dbo", "sysforeignkeys", "%");

          // Printout table data
          while(rs.next())
          {
          // Get dbObject metadata
          String dbObjectCatalog = rs.getString(1);
          String dbObjectSchema = rs.getString(2);
          String dbObjectName = rs.getString(3);
          String dbColumnName = rs.getString(4);
          String dbColumnTypeName = rs.getString(6);
          int dbColumnSize = rs.getInt(7);
          int dbDecimalDigits = rs.getInt(9);
          String dbColumnDefault = rs.getString(13);
          int dbOrdinalPosition = rs.getInt(17);
          String dbColumnIsNullable = rs.getString(18);

          // Printout
          System.out.println("Col(" + dbOrdinalPosition + "): " + dbColumnName
          + " (" + dbColumnTypeName +")");
          System.out.println(" Nullable: " + dbColumnIsNullable +
          ", Size: " + dbColumnSize);
          System.out.println(" Position in table: " + dbOrdinalPosition
          + ", Decimal digits: " + dbDecimalDigits);
          }

          // Free database resources
          rs.close();
          conn.close();
          }
          ---How do I insert an image file (or other raw data) into a database?
          All raw data types (including binary documents or images) should be read and uploaded to the database as an array of bytes, byte[]. Originating from a binary file,
          1. Read all data from the file using a FileInputStream.
          2. Create a byte array from the read data.
          3. Use method setBytes(int index, byte[] data); of java.sql.PreparedStatement to upload the data.

          --How can I connect from an applet to a database on the server?
          There are two ways of connecting to a database on the server side.
          1. The hard way. Untrusted applets cannot touch the hard disk of a computer. Thus, your applet cannot use native or other local files (such as JDBC database drivers) on your hard drive. The first alternative solution is to create a digitally signed applet which may use locally installed JDBC drivers, able to connect directly to the database on the server side.
          2. The easy way. Untrusted applets may only open a network connection to the server from which they were downloaded. Thus, you must place a database listener (either the database itself, or a middleware server) on the server node from which the applet was downloaded. The applet would open a socket connection to the middleware server, located on the same computer node as the webserver from which the applet was downloaded. The middleware server is used as a mediator, connecting to and extract data from the database.
          ---Many connections from an Oracle8i pooled connection returns statement closed. I am using import oracle.jdbc.pool.* with thin driver. If I test with many simultaneous connections, I get an SQLException that the statement is closed.
          ere is an example of concurrent operation of pooled connections from the OracleConnectionPoolDataSource. There is an executable for kicking off threads, a DataSource, and the workerThread.

          The Executable Member
          package package6;

          /**
          * package6.executableTester
          */
          public class executableTester {
          protected static myConnectionPoolDataSource dataSource = null;
          static int i = 0;

          /**
          * Constructor
          */
          public executableTester() throws java.sql.SQLException
          {
          }

          /**
          * main
          * @param args
          */
          public static void main(String[] args) {

          try{
          dataSource = new myConnectionPoolDataSource();
          }
          catch ( Exception ex ){
          ex.printStackTrace();
          }

          while ( i++ < 10 ) {
          try{
          workerClass worker = new workerClass();
          worker.setThreadNumber( i );
          worker.setConnectionPoolDataSource( dataSource.getConnectionPoolDataSource() );
          worker.start();
          System.out.println( "Started Thread#"+i );
          }
          catch ( Exception ex ){
          ex.printStackTrace();
          }
          }
          }

          }

          The DataSource Member

          package package6;
          import oracle.jdbc.pool.*;

          /**
          * package6.myConnectionPoolDataSource.
          *
          */
          public class myConnectionPoolDataSource extends Object {
          protected OracleConnectionPoolDataSource ocpds = null;

          /**
          * Constructor
          */
          public myConnectionPoolDataSource() throws java.sql.SQLException {
          // Create a OracleConnectionPoolDataSource instance
          ocpds = new OracleConnectionPoolDataSource();

          // Set connection parameters
          ocpds.setURL("jdbc:oracle:oci8:@mydb");
          ocpds.setUser("scott");
          ocpds.setPassword("tiger");

          }

          public OracleConnectionPoolDataSource getConnectionPoolDataSource() {
          return ocpds;
          }

          }

          The Worker Thread Member

          package package6;
          import oracle.jdbc.pool.*;
          import java.sql.*;
          import javax.sql.*;

          /**
          * package6.workerClass .
          *
          */
          public class workerClass extends Thread {
          protected OracleConnectionPoolDataSource ocpds = null;
          protected PooledConnection pc = null;

          protected Connection conn = null;

          protected int threadNumber = 0;
          /**
          * Constructor
          */

          public workerClass() {
          }

          public void doWork( ) throws SQLException {

          // Create a pooled connection
          pc = ocpds.getPooledConnection();

          // Get a Logical connection
          conn = pc.getConnection();

          // Create a Statement
          Statement stmt = conn.createStatement ();

          // Select the ENAME column from the EMP table
          ResultSet rset = stmt.executeQuery ("select ename from emp");

          // Iterate through the result and print the employee names
          while (rset.next ())
          // System.out.println (rset.getString (1));
          ;

          // Close the RseultSet
          rset.close();
          rset = null;

          // Close the Statement
          stmt.close();
          stmt = null;

          // Close the logical connection
          conn.close();
          conn = null;

          // Close the pooled connection
          pc.close();
          pc = null;

          System.out.println( "workerClass.thread#"+threadNumber+" completed..");

          }

          public void setThreadNumber( int assignment ){
          threadNumber = assignment;
          }

          public void setConnectionPoolDataSource(OracleConnectionPoolDataSource x){
          ocpds = x;
          }

          public void run() {
          try{
          doWork();
          }
          catch ( Exception ex ){
          ex.printStackTrace();
          }
          }

          }

          The OutPut Produced

          Started Thread#1
          Started Thread#2
          Started Thread#3
          Started Thread#4
          Started Thread#5
          Started Thread#6
          Started Thread#7
          Started Thread#8
          Started Thread#9
          Started Thread#10
          workerClass.thread# 1 completed..
          workerClass.thread# 10 completed..
          workerClass.thread# 3 completed..
          workerClass.thread# 8 completed..
          workerClass.thread# 2 completed..
          workerClass.thread# 9 completed..
          workerClass.thread# 5 completed..
          workerClass.thread# 7 completed..
          workerClass.thread# 6 completed..
          workerClass.thread# 4 completed..

          The oracle.jdbc.pool.OracleConnectionCacheImpl class is another subclass of the oracle.jdbc.pool.OracleDataSource which should also be looked over, that is what you really what to use. Here is a similar example that uses the oracle.jdbc.pool.OracleConnectionCacheImpl. The general construct is the same as the first example but note the differences in workerClass1 where some statements have been commented ( basically a clone of workerClass from previous example ).
          The Executable Member

          package package6;
          import java.sql.*;
          import javax.sql.*;
          import oracle.jdbc.pool.*;

          /**
          * package6.executableTester2
          *
          */
          public class executableTester2 {
          static int i = 0;
          protected static myOracleConnectCache
          connectionCache = null;

          /**
          * Constructor
          */
          public executableTester2() throws SQLException
          {
          }

          /**
          * main
          * @param args
          */
          public static void main(String[] args) {
          OracleConnectionPoolDataSource dataSource = null;

          try{

          dataSource = new OracleConnectionPoolDataSource() ;
          connectionCache = new myOracleConnectCache( dataSource );

          }
          catch ( Exception ex ){
          ex.printStackTrace();
          }

          while ( i++ < 10 ) {
          try{
          workerClass1 worker = new workerClass1();
          worker.setThreadNumber( i );
          worker.setConnection( connectionCache.getConnection() );
          worker.start();
          System.out.println( "Started Thread#"+i );
          }
          catch ( Exception ex ){
          ex.printStackTrace();
          }
          }
          }
          protected void finalize(){
          try{
          connectionCache.close();
          } catch ( SQLException x) {
          x.printStackTrace();
          }
          this.finalize();
          }

          }

          The ConnectCacheImpl Member

          package package6;
          import javax.sql.ConnectionPoolDataSource;
          import oracle.jdbc.pool.*;
          import oracle.jdbc.driver.*;
          import java.sql.*;
          import java.sql.SQLException;

          /**
          * package6.myOracleConnectCache
          *
          */
          public class myOracleConnectCache extends
          OracleConnectionCacheImpl {

          /**
          * Constructor
          */
          public myOracleConnectCache( ConnectionPoolDataSource x)
          throws SQLException {
          initialize();
          }

          public void initialize() throws SQLException {
          setURL("jdbc:oracle:oci8:@myDB");
          setUser("scott");
          setPassword("tiger");
          //
          // prefab 2 connection and only grow to 4 , setting these
          // to various values will demo the behavior
          //clearly, if it is not
          // obvious already
          //
          setMinLimit(2);
          setMaxLimit(4);

          }

          }

          The Worker Thread Member

          package package6;
          import oracle.jdbc.pool.*;
          import java.sql.*;
          import javax.sql.*;

          /**
          * package6.workerClass1
          *
          */
          public class workerClass1 extends Thread {
          // protected OracleConnectionPoolDataSource
          ocpds = null;
          // protected PooledConnection pc = null;

          protected Connection conn = null;

          protected int threadNumber = 0;
          /**
          * Constructor
          */

          public workerClass1() {
          }

          public void doWork( ) throws SQLException {

          // Create a pooled connection
          // pc = ocpds.getPooledConnection();

          // Get a Logical connection
          // conn = pc.getConnection();

          // Create a Statement
          Statement stmt = conn.createStatement ();

          // Select the ENAME column from the EMP table
          ResultSet rset = stmt.executeQuery
          ("select ename from EMP");

          // Iterate through the result
          // and print the employee names
          while (rset.next ())
          // System.out.println (rset.getString (1));
          ;

          // Close the RseultSet
          rset.close();
          rset = null;

          // Close the Statement
          stmt.close();
          stmt = null;

          // Close the logical connection
          conn.close();
          conn = null;

          // Close the pooled connection
          // pc.close();
          // pc = null;

          System.out.println( "workerClass1.thread#
          "+threadNumber+" completed..");

          }

          public void setThreadNumber( int assignment ){
          threadNumber = assignment;
          }

          // public void setConnectionPoolDataSource
          (OracleConnectionPoolDataSource x){
          // ocpds = x;
          // }

          public void setConnection( Connection assignment ){
          conn = assignment;
          }

          public void run() {
          try{
          doWork();
          }
          catch ( Exception ex ){
          ex.printStackTrace();
          }
          }

          }

          The OutPut Produced

          Started Thread#1
          Started Thread#2
          workerClass1.thread# 1 completed..
          workerClass1.thread# 2 completed..
          Started Thread#3
          Started Thread#4
          Started Thread#5
          workerClass1.thread# 5 completed..
          workerClass1.thread# 4 completed..
          workerClass1.thread# 3 completed..
          Started Thread#6
          Started Thread#7
          Started Thread#8
          Started Thread#9
          workerClass1.thread# 8 completed..
          workerClass1.thread# 9 completed..
          workerClass1.thread# 6 completed..
          workerClass1.thread# 7 completed..
          Started Thread#10
          workerClass1.thread# 10 completed..

          posted @ 2007-07-13 01:46 Sun River| 編輯 收藏
          --What is WSDL?

          The Web Services Description Language (WSDL) currently represents the service description layer within the Web service protocol stack.
          In a nutshell, WSDL is an XML grammar for specifying a public interface for a Web service. This public interface can include the following:
          Information on all publicly available functions.
          Data type information for all XML messages.
          Binding information about the specific transport protocol to be used.
          Address information for locating the specified service.
          --

          posted @ 2007-07-12 23:45 Sun River| 編輯 收藏
          僅列出標(biāo)題
          共8頁: 上一頁 1 2 3 4 5 6 7 8 下一頁 
          主站蜘蛛池模板: 宁晋县| 河东区| 炉霍县| 鹰潭市| 庆城县| 乌拉特前旗| 迁安市| 平乡县| 金湖县| 台安县| 社会| 金山区| 乳源| 西盟| 长岭县| 凤阳县| 陇南市| 那曲县| 宁波市| 齐齐哈尔市| 密山市| 平安县| 额济纳旗| 河南省| 绥德县| 临漳县| 赤壁市| 奎屯市| 乐安县| 诸城市| 商南县| 万全县| 许昌市| 县级市| 山东省| 建湖县| 珠海市| 阳江市| 井研县| 临沭县| 吉安市|