package com.passing.unittests;
import java.io.File;
import java.io.FileInputStream;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class DataProcessingImpl implements DataProcessing {
public String getContents(String path) {
Scanner scanner = null;
StringBuilder sb = new StringBuilder(20);
try {
FileInputStream fis = new FileInputStream(new File(path));
scanner = new Scanner(fis);
while ((scanner.hasNextLine())) {
String next = scanner.nextLine();
sb.append(next + "\n");
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if(scanner != null) {
scanner.close();
}
}
return sb.toString().trim();
}
public String getSortedByFirstName(String input) {
if(input == null || input.length() == 0){
throw new IllegalArgumentException("input=" + input);
}
return getSortedContents(input, 0);
}
public String getSortedByLastName(String input) {
if(input == null || input.length() == 0){
throw new IllegalArgumentException("input=" + input);
}
return getSortedContents(input, 1);
}
public String getSortedByYear(String input) {
if(input == null || input.length() == 0){
throw new IllegalArgumentException("input=" + input);
}
return getSortedContents(input, 2);
}
/**
* Generic method to sort using a TreeMap.
* @param input CSV format: first name, last name, year joined
* @param sortIndex index of CSV line to sort by
* @return
*/
private String getSortedContents(String input, int sortIndex){
Map<String, String> map = new TreeMap<String, String>();
String[] split = input.split("\n");
for (String line : split) {
String key = getSortKey(line, sortIndex);
map.put(key, line);
}
StringBuilder sb = new StringBuilder(20);
for (String key : map.keySet()) {
sb.append(map.get(key) + "\n");
}
return sb.toString().trim();
}
/**
* Splits it into an array using "," as delimiter
* and returns the given index, 0 is first name, 1 is last name, and 2 is year joined
* @param line
* @param index
* @return
*/
private static String getSortKey(String line, int index) {
return line.split(",")[index];// extract value you want to sort on
}
}