Approval Batch, prep better JUnit
[aaf/authz.git] / cadi / core / src / main / java / org / onap / aaf / cadi / util / CSV.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 package org.onap.aaf.cadi.util;
22
23 import java.io.BufferedReader;
24 import java.io.File;
25 import java.io.FileNotFoundException;
26 import java.io.FileOutputStream;
27 import java.io.FileReader;
28 import java.io.IOException;
29 import java.io.PrintStream;
30 import java.util.ArrayList;
31 import java.util.List;
32
33 import org.onap.aaf.cadi.Access;
34 import org.onap.aaf.cadi.CadiException;
35 import org.onap.aaf.cadi.Access.Level;
36
37 /**
38  * Read CSV file for various purposes
39  * 
40  * @author Instrumental(Jonathan)
41  *
42  */
43 public class CSV {
44         private File csv;
45         private Access access;
46         private boolean processAll;
47         
48         public CSV(Access access, File file) {
49                 this.access = access;
50                 csv = file;
51                 processAll = false;
52         }
53         
54         public CSV(Access access, String csvFilename) {
55                 this.access = access;
56                 csv = new File(csvFilename);
57                 processAll = false;
58         }
59         
60         public CSV processAll() {
61                 processAll = true;
62                 return this;
63         }
64         /*
65          * Create your code to accept the List<String> row.
66          * 
67          * Your code may keep the List... CSV does not hold onto it.
68          * 
69          * @author Instrumental(Jonathan)
70          *
71          */
72         public interface Visitor {
73                 void visit(List<String> row) throws IOException, CadiException;
74         }
75         
76         public void visit(Visitor visitor) throws IOException, CadiException {
77                 BufferedReader br = new BufferedReader(new FileReader(csv));
78                 try {
79                         String line;
80                         StringBuilder sb = new StringBuilder();
81                         while((line = br.readLine())!=null) {
82                                 line=line.trim();
83                                 if(!line.startsWith("#") && line.length()>0) {
84 //                                      System.out.println(line);  uncomment to debug
85                                         List<String> row = new ArrayList<>();
86                                         boolean quotes=false;
87                                         boolean escape=false;
88                                         char c;
89                                         for(int i=0;i<line.length();++i) {
90                                                 switch(c=line.charAt(i)) {
91                                                         case '"':
92                                                                 if(quotes) {
93                                                                         if(i<line.length()-1) { // may look ahead
94                                                                                 if('"' == line.charAt(i+1)) {
95                                                                                         sb.append(c);
96                                                                                         ++i;
97                                                                                 } else {
98                                                                                         quotes = false;
99                                                                                 }
100                                                                         } else {
101                                                                                 quotes=false;
102                                                                         }
103                                                                 } else {
104                                                                         quotes=true;
105                                                                 }
106                                                                 break;
107                                                         case '\\':
108                                                                 if(escape) {
109                                                                         sb.append(c);
110                                                                         escape = false;
111                                                                 } else {
112                                                                         escape = true;
113                                                                 }
114                                                                 break;
115                                                         case ',':
116                                                                 if(quotes) {
117                                                                         sb.append(c);
118                                                                 } else {
119                                                                         row.add(sb.toString());
120                                                                         sb.setLength(0);
121                                                                 }
122                                                                 break;
123                                                         default:
124                                                                 sb.append(c);
125                                                 }
126                                         }
127                                         if(sb.length()>0) {
128                                                 row.add(sb.toString());
129                                                 sb.setLength(0);
130                                         }
131                                         try {
132                                                 visitor.visit(row);
133                                         } catch (CadiException e) {
134                                                 if(processAll) {
135                                                         access.log(Level.ERROR,e);
136                                                 } else {
137                                                         throw e;
138                                                 }
139                                         }
140                                 }
141                         }
142                 } finally {
143                         br.close();
144                 }
145         }
146         
147         public Writer writer() throws FileNotFoundException {
148                 return new Writer(false);
149         }
150
151         public Writer writer(boolean append) throws FileNotFoundException {
152                 return new Writer(append);
153         }
154
155         public class Writer {
156                 private PrintStream ps;
157                 private Writer(final boolean append) throws FileNotFoundException {
158                         ps = new PrintStream(new FileOutputStream(csv,append));
159                 }
160                 public void row(Object ... objs) {
161                         if(objs.length>0) {
162                                 boolean first = true;
163                                 for(Object o : objs) {
164                                         if(first) {
165                                                 first = false;
166                                         } else {
167                                                 ps.append(',');
168                                         }
169                                         if(o == null) {
170                                         } else if(o instanceof String[]) {
171                                                 for(String str : (String[])o) {
172                                                         print(str);
173                                                 }
174                                         } else {
175                                                 print(o.toString());
176                                         }
177                                 }
178                                 ps.println();
179                         }
180                 }
181                 
182                 private void print(String s) {
183                         boolean quote = s.matches(".*[,|\"].*");
184                         if(quote) {
185                                 ps.append('"');
186                                 ps.print(s.replace("\"", "\"\"")
187                                                   .replace("'", "''")
188                                                   .replace("\\", "\\\\"));
189                                 ps.append('"');
190                         } else {
191                                 ps.append(s);
192                         }
193
194                         
195                 }
196                 /**
197                  * Note: CSV files do not actually support Comments as a standard, but it is useful
198                  * @param comment
199                  */
200                 public void comment(String comment) {
201                         ps.print("# ");
202                         ps.println(comment);
203                 }
204                 
205                 public void flush() {
206                         ps.flush();
207                 }
208                 
209                 public void close() {
210                         ps.close();
211                 }
212                 
213                 public String toString() {
214                         return csv.getAbsolutePath();
215                 }
216         }
217
218         public void delete() {
219                 csv.delete();
220         }
221         
222         public String toString() {
223                 return csv.getAbsolutePath();
224         }
225
226 }