Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load DATETIME object from YAML file?

I'm using JODA TIME library for persisting DATETIMEs. Before I run my tests I need to setup test data. So I've a yaml file where I've defined test data with dates which I was hoping would convert into DATETIME objects but they are not.

I'm using Play Framework 2.0. Any idea how I can convert YAML date into a real DATETIME object.

Here's how my yaml file look like

users:
    - !!models.User
        createdOn:     2001-09-09T01:46:40Z
        fName:         Mike
        lName:         Roller
like image 399
jsf Avatar asked Nov 12 '22 18:11

jsf


1 Answers

Taken from snakeyaml project WIKI. Examples are here.

How to parse JodaTime

Since JodaTime is no JavaBean (because it does not have an empty constructor), it requires some extra treatment when parsing:

private class ConstructJodaTimestamp extends ConstructYamlTimestamp {
    public Object construct(Node node) {
        Date date = (Date) super.construct(node);
        return new DateTime(date, DateTimeZone.UTC);
    }
}

When the JodaTime instance is the JavaBean property you can use the following:

Yaml y = new Yaml(new JodaPropertyConstructor());

class JodaPropertyConstructor extends Constructor {
    public JodaPropertyConstructor() {
        yamlClassConstructors.put(NodeId.scalar, new TimeStampConstruct());
    }

    class TimeStampConstruct extends Constructor.ConstructScalar {
        @Override
        public Object construct(Node nnode) {
            if (nnode.getTag().equals("tag:yaml.org,2002:timestamp")) {
                Construct dateConstructor = yamlConstructors.get(Tag.TIMESTAMP);
                Date date = (Date) dateConstructor.construct(nnode);
                return new DateTime(date, DateTimeZone.UTC);
            } else {
                return super.construct(nnode);
            }
        }

    }
}
like image 55
Sidorov Maxim Avatar answered Nov 15 '22 11:11

Sidorov Maxim