001/*
002 * Copyright (c) 2009 The openGion Project.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
013 * either express or implied. See the License for the specific language
014 * governing permissions and limitations under the License.
015 */
016package org.opengion.hayabusa.mail;
017
018import static org.opengion.fukurou.util.StringUtil.*;
019
020import java.util.ArrayList;
021import java.util.HashMap;
022import java.util.List;
023import java.util.Map;
024
025import javax.mail.Address;
026import javax.mail.SendFailedException;
027import javax.mail.internet.InternetAddress;
028
029import org.opengion.fukurou.db.ConnectionFactory;
030import org.opengion.fukurou.db.DBFunctionName;
031import org.opengion.fukurou.db.DBUtil;
032import org.opengion.fukurou.db.Transaction;
033import org.opengion.fukurou.db.TransactionReal;
034import org.opengion.fukurou.mail.MailTX;
035import org.opengion.fukurou.util.ApplicationInfo;
036import org.opengion.fukurou.util.StringUtil;
037import org.opengion.hayabusa.common.HybsSystem;
038
039/**
040 * タグ mailSender2 及びバッチによる送信の共通処理部分を実装しています。
041 * 送信タグ mailSender2 もしくは送信デーモンからパラメータを受取ります。
042 * パラメータ中の定型文ID及びシステムIDで定型文マスタよりメールの定型文を取得して、
043 * パラメータ値とマージしてメール文を合成します。同時に、宛先にセットした社員ID、
044 * グループIDと定型文の宛先設定に基づき、社員マスタとグループマスタよりメールアドレス
045 * 情報を取得して送信を行います。
046 * エラーがなければ送信した内容を履歴テーブル、宛先テーブルに書き込みます。
047 * 最後に本処理の呼出元に送信結果、エラーメッセージを返します。
048 *
049 * @og.group メールモジュール
050 *
051 * @version  4.0
052 * @author   Sen.Li
053 * @since    JDK1.6
054 */
055public abstract class AbstractMailManager {
056
057        // 5.2.0.0 (2010/09/01) Ver4互換モード対応
058        private static final String CONTENTS = HybsSystem.sysBool( "VER4_COMPATIBLE_MODE" ) ? "CONTENT" : "CONTENTS";
059
060        // 5.9.26.0 (2017/11/02) DB共通化のため、DBFunctionNameを使用して、シーケンスを取得するように変更
061//      private static final String     selYkno = "SELECT GE32S02.NEXTVAL YKNO FROM DUAL";
062
063        // 5.0.3.0 (2009/11/04) CONTENT ⇒ CONTENTS
064        // 5.2.0.0 (2010/09/01) Ver4互換モード対応
065//      private static final String     insGE32         = "INSERT INTO GE32(YKNO,PARA_KEY,PTN_ID,FROM_ADDR,TITLE,CONTENTS,ATTACH1,ATTACH2,ATTACH3,ATTACH4,ATTACH5,DYSET,USRSET,PGUPD,SYSTEM_ID,FGJ)"
066        private static final String     insGE32         = "INSERT INTO GE32(YKNO,PARA_KEY,PTN_ID,FROM_ADDR,TITLE,"+CONTENTS+",ATTACH1,ATTACH2,ATTACH3,ATTACH4,ATTACH5,DYSET,USRSET,PGUPD,SYSTEM_ID,FGJ)"
067                                                                                        + " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'1')";
068        private static final String insGE34             = "INSERT INTO GE34(YKNO,DST_ID,GROUP_ID,DST_NAME,DST_ADDR,DST_KBN,FGJ,DYSET,USRSET,PGUPD)"
069                                                                                        + " VALUES(?,?,?,?,?,?,?,?,?,?)";
070        /** フラグ定数 {@value} */
071        protected static final String FGJ_SEND_WAIT     = "0";
072        /** フラグ定数 {@value} */
073        protected static final String FGJ_SEND_OVER     = "1";
074        /** フラグ定数 {@value} */
075        protected static final String FGJ_ADDR_ERR      = "7";
076        /** フラグ定数 {@value} */
077        protected static final String FGJ_ACNT_ERR      = "8";
078
079        // 内部データのカラム番号(履歴テーブル)
080        private static final int GE32_YKNO              = 0 ;
081        private static final int GE32_PARAKEY   = 1 ;
082        private static final int GE32_PTN_ID    = 2;
083        private static final int GE32_FROM_ADDR = 3;
084        private static final int GE32_TITLE     = 4;
085        private static final int GE32_CONTENTS  = 5;            // 5.0.3.0 (2009/11/04) CONTENT ⇒ CONTENTS
086        private static final int GE32_ATTACH1   = 6;
087        private static final int GE32_ATTACH2   = 7;
088        private static final int GE32_ATTACH3   = 8;
089        private static final int GE32_ATTACH4   = 9;
090        private static final int GE32_ATTACH5   = 10;
091        private static final int GE32_DYSET             = 11;
092        private static final int GE32_USRSET    = 12;
093        private static final int GE32_PGUPD     = 13;
094        private static final int GE32_SYSTEM_ID = 14;
095        // 内部データのカラム番号(履歴テーブル)
096        private static final int GE34_YKNO              = 0 ;
097        private static final int GE34_DST_ID    = 1 ;
098        private static final int GE34_GROUP_ID  = 2 ;
099        private static final int GE34_DST_NAME  = 3 ;
100        private static final int GE34_DST_ADDR  = 4 ;
101        private static final int GE34_DST_KBN   = 5 ;
102        private static final int GE34_FGJ               = 6 ;
103        private static final int GE34_DYSET             = 7 ;
104        private static final int GE34_USRSET    = 8 ;
105        private static final int GE34_PGUPD     = 9 ;
106//      private static String           host            = HybsSystem.sys( "COMMON_MAIL_SERVER" );
107        private static String           charset         = HybsSystem.sys( "MAIL_DEFAULT_CHARSET" );
108//      private static String           smtpPort        = HybsSystem.sys( "SMTP_PORT" );                                // 5.4.3.2 (2012/01/06)
109//      private static String           auth            = HybsSystem.sys( "MAIL_SEND_AUTH" );                   // 5.4.3.2 (2012/01/06)
110//      private static String           authUser        = HybsSystem.sys( "MAIL_SEND_AUTH_USER" );              // 5.4.3.2 (2012/01/06)
111//      private static String           authPass        = HybsSystem.sys( "MAIL_SEND_AUTH_PASSWORD" );  // 5.4.3.2 (2012/01/06)
112        private boolean                         debugFlag   = false;
113        private final List<String>        errAddrList = new ArrayList<String>();
114        private static final int MAX_RETRY              = 3 ;   // メールアドレスエラー発生した場合、メール再送回数
115
116        // 5.6.6.0 (2013/07/05) host等の外部指定に対応
117        private String          host            = HybsSystem.sys( "COMMON_MAIL_SERVER" );               // 5.6.6.0 (2013/07/05)
118        private String          smtpPort        = HybsSystem.sys( "SMTP_PORT" );                                // 5.6.6.0 (2013/07/05)
119        private String          auth            = HybsSystem.sys( "MAIL_SEND_AUTH" );                   // 5.6.6.0 (2013/07/05)
120        private String          authPort        = HybsSystem.sys( "MAIL_SEND_AUTH_PORT" );              // 5.8.1.1 (2014/11/14)
121        private String          authUser        = HybsSystem.sys( "MAIL_SEND_AUTH_USER" );              // 5.6.6.0 (2013/07/05)
122        private String          authPass        = HybsSystem.sys( "MAIL_SEND_AUTH_PASSWORD" );  // 5.6.6.0 (2013/07/05)
123        private boolean         useTLS          = HybsSystem.sysBool( "MAIL_SEND_USE_STARTTLS" );        // 5.9.29.2(2018/02/16)
124
125        private String  mailTitle, mailContent, fromAddr;
126        private String[] attachFiles;
127        private Map<String, String[]>     mailDstMap              = null;
128        private Map<String,String>                initParamMap    = null;         // パラメータマップ
129        private MailTX                                  mail                    = null;
130
131        protected final String DBID = HybsSystem.sys( "RESOURCE_DBID" );                // 5.5.5.1 (2012/08/07) リソース系DBID 付け忘れ対応
132
133        /** コネクションにアプリケーション情報を追記するかどうか指定 */
134        private static final boolean USE_DB_APPLICATION_INFO  = HybsSystem.sysBool( "USE_DB_APPLICATION_INFO" ) ;
135
136        /** アプリケーション情報 */
137        public static final ApplicationInfo appInfo;
138        static {
139                if( USE_DB_APPLICATION_INFO ) {
140                        appInfo = new ApplicationInfo();
141                        // ユーザーID,IPアドレス,ホスト名
142                        appInfo.setClientInfo( "MailModuel", HybsSystem.HOST_ADRS, HybsSystem.HOST_NAME );
143                        // 画面ID,操作,プログラムID
144                        appInfo.setModuleInfo( "MailModuel", "MailManager", "MailManager" );
145                }
146                else {
147                        appInfo = null;
148                }
149        }
150
151        /**
152         * 呼出元よりパラメータマップを受取って、メールオブジェクト(mailObj)を作成します。
153         * メールオブジェクトは定型文ID及びシステムIDに基づいて定型文マスタからメールの定型文を取得して、
154         * パラメータ値とマージしてメール文の各項目を合成します。
155         * 宛先については、宛先にセットした社員ID、グループIDと定型文の宛先設定に基づき、社員マスタとグループマスタ
156         * よりメールアドレスを取得して宛先マップを作成します。
157         * まだ、添付ファイルのセット処理も行っています。
158         *
159         * @og.rev 5.6.6.0 (2013/07/05) host等の外部設定対応
160         * @og.rev 5.9.15.1 (2016/12/09) エラーリストのクリア
161         * @og.rev 5.9.29.2 (2018/02/16) STARTTLS対応
162         *
163         * @param       params  パラメータのマップ
164         */
165        public void create( final Map<String, String> params ) {
166                initParamMap = params;
167                MailPattern mailObj = new MailPattern( params );
168                fromAddr = mailObj.getFromAddr();
169                setAttachFiles( params.get( "ATTACH1" )
170                                          , params.get( "ATTACH2" )
171                                          , params.get( "ATTACH3" )
172                                          , params.get( "ATTACH4" )
173                                          , params.get( "ATTACH5" ) ); // 添付ファイルのセット
174                mailDstMap = mailObj.getDstMap();
175                mailTitle = mailObj.getTitle();
176                mailContent = mailObj.getContent();
177                errAddrList.clear(); // 5.9.15.1 (2016/12/09)
178                errAddrList.addAll( mailObj.getErrList() );
179
180                // 5.6.6.0 (2013/07/05)
181                host            = nval( mailObj.getHost()               ,host           );
182                smtpPort        = nval( mailObj.getSmtpPort()   ,smtpPort       );
183                auth            = nval( mailObj.getAuth()               ,auth           );
184                authPort        = nval( mailObj.getAuthPort()   ,authPort       );              // 5.8.1.1 (2014/11/14)
185                authUser        = nval( mailObj.getAuthUser()   ,authUser       );
186                authPass        = nval( mailObj.getAuthPass()   ,authPass       );
187                useTLS          = mailObj.getUseTLS();                  // 5.9.29.2 (2018/02/13)
188        }
189
190        /**
191         * メール送信を行うメソッドです。
192         * createメソッドより合成した内容で送信を行います。アドレスエラー発生時に、
193         * ユーザー設定(addrCheck)により再送/中止します。
194         * メールサーバーに送信して、例外"SendFailedException"をキャッチできたら、
195         * メールアカウントがエラーとなるのを分かります。そして、例外のオブジェクトから
196         * エラーとなっているアカウントを取得して宛先マップから除外して、残りのアドレスに再送できます。
197         * 送信後履歴テーブル(GE32)、宛先テーブル(GE34)に送信結果を書き込みます。
198         *
199         * @og.rev 5.4.3.2 (2012/01/06) 送信時認証対応
200         * @og.rev 5.9.29.2 (2018/02/16) STARTTLS対応
201         *
202         */
203        public void send() {
204                List<String> invalidAddrBuf       = new ArrayList<String>();
205//              // mail = new MailTX( host, charset );
206//              mail = new MailTX( host, charset, smtpPort, auth, authPort,authUser, authPass ); // 5.4.3.2 認証対応
207                mail = new MailTX( host, charset, smtpPort, auth, authPort,authUser, authPass, useTLS ); // 5.9.29.2 (2019/02/16)
208                mail.setFrom( fromAddr );                       // 送信者アドレス
209                mail.setFilename( attachFiles );        // 添付ファイルをセットします。
210                mail.setSubject( mailTitle );           // メールタイトル
211                mail.setMessage( mailContent );         // メール本文
212                mail.setDebug( debugFlag );
213                setMailDst( invalidAddrBuf );           // 宛先をセットします。
214                // メール送信を行います。
215                int retryCount = MAX_RETRY;
216                while( retryCount > 0 ) {
217                        try {
218                                mail.sendmail();
219                        }
220                        catch( RuntimeException rex ) {
221                                Throwable cause = rex.getCause();
222                                if( cause instanceof SendFailedException ) {
223                                        Address[] invAddress = ( (SendFailedException) cause ).getInvalidAddresses();
224                                        if( invAddress != null ) {
225                                                int invCount = invAddress.length;
226                                                for( int i = 0; i < invCount; i++ ) {
227                                                        invalidAddrBuf.add( ( (InternetAddress) invAddress[i] ).getAddress() );
228                                                }
229                                        }
230                                }
231                                else {
232                                        String errMsg = "送信時にエラー発生しました。" + rex.getMessage();
233                                        throw new RuntimeException( errMsg,rex );
234                                }
235                        }
236
237//                      if( invalidAddrBuf.size() > 0 ) {
238//                              StringBuilder errMsgBuf = new StringBuilder();
239//                              for( int i = 0; i < invalidAddrBuf.size(); i++ ) {
240//                                      errMsgBuf.append( "," ).append( invalidAddrBuf.get( i ) );
241//                              }
242//                              String userIds = getUserIds( invalidAddrBuf );
243//                              String errMsg = "アドレスエラー。ユーザーID:" + userIds + " アドレス:" + errMsgBuf.toString().substring( 1 );
244//                              if( "true".equals( initParamMap.get( "ADDR_CHECK" ) ) ){
245//                                      throw new RuntimeException( errMsg );
246//                              }
247//                              else {
248//                                      // メールアカウントチェックしない場合、無効のメールアドレスを除いて再送します。
249//                                      setMailDst( invalidAddrBuf );
250//                                      retryCount--;
251//                                      invalidAddrBuf.clear();
252//                                      errAddrList.add( errMsg );
253//                              }
254//                      }
255//                      else {
256//                              retryCount = -1;
257//                      }
258
259                        if( invalidAddrBuf.isEmpty() ) {
260                                retryCount = -1;
261                        }
262                        else {
263                                StringBuilder errMsgBuf = new StringBuilder();
264                                for( int i = 0; i < invalidAddrBuf.size(); i++ ) {
265                                        errMsgBuf.append( ',' ).append( invalidAddrBuf.get( i ) );
266                                }
267                                String userIds = getUserIds( invalidAddrBuf );
268                                String errMsg = "アドレスエラー。ユーザーID:" + userIds + " アドレス:" + errMsgBuf.toString().substring( 1 );
269                                if( "true".equals( initParamMap.get( "ADDR_CHECK" ) ) ){
270                                        throw new RuntimeException( errMsg );
271                                }
272                                else {
273                                        // メールアカウントチェックしない場合、無効のメールアドレスを除いて再送します。
274                                        setMailDst( invalidAddrBuf );
275                                        retryCount--;
276                                        invalidAddrBuf.clear();
277                                        errAddrList.add( errMsg );
278                                }
279                        }
280                }
281                commitMailDB();         // 送信結果を履歴テーブル、宛先テーブルにセットします。
282        }
283
284        /**
285         * デバッグ情報の表示を行うかどうか[true/false]をセットします。
286         *
287         * @param   debug  [true:出力する/それ以外:しない]
288         */
289        public void setDebug( final boolean debug ) {
290                debugFlag = debug;
291        }
292
293        /**
294         * メール送信者アドレスをセットします。
295         *
296         * @param  from 送信者アドレス
297         */
298        public void setFromAddr( final String from ) {
299                fromAddr = from;
300        }
301
302        /**
303         * メールタイトルをセットします。
304         *
305         * @param  title メールタイトル
306         */
307        public void setTitle( final String title ) {
308                mailTitle = title;
309        }
310
311        /**
312         * メール本文をセットします。
313         *
314         * @param  content メール本文
315         */
316        public void setContent( final String content ) {
317                mailContent = content;
318        }
319
320        /**
321         * メール送信ホストをセットします。
322         * 初期値は、システム定数のCOMMON_MAIL_SERVER を使用します。
323         *
324         * (初期値:システム定数のCOMMON_MAIL_SERVER[={@og.value org.opengion.hayabusa.common.SystemData#COMMON_MAIL_SERVER}])。
325         *
326         * @og.rev 5.6.6.0 (2013/07/05)
327         *
328         * @param  hostName 送信ホスト
329         */
330        public void setHost( final String hostName ) {
331                host = nval( hostName, host );
332        }
333
334        /**
335         * メール送信ポート番号をセットします。
336         * 初期値は、システム定数のSMTP_PORT を使用します。
337         *
338         * (初期値:システム定数のSMTP_PORT[={@og.value org.opengion.hayabusa.common.SystemData#SMTP_PORT}])。
339         *
340         * @og.rev 5.6.6.0 (2013/07/05)
341         *
342         * @param  port SMTPポート
343         */
344        public void setPort( final String port ) {
345                smtpPort = nval( port, smtpPort );
346        }
347
348        /**
349         * メール送信時認証有無をセットします。
350         * 認証を行う場合は「POP_BEFORE_SMTP」と指定して下さい。
351         * 認証時には認証ユーザと認証パスワードを設定する必要があります。
352         * 初期値は、システム定数のMAIL_SEND_AUTH を使用します。
353         *
354         * (初期値:システム定数のMAIL_SEND_AUTH[={@og.value org.opengion.hayabusa.common.SystemData#MAIL_SEND_AUTH}])。
355         *
356         * @og.rev 5.6.6.0 (2013/07/05)
357         *
358         * @param  useAuth 認証方式
359         */
360        public void setAuth( final String useAuth ) {
361                auth = nval( useAuth, auth );
362        }
363
364        /**
365         * メール送信認証ユーザをセットします。
366         * 初期値は、システム定数のMAIL_SEND_AUTH_USER を使用します。
367         *
368         * (初期値:システム定数のMAIL_SEND_AUTH_USER[={@og.value org.opengion.hayabusa.common.SystemData#MAIL_SEND_AUTH_USER}])。
369         *
370         * @og.rev 5.6.6.0 (2013/07/05)
371         *
372         * @param  user 認証ユーザ
373         */
374        public void setAuthUser( final String user ) {
375                authUser = nval( user, authUser );
376        }
377
378        /**
379         * メール送信認証パスワードをセットします。
380         * 初期値は、システム定数のMAIL_SEND_AUTH_PASSWORD を使用します。
381         *
382         * (初期値:システム定数のMAIL_SEND_AUTH_PASSWORD[={@og.value org.opengion.hayabusa.common.SystemData#MAIL_SEND_AUTH_PASSWORD}])。
383         *
384         * @og.rev 5.6.6.0 (2013/07/05)
385         *
386         * @param  pass 認証パスワード
387         */
388        public void setAuthPass( final String pass ) {
389                authPass = nval( pass, authPass );
390        }
391        
392        /**
393         * メール送信にSTARTTLSを利用するかのフラグをセットします。。
394         * 初期値は、システム定数のMAIL_SEND_USE_STARTTLS を使用します。
395         *
396         * (初期値:システム定数のMAIL_SEND_AUTH_PASSWORD[={@og.value org.opengion.hayabusa.common.SystemData#MAIL_SEND_USE_STARTTLS}])。
397         *
398         * @og.rev 5.9.29.2 (2018/02/16)
399         *
400         * @param  flg TLSの利用有無
401         */
402        public void setUseTLS( final boolean flg ) {
403                useTLS = flg;
404        }
405
406        /**
407         * メール送信者アドレスを返します。
408         *
409         * @return      送信者アドレス
410         */
411        public String getFromAddr() {
412                return fromAddr;
413        }
414
415        /**
416         * メールタイトルを返します。
417         *
418         * @return      メールタイトル
419         */
420        public String getTitle() {
421                return mailTitle;
422        }
423
424        /**
425         * メール本文を返します。
426         *
427         * @return      メール本文
428         */
429        public String getContent() {
430                return mailContent;
431        }
432
433        /**
434         * 送信結果を履歴テーブル(GE32)と宛先テーブル(GE34)に登録します。
435         * 登録時に、桁数オーバーにならないように、テーブル定義の桁数を上限として、
436         * 登録前に各項目の桁数整理を行います。
437         *
438         * @og.rev 5.5.5.1 (2012/08/07) リソース系DBID 付け忘れ対策
439         * @og.rev 5.9.1.3 (2015/10/30) 4000文字カットをやめる
440         */
441        protected void commitMailDB(){
442                // 履歴テーブルの追加
443                String[] insGE32Args = new String[15];
444                String ykno = getYkno();
445                insGE32Args[GE32_YKNO]          = ykno;
446                insGE32Args[GE32_PARAKEY]       = initParamMap.get( "PARAKEY" );
447                insGE32Args[GE32_PTN_ID]        = trim( initParamMap.get( "PTN_ID" ), 20 );
448                insGE32Args[GE32_FROM_ADDR] = trim( fromAddr, 100);
449                insGE32Args[GE32_TITLE]         = trim( mailTitle, 300);
450//              insGE32Args[GE32_CONTENTS]      = trim( mailContent,4000);              // 5.0.3.0 (2009/11/04) CONTENT ⇒ CONTENTS
451                insGE32Args[GE32_CONTENTS]      = mailContent;                                  // 5.9.1.3 (2015/10/30)
452                insGE32Args[GE32_ATTACH1]       = "";
453                insGE32Args[GE32_ATTACH2]       = "";
454                insGE32Args[GE32_ATTACH3]       = "";
455                insGE32Args[GE32_ATTACH4]       = "";
456                insGE32Args[GE32_ATTACH5]       = "";
457                if ( attachFiles != null ) {
458                        int attSize = attachFiles.length;
459                        for( int i = 0; i < attSize; i++ ) {
460                                insGE32Args[6 + i] = trim( attachFiles[i], 256);
461                        }
462                }
463                insGE32Args[GE32_DYSET]  = HybsSystem.getDate( "yyyyMMddHHmmss" );
464                insGE32Args[GE32_USRSET] = initParamMap.get( "LOGIN_USERID" );
465                insGE32Args[GE32_PGUPD] = initParamMap.get( "PGID" );
466                insGE32Args[GE32_SYSTEM_ID] = initParamMap.get( "SYSTEM_ID" );
467//              DBUtil.dbExecute( insGE32, insGE32Args, appInfo );
468                DBUtil.dbExecute( insGE32, insGE32Args, appInfo, DBID );        // 5.5.5.1 (2012/08/07)
469
470                // 宛先テーブル追加
471                String[] insGE34Args = new String[10];
472                insGE34Args[GE34_YKNO]= ykno;
473                for( String dstId : mailDstMap.keySet() ) {
474                        insGE34Args[GE34_DST_ID]        = trim( mailDstMap.get( dstId )[MailPattern.IDX_DST_ID]  , 10 );
475                        insGE34Args[GE34_GROUP_ID]      = trim( mailDstMap.get( dstId )[MailPattern.IDX_GROUP_ID], 20 );
476                        insGE34Args[GE34_DST_NAME]      = trim( mailDstMap.get( dstId )[MailPattern.IDX_DST_NAME], 20 );
477                        insGE34Args[GE34_DST_ADDR]      = trim( mailDstMap.get( dstId )[MailPattern.IDX_DST_ADDR], 100 );
478                        insGE34Args[GE34_DST_KBN]       = mailDstMap.get( dstId )[MailPattern.IDX_DST_KBN];
479                        insGE34Args[GE34_FGJ]           = mailDstMap.get( dstId )[MailPattern.IDX_FGJ];
480                        insGE34Args[GE34_DYSET]         = HybsSystem.getDate( "yyyyMMddHHmmss" );
481                        insGE34Args[GE34_USRSET]        = initParamMap.get( "LOGIN_USERID" );
482                        insGE34Args[GE34_PGUPD]         = initParamMap.get( "PGID" );
483//                      DBUtil.dbExecute( insGE34, insGE34Args, appInfo );
484                        DBUtil.dbExecute( insGE34, insGE34Args, appInfo, DBID );                // 5.5.5.1 (2012/08/07)
485                }
486        }
487
488        /**
489         * パラメータマップをセットします。
490         *
491         * @param       params  パラメータのマップ
492         */
493        protected void setInitParams( final Map<String, String> params ) {
494                initParamMap = params;
495        }
496
497        /**
498         * 添付ファイル配列をセットします。
499         *
500         * @param       attach1 添付ファイル名1
501         * @param       attach2 添付ファイル名2
502         * @param       attach3 添付ファイル名3
503         * @param       attach4 添付ファイル名4
504         * @param       attach5 添付ファイル名5
505         */
506        protected void setAttachFiles( final String attach1
507                                                                , final String attach2
508                                                                , final String attach3
509                                                                , final String attach4
510                                                                , final String attach5 ) {
511                List<String> fileList = new ArrayList<String>();
512                if( attach1 != null && attach1.length() != 0 ) { fileList.add( attach1 ); }
513                if( attach2 != null && attach2.length() != 0 ) { fileList.add( attach2 ); }
514                if( attach3 != null && attach3.length() != 0 ) { fileList.add( attach3 ); }
515                if( attach4 != null && attach4.length() != 0 ) { fileList.add( attach4 ); }
516                if( attach5 != null && attach5.length() != 0 ) { fileList.add( attach5 ); }
517                attachFiles = fileList.toArray( new String[fileList.size()] );
518        }
519
520        /**
521         * メール宛先マップをセットします。
522         *
523         * @param   mailDst     メール宛先マップ
524         */
525        protected void setMailDstMap( final Map<String, String[]> mailDst ) {
526                mailDstMap = mailDst;
527        }
528
529        /**
530         * メール宛先マップをセットします。
531         *
532         * @return      メール宛先マップ
533         */
534        protected Map<String, String[]> getMailDstMap() {
535                return mailDstMap;
536        }
537
538        /**
539         * 指定の長さ以内の文字列を返します。
540         *
541         * @og.rev 5.9.1.3 (2015/10/30) 文字数ではなくByte数に変更
542         *
543         * @param       src             オリジナルの文字列
544         * @param       maxLen  指定の長さ
545         *
546         * @return      指定の長さに短縮された文字列
547         */
548        protected String trim( final String src, final int maxLen ) {
549                String rtn = src;
550                if( src != null && src.length() > maxLen ) {
551//                      rtn = src.substring( 0, maxLen );
552                        rtn = StringUtil.cut( src, maxLen );
553                }
554                return rtn;
555        }
556
557        /**
558         * アドレスチェックのエラーリストを返します。
559         *
560         * @return      エラーリスト
561         */
562        protected List<String> getErrList(){
563                return errAddrList;
564        }
565
566        /**
567         * 宛先マップを元に、送信オブジェクトに宛先をセットします。
568         * セットする際に、アカウントエラーとなっているアドレスを除外します。
569         * 宛先が存在しない場合、例外を投げます。
570         *
571         * @og.rev 4.3.7.5 (2009/07/08) 送信先名称が設定されていない場合は、アドレスを<>で囲わない
572         *
573         * @param invalidAddr 宛先のリスト
574         */
575        private void setMailDst( final List<String> invalidAddr ){
576                ArrayList<String> toList = new ArrayList<String>();
577                ArrayList<String> ccList = new ArrayList<String>();
578                ArrayList<String> bccList = new ArrayList<String>();
579
580                Map<Integer, ArrayList<String>> tempMap = new HashMap<Integer, ArrayList<String>>();
581                tempMap.put( Integer.valueOf( MailPattern.KBN_TO ),  toList );
582                tempMap.put( Integer.valueOf( MailPattern.KBN_CC ),  ccList );
583                tempMap.put( Integer.valueOf( MailPattern.KBN_BCC ), bccList );
584
585                for( String dstId : mailDstMap.keySet() ) {
586                        String[] dstInfo = mailDstMap.get( dstId );
587                        Integer kbn = Integer.valueOf( dstInfo[MailPattern.IDX_DST_KBN] );
588                        if( !invalidAddr.contains( dstInfo[MailPattern.IDX_DST_ADDR] )
589                                        && !FGJ_ADDR_ERR.equals( dstInfo[MailPattern.IDX_FGJ] )){
590                                dstInfo[MailPattern.IDX_FGJ] = FGJ_SEND_OVER;
591
592                                // 4.3.7.5 (2009/07/08)
593                                String name = dstInfo[MailPattern.IDX_DST_NAME];
594                                if( name != null && name.length() > 0 ) {
595                                        tempMap.get( kbn ).add( dstInfo[MailPattern.IDX_DST_NAME] +  "<"+ dstInfo[MailPattern.IDX_DST_ADDR] + ">" );
596                                }
597                                else {
598                                        tempMap.get( kbn ).add( dstInfo[MailPattern.IDX_DST_ADDR] );
599                                }
600                        }
601                        else {
602                                if( FGJ_SEND_OVER.equals( dstInfo[MailPattern.IDX_FGJ] ) ) {
603                                        dstInfo[MailPattern.IDX_FGJ] = FGJ_ACNT_ERR;
604                                }
605                        }
606                }
607
608                mail.clearTo();         // 宛先(TO)をクリア
609                mail.clearCc();         // 宛先(CC)をクリア
610                mail.clearBcc();        // 宛先(BCC)をクリア
611                boolean haveValidAddr = false ;
612//              if( toList.size() > 0 ) {    // toのセット
613                if( ! toList.isEmpty() ) {      // toのセット
614                        haveValidAddr = true;
615                        String[] to = toList.toArray( new String[toList.size()] );
616                        mail.setTo( to );
617                }
618//              if( ccList.size() > 0 ) {    // ccのセット
619                if( ! ccList.isEmpty() ) {      // ccのセット
620                        haveValidAddr = true;
621                        String[] cc = ccList.toArray( new String[ccList.size()] );
622                        mail.setCc( cc );
623                }
624//              if( bccList.size() > 0 ) {   // bccのセット
625                if( ! bccList.isEmpty() ) {     // bccのセット
626                        haveValidAddr = true;
627                        String[] bcc = bccList.toArray( new String[bccList.size()] );
628                        mail.setBcc( bcc );
629                }
630                if( !haveValidAddr ){           // 宛先全部無効の場合、例外を投げます。
631                        String errMsg = "宛先のメールアドレスが有効ではありません。"
632                                                + "TO , CC , BCC のいづれにもアドレスが設定されていません。"; // 5.1.8.0 (2010/07/01) errMsg 修正
633                        throw new RuntimeException( errMsg );
634                }
635        }
636
637        /**
638         * 要求NOを採番します。
639         * この要求NOで履歴テーブル(GE32)と宛先テーブル(GE30)の関連付けを持たせます。
640         *
641         * @og.rev 5.5.5.1 (2012/08/07) リソース系DBID 付け忘れ対策
642         * @og.rev 5.9.26.0 (2017/11/02) DB共通化対応
643         *
644         * @return      要求NO
645         */
646        private String getYkno() {
647// 2017/10/27 DELETE
648//              String[][] tmp = DBUtil.dbExecute( selYkno, new String[0], appInfo );
649//              String[][] tmp = DBUtil.dbExecute( selYkno, new String[0], appInfo, DBID );             // 5.5.5.1 (2012/08/07)
650//              if( tmp == null || tmp.length == 0 ) {
651//                      String errMsg = "要求NO採番エラー"
652//                                              + " SQL=" + selYkno ;           // 5.1.8.0 (2010/07/01) errMsg 修正
653//                      throw new RuntimeException( errMsg );
654//              }
655//              return tmp[0][0];
656
657                // 5.9.26.0 (2017/11/02) DBFnctionNameを利用して、シーケンスを取得
658                String selYkno = "";
659                Transaction tran = new TransactionReal( appInfo );
660                try{
661                        selYkno = String.valueOf(DBFunctionName.getDBName(ConnectionFactory.getDBName(DBID)).getSequence("GE32S02", tran));
662                }finally{
663                        tran.close();
664                }
665
666                return selYkno;
667        }
668
669        /**
670         * メールアドレスのリストよりユーザーIDを逆引きします。
671         *
672         * @param       addressList     メールアドレスのリスト
673         *
674         * @return      ユーザーID
675         */
676        private String getUserIds( final List<String> addressList ){
677                StringBuilder idBuf = new StringBuilder();
678                Map<String,String>  addressMap = new HashMap<String, String>();
679                for( String userId : mailDstMap.keySet() ) {
680                        String[] dstInfo = mailDstMap.get( userId );
681                        addressMap.put( dstInfo[MailPattern.IDX_DST_ADDR], userId );
682                }
683                for(int i=0; i < addressList.size(); i++){
684                        idBuf.append( ',' ).append( addressMap.get( addressList.get( i ) ) );
685                }
686                String rtn = "";
687                if ( idBuf.length() > 0 ) {
688                        rtn = idBuf.toString().substring( 1 );
689                }
690                return rtn;
691        }
692}