mtsar.api.csv.WorkerCSV.java Source code

Java tutorial

Introduction

Here is the source code for mtsar.api.csv.WorkerCSV.java

Source

/*
 * Copyright 2015 Dmitry Ustalov
 *
 * 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 mtsar.api.csv;

import com.google.common.collect.Sets;
import mtsar.api.Stage;
import mtsar.api.Worker;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.StreamSupport;

import static com.google.common.base.Preconditions.checkArgument;

public final class WorkerCSV {
    public static final CSVFormat FORMAT = CSVFormat.EXCEL.withHeader();
    private static final String[] HEADER = { "id", "stage", "datetime", "tags" };
    private static final Comparator<Worker> ORDER = (w1, w2) -> w1.getId().compareTo(w2.getId());

    public static Iterator<Worker> parse(Stage stage, CSVParser csv) {
        final Set<String> header = csv.getHeaderMap().keySet();
        checkArgument(!Sets.intersection(header, Sets.newHashSet(HEADER)).isEmpty(), "Unknown CSV header: %s",
                String.join(",", header));

        return StreamSupport.stream(csv.spliterator(), false).map(row -> {
            final String id = row.isSet("id") ? row.get("id") : null;
            final String[] tags = row.isSet("tags") && !StringUtils.isEmpty(row.get("tags"))
                    ? row.get("tags").split("\\|")
                    : new String[0];
            final String datetime = row.isSet("datetime") ? row.get("datetime") : null;

            return new Worker.Builder().setId(StringUtils.isEmpty(id) ? null : Integer.valueOf(id))
                    .setStage(stage.getId()).addAllTags(Arrays.asList(tags))
                    .setDateTime(new Timestamp(StringUtils.isEmpty(datetime) ? System.currentTimeMillis()
                            : Long.parseLong(datetime) * 1000L))
                    .build();
        }).iterator();
    }

    public static void write(Collection<Worker> workers, OutputStream output) throws IOException {
        try (final Writer writer = new OutputStreamWriter(output, StandardCharsets.UTF_8)) {
            final Iterable<String[]> iterable = () -> workers.stream().sorted(ORDER)
                    .map(worker -> new String[] { Integer.toString(worker.getId()), // id
                            worker.getStage(), // stage
                            Long.toString(worker.getDateTime().toInstant().getEpochSecond()), // datetime
                            String.join("|", worker.getTags()), // tags
                    }).iterator();

            FORMAT.withHeader(HEADER).print(writer).printRecords(iterable);
        }
    }
}