11/27/2009

Oracle 找出loss的數字序列

日遇到個問題。
在table: pt_dltgls裡有location 1 ~ 500(符合條件的max location),其中有些location在輸入時漏掉了。所以要找出這裡漏掉的location,讓使用者來補回。

SQL做法:
1.Oracle語法列出1 ~ max location。
2.再minus現有的location,剩下的就是漏掉的location啦!~


Oracle SQL
Select level location
from dual 
connect by level <= (select nvl(max(location), 0) from pt_dltgls where dp_lot_id='C9J04031' and gls_status='S')
minus 
select distinct location from pt_dltgls t where dp_lot_id='C9J04031' and gls_status='S'

ps:感謝同仁Aming大力幫忙,沒有Aming還真寫不出來呢~哈~

11/25/2009

Wonder girls sing nobody in NY

How to code a class in VB.net 2005

近幾年物件導向愈來愈熱門,每個語言的概念差不多但寫法都不一樣,那要怎麼寫一個VB.net的Class呢?

Imports Microsoft.VisualBasic
Imports System.Data.OleDb
Imports System.Data

Public Class Table
    Private _name As String
    Private _delSql As ArrayList
    Private _dtDel As DataTable
    Private _dsQry As DataSet

    Public Sub New(ByVal name As String)
        'constructor
        Me._name = name
        Me._delSql = New ArrayList()

    End Sub

    Public ReadOnly Property Name() As String
        Get
            Return _name
        End Get
    End Property

    Public Property DataTable() As DataTable
        Get
            Return _dtDel
        End Get
        Set(ByVal value As DataTable)
            _dtDel = value
        End Set
    End Property

    Public Sub putDelSql(ByVal sSql As String)
        If Not sSql Is Nothing Then
            _delSql.Add(sSql)
        End If
    End Sub

    Public Function getDelSql() As ArrayList
        Return _delSql
    End Function

    Public Function getDelSql(ByVal i As Integer) As String
        If i <= _delSql.Count - 1 Then
            Return _delSql(i)
        End If
        Return Nothing
    End Function

    Public Property DataSetQry() As DataSet
        Get
            Return _dsQry
        End Get
        Set(ByVal value As DataSet)
            _dsQry = value
        End Set
    End Property

End Class

11/17/2009

jQuery玩Ajax 後端服務由jsp提供

jQuery強大的支援Ajax呼叫與使用,可要怎麼做呢?

下面的例子要求使用者輸入姓名,使用者按下「Click Me」後,透過ajax機制傳送姓名給jsp程式,而jsp只是單純顯示出使用者所輸入的姓名而已。


Step by Step
1.import js檔。


2.body裡加上下方的tag





3.head裡加入下方的javascript


4.提供Ajax呼叫查詢後端資料的jsp
<%@ page language="java" contentType="text/html; charset=BIG5"
    pageEncoding="BIG5" import="java.util.*;"%>
<%

String gender = request.getParameter("gender");
String name = request.getParameter("name");
out.println((gender.equalsIgnoreCase("male")?"Mr.":"Mrs.") + " " + name);
out.println("Hello world! This message is posted by Server.");
%>

用jQuery操作html Dom object

jQuery怎樣操作html dom呢?下面有個也是學著網上先進做的範例。
效果請參考


Step by Step
1.import js檔。


2.body裡加上下方的tag
jQuery DOM Operation


original



3.head裡加入下方的javascript

First touch jQuery

jQuery是個javascript Library,讓程式人員寫較少的code完成所需功能。
官網:http://jquery.com/
官網說明:
jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.

下面是個簡單的例子,學著網上其它先進做出來的範例。




上方效果若看不到請參考



Step by Step
1.使用jQuery要先Download jQuery API,它是個javascript檔。有幾個版本。以jQuery 1.3.2為例
  • jQuery Minified - 是去掉空白,註解的精簡版本,適用在上線的系統。
  • jQuery Regular - 是標準版本,適用在開發時較容易觀看它原始的code。

2.import js檔到html上。


3.在html的body裡加上下方的tag

4.html的head裡加入下方的javascript

Object to XML by DOM API in Java

有時侯我們想要把java object轉成XML時會使用到的code,轉出來的xml約像下面的格式。

   A12345
   1
   B12345
   2
   Iden123
   李昭慶
   
    d1
    c1
    1
    1
    1
   
   
    d2
    c2
    2
    2
    2
   
   
    d3
    c3
    3
    3
    3
   
  
DOMtoXML.java
/**
 * Object output XML format by DOM.
 */
package com.iden.Dom;

import java.io.*;
import java.util.ArrayList;

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class DOMtoXML {
   
 DOMtoXML(){}
 
 public static void main(String[] args) {  
  DOMtoXML jt = new DOMtoXML();
    
  Lot lot = new Lot("A12345", "1", "B12345", "2", "Iden123", "李昭慶");
  lot.putGlass("d1", "c1", "1", "1", "1");
  lot.putGlass("d2", "c2", "2", "2", "2");
  lot.putGlass("d3", "c3", "3", "3", "3");  
  String xml = lot.genObjectToXML();  
  System.out.println(xml); //print the xml string
 }
  
 private String encoding(String s){     
     try {      
   return new String(s.getBytes(), "UTF-8"); //"ISO-8859-1"
  } catch (UnsupportedEncodingException e) {   
   e.printStackTrace();
  }
  return null;
    }  
}

class Lot {
 DocumentBuilderFactory f;
 DocumentBuilder b;
 Document doc;
 private String lotId1;
 private String glsQty1;
 private String lotId2;
 private String glsQty2;
 private String userId;
 private String userName;
 private ArrayList glasses;
 
 Lot(String lotId1, String glsQty1, String lotId2, String glsQty2, String userId, String userName) { 
  this.glasses = new ArrayList();
  this.lotId1 = lotId1;
  this.glsQty1 = glsQty1;
  this.lotId2 = lotId2;
  this.glsQty2 = glsQty2;
  this.userId = userId;
  this.userName = userName;
    
  f = DocumentBuilderFactory.newInstance();
  try {
   b = f.newDocumentBuilder();
  } catch (ParserConfigurationException e) {   
   e.printStackTrace();
  }
  doc = b.newDocument();
  
 }

 public String genObjectToXML(){  
  try {   
   /*
    * XML output format:    
    */   
   Element root = doc.createElement(this.getClass().getSimpleName()); 
   doc.appendChild(root);
         Element e;
         e = doc.createElement("lotId1");
         root.appendChild(e);
         e.appendChild(doc.createTextNode(this.lotId1));
         e = doc.createElement("glsQty1");
         root.appendChild(e);
         e.appendChild(doc.createTextNode(this.glsQty1));
         e = doc.createElement("lotId2");
         root.appendChild(e);
         e.appendChild(doc.createTextNode(this.lotId2));
         e = doc.createElement("glsQty2");
         root.appendChild(e);
         e.appendChild(doc.createTextNode(this.glsQty2));
         e = doc.createElement("userId");
         root.appendChild(e);
         e.appendChild(doc.createTextNode(this.userId));
         e = doc.createElement("userName");
         root.appendChild(e);
         e.appendChild(doc.createTextNode(this.userName)); 
         
         Element g, dpLot, cutLot, gId, location, orgLocation;
         for(int i=0;i<glasses.size();i++){
          Glass objG = (Glass)glasses.get(i);
          g = doc.createElement("glass");
          root.appendChild(g);
          
          dpLot = doc.createElement("dpLotId");
          g.appendChild(dpLot);
          dpLot.appendChild(doc.createTextNode(objG.getDpLotId()));
          cutLot = doc.createElement("cutLotId");
          g.appendChild(cutLot);
          cutLot.appendChild(doc.createTextNode(objG.getCutLotId()));
          gId = doc.createElement("glsId");
          g.appendChild(gId);
          gId.appendChild(doc.createTextNode(objG.getGlsId()));
          location = doc.createElement("location");
          g.appendChild(location);
          location.appendChild(doc.createTextNode(objG.getLocation()));
          orgLocation = doc.createElement("orgLocation");
          g.appendChild(orgLocation);
          orgLocation.appendChild(doc.createTextNode(objG.getOrgLocation()));
         }
                
         
         TransformerFactory tf = TransformerFactory.newInstance();
   Transformer m = tf.newTransformer();
   DOMSource source = new DOMSource(doc);
   ByteArrayOutputStream byte1 = new ByteArrayOutputStream();
   StreamResult result = new StreamResult(byte1);
   System.out.println("Encoding: " + m.getOutputProperty(OutputKeys.ENCODING));
   m.setOutputProperty(OutputKeys.ENCODING, "BIG5");
   m.transform(source, result);
   return byte1.toString();
   
  } catch (TransformerConfigurationException e) {
   e.printStackTrace();
  } catch (TransformerException e) {   
   e.printStackTrace();  
  }
  return null;
 }
 
 public void putGlass(String dpLotId, String cutLotId, String glsId, String location, String orgLocation) {
  if (dpLotId != null && cutLotId != null && glsId != null && location != null && orgLocation != null) {
   Glass g = new Glass();
   g.setDpLotId(dpLotId);
   g.setCutLotId(cutLotId);   
   g.setGlsId(glsId);
   g.setLocation(location);
   g.setOrgLocation(orgLocation);
   glasses.add(g);
  }
 }

 class Glass {
  private String dpLotId;
  private String cutLotId;
  private String glsId;
  private String location;
  private String orgLocation;

  public String getGlsId() {
   return glsId;
  }
  public void setGlsId(String glsId) {
   this.glsId = glsId;
  }
  public String getLocation() {
   return location;
  }
  public void setLocation(String location) {
   this.location = location;
  }
  public String getDpLotId() {
   return dpLotId;
  }
  public void setDpLotId(String dpLotId) {
   this.dpLotId = dpLotId;
  }
  public String getCutLotId() {
   return cutLotId;
  }
  public void setCutLotId(String cutLotId) {
   this.cutLotId = cutLotId;
  }
  public String getOrgLocation() {
   return orgLocation;
  }
  public void setOrgLocation(String orgLocation) {
   this.orgLocation = orgLocation;
  }
 } 
}

神眼三代與呼叫器無法同步解決法

說媽媽的VIOS被偷兒光顧後,我們家裡就出現三隻神眼三代傳訊鎖了。有用過這隻的朋友都知道這隻鎖最重要的就是鎖體上鎖後會同步呼叫器,當有人打開車門或進入車內時,鎖體會大叫,呼叫器也會第一時間通知車主。

最近有一隻鎖體沒電了,我就依照著說明手冊步驟更換電池,測試時,鎖體打開到open再扣上C型扣,居然有兩個呼叫器都B一聲,同步開機了,糟了! 我再測試另一隻原來鎖體,打開再扣上C型扣,哇~都沒辦法同步配對的呼叫器了。(變成A鎖同步A呼叫器與B呼叫器,而B鎖沒有呼叫器能與它同步)

為了重新同步,打了通電話給神眼的經銷商,居然要我郵寄給他們重設,電話那頭說:「重設定呼叫器就可以了,跟你說你也不會做,寄回來我們重設就好。」

「哇咧~~我們家有三隻鎖耶! 那每次出問題時都寄回去,鎖體很重,郵寄費不低耶~~,重設呼叫器誰不會呀; 步驟說清楚我不就知道了嗎。」心裡OS。

不死心,再打一通給鎖的製造商-超安精密,電話是位聲音很好聽的小姐接聽,說明過鎖的狀況與問題後,她很熱心的解說重設步驟,是這樣低。
  • 1.將無法同步的鎖體與呼叫器拿遠一點,離另外2隻鎖與呼叫器遠一點。
  • 2.鎖體用key打開到open,C型扣扣回,B一聲,閃燈熄滅後,馬上再打開到open。
  • 3.馬上按下呼叫器左鍵(解除鍵),按一下放開。
  • 4.等一下,若成功鎖會BBB之後閃爍呼叫器也會B並且液晶上會有訊號格顯示。

    再一次謝謝超安,客服做的不錯哦~有你們的貼心,真好。

    11/10/2009

    Java 自已動手寫log

    不用log4j自已寫個簡單的log程式。
    分檔規則是將log分年,月記錄,每天一個log檔,日子一久想查某一天的log也比較方便。
    例如:2009年10月11月有log時,log分檔會像這樣。
    • /2009/10/
      • 1.log
      • 2.log
      • 3.log
      • 5.log
      • ......
    • /2009/11/
      • 1.log
      • 2.log
      • 3.log
      • .....

    Log class
    /*
     * Log.java with encode
     * for logging
     *
     * Created on 2009年10月16日
     *
     * @author  Iden
     *
     ****<< Modification Note >>
     *     Date       PTS/PBR/PCR      Label       Editor         Description
     *  ==========  ===============  ==========  ==========  ============================================================
     *  2009/10/16                      0.0.0.1      Iden         create
     */
    package com.iden.util;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    import java.nio.charset.Charset;
    import java.nio.charset.CharsetEncoder;
    import java.text.SimpleDateFormat;
    
    public class Log {
     
     private String filePath = ""; //directory path of Log 
     private String filePrefix = ""; //prefix name of log file
     private String fileSubName = ""; //subname of log file
     String curWorkingDir = System.getProperty("user.dir"); //User working directory
     private String breakLine="\n";  
     private Object encoding;   
     private String encodingStr;   
    
     public Log(String path) {
      this(path, "log", "UTF-8");
     }
     
     public Log(String path, String subname, Object encoding) {
      this(path, "Log", subname, encoding);
     }
     
     public Log(String path, String prefix, String subname, Object encoding) {
      if(encoding ==null)
       new Exception("encoding is empth");
      
      filePath = path;
      filePrefix = prefix;
      fileSubName = subname;
      this.encoding = encoding;  
     }
     
     
     /**
      * Output the log file
      * @param str
      */
     public void write(String str) {  
      OutputStream stream = null;
            Writer writer = null;
      SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");  
      try {
       String folder = generateDirectory();
          
       File file = new File(folder + filePrefix + "_" + getCurrYYYYMMDD() + "." + fileSubName);
       
       StringBuffer sb = new StringBuffer("");
       sb.append("[" + formatter.format(new java.util.Date()) + "] [start]" + breakLine)
        .append(str)
        .append(breakLine + "[end]" + breakLine);
          
             stream = new FileOutputStream(file, true);
             
                if (encoding instanceof Charset) {
                    writer = new OutputStreamWriter(stream, (Charset)encoding);
                } else if (encoding instanceof CharsetEncoder) {
                    writer = new OutputStreamWriter(stream, (CharsetEncoder)encoding);
                } else {
                    writer = new OutputStreamWriter(stream, (String)encoding);
                }
                OutputStreamWriter osw =(OutputStreamWriter)writer;
          encodingStr =  osw.getEncoding();      
          osw = null;
                
                writer.write(sb.toString());
                writer.flush();
                writer.close();
                
      } catch (java.io.FileNotFoundException efnf) {
       writeException("FileNotFoundException at open log file: " + efnf.getMessage());   
      } catch (java.io.IOException exio) {
       writeException("IOException at write log file: " + exio.getMessage());   
      } catch (java.lang.Exception e) {
       writeException("Exception at write log file: " + e.getMessage());   
      } finally {
       writer = null;
      }
     }
     
     /**
      * Output the log file with default encoding
      * @param str
      */
     public void writeDefaultEncode(String str) {
      java.io.FileWriter fw = null;  
      SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");  
      try {
       String folder = generateDirectory();
    
       fw = new java.io.FileWriter(folder + filePrefix + "_"
         + getCurrYYYYMMDD() + "." + fileSubName, true);
       
       fw.write("[" + formatter.format(new java.util.Date()) + "] " + breakLine + "[start]" + breakLine);
       fw.write(str);
       fw.write(breakLine + "[end]" + breakLine);
       fw.flush();
       fw.close();     
                   
      } catch (java.io.FileNotFoundException efnf) {
       writeException("FileNotFoundException at open log file: " + efnf.getMessage());   
      } catch (java.io.IOException exio) {
       writeException("IOException at write log file: " + exio.getMessage());   
      } catch (java.lang.Exception e) {
       writeException("Exception at write log file: " + e.getMessage());   
      } finally {
       fw = null;
      }
     } 
     
     /**
      * Get the encoding string
      */
     public String getEncoding(){
      if(encodingStr != null)
       return encodingStr;
      return null;
     } 
    
     /**
      * Generate directory path
      * @return
      */
     private String generateDirectory() {
      String folder = defineDirectoryName(filePath);
      java.io.File file = new java.io.File(folder);
      file.mkdirs();
      return folder;
     }
    
     /**
      * Define the directory path of Log. format is path\YYYY\MM
      * @param path
      * @return current directory path
      */
     private String defineDirectoryName(String path) {
      java.util.Calendar cal = java.util.Calendar.getInstance(java.util.Locale.TAIWAN);
      String folder = path;  
      
      folder = folder + "\\" + String.valueOf(cal.get(java.util.Calendar.YEAR));
      if (String.valueOf((cal.get(java.util.Calendar.MONTH) + 1)).length() == 1) {
       folder = folder + "\\0" + String.valueOf((cal.get(java.util.Calendar.MONTH) + 1));
      } else {
       folder = folder + "\\" + String.valueOf((cal.get(java.util.Calendar.MONTH) + 1));
      } 
      folder = folder + "\\";
      return folder;
     }
     
     /**
      * Get the current date. format is YYYYMMDD
      * @return String of YYYYMMDD
      */
     private String getCurrYYYYMMDD() {  
      SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); //yyyy/MM/dd HH:mm:ss
      return formatter.format(new java.util.Date());
     } 
     
     /**
      * Output Exception message from this object
      * @param msg
      */
     private void writeException(String msg){
      new Log(this.curWorkingDir).write(msg);
     }
     
    }
    
    

    Java中像 printStackTrace() 拋出 Stack String

    有時侯需要將stack中的例外訊息拋出來給使用者查詢或寫成log,這時侯就需要下面的程式了。
    package com.iden.util;
    
    import java.io.PrintWriter;
    import java.io.StringWriter;
    import java.io.Writer;
    
    public class HandleException {
     
     /**
      * Return StackTrace information
      * @param throwObj
      * @return
      */
     private static String getStackTrace(Throwable throwObj) {
      final Writer result = new StringWriter();
      final PrintWriter printWriter = new PrintWriter(result);
      throwObj.printStackTrace(printWriter);
      return result.toString();
     }
     
     /**
      * Return custom StackTrace information
      * @param throwObj
      * @return
      */
     private static String getCuctomStackTrace(Throwable throwObj) {  
      final StringBuilder result = new StringBuilder("HandleException.getCuctomStackTrace(): ");
      result.append(throwObj.toString());
      final String NEW_LINE = System.getProperty("line.separator");
      result.append(NEW_LINE);
      
      for (StackTraceElement element : throwObj.getStackTrace()) {
       result.append(element);
       result.append(NEW_LINE);
      }
      return result.toString();
     }
     
     public static void main(String[] args){
      try{
       throw new NullPointerException("Iden test");
       //throw new AlreadyBoundException("Iden test");
      }catch(Exception e){
       if(e instanceof java.lang.NullPointerException){ 
        System.out.println(getStackTrace(e));
        System.out.println(getCuctomStackTrace(e));
       } 
      }  
     }
     
    }
    

    Java load properties file

    如何用Java去讀取外部resource檔,要怎麼做呢?
    EIF.properties是個文件檔,放在class可以讀到的路徑下,在這裡是放在/bin。

    PropertyLoader class
    package com.iden.resource;
    
    import java.util.Properties;
    
    public class PropertyLoader {
    
     private Properties prop = null;
     private Boolean isSet;
    
     PropertyLoader() {
      prop = new Properties();
      try {
       prop.load(getClass().getResourceAsStream("/EIF.properties"));
      } catch (Exception e) {
       e.printStackTrace();
      }
      if (new String(
        prop.getProperty("PropertyLoaderTest.isSet") != null ? prop
          .getProperty("PropertyLoaderTest.isSet") : "").trim()
        .equalsIgnoreCase("1"))
       isSet = true;
      else
       isSet = false;
     }
     
     public static void main(String[] args){
      PropertyLoader loader = new PropertyLoader();
      System.out.println("PropertyLoaderTest.isSet=" + loader.isSet);
      
     }
    }
    

    EIF.properties
    # 1 or 0  / 1:short data model: update data when start time, end time, shift time  0:every data update model
    PropertyLoaderTest.isSet=1
    

    11/04/2009

    VB Window Form 限制輸入字數 code

    VB.net限制只能輸入多少字並大寫,以下是練習。
    'TextBox limit character digits user input
        Public Sub limitTextBoxDigits(ByRef obj As System.Windows.Forms.TextBox, ByVal digits As Integer)
            obj.CharacterCasing = Windows.Forms.CharacterCasing.Upper
            If obj.SelectedText <> "" Then 
                Dim selIdx As Integer = obj.SelectionStart
                obj.Text = obj.Text.Remove(obj.SelectionStart, obj.SelectionLength)
                obj.Select(selIdx, 1)
            End If
            If obj.Text.Length >= digits Then obj.Text = obj.Text.Remove(digits - 1, 1) : obj.Select(digits - 1, 1)
        End Sub