搜尋此網誌

2013年4月26日 星期五

Log4j的使用方式

以下是log4j的source code拿出來做解釋

MyLoggerFactory.java: 製作MyLogger物件實體的工廠類別.


 /*  
  * Licensed to the Apache Software Foundation (ASF) under one or more  
  * contributor license agreements. See the NOTICE file distributed with  
  * this work for additional information regarding copyright ownership.  
  * The ASF licenses this file to You under the Apache License, Version 2.0  
  * (the "License"); you may not use this file except in compliance with  
  * the License. You may obtain a copy of the License at  
  *   
  *   http://www.apache.org/licenses/LICENSE-2.0  
  *   
  * Unless required by applicable law or agreed to in writing, software  
  * distributed under the License is distributed on an "AS IS" BASIS,  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  * See the License for the specific language governing permissions and  
  * limitations under the License.  
  */  
 package examples.subclass;  
 import org.apache.log4j.Logger;  
 import org.apache.log4j.spi.LoggerFactory;  
 /**  
   A factory that makes new {@link MyLogger} objects.  
   See <b><a href="doc-files/MyLoggerFactory.java">source  
   code</a></b> for more details.  
   @author Ceki G&uuml;lc&uuml; */  
 public class MyLoggerFactory implements LoggerFactory {  
  /**  
    The constructor should be public as it will be called by  
    configurators in different packages. */  
  public  
  MyLoggerFactory() {  
  }  
  public  
  Logger makeNewLoggerInstance(String name) {  
   return new MyLogger(name);  
  }  
 }  

MyLogger.java: 在這裡定義每個 log level (warn, info , debug etc)想要印出的訊息.

以下這段程式碼是靜態的獨體模式(singleton design pattern)

private static MyLoggerFactory myFactory = new MyLoggerFactory();


 /*  
  * Licensed to the Apache Software Foundation (ASF) under one or more  
  * contributor license agreements. See the NOTICE file distributed with  
  * this work for additional information regarding copyright ownership.  
  * The ASF licenses this file to You under the Apache License, Version 2.0  
  * (the "License"); you may not use this file except in compliance with  
  * the License. You may obtain a copy of the License at  
  *   
  *   http://www.apache.org/licenses/LICENSE-2.0  
  *   
  * Unless required by applicable law or agreed to in writing, software  
  * distributed under the License is distributed on an "AS IS" BASIS,  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  * See the License for the specific language governing permissions and  
  * limitations under the License.  
  */  
 package examples.subclass;  
 import org.apache.log4j.*;  
 /**  
   A simple example showing logger subclassing.   
   <p>See <b><a href="doc-files/MyLogger.java">source code</a></b>  
   for more details.  
   <p>See {@link MyLoggerTest} for a usage example.  
  */  
 public class MyLogger extends Logger {  
  // It's usually a good idea to add a dot suffix to the fully  
  // qualified class name. This makes caller localization to work  
  // properly even from classes that have almost the same fully  
  // qualified class name as MyLogger, e.g. MyLoggerTest.  
  static String FQCN = MyLogger.class.getName() + ".";  
  // It's enough to instantiate a factory once and for all.  
  private static MyLoggerFactory myFactory = new MyLoggerFactory();  
  /**  
    Just calls the parent constuctor.  
   */  
  public MyLogger(String name) {  
   super(name);  
  }  
  /**  
    Overrides the standard debug method by appending " world" at the  
    end of each message. */  
  public   
  void debug(Object message) {  
   super.log(FQCN, Level.DEBUG, message + " world.", null);    
  }  
  /**  
    This method overrides {@link Logger#getLogger} by supplying  
    its own factory type as a parameter.  
  */  
  public   
  static  
  Logger getLogger(String name) {  
   return Logger.getLogger(name, myFactory);   
  }  
  public  
  void trace(Object message) {  
   //super.log(FQCN, XLevel.TRACE, message, null);   
  }  
 }  

MyLoggerTest.java:

當不傳入任何參數的時候,使用預設的log設定, 並且在console輸出 (系統標準輸出介面)

或是傳入xml, properties設定檔, 套用裡面的設定值


 /*  
  * Licensed to the Apache Software Foundation (ASF) under one or more  
  * contributor license agreements. See the NOTICE file distributed with  
  * this work for additional information regarding copyright ownership.  
  * The ASF licenses this file to You under the Apache License, Version 2.0  
  * (the "License"); you may not use this file except in compliance with  
  * the License. You may obtain a copy of the License at  
  *   
  *   http://www.apache.org/licenses/LICENSE-2.0  
  *   
  * Unless required by applicable law or agreed to in writing, software  
  * distributed under the License is distributed on an "AS IS" BASIS,  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  * See the License for the specific language governing permissions and  
  * limitations under the License.  
  */  
 package examples.subclass;  
 import org.apache.log4j.*;  
 import org.apache.log4j.xml.DOMConfigurator;  
 import org.apache.log4j.PropertyConfigurator;  
 import org.apache.log4j.helpers.LogLog;  
 /**  
   A simple example showing logger subclassing.   
   <p>The example should make it clear that subclasses follow the  
   hierarchy. You should also try running this example with a <a  
   href="doc-files/mycat.bad">bad</a> and <a  
   href="doc-files/mycat.good">good</a> configuration file samples.  
   <p>See <b><a  
   href="doc-files/MyLogger.java">source code</a></b> for more details.  
 */  
 public class MyLoggerTest {  
  /**  
    When called wihtout arguments, this program will just print   
    <pre>  
     DEBUG [main] some.cat - Hello world.  
    </pre>  
    and exit.  
    <b>However, it can be called with a configuration file in XML or  
    properties format.  
   */  
  static public void main(String[] args) {  
   if(args.length == 0) {  
    // Note that the appender is added to root but that the log  
    // request is made to an instance of MyLogger. The output still  
    // goes to System.out.  
    Logger root = Logger.getRootLogger();  
    Layout layout = new PatternLayout("%p [%t] %c (%F:%L) - %m%n");  
    root.addAppender(new ConsoleAppender(layout, ConsoleAppender.SYSTEM_OUT));  
   }  
   else if(args.length == 1) {  
    if(args[0].endsWith("xml")) {  
      DOMConfigurator.configure(args[0]);  
    } else {  
      PropertyConfigurator.configure(args[0]);  
    }  
   } else {  
    usage("Incorrect number of parameters.");  
   }  
   try {  
    MyLogger c = (MyLogger) MyLogger.getLogger("some.cat");    
    c.debug("Hello");  
   } catch(ClassCastException e) {  
    LogLog.error("Did you forget to set the factory in the config file?", e);  
   }  
  }  
  static  
  void usage(String errMsg) {  
   System.err.println(errMsg);  
   System.err.println("\nUsage: "+MyLogger.class.getName() + "[configFile]\n"  
         + " where *configFile* is an optional configuration file, "+  
               "either in properties or XML format.");  
   System.exit(1);  
  }  
 }  

2013年4月25日 星期四

用介面寫程式

用介面寫程式的好處 , 是你可以抽換運算或資料處理方式的演算法 , 而不必大幅更動程式碼

如下例 , 只要重新new 一個AnotherCustomMathAdd物件 , 把CustomMathAdd物件換掉 , 就會

得到新的結果.


 package convention;  
 public class CodingByInterface {  
      public static void main(String[] args){  
           CustomMathAdd cma = new CustomMathAdd();  
           add(cma , 1, 2);  
      }  
      public static void add(MathAdd ma , int a , int b){  
           System.out.println(ma.basicAdd(a, b));  
      }  
 }  
 interface MathAdd{  
      public int basicAdd(int a , int b);  
      public int advanceAdd(int a , int b);  
 }  
 class CustomMathAdd implements MathAdd {  
      public int basicAdd(int a, int b) {  
           return a + b;  
      }  
      public int advanceAdd(int a, int b) {  
           return a*2 + b;  
      }  
 }  
 class AnotherCustomMathAdd implements MathAdd {  
      public int basicAdd(int a, int b) {  
           return 0;  
      }  
      public int advanceAdd(int a, int b) {  
           return 1;  
      }  
 }  

2013年4月24日 星期三

Rename a file

 import java.io.File;  
 public class FileRenameDemo {  
      public static void main(String[] args){  
           File original = new File("src/dom/employee.xml");  
           boolean result = original.renameTo(new File("src/dom/employee.xml.backup"));  
           System.out.println(result);  
      }  
 }  

2013年4月23日 星期二

Set usage

Set不包含兩個同樣的元素e1 and e2 , 當e1.equals(e2)為真的時候,並且Set最多只可有一個null元素.
範例:
 import java.util.HashSet;  
 import java.util.Set;  
 public class SetDemo {  
      public static void main(String [] args){  
           String a = "a";  
           String b = a;  
           //String b = "b";  
           Set s = new HashSet();  
           s.add(a);  
           s.add(b);  
           System.out.println(s.toString());  
      }  
 }  
若變數b 宣告為:
String b = "b";
則會印出b, a

list to array

 import java.util.LinkedList;  
 public class LinkedListToArray {  
      public static void main(String[] args){  
           LinkedList<String> ll = new LinkedList<String>();  
           ll.add("1");  
           ll.add("2");  
           ll.add("3");  
           String[] array = ll.toArray(new String[0]);  
           for(int i = 0 ; i < array.length ; i++){  
                System.out.println(array[i]);  
           }  
      }  
 }  

2013年4月21日 星期日

How to read xml files in Java(Java讀取xml文件)

SAX is the Simple API for XML, originally a Java-only API employee.xml :
 <?xml version="1.0" encoding="UTF-8"?>  
 <company>  
      <employee>  
           <firstname>Michael</firstname>  
           <lastname>Jordan</lastname>  
      </employee>  
      <employee>  
           <firstname>Larry</firstname>  
           <lastname>Bird</lastname>  
      </employee>  
      <employee>  
           <firstname>Tiger</firstname>  
           <lastname>Woods</lastname>  
      </employee>  
 </company>  

W3c DOM sample :(from Java Tips):
 package dom;  
 import java.io.File;  
 import javax.xml.parsers.DocumentBuilder;  
 import javax.xml.parsers.DocumentBuilderFactory;  
 import org.w3c.dom.Document;  
 import org.w3c.dom.Element;  
 import org.w3c.dom.Node;  
 import org.w3c.dom.NodeList;  
 public class W3cDomDemo {  
      public static void main(String argv[]) {  
           try {  
                String path = "./bin/dom/employee.xml";  
                File file = new File(path);  
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
                DocumentBuilder db = dbf.newDocumentBuilder();  
                Document doc = db.parse(file);  
                doc.getDocumentElement().normalize();  
                System.out.println("Root element "  
                          + doc.getDocumentElement().getNodeName());  
                NodeList nodeLst = doc.getElementsByTagName("employee");  
                System.out.println("Information of all employees");  
                for (int s = 0; s < nodeLst.getLength(); s++) {  
                     Node fstNode = nodeLst.item(s);  
                     if (fstNode.getNodeType() == Node.ELEMENT_NODE) {  
                          Element fstElmnt = (Element) fstNode;  
                          NodeList fstNmElmntLst = fstElmnt  
                                    .getElementsByTagName("firstname");  
                          Element fstNmElmnt = (Element) fstNmElmntLst.item(0);  
                          NodeList fstNm = fstNmElmnt.getChildNodes();  
                          System.out.println("First Name : "  
                                    + ((Node) fstNm.item(0)).getNodeValue());  
                          NodeList lstNmElmntLst = fstElmnt  
                                    .getElementsByTagName("lastname");  
                          Element lstNmElmnt = (Element) lstNmElmntLst.item(0);  
                          NodeList lstNm = lstNmElmnt.getChildNodes();  
                          System.out.println("Last Name : "  
                                    + ((Node) lstNm.item(0)).getNodeValue());  
                     }  
                }  
           } catch (Exception e) {  
                e.printStackTrace();  
           }  
      }  
 }  

using Dom4j: dom4j , you must have dom4j library to execute below sample code
 package dom;  
 import org.dom4j.Document;  
 import org.dom4j.dom.DOMDocumentFactory;  
 import org.dom4j.io.SAXReader;  
 import org.w3c.dom.Element;  
 import org.w3c.dom.Node;  
 import org.w3c.dom.NodeList;  
 public class NativeDomDemo {  
   public static void main(String[] args) {  
        String path = "./bin/dom/employee.xml";  
     new NativeDomDemo().run(path);  
   }  
   public NativeDomDemo() {  
   }  
      private void run(String xmlFile) {  
           try {  
                parseDOM(xmlFile);  
           } catch (Exception e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  
   protected void parseDOM(String xmlFile) throws Exception {  
     System.out.println("Loading document: " + xmlFile);  
     SAXReader reader = new SAXReader(DOMDocumentFactory.getInstance());  
     Document document = reader.read(xmlFile);  
     System.out.println("Created <dom4j> document: " + document);  
     if (document instanceof org.w3c.dom.Document) {  
       org.w3c.dom.Document domDocument = (org.w3c.dom.Document) document;  
       System.out.println("Created W3C DOM document: " + domDocument);  
       processDOM(domDocument);  
     } else {  
          System.out.println("FAILED to make a native W3C DOM document!!");  
     }  
   }  
   protected void processDOM(org.w3c.dom.Document doc) throws Exception {  
        NodeList nodeLst = doc.getElementsByTagName("employee");  
           System.out.println("Information of all employees");  
           for (int s = 0; s < nodeLst.getLength(); s++) {  
                Node fstNode = nodeLst.item(s);  
                if (fstNode.getNodeType() == Node.ELEMENT_NODE) {  
                     Element fstElmnt = (Element) fstNode;  
                     NodeList fstNmElmntLst = fstElmnt  
                               .getElementsByTagName("firstname");  
                     Element fstNmElmnt = (Element) fstNmElmntLst.item(0);  
                     NodeList fstNm = fstNmElmnt.getChildNodes();  
                     System.out.println("First Name : "  
                               + ((Node) fstNm.item(0)).getNodeValue());  
                     NodeList lstNmElmntLst = fstElmnt  
                               .getElementsByTagName("lastname");  
                     Element lstNmElmnt = (Element) lstNmElmntLst.item(0);  
                     NodeList lstNm = lstNmElmnt.getChildNodes();  
                     System.out.println("Last Name : "  
                               + ((Node) lstNm.item(0)).getNodeValue());  
                }  
           }  
   }  
 }  

2013年4月20日 星期六

用常數字串宣告取代hard-code字串.

這種寫法比較靈活 , 當下次要更改提示訊息時, 只要更動到一個地方即可. 也不會發生漏改的情形.
 package convention;  
 public class ConstantDemo {  
      private final static String prompInfo = "123";  
      public static void main(String [] args){  
           System.out.println(ConstantDemo.prompInfo);  
      }  
 }  

2013年4月16日 星期二

如何安裝GWT .

GWT安裝指引

1.開啟Eclipse, 然後選擇 Help > Install New Software..把更新連結貼到Work with這個文字欄位.

http://dl.google.com/eclipse/plugin/3.6

2.畫面中央會出現可下載的plugin清單.  把Google App Engine Java SDK and a Google Web Toolkit SDK打勾
3. 接著就是按下一步,然後同意安裝

20130416由選擇權未平倉量來做大盤分析

悶盤又來了,五月擺明了8000過不去,,至於下檔的支撐在7500~7600附近, 要等開倉幾天才能更確定

2013年4月10日 星期三

Java位元運算

& :  位元and
^  :  位元互斥or
|   :  位元or


 public class OperatorDemo {  
      public static void main(String [] args){  
           int one = 0x01;  
           int zero = 0x00;  
           System.out.println(one & zero);  
           System.out.println(one ^ zero);  
           System.out.println(one | zero);  
      }  
 }  

股市紀錄



大盤頭部形成, 偏空.

台積電頭部出現 , 偏空


新聞: 台積電第一季營收超標 創史上次高


4/25線型 , w底成形??..讓我們繼續看下去





5/6, 大盤收8169點 : 突破下降軌道線, 然後等拉回做多???



5/9, 大盤收8285, 會拉回嗎 ? 會拉到哪 ?




5/16 , 收8319 , 小小整理一下就上去了 . 會漲到哪?