最終回:SFDCのデータを抽出してAWSのS3にCSVを出力する(その4)

このシリーズいよいよ最終回です。今回は前回のクラス群をまとめて、そいつをバッチ化するところをやっていきます。これでひとまず、SFDCに登録されたデータをSOQLで抽出してS3CSVとしてアップロードということができました。ひとまずはやりたいことができたので一安心です。
(開発者エディションでやったので本番アップロード手順は知らない。)

◆大枠の手順

1.AWSでS3を設定する
 1)S3バケット作成
 2)IAMポリシー設定
 3)IAMユーザ追加
2.SFDC設定
 1)環境変数関連設定
 2)パラメータ入力
 3)リモートサイト許可
3.プログラム作成(単体レベル)
 1)環境変数抽出
 2)SOQLを使用してデータ抽出
 3)S3にCSVファイルをアップロード
4.バッチ設定

◆プログラム群

CsvSendController
--------------------
global class CsvSendController implements Schedulable,Database.AllowsCallouts{
   public void execute(SchedulableContext sc) {
       main();
   }
   //メール送信
   public void doSendMail(String subject,String body) {
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setToAddresses(new String[] { 'Mailaddr@example.com' });
        email.setSubject(subject);
        email.setPlainTextBody(body);
        List results = 
            Messaging.sendEmail(new Messaging.Email[] { email }, false);
        if (!results.get(0).isSuccess()) {
            System.StatusCode statusCode = results.get(0).getErrors()[0].getStatusCode();
            String errorMessage = results.get(0).getErrors()[0].getMessage();
        }    
   } 
  //主処理
  public void main(){
      String AccessKeyId;
      String SecretAccessKey;
      String BucketName;
      String Domain;
      try{
          //S3の設定値取得
          Map S3Param = new Map();
          GetEnvironment ge = new GetEnvironment();
          S3Param = ge.GetEnv();
          for(String sKey:S3Param.keySet()){
               if(sKey == 'S3Key'){
                 AccessKeyId = S3Param.get(sKey);
               }
               if(sKey == 'S3Token'){
                 SecretAccessKey = S3Param.get(sKey);
               }
               if(sKey == 'S3Bucket'){
                 BucketName = S3Param.get(sKey);
               }
               if(sKey == 'S3Domain'){
                 Domain = S3Param.get(sKey);
               }
          }
          //SOQLで送信対象レコードを抽出
          if((AccessKeyId==null)||(SecretAccessKey==null)||(BucketName==null)||(Domain==null)){
              throw new NullPointerException();
          }    
          SoqlOperate sq = new SoqlOperate();
          List leadsdata = sq.GetLeads();
          if(!leadsdata.isEmpty()){
              String body = sq.RecordsTransferCsv(leadsdata);
              List ids = sq.ReturnKeyId(leadsdata);
              //S3にファイル送信
              if(body==null){
                  throw new NullPointerException();
              }    
              String pfx =Datetime.now().format('yyyyMMddHHmmss');
              String fn = pfx + '_sample.csv';
              PutFiletoS3.PutS3(body,fn,AccessKeyId,SecretAccessKey,BucketName,Domain,ids);
              //処理完了時メール送信
              doSendMail('Complete','File Send Complete!');
          }else{
           System.debug('Processing target was 0');
          }
      }catch(Exception e){
          System.debug('Exception caught: ' + e.getMessage());
          system.debug(e.getLineNumber());
          String error = 'Exception caught: ' + e.getMessage() + '\r\n' + e.getLineNumber();
          doSendMail('Exception',error);
      }
  }
}
--------------------
CSVSendControllerTest
--------------------
@isTest(SeeAllData=true)
private class CSVSendControllerTest {
 @isTest static void doSendMail(){
        CsvSendController cs = new CsvSendController();
  String subject = 'This is subject';
        String body = 'This is Body!!';
  cs.doSendMail(subject,body);
    }
    @isTest static void mainTest(){
        CsvSendController cs = new CsvSendController();
  cs.main();
    }
}
--------------------
以下のコードをデバッグ登録
--------------------
//スケジューラ登録
CsvSendController cs = new CsvSendController();
//10分ごとのジョブ名指定
List sch = new List {
    '0 0 * * * ?','0 10 * * * ?','0 20 * * * ?',
    '0 30 * * * ?','0 40 * * * ?','0 50 * * * ?'
};
List Jobname = new List {
    'CsvSendController_00','CsvSendController_10','CsvSendController_20',
    'CsvSendController_30','CsvSendController_40','CsvSendController_50'
};
//スケジュール設定
for (Integer i = 0; i < 6 ; i++) {
     System.schedule(Jobname[i], sch[i] , cs);
}
--------------------


◆その他補足

1.デバッガを開く方法














2.スケジューラ登録状況









◆参考サイト

・バッチスケジューラ登録

https://tyoshikawa1106.hatenablog.com/entry/2019/09/16/090707
 https://qiita.com/riunraku/items/493649dbab0518ee9a32
 http://blog.subnetwork.jp/?p=1330
 https://salesforce.oikeru.com/entry/batch-testclass-execute-method-no-cover
 https://developer.salesforce.com/docs/atlas.ja-jp.apexcode.meta/apexcode/apex_scheduler.htm#!
 http://blog.flect.co.jp/salesforce/2010/08/apex-02db.html
 http://kayakuguri.github.io/blog/2015/06/11/apex-batch-schedule/
 https://developer.salesforce.com/forums/?id=906F00000009BP6IAM
 https://qiita.com/naoto_koyama/items/292eff57c780b2ee8c6b
 https://dev.classmethod.jp/cloud/salesforce_batch_test/
 https://www.xgeek.net/ja/salesforce/batch-apex-running-mode-parallel-and-series-and-how-to-maintain-state-in-it/
 https://note.com/20190504/n/n3aa4af95e06a
   https://developer.salesforce.com/forums/?id=906F00000009BPtIAM
 https://qiita.com/naoto_koyama/items/83624f70e29dfa7067eb
 http://blog.flect.co.jp/salesforce/2010/08/apex-2136.html
 https://qiita.com/esira/items/bc4205d7d581fdc75757
 https://www.cnblogs.com/dlywang0411/p/11579196.html
 https://tyoshikawa1106.hatenablog.com/entry/2019/09/16/110039
 http://sfsupport.blog.fc2.com/blog-entry-22.html
   http://kayakuguri.github.io/blog/2015/06/11/apex-batch-schedule/
   http://magnet88jp.hateblo.jp/entry/2013/08/30/201543
   https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_scheduler.htm
   http://blog.flect.co.jp/salesforce/2010/08/apex-2136.html
   https://odekakeshimasyo.me/salesforce-schedule.html
   https://www.xgeek.net/ja/salesforce/writing-a-schedulable-batch-apex-in-salesforce/
 https://www.kokyakukanri.info/salesforce/blog/2010/12/apex-4.html
 https://developer.salesforce.com/blogs/developer-relations/2015/05/queueable-apex-future.html

・メール送信

  https://tyoshikawa1106.hatenablog.com/entry/2019/03/24/125332


しょせん素人なので結局は以下のコピペです。
まぁもっとツヨツヨな方が色々と書かれているのでそちらを参考にされた方がいいかとは思います。SFDCapexはよくわかりませんでしたが何とかなりました。
先人の皆様ありがとうございます。
*但しもう二度と触りたくない、、、、

1.時刻を指定してSOQLでデータ抽出
2.S3(環境変数にS3のアクセスキー埋め込んで接続してCSV出力)
3.スケジューラ設定

コメント

このブログの人気の投稿

証券外務員1種勉強(計算式暗記用メモ)

GASでGoogleDriveのサブフォルダとファイル一覧を出力する

マクロ経済学(IS-LM分析)