View Javadoc

1   /**
2    * Copyright 2012 The Kuali Foundation Licensed under the
3    * Educational Community License, Version 2.0 (the "License"); you may
4    * not use this file except in compliance with the License. You may
5    * obtain a copy of the License at
6    *
7    * http://www.osedu.org/licenses/ECL-2.0
8    *
9    * Unless required by applicable law or agreed to in writing,
10   * software distributed under the License is distributed on an "AS IS"
11   * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12   * or implied. See the License for the specific language governing
13   * permissions and limitations under the License.
14   *
15   * Created by Charles on 11/15/12
16   */
17  package org.kuali.student.enrollment.class2.courseoffering.refdata;
18  
19  import org.apache.log4j.Logger;
20  import org.kuali.student.r2.common.exceptions.InvalidParameterException;
21  
22  import java.io.File;
23  import java.io.FileNotFoundException;
24  import java.util.ArrayList;
25  import java.util.Arrays;
26  import java.util.List;
27  import java.util.Scanner;
28  
29  /**
30   * This class provides a basic conversion from a CSV file to a SpreadsheetData object
31   *
32   * @author Kuali Student Team
33   */
34  public class BasicCSVParser {
35      private static final Logger LOGGER = Logger.getLogger(BasicCSVParser.class);
36  
37      /**
38       * Assumes splitting each row based on
39       * @param filename
40       * @return
41       * @throws FileNotFoundException
42       */
43      public static SpreadsheetData parseSimpleCSV(String filename) throws FileNotFoundException, InvalidParameterException {
44          if (filename == null) {
45              return null;
46          } else if (!filename.toLowerCase().endsWith(".csv")) {
47              LOGGER.warn(filename +  " does not end in .csv");
48              return null;
49          }
50          File file = new File(filename);
51          Scanner scanner = new Scanner(file);
52          SpreadsheetData data = new SpreadsheetData();
53          boolean hasProcessedHeader = false;
54          while (scanner.hasNextLine()) {
55              String line = scanner.nextLine();
56              if (line.trim().isEmpty()) {
57                  continue; // Shouldn't happen, but doesn't hurt
58              }
59              String[] row = line.split(",");
60              List<String> rowList = new ArrayList<String>(Arrays.asList(row));
61              for (int i = 0; i < rowList.size(); i++) {
62                  rowList.set(i, rowList.get(i).trim());
63              }
64              if (!hasProcessedHeader) {
65                  data.addHeaders(rowList);
66                  hasProcessedHeader = true;
67              } else {
68                  data.addRow(rowList);
69              }
70          }
71          return data;
72      }
73  }