changed to unmaintained
[aaf/authz.git] / auth / auth-batch / src / main / java / org / onap / aaf / auth / batch / update / Upload.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
4  * ===========================================================================
5  * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
6  *
7  * Modifications Copyright (C) 2018 IBM.
8  * ===========================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END====================================================
21  */
22
23 package org.onap.aaf.auth.batch.update;
24
25 import java.io.File;
26 import java.io.IOException;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Map;
31
32 import org.onap.aaf.auth.batch.Batch;
33 import org.onap.aaf.auth.batch.helpers.CQLBatch;
34 import org.onap.aaf.auth.batch.helpers.CQLBatchLoop;
35 import org.onap.aaf.auth.env.AuthzTrans;
36 import org.onap.aaf.auth.org.OrganizationException;
37 import org.onap.aaf.cadi.util.CSV;
38 import org.onap.aaf.misc.env.APIException;
39 import org.onap.aaf.misc.env.Env;
40 import org.onap.aaf.misc.env.LogTarget;
41 import org.onap.aaf.misc.env.TimeTaken;
42 import org.onap.aaf.misc.env.util.Split;
43
44 public class Upload extends Batch {
45
46     private static final String DAT = ".dat";
47
48     private CQLBatch cqlBatch;
49
50     private Map<String,Feed> feeds;
51
52
53     public Upload(AuthzTrans trans) throws APIException, IOException, OrganizationException {
54         super(trans.env());
55         trans.info().log("Starting Connection Process");
56
57         TimeTaken tt0 = trans.start("Cassandra Initialization", Env.SUB);
58         try {
59             TimeTaken tt = trans.start("Connect to Cluster", Env.REMOTE);
60             try {
61                 session = cluster.connect();
62             } finally {
63                 tt.done();
64             }
65
66             cqlBatch = new CQLBatch(LogTarget.NULL,session);
67
68             feeds=new HashMap<>();
69             new Feed(feeds,"ns",1,"name,description,parent,scope=int,type=int",300);
70             new Feed(feeds,"notified",3,"user,target,key,last",300);
71             new Feed(feeds,"approval",1,"id=UUID,approver,last_notified,memo,operation,status,ticket=UUID,type,user",200);
72             new Feed(feeds,"artifact",2,"mechid,machine,ca,dir,expires,notify,ns,os_user,renewdays=int,sans=set,sponsor,type=set",200);
73             new Feed(feeds,"cred",1,"id,type=int,expires,cred=blob,notes,ns,other=int,prev=blob,tag",200);
74             new Feed(feeds,"x509",2,"ca,serial=blob,id,x500,x509=C/R",200);
75             new Feed(feeds,"role",2,"ns,name,description,perms=set",200);
76             new Feed(feeds,"perm",4,"ns,type,instance,action,description,roles=set",200);
77             new Feed(feeds,"history",1,"id=UUID,action,memo,reconstruct=blob,subject,target,user,yr_mon=int",300);
78
79         } finally {
80             tt0.done();
81         }
82     }
83
84
85     @Override
86     protected void run(AuthzTrans trans) {
87         List<File> files = new ArrayList<>();
88         for(String s : args()) {
89                 trans.init().log(s);
90         }
91         
92         if(args().length>0) {
93             File dir = new File(args()[0]);
94             if(dir.isDirectory()) {
95                 for(File f : dir.listFiles(pathname -> {
96                     return pathname.getName().endsWith(DAT);
97                 })) {
98                     files.add(f);
99                 }
100             } else {
101                 File f;
102                 for(String arg : args()) {
103                     if(arg.endsWith(DAT)) {
104                         f=new File(arg);
105                     } else {
106                         f=new File(arg+DAT);
107                     }
108                     files.add(f);
109                 }
110             }
111         }
112         
113         for(File file : files) {
114             String f = file.getName();
115             final Feed feed = feeds.get(f.substring(0,f.length()-4));
116             if(feed!=null) {
117                 TimeTaken tt = trans.start(file.getAbsolutePath(), Env.SUB);
118                 String msg = String.format("#### Running %s.dat Feed ####",feed.getName());
119                 trans.info().log(msg);
120                 System.out.println(msg);
121                 CQLBatchLoop cbl = new CQLBatchLoop(cqlBatch,feed.batchSize,dryRun).showProgress();
122
123                 try {
124                     if(file.exists()) {
125                         CSV csv = new CSV(trans.env().access(),file).setDelimiter('|');
126                         csv.visit( row -> {
127                             feed.insert(cbl.inc(),row);
128                         });
129                     }
130                     cbl.flush();
131                 } catch (Throwable e) {
132                     e.printStackTrace();
133                 } finally {
134                     tt.done();
135                     System.err.flush();
136                     msg = String.format("\n%d applied in %d batches\n",cbl.total(), cbl.batches());
137                     trans.info().log(msg);
138                     System.out.println(msg);
139                 }
140             }
141         }
142     }
143
144     @Override
145     protected void _close(AuthzTrans trans) {
146         session.close();
147     }
148
149     private class Feed {
150         private final String name;
151         private final String[] flds;
152         private final String[] types;
153         private final int key;
154         private final int batchSize;
155         public Feed(Map<String, Feed> feeds, String feed, int keyLength, String fields,int batchSize) {
156             name=feed;
157             key = keyLength;
158             flds = Split.splitTrim(',', fields);
159             types = new String[flds.length];
160             this.batchSize = batchSize;
161             int equals;
162             for(int i=0;i<flds.length;++i) {
163                 if((equals = flds[i].indexOf('='))>0) {
164                     types[i]=flds[i].substring(equals+1);
165                     flds[i]=flds[i].substring(0, equals);
166                 }
167             }
168             feeds.put(feed,this);
169         }
170
171         public String getName() {
172             return name;
173         }
174
175         public void insert(StringBuilder sb,List<String> row) {
176             sb.append("INSERT INTO authz.");
177             sb.append(name);
178             sb.append(" (");
179             boolean first = true;
180             StringBuilder values = new StringBuilder(") VALUES (");
181             String value;
182             String type;
183             for(int idx=0;idx<row.size();++idx) {
184                 value = row.get(idx).trim();
185                 if(idx<key || !(value.isEmpty() || "null".equals(value))) {
186                     if(first) {
187                         first = false;
188                     } else {
189                         sb.append(',');
190                         values.append(',');
191                     }
192                     sb.append(flds[idx]);
193                     type=types[idx];
194                     if(type==null) { // String is default.
195                         switch(value) {
196                           case "":
197                             if(idx<key) {
198                                 // Key value has to be something, but can't be actual null
199                                 values.append("''");
200                             } else {
201                                 values.append("null");
202                             }
203                             break;
204                           default:
205                             values.append('\'');
206                             values.append(value.replaceAll("'","''"));
207                             values.append('\'');
208                         }
209                     } else switch(type) {
210                             case "C/R":
211                                 values.append('\'');
212                                 values.append(value.replaceAll("\\\\n", "\n"));
213                                 values.append('\'');
214                                 break;
215                             default:
216                                 values.append(value);
217                                 break;
218
219                     }
220                 }
221             }
222             sb.append(values);
223             sb.append(");\n");
224         }
225     }
226 }
227