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

io.annot8.common.data.content.Row Maven / Gradle / Ivy

The newest version!
/* Annot8 (annot8.io) - Licensed under Apache-2.0. */
package io.annot8.common.data.content;

import io.annot8.common.utils.java.ConversionUtils;
import java.util.List;
import java.util.Optional;

public interface Row {

  List getColumnNames();

  int getColumnCount();

  int getRowIndex();

  Optional getValueAt(int index);

  default Optional getColumnName(int index) {
    if (getColumnNames() == null || getColumnNames().isEmpty() || index > getColumnCount()) {
      return Optional.empty();
    }
    return Optional.ofNullable(getColumnNames().get(index));
  }

  default Optional getString(int index) {
    return getValueAt(index).map(Object::toString);
  }

  default Optional getInt(int index) {
    return ConversionUtils.toInt(getValueAt(index));
  }

  default Optional getLong(int index) {
    return ConversionUtils.toLong(getValueAt(index));
  }

  default Optional getDouble(int index) {
    return ConversionUtils.toDouble(getValueAt(index));
  }

  default Optional getValueAt(String columnName) {
    return getIndex(columnName)
        .map(this::getValueAt)
        .filter(Optional::isPresent)
        .map(Optional::get);
  }

  default Optional getString(String columnName) {
    return getValueAt(columnName).map(Object::toString);
  }

  default Optional getInt(String columnName) {
    return ConversionUtils.toInt(getValueAt(columnName));
  }

  default Optional getLong(String columnName) {
    return ConversionUtils.toLong(getValueAt(columnName));
  }

  default Optional getDouble(String columnName) {
    return ConversionUtils.toDouble(getValueAt(columnName));
  }

  default Optional getIndex(String columnName) {
    if (getColumnNames() != null && getColumnNames().contains(columnName)) {
      return Optional.of(getColumnNames().indexOf(columnName));
    }
    return Optional.empty();
  }

  default  Optional getObject(int index, Class requiredClass) {
    return getValueAt(index)
        .map(
            v -> {
              try {
                return requiredClass.cast(v);
              } catch (ClassCastException e) {
                return null;
              }
            });
  }

  default  Optional getObject(String columnName, Class requiredClass) {
    return getIndex(columnName)
        .map(i -> this.getObject(i, requiredClass))
        .filter(Optional::isPresent)
        .map(Optional::get);
  }
}