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