1 package junitparams.custom; 2 3 import java.io.FileInputStream; 4 import java.io.FileReader; 5 import java.io.IOException; 6 import java.io.InputStreamReader; 7 import java.io.Reader; 8 9 import junitparams.FileParameters; 10 import junitparams.mappers.DataMapper; 11 12 public class FileParametersProvider implements ParametersProvider<FileParameters> { 13 14 private FileParameters fileParameters; 15 16 @Override initialize(FileParameters fileParameters)17 public void initialize(FileParameters fileParameters) { 18 this.fileParameters = fileParameters; 19 } 20 21 @Override getParameters()22 public Object[] getParameters() { 23 return paramsFromFile(); 24 } 25 paramsFromFile()26 private Object[] paramsFromFile() { 27 try { 28 Reader reader = createProperReader(); 29 DataMapper mapper = fileParameters.mapper().newInstance(); 30 try { 31 return mapper.map(reader); 32 } finally { 33 reader.close(); 34 } 35 } catch (Exception e) { 36 e.printStackTrace(); 37 throw new RuntimeException( 38 "Could not successfully read parameters from file: " + fileParameters.value(), e); 39 } 40 } 41 createProperReader()42 private Reader createProperReader() throws IOException { 43 String filepath = fileParameters.value(); 44 String encoding = fileParameters.encoding(); 45 46 if (filepath.indexOf(':') < 0) { 47 return new FileReader(filepath); 48 } 49 50 String protocol = filepath.substring(0, filepath.indexOf(':')); 51 String filename = filepath.substring(filepath.indexOf(':') + 1); 52 53 if ("classpath".equals(protocol)) { 54 return new InputStreamReader(getClass().getClassLoader().getResourceAsStream(filename), encoding); 55 } else if ("file".equals(protocol)) { 56 return new InputStreamReader(new FileInputStream(filename), encoding); 57 } 58 59 throw new IllegalArgumentException("Unknown file access protocol. Only 'file' and 'classpath' are supported!"); 60 } 61 62 } 63