public class BigDecimalParser extends AbstractParser {
    public BigDecimal parseIt(String toparse) throws NumberFormatException {
        if (null == toparse)
            return null;
        return new BigDecimal(toparse);
    }

    public String format(Object o) {
        BigDecimal v = (BigDecimal)o;
        return v.toString();
    }
} public class BigIntegerParser extends AbstractParser {
    public BigInteger parseIt(String toparse) throws NumberFormatException {
        if (null == toparse)
            return null;
        return new BigInteger(toparse);
    }

    public String format(Object o) {
        BigInteger v = (BigInteger)o;
        return v.toString();
    }
} public class BooleanParser extends AbstractParser {
    public static enum BoolStyle { 
        BoolStyle_TrueFalse("TRUE_FALSE", "TRUE", "FALSE"), 
        BoolStyle_10("1_0", "1", "0"), 
        BoolStyle_TF("T_F", "T", "F"), 
        BoolStyle_YN("Y_N", "Y", "N"), 
        BoolStyle_YesNo("YES_NO", "YES", "NO");

        private String styleStr;
        private String trueStr;
        private String falseStr;

        BoolStyle(String inStyleStr, String inTrueStr, String inFalseStr) {
            styleStr = inStyleStr;
            trueStr = inTrueStr;
            falseStr = inFalseStr;
        }

        public String getStyle() {
            return styleStr;
        }

        public String getTrueStr() {
            return trueStr;
        }

        public String getFalseStr() {
            return falseStr;
        }
    }
    
    private String boolTrue;
    private String boolFalse;
    private static String BOOLSTYLE_1_0 = "1_0";
    private static String BOOLSTYLE_T_F = "T_F";
    private static String BOOLSTYLE_Y_N = "Y_N";
    private static String BOOLSTYLE_YES_NO = "YES_NO";
    private static String BOOLSTYLE_TRUE_FALSE = "TRUE_FALSE";
    
    public BooleanParser() {
        this(BoolStyle.BoolStyle_TrueFalse);
    }
    
    public BooleanParser(BoolStyle inBoolStyle) {
        if (null == inBoolStyle)
            inBoolStyle = BoolStyle.BoolStyle_TrueFalse;
        boolTrue = inBoolStyle.getTrueStr();
        boolFalse = inBoolStyle.getFalseStr();
    }

    public BooleanParser(String inBoolTrue, String inBoolFalse) {
        boolTrue = inBoolTrue;
        boolFalse = inBoolFalse;                
    }

    public static BoolStyle getBoolStyle(String instr) {
        for (BoolStyle bs : BoolStyle.values()) {
            if (bs.getStyle().equalsIgnoreCase(instr)) {
                return bs;
            }
        }
        return null;
    }

    public static String getOptions() {
        String ret = "'" + BOOLSTYLE_1_0 + "'";
        ret = ret + ", '" + BOOLSTYLE_T_F + "'";
        ret = ret + ", '" + BOOLSTYLE_Y_N + "'";
        ret = ret + ", '" + BOOLSTYLE_TRUE_FALSE + "'";
        ret = ret + ", '" + BOOLSTYLE_YES_NO + "'";
        return ret;
    };

    public Boolean parseIt(String toparse) throws ParseException {
        if (null == toparse)
            return null;
        if (boolTrue.equalsIgnoreCase(toparse))
            return new Boolean("TRUE");
        if (boolFalse.equalsIgnoreCase(toparse))
            return new Boolean("FALSE");
        throw new ParseException("Boolean was not TRUE (" + boolTrue + ") or FALSE (" + boolFalse + ")", 0);
    }

    public String format(Object o) {
        Boolean v = (Boolean)o;
        if (v)
            return boolTrue;
        return boolFalse;
    }
} public class ByteBufferParser extends AbstractParser {
    public ByteBuffer parseIt(String toparse) {
        if (null == toparse)
            return null;
        byte[] barry = DatatypeConverter.parseBase64Binary(toparse);
        return ByteBuffer.wrap(barry);
    }

    public String format(Object o) {
        ByteBuffer v = (ByteBuffer)o;
        return DatatypeConverter.printBase64Binary(v.array());
    }
} public class ByteParser extends NumberParser {
    public ByteParser() {
        super();
    }
    
    public ByteParser(Locale inLocale) {
        super(inLocale);
    }
    
    public ByteParser(Locale inLocale, Boolean grouping) {
        super(inLocale, grouping);
    }
    
    public Byte parseIt(String toparse) throws ParseException {
        Number val = super.parseIt(toparse);
        return (null == val) ? null : val.byteValue();
    }
} public class DateParser extends AbstractParser {
    private DateFormat format;
    public DateParser(String inFormatString) {
        if (null == inFormatString)
            format = new SimpleDateFormat();
        else
            format = new SimpleDateFormat(inFormatString, Locale.ENGLISH);
    }
    
    public Date parseIt(String toparse) throws ParseException {
        if (null == toparse)
            return null;
        return format.parse(toparse);
    }

    public String format(Object o) {
        Date v = (Date)o;
    if (v == null)
        return null;
        return format.format(v);
    }
} public class DelimParser {
    private List<Parser> parsers;
    private int parsersSize;
    private List<Object> elements;
    private String delimiter;
    private int charsPerColumn;
    private String nullString;
    private char delim;
    private char quote;
    private char escape;
    private char comment;
    private List<Boolean> skip;

    private CsvParser csvp = null;

    public static String DEFAULT_DELIMITER = ",";
    public static String DEFAULT_NULLSTRING = "";
    public static String DEFAULT_COMMENT_STRING = "\0";
    public static int DEFAULT_CHARSPERCOLUMN = 4096;

    public DelimParser() {
        this(DEFAULT_DELIMITER);
    }

    public DelimParser(String inDelimiter) {
        this(inDelimiter, DEFAULT_CHARSPERCOLUMN, DEFAULT_NULLSTRING, DEFAULT_COMMENT_STRING);
    }

    public DelimParser(String inDelimiter, int inCharsPerColumn,
                       String inNullString, String inComment) {
        parsers = new ArrayList<Parser>();
        elements = new ArrayList<Object>();
        skip = new ArrayList<Boolean>();
        parsersSize = parsers.size();
        if (null == inDelimiter)
            delimiter = DEFAULT_DELIMITER;
        else
            delimiter = inDelimiter;
        if (null == inNullString)
            nullString = DEFAULT_NULLSTRING;
        else
            nullString = inNullString;
        if (null == inComment)
            comment = DEFAULT_COMMENT_STRING.charAt(0);
        else
            comment = inComment.charAt(0);
        charsPerColumn = inCharsPerColumn;
        delim = ("\\t".equals(delimiter)) ?  '\t' : delimiter.charAt(0);
        quote = '\"';
        escape = '\\';

        CsvParserSettings settings = new CsvParserSettings();
        settings.getFormat().setLineSeparator("\n");
        settings.getFormat().setDelimiter(delim);
        settings.setMaxCharsPerColumn(charsPerColumn);
        settings.getFormat().setQuote(quote);
        settings.getFormat().setQuoteEscape(escape);
        settings.getFormat().setCharToEscapeQuoteEscaping(escape);
        settings.setKeepQuotes(true);
        settings.setKeepEscapeSequences(true);
        settings.getFormat().setComment(comment);

        csvp = new CsvParser(settings);
    }

    // Adds a parser to the list
    public void add(Parser p) {
        parsers.add(p);
        skip.add(false);
        parsersSize = parsers.size();
    }

    public void addSkip(int idx) {
        parsers.add(idx, new StringParser());
        skip.add(idx, true);
        parsersSize = parsers.size();
    }

    // This is where we apply rules like quoting, NULL, etc
    private String prepareToParse(String toparse) {
        String trimmedToParse = toparse.trim();
        if (trimmedToParse.startsWith("\"") && trimmedToParse.endsWith("\""))
            trimmedToParse = trimmedToParse.substring(1, trimmedToParse.length() - 1);
        if (trimmedToParse.equals(nullString))
            return null;
        return trimmedToParse;
    }

    public List<Object> parse(String line) {
        //return parseComplex(line);
        return parseWithUnivocity(line);
    }

    public List<Object> parseWithUnivocity(String line) {
        String[] row = csvp.parseLine(line);
        return parse(row);
    }

    public List<Object> parse(String[] row) {
        if (row.length != parsersSize) {
            System.err.println("Row has different number of fields (" + row.length + ") than expected (" + parsersSize + ")");
            return null;
        }
        elements.clear();
        Object toAdd;
        for (int i = 0; i < parsersSize; i++) {
            try {
                String toparse = row[i];
                if ((null == toparse) ||
                    ((null != nullString) &&
                     (nullString.equalsIgnoreCase(AbstractParser.unquote(toparse)))))
                    toAdd = null;
                else
                    toAdd = parsers.get(i).parse(toparse);

                if (!skip.get(i))
                    elements.add(toAdd);
            }
            catch (NumberFormatException e) {
                System.err.println(String.format("Invalid number in input number %d: %s", i, e.getMessage()));
                return null;
            }
            catch (ParseException pe) {
                System.err.println(String.format("Invalid format in input %d: %s", i, pe.getMessage()));
                return null;
            }
        }

        return elements;
    }

    public List<Object> parseComplex(String line) {
        elements.clear();
        IndexedLine sr = new IndexedLine(line);
        for (int i = 0; i < parsersSize; i++) {
            try {
                Object toAdd = parsers.get(i).parse(sr, nullString, delim, 
                                                    escape, quote, 
                                                    (parsersSize-1 == i));
                if (!skip.get(i))
                    elements.add(toAdd);
            }
            catch (NumberFormatException e) {
                System.err.println(String.format("Invalid number in input number %d: %s", i, e.getMessage()));
                return null;
            }
            catch (ParseException pe) {
                System.err.println(String.format("Invalid format in input %d: %s", i, pe.getMessage()));
                return null;
            }
            catch (IOException e) {
                System.err.println(String.format("Invalid number of fields - ran out of string: %s", i, e.getMessage()));
                return null;
            }
        }
        return elements;
    }

    // returns an array of Objects - to be used in PreparedStatement.bind()
    public Object[] getElements() {
        return elements.toArray();
    }

    public String format(Row row) throws IndexOutOfBoundsException, InvalidTypeException {
        StringBuilder retVal = new StringBuilder();
        String[] stringVals = stringVals(row);
        retVal.append(stringVals[0]);
        for (int i = 1; i < parsersSize; i++) {
            retVal.append(delimiter).append(stringVals[i]);
        }
        return retVal.toString();
    }

    public String[] stringVals(Row row) throws IndexOutOfBoundsException, InvalidTypeException {
        String[] stringVals = new String[parsers.size()];
        for (int i = 0; i < parsersSize; i++) {
            stringVals[i] = parsers.get(i).format(row, i);
            if (null == stringVals[i])
                stringVals[i] = nullString;
        }
        return stringVals;
    }
} public class DoubleParser extends NumberParser {
    public DoubleParser() {
        super();
    }
    
    public DoubleParser(Locale inLocale) {
        super(inLocale);
    }

    public DoubleParser(Locale inLocale, Boolean grouping) {
        super(inLocale, grouping);
    }
    
    public Double parseIt(String toparse) throws ParseException {
        Number val = super.parseIt(toparse);
        return (null == val) ? null : val.doubleValue();
    }
} public class FloatParser extends NumberParser {
    public FloatParser() {
        super();
    }
    
    public FloatParser(Locale inLocale) {
        super(inLocale);
    }
    
    public FloatParser(Locale inLocale, Boolean grouping) {
        super(inLocale, grouping);
    }

    public Float parseIt(String toparse) throws ParseException {
        Number val = super.parseIt(toparse);
        return (null == val) ? null : val.floatValue();
    }
} public class InetAddressParser extends AbstractParser {
    public InetAddress parseIt(String toparse) throws ParseException {
        if (null == toparse)
            return null;
        InetAddress ret;
        try {
            ret = InetAddress.getByName(toparse);
        }
        catch (UnknownHostException uhe) {
            throw new ParseException("Error parsing Inet: " + uhe.getMessage(), 0);
        }
        return ret;
    }

    public String format(Object o) {
        InetAddress v = (InetAddress)o;
        return v.getHostAddress();
    }
} public class IntegerParser extends NumberParser {
    public IntegerParser() {
        super();
    }
    
    public IntegerParser(Locale inLocale) {
        super(inLocale);
    }
    
    public IntegerParser(Locale inLocale, Boolean grouping) {
        super(inLocale, grouping);
    }
    
    public Integer parseIt(String toparse) throws ParseException {
        Number val = super.parseIt(toparse);
        return (null == val) ? null : val.intValue();
    }
} public class ListParser extends AbstractParser {
    private Parser parser;
    private char collectionDelim;
    private char collectionBegin;
    private char collectionEnd;
    private char collectionQuote = '\"';
    private char collectionEscape = '\\';
    private String collectionNullString = "null";
    private List<Object> elements;
    
    private CsvParser csvp = null;
    
    public ListParser(Parser inParser, char inCollectionDelim, 
                      char inCollectionBegin, char inCollectionEnd) {
        parser = inParser;
        collectionDelim = inCollectionDelim;
        collectionBegin = inCollectionBegin;
        collectionEnd = inCollectionEnd;
        elements = new ArrayList<Object>();

        CsvParserSettings settings = new CsvParserSettings();
        settings.getFormat().setLineSeparator("\n");
        settings.getFormat().setDelimiter(collectionDelim);
        settings.getFormat().setQuote(collectionQuote);
        settings.getFormat().setQuoteEscape(collectionEscape);
        settings.getFormat().setCharToEscapeQuoteEscaping(collectionEscape);
        settings.setKeepQuotes(true);
        settings.setKeepEscapeSequences(true);
        
        csvp = new CsvParser(settings);
    }

    public Object parseIt(String toparse) throws ParseException {
        if (null == toparse)
            return null;
        if (!toparse.startsWith(Character.toString(collectionBegin)))
            throw new ParseException("Must begin with " + collectionBegin 
                                     + "\n", 0);
        if (!toparse.endsWith(Character.toString(collectionEnd)))
            throw new ParseException("Must end with " + collectionEnd 
                                     + "\n", 0);
        toparse = toparse.substring(1, toparse.length() - 1);
        String[] row = csvp.parseLine(toparse);
        elements.clear();
        try {
            for (int i = 0; i < row.length; i++) 
                elements.add(parser.parse(row[i]));
        }
        catch (Exception e) {
            System.err.println("Trouble parsing : " + e.getMessage());
            return null;
        }
        return elements;
    }

    //public String format(Row row, int index) {
    //  if (row.isNull(index))
    //      return null;
    //  List<Object> list = row.getList(index, Object.class);
    @SuppressWarnings("unchecked")
    public String format(Object o) {
        List<Object> list = (List<Object>)o;
        StringBuilder sb = new StringBuilder();
        sb.append(collectionBegin);
        if (list.size() > 0) {
            for (int i = 0; i < list.size() - 1; i++) {
                sb.append(parser.format(list.get(i)));
                sb.append(collectionDelim);
            }
            sb.append(parser.format(list.get(list.size() - 1)));
        }
        sb.append(collectionEnd);
        return quote(sb.toString());
    }
} public class LocalDateParser extends AbstractParser {
    private DateParser dateParser;

    public LocalDateParser(String inFormatString) {
        dateParser = new DateParser(inFormatString);
    }

    public LocalDate parseIt(String toparse) throws ParseException {
        if (null == toparse)
            return null;
        Date d = dateParser.parseIt(toparse);
        LocalDate ret = LocalDate.fromMillisSinceEpoch(d.getTime());
        return ret;
    }

    public String format(Object o) {
        LocalDate v = (LocalDate)o;
        if (v == null)
            return null;
        Date d = new Date(v.getMillisSinceEpoch());
        return dateParser.format(d);
    }
} public class LongParser extends NumberParser {
    public LongParser() {
        super();
    }
    
    public LongParser(Locale inLocale) {
        super(inLocale);
    }
    
    public LongParser(Locale inLocale, Boolean grouping) {
        super(inLocale, grouping);
    }
    
    public Long parseIt(String toparse) throws ParseException {
        Number val = super.parseIt(toparse);
        return (null == val) ? null : val.longValue();
    }
} public class MapParser extends AbstractParser {
    private Parser keyParser;
    private Parser valueParser;
    private char collectionDelim;
    private char collectionBegin;
    private char collectionEnd;
    private char collectionQuote = '\"';
    private char collectionEscape = '\\';
    private char mapDelim;
    private String collectionNullString = null;
    private Map<Object,Object> elements;
    
    private CsvParser csvp = null;

    public MapParser(Parser inKeyParser, Parser inValueParser,
                     char inCollectionDelim, char inCollectionBegin, 
                     char inCollectionEnd, char inMapDelim) {
        keyParser = inKeyParser;
        valueParser = inValueParser;
        collectionDelim = inCollectionDelim;
        collectionBegin = inCollectionBegin;
        collectionEnd = inCollectionEnd;
        mapDelim = inMapDelim;
        elements = new HashMap<Object,Object>();

        CsvParserSettings settings = new CsvParserSettings();
        settings.getFormat().setLineSeparator("" + collectionDelim);
        settings.getFormat().setNormalizedNewline(collectionDelim);
        settings.getFormat().setDelimiter(mapDelim);
        settings.getFormat().setQuote(collectionQuote);
        settings.getFormat().setQuoteEscape(collectionEscape);
        settings.getFormat().setCharToEscapeQuoteEscaping(collectionEscape);
        settings.setKeepQuotes(true);
        settings.setKeepEscapeSequences(true);
        
        csvp = new CsvParser(settings);
    }
    public Object parseIt(String toparse) throws ParseException {
        if (null == toparse)
            return null;
        if (!toparse.startsWith(Character.toString(collectionBegin)))
            throw new ParseException("Must begin with " + collectionBegin 
                                     + "\n", 0);
        if (!toparse.endsWith(Character.toString(collectionEnd)))
            throw new ParseException("Must end with " + collectionEnd 
                                     + "\n", 0);
        toparse = toparse.substring(1, toparse.length() - 1);
        elements.clear();
        StringReader sr = new StringReader(toparse);
        csvp.beginParsing(sr);
        try {
            String[] row;
            while ((row = csvp.parseNext()) != null) {
                Object key = keyParser.parse(row[0]);
                Object value = valueParser.parse(row[1]);
                elements.put(key, value);
            }
        }
        catch (Exception e) {
            System.err.println("Trouble parsing : " + e.getMessage());
            e.printStackTrace();
            return null;
        }
        return elements;
    }

    @SuppressWarnings("unchecked")
    public String format(Object o) {
        Map<Object,Object> map = (Map<Object,Object>)o;
        Iterator<Map.Entry<Object,Object> > iter = map.entrySet().iterator();
        Map.Entry<Object,Object> me;
        StringBuilder sb = new StringBuilder();
        sb.append(collectionBegin);
        if (iter.hasNext()) {
            me = iter.next();
            sb.append(keyParser.format(me.getKey()));
            sb.append(mapDelim);
            sb.append(valueParser.format(me.getValue()));
        }
        while (iter.hasNext()) {
            sb.append(collectionDelim);
            me = iter.next();
            sb.append(keyParser.format(me.getKey()));
            sb.append(mapDelim);
            sb.append(valueParser.format(me.getValue()));
        }
        sb.append(collectionEnd);

        return quote(sb.toString());
    }
} public interface Parser {
    public Object parse(String toparse) throws ParseException;
    public Object parse(IndexedLine il, String nullString, Character delim, 
                        Character escape, Character quote, boolean last)
        throws IOException, ParseException;
    public String format(Row row, int index) throws IndexOutOfBoundsException, InvalidTypeException;
    public String format(Object o);
} public class SetParser extends AbstractParser {
    private Parser parser;
    private char collectionDelim;
    private char collectionBegin;
    private char collectionEnd;
    private char collectionQuote = '\"';
    private char collectionEscape = '\\';
    private String collectionNullString = "null";
    private Set<Object> elements;
    
    private CsvParser csvp = null;

    public SetParser(Parser inParser, char inCollectionDelim, 
                     char inCollectionBegin, char inCollectionEnd) {
        parser = inParser;
        collectionDelim = inCollectionDelim;
        collectionBegin = inCollectionBegin;
        collectionEnd = inCollectionEnd;
        elements = new HashSet<Object>();

        CsvParserSettings settings = new CsvParserSettings();
        settings.getFormat().setLineSeparator("\n");
        settings.getFormat().setDelimiter(collectionDelim);
        settings.getFormat().setQuote(collectionQuote);
        settings.getFormat().setQuoteEscape(collectionEscape);
        settings.getFormat().setCharToEscapeQuoteEscaping(collectionEscape);
        settings.setKeepQuotes(true);
        settings.setKeepEscapeSequences(true);
        
        csvp = new CsvParser(settings);
    }
    public Object parseIt(String toparse) throws ParseException {
        if (null == toparse)
            return null;
        if (!toparse.startsWith(Character.toString(collectionBegin)))
            throw new ParseException("Must begin with " + collectionBegin 
                                     + "\n", 0);
        if (!toparse.endsWith(Character.toString(collectionEnd)))
            throw new ParseException("Must end with " + collectionEnd 
                                     + "\n", 0);
        toparse = toparse.substring(1, toparse.length() - 1);
        String[] row = csvp.parseLine(toparse);
        elements.clear();
        try {
            for (int i = 0; i < row.length; i++) 
                elements.add(parser.parse(row[i]));
        }
        catch (Exception e) {
            System.err.println("Trouble parsing : " + e.getMessage());
            e.printStackTrace();
            return null;
        }
        return elements;
    }

    //public String format(Row row, int index) {
    //  if (row.isNull(index))
    //      return null;
    //  Set<Object> set = row.getSet(index, Object.class);
    @SuppressWarnings("unchecked")
    public String format(Object o) {
        Set<Object> set = (Set<Object>)o;
        Iterator<Object> iter = set.iterator();
        StringBuilder sb = new StringBuilder();
        sb.append(collectionBegin);
        if (iter.hasNext())
            sb.append(parser.format(iter.next()));
        while (iter.hasNext()) {
            sb.append(collectionDelim);
            sb.append(parser.format(iter.next()));
        }
        sb.append(collectionEnd);

        return quote(sb.toString());
    }
} public class ShortParser extends NumberParser {
    public ShortParser() {
        super();
    }
    
    public ShortParser(Locale inLocale) {
        super(inLocale);
    }
    
    public ShortParser(Locale inLocale, Boolean grouping) {
        super(inLocale, grouping);
    }
    
    public Short parseIt(String toparse) throws ParseException {
        Number val = super.parseIt(toparse);
        return (null == val) ? null : val.shortValue();
    }
} public class StringParser extends AbstractParser {
    public String parseIt(String toparse) {
        return toparse;
    }

    public String format(Object o) {
        String iv = (String)o;
        return quote(iv);
    }
} public class UUIDParser extends AbstractParser {
    public UUID parseIt(String toparse) throws IllegalArgumentException {
        if (null == toparse)
            return null;
        return UUID.fromString(toparse);
    }
    public String format(Object o) {
        UUID v = (UUID)o;
        return v.toString();
    }
}
import com.datastax.driver.core.ColumnMetadata;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.TableMetadata;
import com.datastax.driver.core.KeyspaceMetadata;
import com.datastax.driver.core.exceptions.InvalidTypeException;
import com.datastax.loader.parser.BigDecimalParser;
import com.datastax.loader.parser.BigIntegerParser;
import com.datastax.loader.parser.BooleanParser;
import com.datastax.loader.parser.ByteBufferParser;
import com.datastax.loader.parser.ByteParser;
import com.datastax.loader.parser.DateParser;
import com.datastax.loader.parser.DelimParser;
import com.datastax.loader.parser.DoubleParser;
import com.datastax.loader.parser.FloatParser;
import com.datastax.loader.parser.InetAddressParser;
import com.datastax.loader.parser.IntegerParser;
import com.datastax.loader.parser.ListParser;
import com.datastax.loader.parser.LocalDateParser;
import com.datastax.loader.parser.LongParser;
import com.datastax.loader.parser.MapParser;
import com.datastax.loader.parser.Parser;
import com.datastax.loader.parser.SetParser;
import com.datastax.loader.parser.ShortParser;
import com.datastax.loader.parser.StringParser;
import com.datastax.loader.parser.UUIDParser;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import com.univocity.parsers.csv.CsvParser;
import com.univocity.parsers.csv.CsvParserSettings;
/*
 * Copyright 2015 Brian Hess
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.datastax.loader;





public class CqlDelimParser {
    private Map<DataType.Name, Parser> pmap;
    private List<SchemaBits> sbl;
    private List<String> columnNames;
    private String keyspace;
    private String tablename;
    private DelimParser delimParser;
    private JSONParser jsonParser;
    private int ttl = -1;

    public CqlDelimParser(String inCqlSchema, String inDelimiter, int inCharsPerColumn,
                          String inNullString, String inCommentString, 
                          String inDateFormatString, String inLocalDateFormatString,
                          BooleanParser.BoolStyle inBoolStyle, Locale inLocale,
                          String skipList, Session session, boolean bLoader, int inTtl) 
        throws ParseException {
        // Optionally provide things for the line parser - date format, boolean format, locale
	ttl = inTtl;
        initPmap(inDateFormatString, inLocalDateFormatString, inBoolStyle, 
                 inLocale, bLoader);
        processCqlSchema(inCqlSchema, session);
        createDelimParser(inDelimiter, inCharsPerColumn, inNullString, inCommentString, skipList);
    }   

    public CqlDelimParser(String inKeyspace, String inTable, String inDelimiter,
                          int inCharsPerColumn,
                          String inNullString, String inCommentString, 
                          String inDateFormatString, String inLocalDateFormatString,
                          BooleanParser.BoolStyle inBoolStyle, Locale inLocale,
                          String skipList, Session session, boolean bLoader, int inTtl) 
        throws ParseException {
        // Optionally provide things for the line parser - date format, boolean format, locale
	ttl = inTtl;
        keyspace = inKeyspace;
        tablename = inTable;
        initPmap(inDateFormatString, inLocalDateFormatString, inBoolStyle, 
                 inLocale, bLoader);
        processCqlSchema(session);
        createDelimParser(inDelimiter, inCharsPerColumn, inNullString, inCommentString,  skipList);
    }

    public List<String> getColumnNames() {
        return columnNames;
    }

    private void setColumnNames(List<String> columnNames) {
        this.columnNames = columnNames;
    }

    // used internally to store schema information
    private class SchemaBits {
        public String name;
        public DataType.Name datatype;
        public Parser parser;
    }

    // intialize the Parsers and the parser map
    private void initPmap(String dateFormatString, String localDateFormatString,
                          BooleanParser.BoolStyle inBoolStyle, 
                          Locale inLocale, boolean bLoader) {
        pmap = new HashMap<DataType.Name, Parser>();
        Parser byteParser = new ByteParser(inLocale, bLoader);
        Parser shortParser = new ShortParser(inLocale, bLoader);
        Parser integerParser = new IntegerParser(inLocale, bLoader);
        Parser longParser = new LongParser(inLocale, bLoader);
        Parser floatParser = new FloatParser(inLocale, bLoader);
        Parser doubleParser = new DoubleParser(inLocale, bLoader);
        Parser stringParser = new StringParser();
        Parser booleanParser = new BooleanParser(inBoolStyle);
        Parser uuidParser = new UUIDParser();
        Parser bigDecimalParser = new BigDecimalParser();
        Parser bigIntegerParser = new BigIntegerParser();
        Parser byteBufferParser = new ByteBufferParser();
        Parser inetAddressParser = new InetAddressParser();