2014年7月2日 星期三

Lotus Domino 7.0利用Java呼叫BAPI的範例

這次我們讓Notes的支援工時報工單可以利用BAPI來取回工單的材料說明及實際核發日期來做為簽核的參考.

這篇比上次叫RFC的範例多了
1.取回Structure並輸入參數的例子(有Import及Table)
2.BAPI傳回的Table取值的範例

import lotus.domino.*;
import java.util.*;
import com.sap.mw.jco.*;
public class SAPApprove extends AgentBase {
private Session session;
private AgentContext agentContext;
private Database db;
private String sapIP,sapClient,sapAccount,sapPasswd,sapLang,sapSysNo;
private JCO.Function function;
private JCO.Client client ;
private Log log;
private boolean isError=false;
private String errMsg="";
private String resultCode;
private String resultMsg ;
private JCO.Structure returnStructure;
private Document doc;
private JCO.ParameterList params;

public void init(Session session,AgentContext agentContext) throws NotesException{
try {
this.session=session;
this.agentContext=agentContext;
this.db=agentContext.getCurrentDatabase();
Document profile=db.getProfileDocument("SystemProfile",null);
sapIP=profile.getItemValueString("SAPIP");
sapClient=profile.getItemValueString("SAPClient");
sapAccount=profile.getItemValueString("SAPAccount");
sapPasswd=profile.getItemValueString("SAPPasswd");
sapLang=profile.getItemValueString("SAPCode");
sapSysNo=profile.getItemValueString("SAPSysNO");
String logPath=profile.getItemValueString("LogPath");
log = session.createLog( db.getTitle()+" 's Agent "+agentContext.getCurrentAgent().getName()+" on " + db.getServer());
log.openNotesLog(db.getServer(),logPath);

Agent agent = agentContext.getCurrentAgent();
doc = db.getDocumentByID(agent.getParameterDocID());

System.out.println("Load Profile OK.");
}catch(Exception e) {
e.printStackTrace();
try{
session.setEnvironmentVar("AgentResult","載入SAP 設定時,發生錯誤 !!");
}catch ( Exception ex){}
}
}


public void processApprove() {
boolean isok;
Item notifyitem;
try{
System.out.println("Begin JCO Connection....");
log.logAction("Begin JCO Connection....");
client = JCO.createClient(sapClient, sapAccount, sapPasswd, sapLang, sapIP, sapSysNo);
client.connect();
JCO.Repository repository = new JCO.Repository( "Notes", client );
JCO.Attributes attr = client.getAttributes();
IFunctionTemplate ftemplate = repository.getFunctionTemplate( "BAPI_PROCORD_GET_DETAIL" );
function = new JCO.Function( ftemplate );
//取回structure來設定輸入參數
params = function.getImportParameterList();
JCO.Structure structure1 = params.getStructure("ORDER_OBJECTS");
structure1.setValue("1", "HEADER");

//用Table傳參數的例子
//     JCoTable table = function.getTableParameterList().getTable(targetTableUnderBAPI); //it is taken from the response value of metadata
//System.out.println("No of Columns: "+ table.getNumColumns());
//      System.out.println("Trying to execute append row");
//        table.appendRow();
 //          table.setValue(query_input_column1,query_input_column1_value);
 //        table.setValue(query_input_column2,query_input_column2_value);
 //      table.setValue(query_input_column3,query_input_column3_value);
 //table.setValue(query_input_column4,new java.util.Date(query_input_column4_value));
 //-----------------------------------------------------------------------------------------------------------------------------

System.out.println("Begin Load Not Procsess Documents....");
log.logAction("Begin Load Not Procsess Documents....");
if (doc != null) {
String sn="00"+doc.getItemValueString("PONumber").replaceAll("\\s+", "");
System.out.println("Begin Process PO No: " + sn );
log.logAction("Begin ProcessPO No: " + sn );
function.getImportParameterList().setValue(sn,"NUMBER");
function.getImportParameterList().setValue(structure1,"ORDER_OBJECTS");
client.execute( function );
returnStructure = (JCO.Structure)function.getExportParameterList().getValue("RETURN");
//取回結果的Table並取值
JCO.Table returnTable1 = function.getTableParameterList().getTable("HEADER");
int records = returnTable1.getNumRows();
if (records == 0) {
session.setEnvironmentVar("AgentResult","無此工單");
session.setEnvironmentVar("AgentResult2", "");
}
else {
String rMessage="";
for (int i=0;i<records;i++) {
returnTable1.setRow(i);
rMessage =  rMessage + returnTable1.getString("MATERIAL_TEXT") + "; "; }
returnTable1.setRow(1);
// Date RelaseDate= returnTable1.getDate("ACTUAL_RELEASE_DATE");
String dateString = returnTable1.getString("ACTUAL_RELEASE_DATE");
session.setEnvironmentVar("AgentResult",rMessage);
session.setEnvironmentVar("AgentResult2", dateString);
}
log.logAction("BAPI_PROCORD_GET_DETAIL PONumber: " + sn);
}
}catch(java.lang.NoClassDefFoundError e){
e.printStackTrace();
try{
session.setEnvironmentVar("AgentResult","SAP 元件未安裝!!");
}catch ( Exception ex){}
}
catch(Exception e) {
e.printStackTrace();
try{
log.logError(0,e.getLocalizedMessage());
session.setEnvironmentVar("AgentResult","代理程式發生不明錯誤!!");
}catch(Exception err){}
}finally{
try{
  JCO.releaseClient(client);
log.close();
}catch(Exception err){}
}
}

public void NotesMain() {

try {
Session session = getSession();
AgentContext agentContext = session.getAgentContext();
SAPApprove sapobj=new SAPApprove();
sapobj.init(session,agentContext);

Agent agent = agentContext.getCurrentAgent();

sapobj.processApprove();

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

2014年4月24日 星期四

Domino Notes 7.0 呼叫SAP RFC來取得資產說明

上一篇做了一個簡單的RFC, 這一篇是紀錄如何呼叫SAP RFC來取得資產說明

1.首先要做一個Java agent, 接受doc.NoteID,並將結果用
session.setEnvironmentVar("AgentResult",resultMsg);來傳回Lotusscript

範例:
import lotus.domino.*;
import java.util.*;
import com.sap.mw.jco.*;
public class SAPApprove extends AgentBase {
private Session session;
private AgentContext agentContext;
private Database db;
private String sapIP,sapClient,sapAccount,sapPasswd,sapLang,sapSysNo;
private JCO.Function function;
private JCO.Client client ;
private Log log;
private boolean isError=false;
private String errMsg="";
private String resultCode;
private String resultMsg ;
private Document doc;

public void init(Session session,AgentContext agentContext) throws NotesException{
try {
this.session=session;
this.agentContext=agentContext;
this.db=agentContext.getCurrentDatabase();
Document profile=db.getProfileDocument("SystemProfile",null);
sapIP=profile.getItemValueString("SAPIP");
sapClient=profile.getItemValueString("SAPClient");
sapAccount=profile.getItemValueString("SAPAccount");
sapPasswd=profile.getItemValueString("SAPPasswd");
sapLang=profile.getItemValueString("SAPCode");
sapSysNo=profile.getItemValueString("SAPSysNO");
String logPath=profile.getItemValueString("LogPath");
log = session.createLog( db.getTitle()+" 's Agent "+agentContext.getCurrentAgent().getName()+" on " + db.getServer());
log.openNotesLog(db.getServer(),logPath);

Agent agent = agentContext.getCurrentAgent();
doc = db.getDocumentByID(agent.getParameterDocID());

System.out.println("Load Profile OK.");
}catch(Exception e) {
e.printStackTrace();
try{
session.setEnvironmentVar("AgentResult","載入SAP 設定時,發生錯誤 !!");
}catch ( Exception ex){}
}
}


public void processApprove() {
boolean isok;
Item notifyitem;
try{
System.out.println("Begin JCO Connection....");
log.logAction("Begin JCO Connection....");
client = JCO.createClient(sapClient, sapAccount, sapPasswd, sapLang, sapIP, sapSysNo);
client.connect();
JCO.Repository repository = new JCO.Repository( "Notes", client );
JCO.Attributes attr = client.getAttributes();
IFunctionTemplate ftemplate = repository.getFunctionTemplate( "Z_RFC_ASSETCHECK" );
function = new JCO.Function( ftemplate );
System.out.println("Begin Load Not Procsess Documents....");
log.logAction("Begin Load Not Procsess Documents....");
if (doc != null) {
String sn=doc.getItemValueString("ANLN1").replaceAll("\\s+", "");
String sn2=doc.getItemValueString("ANLN2").replaceAll("\\s+", "");
System.out.println("Begin Process Asset No: " + sn + "-" + sn2);
log.logAction("Begin Process Asset No: " + sn + "-" + sn2);
function.getImportParameterList().setValue(sn,"IANLN1");
function.getImportParameterList().setValue(sn2,"IANLN2");
client.execute( function );
resultCode = (String)function.getExportParameterList().getValue("STATUS");
resultMsg = (String)function.getExportParameterList().getValue("MESSAGE");
if (! (resultCode.equals("") | resultCode.equals("O")) ){
System.out.println("Return Code :"+resultCode);
System.out.println("Return Message :"+resultMsg);
log.logError(1,"Error Code : "+resultCode);
log.logError(1,"Error Message : "+sn+ "-" + sn2+" - "+resultMsg);
isError=true;
errMsg="Notes 與 SAP 溝通作業時發生錯誤";
session.setEnvironmentVar("AgentResult",resultMsg);
}else{
log.logAction("Z_RFC_ASSETCHECK SN: " + sn + "-" + sn2);
isError=false;
session.setEnvironmentVar("AgentResult",resultMsg);
}
}
}catch(java.lang.NoClassDefFoundError e){
e.printStackTrace();
try{
session.setEnvironmentVar("AgentResult","SAP 元件未安裝!!");
}catch ( Exception ex){}
}
catch(Exception e) {
e.printStackTrace();
try{
log.logError(0,e.getLocalizedMessage());
session.setEnvironmentVar("AgentResult","代理程式發生不明錯誤!!");
}catch(Exception err){}
}finally{
try{
  JCO.releaseClient(client);
log.close();
}catch(Exception err){}
}
}

public void NotesMain() {

try {
Session session = getSession();
AgentContext agentContext = session.getAgentContext();
SAPApprove sapobj=new SAPApprove();
sapobj.init(session,agentContext);

Agent agent = agentContext.getCurrentAgent();

sapobj.processApprove();

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

2.Lotusscript呼叫範例:

Sub Click(Source As Button)
If uidoc.EditMode Then
uidoc.Save
Dim agent As NotesAgent
Dim m_agnrtn As String
Set agent=db.GetAgent("SAPAssetCheck")
If (agent.Run(doc.NoteID)><0) Then
Messagebox "執行 SAP 溝通之代理程式,執行錯誤!!",MB_ICONSTOP,"執行錯誤!!"
Exit Sub
End If
m_agnrtn=session.GetEnvironmentString("AgentResult")
If m_agnrtn="SAP 元件未安裝!!" Then
Messagebox "您尚未安裝與SAP溝通之必要元件,若要使用此功能,請連絡相關人員,謝謝!!",MB_ICONSTOP,"元件未安裝"
Exit Sub
End If
Call uidoc.FieldSetText("ANLATXT50", m_agnrtn )
End If
End Sub

2014年4月17日 星期四

我的第一個SAP RFC喔!

由於單據報銷電子簽核時,有要求資產必須先進SAP建檔才可進財務請款,

因此就需要寫個SAP RFC來檢查報銷單據所輸入的資產編碼是否有在SAP當中輸入完成

FUNCTION Z_RFC_ASSETCHECK.
*"----------------------------------------------------------------------
*"*"區域介面:
*"  IMPORTING
*"     VALUE(IANLN1) TYPE  ANLN1
*"     VALUE(IANLN2) TYPE  ANLN2
*"  EXPORTING
*"     VALUE(STATUS) TYPE  CHAR1
*"     VALUE(MESSAGE) TYPE  TEXT300
*"----------------------------------------------------------------------

  DATA : wa_ANLA TYPE  ANLA.

 IF ianln1 IS INITIAL.
    status = 'E'.
    message = '資產編號不得為空值'.
    RETURN.
  ENDIF.

 IF ianln2 IS INITIAL.
    status = 'E'.
    message = '資產子編號不得為空值'.
    RETURN.
  ENDIF.

  SELECT SINGLE *
    FROM ANLA
        INTO  wa_ANLA
    WHERE anln1 EQ ianln1
      AND anln2  EQ ianln2.
  IF sy-subrc NE 0.
    status = 'E'.
    message = '查無此資產'.
  ELSE.
    status = 'O'.
    message = wa_ANLA-TXT50.
  ENDIF.

    RETURN.
ENDFUNCTION.

2014年4月15日 星期二

Domino Notes 7.0 透過web API撈Json資料的範例

取網頁資料請參考這一篇(Notes Client只能在Windows平台上操作喔)

http://stackoverflow.com/questions/12719192/get-a-field-value-from-a-webpage-lotusscript

取json則請使用這個ntf建好的script程式庫

http://www.openntf.org/main.nsf/project.xsp?r=project/JSON%20LS

請先把用到的Class先準備好

這個例子是做當人事單位按開始審核按鈕時,系統自動透過webAPI取回相關打卡紀錄存入PunchCards欄位做佐證.

我放在Form的Postopen事件

Sub Postopen(Source As Notesuidocument)
If source.EditMode Then
Dim internet As New RemoteHTML()
Dim html As String
Dim sJSON As String
Dim PunchTime As String
Dim jsonReader As JSONReader
Dim vResults As Variant
Set jsonReader = New JSONReader
Set doc=uidoc.Document
url$="http://10.100.2.1:8080/API/Employees/"
url2$="/"+Format$(doc.STime(0),"yyyymmdd")+"/"+Format$(doc.ETime(0),"yyyymmdd")
url1$=url$+Ucase(Trim(doc.EmployeeID(0)))+url2$
html = internet.GetHTTP(url1$)
Set vResults = jsonReader.Parse(html) 'this is a JSONObject
If  vResults.Count > 0 Then
PunchTime = PunchTime +Chr(13) + Chr(10)+ vResults.items(0).GetItemValue("RSENO") + vResults.items(0).GetItemValue("BPNME")
For iV = 1 To  vResults.Count
PunchTime = PunchTime +Chr(13) + Chr(10) + "                   "+FindReplace(vResults.items(iv-1).GetItemValue("RSNOW"),"T", "   ")
Next
End If
Dim m_item As NotesItem
Set m_item=doc.GetFirstItem("ApplyListID")
If Not m_item  Is Nothing Then
Forall x In m_item.Values
If Len(Ucase(Cstr(x))) > 0 Then
url1$=url$+Ucase(Cstr(x))+url2$
html = internet.GetHTTP(url1$)
Set vResults = jsonReader.Parse(html) 'this is a JSONObject
If  vResults.Count > 0 Then
PunchTime = PunchTime +Chr(13) + Chr(10)+ vResults.items(0).GetItemValue("RSENO") + vResults.items(0).GetItemValue("BPNME")
For iV = 1 To  vResults.Count
PunchTime = PunchTime +Chr(13) + Chr(10)+ "                   "+FindReplace(vResults.items(iv-1).GetItemValue("RSNOW") , "T", "   ")
Next
End If
End If
End Forall
End If
Call Source.FieldSetText("PunchCards",PunchTime)
End If
End Sub

WebAPI Help

http://10.100.2.1:8080/API/Employees/ID/DATE1/DATE2

ID: 卡號 (EX:K1116)
DATE1 :日期 (EX:20140101)
DATE 2:日期 (EX:20140131)


傳回json範例

[{"RSENO":"K1116","RSTME":"07:53","RSDAT":"2014-04-01T00:00:00","RSNOW":"2014-04-01T07:53:00","BPNME":"Jeff","BPEML":"Jeff@adimxxne.com.tw"},{"RSENO":"K1116","RSTME":"17:24","RSDAT":"2014-04-01T00:00:00","RSNOW":"2014-04-01T17:24:00","BPNME":"Jeff","BPEML":"Jeff@adimxxne.com.tw"}

2014年2月11日 星期二

C#使用OLE來操作Lotus Notes 的 UI

1.加入lotus的參考(當然要先裝Lotus Notes Client)


2.Source Code Sample

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using lotus;
using System.Reflection;


namespace NotesOle
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Type NotesSession = Type.GetTypeFromProgID("Notes.NotesSession");
            Type NotesUIWorkspace = Type.GetTypeFromProgID("Notes.NotesUIWorkspace");
            Object sess = Activator.CreateInstance(NotesSession);
            Object ws = Activator.CreateInstance(NotesUIWorkspace);

            NotesUIWorkspace.InvokeMember("OpenDatabase", BindingFlags.InvokeMethod, null, ws, new Object[] { "NotesSrv3/Adimmune", "Record\\AgnSchedule.nsf", "MailView" });
            Object uidb = NotesUIWorkspace.InvokeMember("GetCurrentDatabase", BindingFlags.InvokeMethod, null, ws, null);

            Object db = NotesUIWorkspace.InvokeMember("Database", BindingFlags.GetProperty, null, uidb, null);
            Type NotesDatabase = db.GetType();

            Type NotesView = Type.GetTypeFromProgID("Notes.NotesView");
            Object view = NotesUIWorkspace.InvokeMember("GetView", BindingFlags.InvokeMethod, null, db, new Object[] { "MailView" });

            Object Document = NotesUIWorkspace.InvokeMember("GetFirstDocument", BindingFlags.InvokeMethod, null, view, new Object[] { });
            Object DocumentUI = NotesUIWorkspace.InvokeMember("EditDocument", BindingFlags.InvokeMethod, null, ws, new Object[] { true, Document });

            //Object uidoc = NotesUIWorkspace.InvokeMember("ComposeDocument", BindingFlags.InvokeMethod, null, ws, new Object[] { "NotesSrv3/Adimmune", "Record\\AgnSchedule.nsf", "Memo", 0, 0, true });
            //Type NotesUIDocument = uidoc.GetType();
            Type NotesUIDocument2 = Document.GetType();

            //NotesUIDocument.InvokeMember("FieldSetText", BindingFlags.InvokeMethod, null, uidoc, new Object[] { "EnterSendTo", "Test sendto" });
            //NotesUIDocument.InvokeMember("FieldSetText", BindingFlags.InvokeMethod, null, uidoc, new Object[] { "Subject", "Test subject" });
            //NotesUIDocument.InvokeMember("FieldSetText", BindingFlags.InvokeMethod, null, uidoc, new Object[] { "Body", "Test body" });

            // bring the Notes window to the front
            //String windowTitle = (String)NotesUIDocument.InvokeMember("WindowTitle", BindingFlags.GetProperty, null, uidoc, null);
            String[] TestString= (String[])NotesUIDocument2.InvokeMember("SendTO", BindingFlags.GetProperty, null, Document, null);

        }
    }
}


2014年1月13日 星期一

Calling Lotus Notes Agent From .NET (Domino 7)

今天參考 http://ithelp.ithome.com.tw/question/10109131 的做法來寫一支Winform去啟動 Notes的Agent(因為Scheduled Agent經常會罷工只好手動).

做完之後, 發現大部份Agent都無法執行RunOnServer.(報錯)

找不到原因之下,最後只好在其中一個看板寫一個簡單的啟動其他Agent之轉接Agent程式.再由C#來啟動這支轉接Agent就都OK啦!

這支轉接Agent的Code 如下
(Declarations)
Dim session As NotesSession
Dim db As NotesDatabase
Dim doc As NotesDocument
Dim view As NotesView

Dim agent As NotesAgent
Dim profile As NotesDocument
Dim currentLog As NotesLog

Sub Initialize
Dim m_item As NotesItem
Dim m_db As NotesDatabase
Dim m_agent As NotesAgent
'Dim m_col As NotesDocumentCollection
Dim m_mail As NotesDocument
Set session=New NotesSession
Set db=session.CurrentDatabase
Set agent = session.CurrentAgent
Set currentLog = New NotesLog( db.Title+" - Agent - "+agent.Name+" on "+db.Server )
Set profile=db.GetProfileDocument("SystemProfile")
Call currentLog.OpenNotesLog( db.Server, profile.LogPath(0) )
Call currentLog.LogAction("代理程式執行檢查 : "+agent.Name)
Set m_db=session.GetDatabase(db.Server,"Flow\CheckFlow.nsf",False)
If Not m_db Is Nothing Then
Call currentLog.LogAction("取得資料庫 : "+m_db.Title)
Set m_agent =m_db.GetAgent("GetSapDataAgent")
If Not m_agent Is Nothing Then
m_find=True
Print "Run Agent : "+m_agent.Name
Call currentLog.LogAction("開始執行代理程式 : "+m_agent.Name)
If m_agent.RunOnServer=0 Then
m_runOk=True
Call currentLog.LogAction("完成執行代理程式 : "+m_agent.Name)
Else
Call currentLog.LogError(1,"代理程式執行錯誤!!")
End If
Else
Call currentLog.LogError(1,"無法取得代理程式,代理程式執行錯誤!!")
End If
Else
Call currentLog.LogError(1,"無法取得資料庫,代理程式執行錯誤!!")
End If
currentLog.LogAction("代理程式結束作業完成!!")
Call currentLog.Close
End Sub

2013年12月6日 星期五

Notes Domino R7 自動抓取國衛院網頁上的公告招標資訊並匯入看板

老大說希望有新的標案就自動通知相關人員, 所以就先做了自動匯入來玩玩看

網址如下,

http://po.nhri.org.tw/po_board/po_query.jsp

代理程式如下 : (使用Java)

import lotus.domino.*;
import java.net.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Date;
import java.util.Vector;
import java.text.*;

public class JavaAgent extends AgentBase {

private Session session;
private AgentContext agentContext;
private Database db;
private Log log;
private Document doc;

public void NotesMain() {

try {
Session session = getSession();
AgentContext agentContext = session.getAgentContext();
Agent agent = agentContext.getCurrentAgent();

// (您的程式碼移至此處)
String web1 = "http://po.nhri.org.tw/po_board/po_query.jsp" ;//UTF-8 國衛院
read1(session,agentContext,web1);


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

public void read1( Session session,AgentContext agentContext,String strURL ) throws NotesException{
         int chunksize = 4096;
        byte[] chunk = new byte[chunksize];
        int count,idx;
        try  {
db=agentContext.getCurrentDatabase();
            URL pageUrl = new URL(strURL );
            // 讀入網頁(位元串流)
            //http://po.nhri.org.tw/po_board/docdownload.jsp?ticket_id=1020432&file_id=201312021140130.pdf
            BufferedInputStream bis = new BufferedInputStream(pageUrl.openStream());
            //BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("URL1.txt", false));
            System.out.println("國衛院資料讀取中" );
            String cname;
            while ((count = bis.read(chunk, 0, chunksize)) != -1) {
               // bos.write(chunk, 0, count); // 寫入檔案
                cname=new String(chunk,"UTF-8");
                int nn=0;
View viewR = db.getView ("ViewByNoA");
Pattern pattern = Pattern.compile("<(td|a href)[^>]*>(.*?)</(td|a)>");
Matcher matcher = pattern.matcher(cname);
while(matcher.find()) {
if (matcher.group().substring(0, 2).compareTo("<a")==0 & nn>0) {
nn=nn+1;
doc.replaceItemValue ("Name",matcher.group().replaceAll("</?[a-z][a-z0-9]*[^<>]*>", ""));    
System.out.println(Integer.toString(nn)+":"+matcher.group().replaceAll("</?[a-z][a-z0-9]*[^<>]*>", ""));
Pattern pattern1 = Pattern.compile("(\"d)(.*?)\"");
Matcher matcher1 = pattern1.matcher(matcher.group());
while(matcher1.find()) {
nn=nn+1;
doc.replaceItemValue ("Hyper","http://po.nhri.org.tw/po_board/"+matcher1.group().replaceAll("\"",""));
System.out.println(Integer.toString(nn)+":"+"檔案網址:http://po.nhri.org.tw/po_board/"+matcher1.group().replaceAll("\"",""));
}
}
else {    
if (matcher.group().replaceAll("</?[a-z][a-z0-9]*[^<>]*>", "").replaceAll("&nbsp;","").compareTo("標的案號")==0 | nn>0) {
nn= nn+1;
cname=matcher.group().replaceAll("</?[a-z][a-z0-9]*[^<>]*>", "").replaceAll("&nbsp;","");
System.out.println(Integer.toString(nn)+":"+cname);
switch(nn) {
  case 1:
      break;
  case 2:
      boolean NotFound = true;
   DocumentCollection dc = db.getAllDocuments();
   Document docR = dc.getFirstDocument ();
   while (docR != null){          
        if (docR.getItemValueString("No").equals(cname) & docR.getItemValueString("Customer").equals("國衛院") ){
                NotFound = false;
            System.out.println("Find:"+cname);
break;
};
       docR = dc.getNextDocument();
    };
   if ( NotFound ) {  
      Date dt = new Date();
   SimpleDateFormat ft =  new SimpleDateFormat (" yyyy.MM.dd E");
   doc = db.createDocument ();
      doc.replaceItemValue ("Form","Form1");
      doc.replaceItemValue ("Customer","國衛院");
      doc.replaceItemValue ("IDay",ft.format(dt));
      doc.replaceItemValue ("No",cname);
      }
      else {      
      nn=0;
      }
      break;
  case 4:
      doc.replaceItemValue ("Item",cname);
      break;
  case 8:
      doc.replaceItemValue ("Type",cname);
      break;
   case 16:
      doc.replaceItemValue ("DDay",cname);
      break;
  case 18:
      doc.replaceItemValue ("Aday",cname);
      if (doc.save ()) {
System.out.println ("Document created and saved");
} else {
System.out.println ("Something went wrong");
}
nn=0;
      break;
  default:      
      break;
}      
}
    }  
};
// System.out.println(cname);
            }
            //bos.close();
            bis.close();
           System.out.println("國衛院資料讀取完成");
         }catch (IOException e) {
             e.printStackTrace();
             try{
session.setEnvironmentVar("AgentResult","國衛院資料讀取時,發生錯誤 !!");
}catch ( Exception ex){}
         }
      }
}