<commit_before>/*
 * Copyright (c) 2013-2015 Cinchapi, Inc.
 * 
 * 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 org.cinchapi.concourse.importer;

import java.util.List;
import java.util.Set;

import javax.annotation.Nullable;

import org.apache.commons.lang.StringUtils;
import org.cinchapi.concourse.Concourse;
import org.cinchapi.concourse.Constants;
import org.cinchapi.concourse.importer.util.Files;
import org.cinchapi.concourse.thrift.Operator;
import org.cinchapi.concourse.util.Convert;
import org.cinchapi.concourse.util.Strings;

import ch.qos.logback.classic.Logger;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;

/**
 * An {@link Importer} that handles data from a file that can be delimited into
 * one or more lines. Each line is considered a single group of data that can be
 * converted to a multimap and imported in one or more records in Concourse.
 * 
 * @author <NAME>
 */
public abstract class LineBasedImporter extends JsonImporter {

    /**
     * Construct a new instance.
     * 
     * @param concourse
     */
    protected LineBasedImporter(Concourse concourse, Logger log) {
        super(concourse, log);
    }

    /**
     * Construct a new instance.
     * 
     * @param concourse
     */
    protected LineBasedImporter(Concourse concourse) {
        super(concourse);
    }

    @Override
    public final Set<Long> importFile(String file) {
        return importFile(file, null);
    }

    /**
     * Import the data contained in {@code file} into {@link Concourse}.
     * <p>
     * <strong>Note</strong> that if {@code resolveKey} is specified, an attempt
     * will be made to add the data in from each group into the existing records
     * that are found using {@code resolveKey} and its corresponding value in
     * the group.
     * </p>
     * 
     * @param file
     * @param resolveKey
     * @return a collection of {@link ImportResult} objects that describes the
     *         records created/affected from the import and whether any errors
     *         occurred.
     */
    public final Set<Long> importFile(String file, @Nullable String resolveKey) {
        // TODO add option to specify batchSize, which is how many objects to
        // send over the wire in one atomic batch
        List<String> lines = Files.readLines(file);
        String[] keys = header();
        JsonArray array = new JsonArray();
        boolean upsert = false;
        for (String line : lines) {
            if(keys == null) {
                keys = parseKeys(line);
                log.info("Parsed keys from header: " + line);
            }
            else {
                JsonObject object = parseLine(line, keys);
                if(resolveKey != null && object.has(resolveKey)) {
                    upsert = true;
                    JsonElement resolveValue = object.get(resolveKey);
                    if(!resolveValue.isJsonArray()) {
                        JsonArray temp = new JsonArray();
                        temp.add(resolveValue);
                        resolveValue = temp;
                    }
                    for (int i = 0; i < resolveValue.getAsJsonArray().size(); ++i) {
                        String value = resolveValue.getAsJsonArray().get(i)
                                .toString();
                        Object stored = Convert.stringToJava(value);
                        Set<Long> resolved = concourse.find(resolveKey,
                                Operator.EQUALS, stored);
                        for (long record : resolved) {
                            object = parseLine(line, keys); // this is
                                                            // inefficient, but
                                                            // there is no good
                                                            // way to clone the
                                                            // original object
                            object.addProperty(
                                    Constants.JSON_RESERVED_IDENTIFIER_NAME,
                                    record);
                            array.add(object);
                        }
                    }
                }
                else {
                    array.add(object);
                }
                log.info("Importing {}", line);;
            }

        }
        Set<Long> records = upsert ? upsertJsonString(array.toString())
                : importJsonString(array.toString());
        return records;
    }

    /**
     * The delimiter that is used to split fields on each line.
     * 
     * @return
     */
    protected abstract String delimiter();

    /**
     * This method is provided so the subclass can provide an ordered array of
     * headers if they are not provided in the file as the first line.
     * 
     * @return the header information
     */
    protected String[] header() {
        return null;
    }

    /**
     * At a minimum, this method is responsible for taking a raw source string<commit_msg>remove double semi colons<commit_after>/*
 * Copyright (c) 2013-2015 Cinchapi, Inc.
 * 
 * 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 org.cinchapi.concourse.importer;

import java.util.List;
import java.util.Set;

import javax.annotation.Nullable;

import org.apache.commons.lang.StringUtils;
import org.cinchapi.concourse.Concourse;
import org.cinchapi.concourse.Constants;
import org.cinchapi.concourse.importer.util.Files;
import org.cinchapi.concourse.thrift.Operator;
import org.cinchapi.concourse.util.Convert;
import org.cinchapi.concourse.util.Strings;

import ch.qos.logback.classic.Logger;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;

/**
 * An {@link Importer} that handles data from a file that can be delimited into
 * one or more lines. Each line is considered a single group of data that can be
 * converted to a multimap and imported in one or more records in Concourse.
 * 
 * @author <NAME>
 */
public abstract class LineBasedImporter extends JsonImporter {

    /**
     * Construct a new instance.
     * 
     * @param concourse
     */
    protected LineBasedImporter(Concourse concourse, Logger log) {
        super(concourse, log);
    }

    /**
     * Construct a new instance.
     * 
     * @param concourse
     */
    protected LineBasedImporter(Concourse concourse) {
        super(concourse);
    }

    @Override
    public final Set<Long> importFile(String file) {
        return importFile(file, null);
    }

    /**
     * Import the data contained in {@code file} into {@link Concourse}.
     * <p>
     * <strong>Note</strong> that if {@code resolveKey} is specified, an attempt
     * will be made to add the data in from each group into the existing records
     * that are found using {@code resolveKey} and its corresponding value in
     * the group.
     * </p>
     * 
     * @param file
     * @param resolveKey
     * @return a collection of {@link ImportResult} objects that describes the
     *         records created/affected from the import and whether any errors
     *         occurred.
     */
    public final Set<Long> importFile(String file, @Nullable String resolveKey) {
        // TODO add option to specify batchSize, which is how many objects to
        // send over the wire in one atomic batch
        List<String> lines = Files.readLines(file);
        String[] keys = header();
        JsonArray array = new JsonArray();
        boolean upsert = false;
        for (String line : lines) {
            if(keys == null) {
                keys = parseKeys(line);
                log.info("Parsed keys from header: " + line);
            }
            else {
                JsonObject object = parseLine(line, keys);
                if(resolveKey != null && object.has(resolveKey)) {
                    upsert = true;
                    JsonElement resolveValue = object.get(resolveKey);
                    if(!resolveValue.isJsonArray()) {
                        JsonArray temp = new JsonArray();
                        temp.add(resolveValue);
                        resolveValue = temp;
                    }
                    for (int i = 0; i < resolveValue.getAsJsonArray().size(); ++i) {
                        String value = resolveValue.getAsJsonArray().get(i)
                                .toString();
                        Object stored = Convert.stringToJava(value);
                        Set<Long> resolved = concourse.find(resolveKey,
                                Operator.EQUALS, stored);
                        for (long record : resolved) {
                            object = parseLine(line, keys); // this is
                                                            // inefficient, but
                                                            // there is no good
                                                            // way to clone the
                                                            // original object
                            object.addProperty(
                                    Constants.JSON_RESERVED_IDENTIFIER_NAME,
                                    record);
                            array.add(object);
                        }
                    }
                }
                else {
                    array.add(object);
                }
                log.info("Importing {}", line);
            }

        }
        Set<Long> records = upsert ? upsertJsonString(array.toString())
                : importJsonString(array.toString());
        return records;
    }

    /**
     * The delimiter that is used to split fields on each line.
     * 
     * @return
     */
    protected abstract String delimiter();

    /**
     * This method is provided so the subclass can provide an ordered array of
     * headers if they are not provided in the file as the first line.
     * 
     * @return the header information
     */
    protected String[] header() {
        return null;
    }

    /**
     * At a minimum, this method is responsible for taking a raw source string
{'fraction_non_alphanumeric': 0.08387211053051102, 'fraction_numerical': 0.00230271897971836, 'mean_word_length': 1.686013320647003, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 20, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5399946', 'n_tokens_mistral': 2818, 'n_tokens_neox': 2703, 'n_words': 934}