package com.liosha.services;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.liosha.domain.FileFormatException;
@Component("fileParserService")
public class FileParserServiceImpl implements FileParserService {
@Value("#{appProperties['route.parse.from.token']}")
protected String fromToken;
@Value("#{appProperties['route.parse.to.token']}")
protected String toToken;
public Map<String, String> parse(InputStream inputStream) throws FileFormatException, IOException {
Map<String, String> fromToValues = new HashMap<String, String>();
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer);
String inputString = writer.toString();
StringTokenizer stringTokenizer = new StringTokenizer(inputString, "\n");
String from = null;
while (stringTokenizer.hasMoreElements()) {
String fromToLine = stringTokenizer.nextToken();
if (fromToLine.toLowerCase().startsWith(fromToken)) {
StringTokenizer fromTokenizer = new StringTokenizer(fromToLine, ":");
fromTokenizer.nextToken();
from = fromTokenizer.nextToken().trim();
continue;
}
if (from != null && fromToLine.toLowerCase().startsWith(toToken)) {
StringTokenizer toTokenizer = new StringTokenizer(fromToLine, ":");
toTokenizer.nextToken();
fromToValues.put(from, toTokenizer.nextToken().trim());
from = null;
}
}
if (fromToValues.size() == 0) {
throw new FileFormatException("Not valid file, please check the file or choose another one");
}
return fromToValues;
}
}