Search in sources :

Example 6 with CsvReader

use of com.csvreader.CsvReader in project OpenTripPlanner by opentripplanner.

the class CSVPopulation method createIndividuals.

@Override
public void createIndividuals() {
    try {
        CsvReader reader = new CsvReader(sourceFilename, ',', Charset.forName("UTF8"));
        if (skipHeaders) {
            reader.readHeaders();
        }
        // deal with non-WGS84 data
        MathTransform mathTransform = null;
        boolean transform = false;
        CoordinateReferenceSystem destCrs = CRS.decode("EPSG:4326");
        Boolean latLon = null;
        if (crs != null) {
            CoordinateReferenceSystem sourceCrs = CRS.decode(crs);
            // lat,lon: geotools default
            if (CRS.getAxisOrder(destCrs) == CRS.AxisOrder.NORTH_EAST)
                latLon = true;
            else if (CRS.getAxisOrder(destCrs) == CRS.AxisOrder.EAST_NORTH)
                latLon = false;
            else
                throw new UnsupportedOperationException("Coordinate axis order for WGS 84 unknown.");
            if (!destCrs.equals(sourceCrs)) {
                transform = true;
                // find the transformation, being strict about datums &c.
                mathTransform = CRS.findMathTransform(sourceCrs, destCrs, false);
            }
        }
        while (reader.readRecord()) {
            double y = Double.parseDouble(reader.get(yCol));
            double x = Double.parseDouble(reader.get(xCol));
            double lon, lat;
            if (transform) {
                DirectPosition2D orig = new DirectPosition2D(x, y);
                DirectPosition2D transformed = new DirectPosition2D();
                mathTransform.transform(orig, transformed);
                // x: lat, y: lon. This seems backwards but is the way Geotools does it.
                if (latLon) {
                    lon = transformed.getY();
                    lat = transformed.getX();
                } else // x: lon, y: lat
                {
                    lon = transformed.getX();
                    lat = transformed.getY();
                }
            } else {
                lon = x;
                lat = y;
            }
            String label = reader.get(labelCol);
            Double input = Double.parseDouble(reader.get(inputCol));
            // at this point x and y are expressed in WGS84
            Individual individual = new Individual(label, lon, lat, input);
            this.addIndividual(individual);
        }
        reader.close();
    } catch (Exception e) {
        LOG.error("exception while loading individuals from CSV file", e);
    }
}
Also used : CsvReader(com.csvreader.CsvReader) MathTransform(org.opengis.referencing.operation.MathTransform) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) DirectPosition2D(org.geotools.geometry.DirectPosition2D)

Example 7 with CsvReader

use of com.csvreader.CsvReader in project OpenTripPlanner by opentripplanner.

the class OtpsPopulation method loadFromCSV.

// TODO Specify the CRS to use
// TODO Use a Map<String, Object> for optional parameters?
protected static OtpsPopulation loadFromCSV(String filename, String latColName, String lonColName) throws IOException {
    OtpsPopulation ret = new OtpsPopulation();
    CsvReader reader = new CsvReader(filename, ',', Charset.forName("UTF8"));
    reader.readHeaders();
    // Read headers
    List<String> dataHeaders = new ArrayList<>(reader.getHeaderCount());
    for (String header : reader.getHeaders()) {
        if (header.equals(latColName) || header.equals(lonColName))
            continue;
        dataHeaders.add(header);
    }
    ret.setHeaders(dataHeaders.toArray(new String[dataHeaders.size()]));
    // Read records
    while (reader.readRecord()) {
        double lat = Double.parseDouble(reader.get(latColName));
        double lon = Double.parseDouble(reader.get(lonColName));
        List<String> data = new ArrayList<String>();
        for (String header : dataHeaders) {
            data.add(reader.get(header));
        }
        OtpsIndividual individual = new OtpsIndividual(lat, lon, data.toArray(new String[data.size()]), ret);
        ret.individuals.add(individual);
    }
    reader.close();
    return ret;
}
Also used : CsvReader(com.csvreader.CsvReader) ArrayList(java.util.ArrayList)

Example 8 with CsvReader

use of com.csvreader.CsvReader in project DataX by alibaba.

the class UnstructuredStorageReaderUtil method splitOneLine.

/**
 * @param inputLine
 *            输入待分隔字符串
 * @param delimiter
 *            字符串分割符
 * @return 分隔符分隔后的字符串数组,出现异常时返回为null 支持转义,即数据中可包含分隔符
 */
public static String[] splitOneLine(String inputLine, char delimiter) {
    String[] splitedResult = null;
    if (null != inputLine) {
        try {
            CsvReader csvReader = new CsvReader(new StringReader(inputLine));
            csvReader.setDelimiter(delimiter);
            setCsvReaderConfig(csvReader);
            if (csvReader.readRecord()) {
                splitedResult = csvReader.getValues();
            }
        } catch (IOException e) {
        // nothing to do
        }
    }
    return splitedResult;
}
Also used : CsvReader(com.csvreader.CsvReader)

Example 9 with CsvReader

use of com.csvreader.CsvReader in project meclipse by flaper87.

the class MeclipsePlugin method loadSavedServers.

private MongoInstance[] loadSavedServers() {
    CsvReader reader = null;
    try {
        IPath libPath = MeclipsePlugin.getDefault().getStateLocation();
        libPath = libPath.append("servers.cfg");
        File file = libPath.toFile();
        if (!file.exists())
            return new MongoInstance[0];
        reader = new CsvReader(new BufferedReader(new FileReader(file)));
        java.util.List<MongoInstance> savedServersList = new ArrayList<MongoInstance>();
        while (reader.readRecord()) {
            MongoInstance server = new MongoInstance(reader.get(0));
            server.setHost(reader.get(1));
            try {
                server.setPort(Integer.valueOf(reader.get(2)));
            } catch (NumberFormatException e) {
                System.out.println(e);
            }
            savedServersList.add(server);
        }
        return savedServersList.toArray(new MongoInstance[savedServersList.size()]);
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
    return new MongoInstance[0];
}
Also used : CsvReader(com.csvreader.CsvReader) IPath(org.eclipse.core.runtime.IPath) MongoInstance(org.mongodb.meclipse.preferences.MongoInstance) BufferedReader(java.io.BufferedReader) ArrayList(java.util.ArrayList) FileReader(java.io.FileReader) IOException(java.io.IOException) File(java.io.File)

Example 10 with CsvReader

use of com.csvreader.CsvReader in project dhis2-core by dhis2.

the class DefaultCsvImportService method setOptionGroupsFromCsv.

/**
 * Option group format:
 * <p>
 * <ul>
 * <li>option group name</li>
 * <li>option group uid</li>
 * <li>option group code</li>
 * <li>option group short name</li>
 * <li>option set uid</li>
 * <li>option uid</li>
 * </ul>
 */
private void setOptionGroupsFromCsv(CsvReader reader, Metadata metadata) throws IOException {
    ListMap<String, Option> nameOptionMap = new ListMap<>();
    Map<String, OptionGroup> nameOptionGroupMap = new HashMap<>();
    Map<String, OptionSet> mapOptionSet = new HashMap<>();
    while (reader.readRecord()) {
        String[] values = reader.getValues();
        if (values != null && values.length > 0) {
            OptionGroup optionGroup = new OptionGroup();
            setIdentifiableObject(optionGroup, values);
            optionGroup.setShortName(getSafe(values, 3, 50));
            optionGroup.setAutoFields();
            if (optionGroup.getName() == null || optionGroup.getShortName() == null) {
                continue;
            }
            OptionSet optionSet = new OptionSet();
            optionSet.setUid(getSafe(values, 4, 11));
            if (optionSet.getUid() == null) {
                continue;
            }
            OptionSet persistedOptionSet = optionSet.getUid() != null ? mapOptionSet.computeIfAbsent(optionSet.getUid(), key -> optionService.getOptionSet(optionSet.getUid())) : mapOptionSet.computeIfAbsent(optionSet.getCode(), key -> optionService.getOptionSetByCode(optionSet.getCode()));
            if (persistedOptionSet == null) {
                continue;
            }
            optionGroup.setOptionSet(optionSet);
            Option option = new Option();
            option.setUid(getSafe(values, 5, 11));
            option.setCode(getSafe(values, 6, 50));
            if (option.getCode() == null && option.getUid() == null) {
                continue;
            }
            Optional<Option> isOptionExisted = persistedOptionSet.getOptions().stream().filter(persistedOption -> {
                if (option.getUid() != null) {
                    return persistedOption.getUid().equals(option.getUid());
                } else {
                    return persistedOption.getCode().equals(option.getCode());
                }
            }).findFirst();
            if (!isOptionExisted.isPresent()) {
                continue;
            }
            nameOptionGroupMap.put(optionGroup.getName(), optionGroup);
            nameOptionMap.putValue(optionGroup.getName(), isOptionExisted.get());
        }
    }
    // Read option groups from map and set in meta data
    for (Entry<String, OptionGroup> optionGroupEntry : nameOptionGroupMap.entrySet()) {
        optionGroupEntry.getValue().setMembers(new HashSet<>(nameOptionMap.get(optionGroupEntry.getKey())));
    }
    metadata.setOptionGroups(new ArrayList<>(nameOptionGroupMap.values()));
}
Also used : CategoryService(org.hisp.dhis.category.CategoryService) Importance(org.hisp.dhis.validation.Importance) CategoryOption(org.hisp.dhis.category.CategoryOption) ValueType(org.hisp.dhis.common.ValueType) StringUtils(org.apache.commons.lang3.StringUtils) OptionGroup(org.hisp.dhis.option.OptionGroup) MonthlyPeriodType(org.hisp.dhis.period.MonthlyPeriodType) Metadata(org.hisp.dhis.dxf2.metadata.Metadata) Map(java.util.Map) IndicatorGroup(org.hisp.dhis.indicator.IndicatorGroup) OrganisationUnitGroupService(org.hisp.dhis.organisationunit.OrganisationUnitGroupService) BaseIdentifiableObject(org.hisp.dhis.common.BaseIdentifiableObject) OrganisationUnitGroup(org.hisp.dhis.organisationunit.OrganisationUnitGroup) OptionGroupSet(org.hisp.dhis.option.OptionGroupSet) Category(org.hisp.dhis.category.Category) Operator(org.hisp.dhis.expression.Operator) DataElementGroupService(org.hisp.dhis.dataelement.DataElementGroupService) List(java.util.List) IndicatorGroupService(org.hisp.dhis.indicator.IndicatorGroupService) Entry(java.util.Map.Entry) CsvReader(com.csvreader.CsvReader) Optional(java.util.Optional) CategoryCombo(org.hisp.dhis.category.CategoryCombo) DataDimensionType(org.hisp.dhis.common.DataDimensionType) ListMap(org.hisp.dhis.common.ListMap) DateUtils.getMediumDate(org.hisp.dhis.util.DateUtils.getMediumDate) HashMap(java.util.HashMap) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) DataElement(org.hisp.dhis.dataelement.DataElement) MissingValueStrategy(org.hisp.dhis.expression.MissingValueStrategy) Service(org.springframework.stereotype.Service) Indicator(org.hisp.dhis.indicator.Indicator) CategoryOptionGroup(org.hisp.dhis.category.CategoryOptionGroup) OptionService(org.hisp.dhis.option.OptionService) CsvUtils(org.hisp.dhis.system.util.CsvUtils) DataElementDomain(org.hisp.dhis.dataelement.DataElementDomain) AggregationType(org.hisp.dhis.analytics.AggregationType) IOException(java.io.IOException) ValidationRule(org.hisp.dhis.validation.ValidationRule) OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) Option(org.hisp.dhis.option.Option) FeatureType(org.hisp.dhis.organisationunit.FeatureType) OptionSet(org.hisp.dhis.option.OptionSet) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) PeriodType(org.hisp.dhis.period.PeriodType) CodeGenerator(org.hisp.dhis.common.CodeGenerator) Expression(org.hisp.dhis.expression.Expression) AllArgsConstructor(lombok.AllArgsConstructor) DataElementGroup(org.hisp.dhis.dataelement.DataElementGroup) InputStream(java.io.InputStream) HashMap(java.util.HashMap) ListMap(org.hisp.dhis.common.ListMap) OptionGroup(org.hisp.dhis.option.OptionGroup) CategoryOptionGroup(org.hisp.dhis.category.CategoryOptionGroup) CategoryOption(org.hisp.dhis.category.CategoryOption) Option(org.hisp.dhis.option.Option) OptionSet(org.hisp.dhis.option.OptionSet)

Aggregations

CsvReader (com.csvreader.CsvReader)24 IOException (java.io.IOException)11 ArrayList (java.util.ArrayList)8 FileInputStream (java.io.FileInputStream)4 InputStream (java.io.InputStream)4 HashMap (java.util.HashMap)4 BufferedInputStream (java.io.BufferedInputStream)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 FileNotFoundException (java.io.FileNotFoundException)3 HashSet (java.util.HashSet)3 Column (org.gephi.graph.api.Column)3 Metadata (org.hisp.dhis.dxf2.metadata.Metadata)3 CsvWriter (com.csvreader.CsvWriter)2 BufferedOutputStream (java.io.BufferedOutputStream)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 List (java.util.List)2 Map (java.util.Map)2 Entry (java.util.Map.Entry)2 Optional (java.util.Optional)2 Supplier (java.util.function.Supplier)2