All Downloads are FREE. Search and download functionalities are using the official Maven repository.

akka.stream.alpakka.csv.javadsl.CsvFormatting Maven / Gradle / Ivy

Go to download

Alpakka is a Reactive Enterprise Integration library for Java and Scala, based on Reactive Streams and Akka.

There is a newer version: 6.0.2
Show newest version
/*
 * Copyright (C) since 2016 Lightbend Inc. 
 */

package akka.stream.alpakka.csv.javadsl;

import akka.NotUsed;
import akka.stream.alpakka.csv.scaladsl.CsvQuotingStyle$;
import akka.stream.javadsl.Flow;
import akka.util.ByteString;
import scala.Option;
import scala.Some;
import scala.collection.JavaConverters;
import scala.collection.immutable.List;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Optional;

/**
 * Provides CSV formatting flows that convert a sequence of String into their CSV representation in
 * {@see akka.util.ByteString}.
 */
public class CsvFormatting {

  public static final char BACKSLASH = '\\';
  public static final char COMMA = ',';
  public static final char SEMI_COLON = ';';
  public static final char COLON = ':';
  public static final char TAB = '\t';
  public static final char DOUBLE_QUOTE = '"';
  public static final String CR_LF = "\r\n";

  /**
   * Generates standard CSV format (with commas).
   *
   * @param  Any collection implementation
   * @return The formatting flow
   */
  public static > Flow format() {
    return format(
        COMMA,
        DOUBLE_QUOTE,
        BACKSLASH,
        CR_LF,
        CsvQuotingStyle.REQUIRED,
        StandardCharsets.UTF_8,
        Optional.empty());
  }

  /**
   * Generates CSV with the specified special characters and character set.
   *
   * @param delimiter Delimiter between columns
   * @param quoteChar Quoting character
   * @param escapeChar Escape character
   * @param endOfLine End of line character sequence
   * @param quotingStyle Quote all values or as required
   * @param charset Character set to be used
   * @param  Any collection implementation
   * @return The formatting flow
   */
  public static > Flow format(
      char delimiter,
      char quoteChar,
      char escapeChar,
      String endOfLine,
      CsvQuotingStyle quotingStyle,
      Charset charset,
      Optional byteOrderMark) {
    akka.stream.alpakka.csv.scaladsl.CsvQuotingStyle qs =
        CsvQuotingStyle$.MODULE$.asScala(quotingStyle);
    Option byteOrderMarkScala =
        byteOrderMark.>map(Some::apply).orElse(Option.empty());
    akka.stream.scaladsl.Flow, ByteString, NotUsed> formattingFlow =
        akka.stream.alpakka.csv.scaladsl.CsvFormatting.format(
            delimiter, quoteChar, escapeChar, endOfLine, qs, charset, byteOrderMarkScala);
    return Flow.create()
        .map(c -> JavaConverters.collectionAsScalaIterableConverter(c).asScala().toList())
        .via(formattingFlow);
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy