ibragimova_mariam

LoadFile.java

Jul 12th, 2018
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.99 KB | None | 0 0
  1. public class LoadFile extends Action {
  2.  
  3. static final String PATH_PARAM = "Path";
  4. static final String ROW_SUCCESS = "SUCCESS";
  5. static final String ROW_FAIL = "FAIL";
  6. static final String ROW_UNCHECKED = "UNCHECKED";
  7. static final String ROW_STATUS = "IS_CHECKED";
  8. static final String DATA_TABLE = "data";
  9.  
  10. public static String getValueByParam(String param, LinkedHashMap<String, String> inputParams) throws ResultException {
  11. InputParamsHandler handler = new InputParamsHandler(inputParams);
  12. String path;
  13.  
  14. try {
  15. path = handler.getRequiredString(param);
  16. } finally {
  17. handler.check();
  18. }
  19.  
  20. return path;
  21. }
  22.  
  23. private ArrayList<Map<String, String>> getTableFromFile(CsvReader cr) throws IOException {
  24. ArrayList<Map<String, String>> table = new ArrayList<>();
  25.  
  26. cr.readHeaders();
  27. String[] headers = cr.getHeaders();
  28.  
  29. while (cr.readRecord()) {
  30. Map<String, String> row = new HashMap<>();
  31.  
  32. for (int i = 0; i < headers.length; i++) {
  33. row.put(headers[i], cr.get(i));
  34. }
  35.  
  36. row.put(ROW_STATUS, ROW_UNCHECKED);
  37. table.add(row);
  38. }
  39.  
  40. return table;
  41. }
  42.  
  43. @Override
  44. protected Result run(StepContext stepContext, MatrixContext matrixContext, GlobalContext globalContext) {
  45. String path;
  46. try {
  47. path = getValueByParam(PATH_PARAM, inputParams);
  48. } catch (ResultException e) {
  49. return DefaultResult.failedWithException(e);
  50. }
  51.  
  52. CsvReader cr;
  53. try {
  54. cr = new CsvReader(new FileReader(new File(path)));
  55. } catch (FileNotFoundException e) {
  56. return DefaultResult.failedWithComment(String.format("File by path \"%s\" was not found", path));
  57. }
  58.  
  59. ArrayList<Map<String, String>> table;
  60. try {
  61. table = getTableFromFile(cr);
  62. } catch (IOException e) {
  63. return DefaultResult.failedWithException(e);
  64. }
  65. finally {
  66. if (cr != null) {
  67. cr.close();
  68. }
  69. }
  70.  
  71. matrixContext.setContext(DATA_TABLE, table);
  72.  
  73. return null;
  74. }
  75. }
Add Comment
Please, Sign In to add comment