Approval Batch, prep better JUnit
[aaf/authz.git] / auth / auth-batch / src / main / java / org / onap / aaf / auth / batch / update / Approvals.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
4  * ===========================================================================
5  * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
6  * ===========================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END====================================================
19  *
20  */
21
22 package org.onap.aaf.auth.batch.update;
23
24 import java.io.File;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.GregorianCalendar;
28 import java.util.List;
29
30 import org.onap.aaf.auth.batch.Batch;
31 import org.onap.aaf.auth.batch.BatchPrincipal;
32 import org.onap.aaf.auth.batch.approvalsets.ApprovalSet;
33 import org.onap.aaf.auth.batch.approvalsets.URApprovalSet;
34 import org.onap.aaf.auth.batch.helpers.Approval;
35 import org.onap.aaf.auth.batch.helpers.BatchDataView;
36 import org.onap.aaf.auth.batch.helpers.Future;
37 import org.onap.aaf.auth.batch.helpers.NS;
38 import org.onap.aaf.auth.batch.helpers.Role;
39 import org.onap.aaf.auth.batch.helpers.UserRole;
40 import org.onap.aaf.auth.dao.cass.UserRoleDAO;
41 import org.onap.aaf.auth.env.AuthzTrans;
42 import org.onap.aaf.auth.layer.Result;
43 import org.onap.aaf.auth.org.OrganizationException;
44 import org.onap.aaf.cadi.CadiException;
45 import org.onap.aaf.cadi.util.CSV;
46 import org.onap.aaf.misc.env.APIException;
47 import org.onap.aaf.misc.env.util.Chrono;
48
49 public class Approvals extends Batch {
50     private final AuthzTrans noAvg;
51         private BatchDataView dataview;
52
53     public Approvals(AuthzTrans trans) throws APIException, IOException, OrganizationException {
54         super(trans.env());
55         
56         noAvg = env.newTransNoAvg();
57         noAvg.setUser(new BatchPrincipal("batch:Approvals"));
58
59         dataview = new BatchDataView(noAvg,cluster,dryRun);
60         
61         session = dataview.getSession(trans);
62         
63         Approval.load(trans, session, Approval.v2_0_17);
64         Future.load(trans, session, Future.v2_0_17);
65         Role.load(trans, session);
66         NS.load(trans, session, NS.v2_0_11);
67         UserRole.load(trans, session, UserRole.v2_0_11);
68     }
69
70     @Override
71     protected void run(AuthzTrans trans) {
72         // Create Intermediate Output 
73         final GregorianCalendar now = new GregorianCalendar();
74         
75         List<File> approveFiles = new ArrayList<>();
76         if(args().length>0) {
77                 for(int i=0;i<args().length;++i) {
78                         approveFiles.add(new File(logDir(), args()[i]));
79                 }
80         } else {
81                 approveFiles.add(new File(logDir(),"OneMonth"+Chrono.dateOnlyStamp()+".csv"));
82         }
83         
84         for(File f : approveFiles) {
85                 trans.init().log("Processing File:",f.getAbsolutePath());
86         }
87         
88 //        GregorianCalendar gc = new GregorianCalendar();
89 //        Date now = gc.getTime();
90 //        String today = Chrono.dateOnlyStamp(now);
91         for(File f : approveFiles) {
92                 trans.info().log("Processing ",f.getAbsolutePath(),"for Approvals");
93                 if(f.exists()) {
94                         CSV approveCSV = new CSV(env.access(),f).processAll();
95                         try {
96                                         approveCSV.visit(row -> {
97                                                 switch(row.get(0)) {
98                                                         case "ur":
99                                                                 UserRoleDAO.Data urdd = UserRole.row(row);
100                                                                 List<Approval> apvs = Approval.byUser.get(urdd.user);
101                                                                 
102                                                                 System.out.println(row);
103                                                                 if(apvs==null) {
104                                                                         // Create an Approval
105                                                                         ApprovalSet uras = new URApprovalSet(noAvg, now, dataview, () -> {
106                                                                                 return urdd;
107                                                                         });
108                                                                         Result<Void> rw = uras.write(noAvg);
109                                                                         if(rw.notOK()) {
110                                                                                 System.out.println(rw.errorString());
111                                                                         }
112                                                                 } else {
113                                                                         // Check that Existing Approval is still valid
114                                                                         for(Approval a : apvs) {
115                                                                                 Future ticket = Future.data.get(a.add.ticket);
116                                                                                 if(ticket==null) {
117                                                                                         // Orphaned Approval - delete
118                                                                                 } else {
119                                                                                         
120                                                                                 }
121                                                                         }
122                                                                 }
123                                                                 break;
124                                                         default:
125                                                                 System.out.println(row);
126                                                                 //noAvg.debug().printf("Ignoring %s",type);
127                                                 }
128                                         });
129                                 } catch (IOException | CadiException e) {
130                                         e.printStackTrace();
131                                         // .... but continue with next row
132                                 }
133                         
134                         /*
135         List<Approval> pending = new ArrayList<>();
136         boolean isOwner,isSupervisor;
137         for (Entry<String, List<Approval>> es : Approval.byApprover.entrySet()) {
138             isOwner = isSupervisor = false;
139             String approver = es.getKey();
140             if (approver.indexOf('@')<0) {
141                 approver += org.getRealm();
142             }
143             Date latestNotify=null, soonestExpire=null;
144             GregorianCalendar latest=new GregorianCalendar();
145             GregorianCalendar soonest=new GregorianCalendar();
146             pending.clear();
147             
148             for (Approval app : es.getValue()) {
149                 Future f = app.getTicket()==null?null:Future.data.get(app.getTicket());
150                 if (f==null) { // only Ticketed Approvals are valid.. the others are records.
151                     // Approvals without Tickets are no longer valid. 
152                     if ("pending".equals(app.getStatus())) {
153                         app.setStatus("lapsed");
154                         app.update(noAvg,apprDAO,dryRun); // obeys dryRun
155                     }
156                 } else {
157                     if ((soonestExpire==null && f.expires()!=null) || (soonestExpire!=null && f.expires()!=null && soonestExpire.before(f.expires()))) {
158                         soonestExpire=f.expires();
159                     }
160
161                     if ("pending".equals(app.getStatus())) {
162                         if (!isOwner) {
163                             isOwner = "owner".equals(app.getType());
164                         }
165                         if (!isSupervisor) {
166                             isSupervisor = "supervisor".equals(app.getType());
167                         }
168
169                         if ((latestNotify==null && app.getLast_notified()!=null) ||(latestNotify!=null && app.getLast_notified()!=null && latestNotify.before(app.getLast_notified()))) {
170                             latestNotify=app.getLast_notified();
171                         }
172                         pending.add(app);
173                     }
174                 }
175             }
176
177             if (!pending.isEmpty()) {
178                 boolean go = false;
179                 if (latestNotify==null) { // never notified... make it so
180                     go=true;
181                 } else {
182                     if (!today.equals(Chrono.dateOnlyStamp(latest))) { // already notified today
183                         latest.setTime(latestNotify);
184                         soonest.setTime(soonestExpire);
185                         int year;
186                         int days = soonest.get(GregorianCalendar.DAY_OF_YEAR)-latest.get(GregorianCalendar.DAY_OF_YEAR);
187                         days+=((year=soonest.get(GregorianCalendar.YEAR))-latest.get(GregorianCalendar.YEAR))*365 + 
188                                 (soonest.isLeapYear(year)?1:0);
189                         if (days<7) { // If Expirations get within a Week (or expired), notify everytime.
190                             go = true;
191                         }
192                     }
193                 }
194             }
195           */
196                 }
197         }
198     }
199     
200     @Override
201     protected void _close(AuthzTrans trans) {
202         if(session!=null) {
203                 session.close();
204                 session = null;
205         }
206     }
207 }