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

br.com.objectos.io.flat.LocalDateColumn Maven / Gradle / Ivy

The newest version!
/*
 * Copyright 2015 Objectos, Fábrica de Software LTDA.
 *
 * 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 br.com.objectos.io.flat;

import java.time.format.DateTimeParseException;
import java.util.Optional;

import br.com.objectos.io.flat.annotation.LocalDatePattern;

/**
 * @author [email protected] (Marcio Endo)
 */
abstract class LocalDateColumn extends Column {

  final LocalDatePattern pattern;

  private LocalDateColumn(int index, int length, LocalDatePattern pattern) {
    super(index, length);
    this.pattern = pattern;
  }

  public static LocalDateColumn get(LocalDatePattern pattern) {
    int index = 0;
    return get(index, pattern);
  }

  public static LocalDateColumn get(LocalDatePattern pattern, String whenAbsent) {
    int index = 0;
    return get(index, pattern, whenAbsent);
  }

  public static LocalDateColumn get(int index, LocalDatePattern pattern) {
    int length = pattern.length();
    return new MandatoryColumn(index, length, pattern);
  }

  public static LocalDateColumn get(int index, LocalDatePattern pattern, String whenAbsent) {
    int length = pattern.length();
    return new OptionalColumn(index, length, pattern, whenAbsent);
  }

  @Override
  Token parse(Line line, String text) {
    try {
      Object value = parseText(text);
      return new ObjectValue(this, text, value);
    } catch (DateTimeParseException e) {
      return ColumnParseError.exception(this, line, text, e);
    }
  }

  abstract Object parseText(String text);

  private static class MandatoryColumn extends LocalDateColumn {

    public MandatoryColumn(int index, int length, LocalDatePattern pattern) {
      super(index, length, pattern);
    }

    @Override
    Object parseText(String text) {
      return pattern.parse(text);
    }

  }

  private static class OptionalColumn extends LocalDateColumn {

    private final String whenAbsent;

    public OptionalColumn(int index, int length, LocalDatePattern pattern, String whenAbsent) {
      super(index, length, pattern);
      this.whenAbsent = whenAbsent;
    }

    @Override
    Object parseText(String text) {
      return text.equals(whenAbsent)
          ? Optional.empty()
          : Optional.of(pattern.parse(text));
    }

  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy