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

org.tools4j.groovytables.CreateFromTable.groovy Maven / Gradle / Ivy

Go to download

A groovy API which allows you to create lists of objects using a table like grammar.

There is a newer version: 1.6
Show newest version
package org.tools4j.groovytables

import groovy.transform.TypeChecked

import java.util.function.Predicate

import static org.tools4j.groovytables.SimpleTableParser.Var

/**
 * User: ben
 * Date: 10/02/2016
 * Time: 5:46 PM
 */
@TypeChecked
class CreateFromTable {
    static  List createFromTable(final Class clazz, final Closure tableContent) {
        return createFromTable(clazz, ConstructionMethodFilter.INCLUDE_ALL, tableContent)
    }

    static  List createFromTable(final Class clazz, final Predicate constructionMethodFilter, final Closure tableContent) {
        final long startTime = System.currentTimeMillis()
        final List rows = SimpleTableParser.asListOfRows(tableContent);
        final List rowsAsObjects = new ArrayList(rows.size())

        if(rows.size() == 0){
            return rowsAsObjects
        }

        boolean firstRowContainsColumnHeadings = rows.get(0).asArray().every{it instanceof Var}
        List columnHeadings;
        if(firstRowContainsColumnHeadings){
            columnHeadings = rows.get(0).asArray().collect{ Var var -> var.name}
            rows.remove(0)
        } else {
            columnHeadings = [];
        }

        for(final Row row: rows){
            final Object[] args = row.asArray()
            final TypeCoercionResult coercionResult = TypeCoercion.coerceToType(clazz, constructionMethodFilter, columnHeadings, args)
            if(coercionResult.suitability == Suitability.NOT_SUITABLE){
                throw new IllegalArgumentException("Could not coerce to type [$clazz.simpleName] row with args $args");
            }
            T rowAsObject = coercionResult.result
            rowsAsObjects.add(rowAsObject)
        }
        final long endTime = System.currentTimeMillis()
        final long duration = endTime - startTime
        Logger.info("createFromTable took: $duration ms")
        return rowsAsObjects;
    }

    /*
    Using chained statements
     */

    static class Builder{
        final Class clazz

        Builder(final Class clazz) {
            this.clazz = clazz
        }

        List fromTable(final Closure tableContent){
            return createFromTable(clazz, tableContent)
        }
    }

    static  Builder createListOf(final Class clazz) {
        return new Builder(clazz)
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy