/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package clips.directory.editors.mkb10;
import beans.directory.mkb10.MkbItem;
import cli_fmw.main.ClipsException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
/**
*
* @author finder
*/
public class MahonParser {
static final char MKB_ID_SEPARATOR = ' ';
static final char INDEX_SEPARATOR = ';';
BufferedReader input;
public MahonParser(File sourse) throws FileNotFoundException{
input = new BufferedReader(new FileReader(sourse));
}
public ArrayList<MkbItem> read() throws IOException, ClipsException{
ArrayList<MkbItem> target = new ArrayList<MkbItem>(8192);
String line = input.readLine();
if (line == null) {
throw new ClipsException("Некорректный фомат файла!");
}
line = input.readLine();
while (line != null){
target.add(parseLine(line));
line = input.readLine();
}
return target;
}
private void throwFormatError(String line) throws ClipsException{
throw new ClipsException("Некорректный фомат файла! \"" + line + "\"");
}
private MkbItem parseLine(String line) throws ClipsException{
int mkbIdx = line.indexOf(MKB_ID_SEPARATOR);
int idIdx;
int pIDidx;
if (mkbIdx < 0) {
throwFormatError(line);
}
String mkbID = line.substring(0, mkbIdx).trim();
Integer id;
Integer parent;
try{
idIdx = line.lastIndexOf(INDEX_SEPARATOR);
if (idIdx < 0) {
throwFormatError(line);
}
String idStr = line.substring(idIdx + 1, line.length()).trim();
id = new Integer(idStr);
pIDidx = line.lastIndexOf(INDEX_SEPARATOR, idIdx - 1);
if (pIDidx < 0) {
throwFormatError(line);
}
String pIdStr = line.substring(pIDidx + 1, idIdx).trim();
parent = new Integer(pIdStr);
if (parent.intValue() == 0) {
parent = null;
}
}
catch (NumberFormatException ex){
throw new ClipsException("Некорректный фомат файла! Id не число! \"" + line + "\"", ex);
}
String text = line.substring(mkbIdx + 1, pIDidx).trim();
text = text.substring(0, 1) + text.substring(1).toLowerCase();
return new MkbItem(text, mkbID, id, parent);
}
}