com.anhth12.lambda.common.text.TextUtils.java Source code

Java tutorial

Introduction

Here is the source code for com.anhth12.lambda.common.text.TextUtils.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.anhth12.lambda.common.text;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Iterators;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.csv.QuoteMode;

/**
 *
 * @author Tong Hoang Anh
 */
public class TextUtils {

    private static final ObjectMapper MAPPER = new ObjectMapper();
    private static final CSVFormat CSV_FORMAT = CSVFormat.RFC4180.withSkipHeaderRecord().withEscape('\\');
    private static final String[] EMPTY_STRING = { "" };
    private static final Pattern TWO_DOUBLE_QUOTE_ESC = Pattern.compile("\"\"", Pattern.LITERAL);
    private static final String SLASH_QUOTE_ESC = Matcher.quoteReplacement("\\\"");

    public static String[] parseJSONArray(String line) throws IOException {
        return MAPPER.readValue(line, String[].class);
    }

    public static String joinJSON(Iterable<?> element) {
        try {
            return MAPPER.writeValueAsString(element);
        } catch (JsonProcessingException ex) {
            throw new IllegalArgumentException(ex);
        }
    }

    public static String[] parseDelimited(String line, char c) {
        return doParseDelimited(line, formatForDelimiter(c));
    }

    private static String[] doParseDelimited(String delimited, CSVFormat format) {
        Iterator<CSVRecord> records;
        try {
            records = CSVParser.parse(delimited, format).iterator();
        } catch (IOException ex) {
            throw new IllegalStateException(ex);
        }

        if (records.hasNext()) {
            return Iterators.toArray(records.next().iterator(), String.class);
        } else {
            return EMPTY_STRING;
        }
    }

    private static CSVFormat formatForDelimiter(char delimiter) {
        CSVFormat format = CSV_FORMAT;
        if (delimiter != format.getDelimiter()) {
            format = format.withDelimiter(delimiter);
        }
        return format;
    }

    public static String[] parsePMMLDelimited(String delimited) {
        // Although you'd think ignoreSurroundingSpaces helps here, won't work with space
        // delimiter. So manually trim below.
        String[] rawResult = doParseDelimited(delimited, formatForDelimiter(' '));
        List<String> resultList = new ArrayList<>();
        for (String raw : rawResult) {
            if (!raw.isEmpty()) {
                resultList.add(raw);
            }
        }
        return resultList.toArray(new String[resultList.size()]);

    }

    public static String joinPMMLDelimited(Iterable<?> elements) {
        String rawResult = doJoinDelimited(elements, formatForDelimiter(' '));
        // Must change "" into \"
        return TWO_DOUBLE_QUOTE_ESC.matcher(rawResult).replaceAll(SLASH_QUOTE_ESC);
    }

    public static String joinPMMLDelimitedNumbers(Iterable<? extends Number> elements) {
        // bit of a workaround because NON_NUMERIC quote mode still quote "-1"!
        CSVFormat format = formatForDelimiter(' ').withQuoteMode(QuoteMode.NONE);
        // No quoting, no need to convert quoting
        return doJoinDelimited(elements, format);
    }

    public static String joinDelimited(Iterable<?> elements, char delimiter) {
        return doJoinDelimited(elements, formatForDelimiter(delimiter));
    }

    private static String doJoinDelimited(Iterable<?> elements, CSVFormat format) {
        StringWriter out = new StringWriter();
        try (CSVPrinter printer = new CSVPrinter(out, format)) {
            for (Object element : elements) {
                printer.print(element);
            }
            printer.flush();
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
        return out.toString();
    }

}