Sunday, 3 June 2018

YAML: - : represent list members

List members are denoted by a leading hyphen (-) with one member per line, or enclosed in square brackets ([ ]) and separated by comma space (, ).


employee.yaml
# YAML file represent employee details
---
- id: 1
  firstName: "Krishna"
  lastName: "Gurram"
  address:
    city: "Bangalore"
    country: "India"
    street: "temple street"
    pinCode: "12345"
- id: 2
  firstName: "Siva"
  lastName: "Ponnam"
  address:
    city: "Nuzvid"
    country: "India"
    street: "KV Palem"
    pinCode: "187652345"

Below java application reads above employees information and convert it into list of employees.

Address.java
package com.sample.model;

public class Address {
 private String city;
 private String country;
 private String street;
 private String pinCode;

 public String getCity() {
  return city;
 }

 public void setCity(String city) {
  this.city = city;
 }

 public String getCountry() {
  return country;
 }

 public void setCountry(String country) {
  this.country = country;
 }

 public String getStreet() {
  return street;
 }

 public void setStreet(String street) {
  this.street = street;
 }

 public String getPinCode() {
  return pinCode;
 }

 public void setPinCode(String pinCode) {
  this.pinCode = pinCode;
 }

 @Override
 public String toString() {
  return "Address [city=" + city + ", country=" + country + ", street=" + street + ", pinCode=" + pinCode + "]";
 }

}

Employee.java

package com.sample.model;

public class Employee {

 private int id;
 private String firstName;
 private String lastName;
 private Address address;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public Address getAddress() {
  return address;
 }

 public void setAddress(Address address) {
  this.address = address;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", address=" + address
    + "]";
 }

}

YAMLUtil.java

package com.sample.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

public class YAMLUtil {

 private static ObjectMapper mapper = new ObjectMapper(new YAMLFactory());

 public static void printYAML(Object obj) throws JsonGenerationException, JsonMappingException, IOException {
  mapper.writeValue(System.out, obj);
 }

 public static <T> T getObject(String yaml, Class<T> clazz)
   throws JsonParseException, JsonMappingException, IOException {
  return mapper.readValue(yaml, clazz);

 }

 public static <T> List<T> getListOfObjects(String yaml, Class<T> clazz)
   throws JsonParseException, JsonMappingException, IOException {
  CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, clazz);
  List<T> ts = mapper.readValue(yaml, listType);
  return ts;

 }
}


Test.java

package com.sample.app;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.sample.model.Employee;
import com.sample.util.YAMLUtil;

public class Test {

 private static final String filePath = "C:\\Users\\krishna\\Documents\\Study\\YAML\\yaml files\\employee.yml";

 public static void main(String args[]) throws JsonGenerationException, JsonMappingException, IOException {

  String fileString = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);

  List<Employee> emps = YAMLUtil.getListOfObjects(fileString, Employee.class);

  for(int i=0; i < emps.size(); i++) {
   Employee emp = emps.get(i);
   System.out.println(emp);
  }
 }
}

Output

Employee [id=1, firstName=Krishna, lastName=Gurram, address=Address [city=Bangalore, country=India, street=temple street, pinCode=12345]]
Employee [id=2, firstName=Siva, lastName=Ponnam, address=Address [city=Nuzvid, country=India, street=KV Palem, pinCode=187652345]]


Previous                                                 Next                                                 Home

Saturday, 2 June 2018

Is YAML support block comments?

YAML doesn’t support block comments.

If you want to comment multiple lines, then you should use multiple # symbols.

For example, to comment three lines, we require 3 # symbols.

#   Failure never overtake me
#   if my determination to succeed is
#   strong enough.

How can I comment multiple yaml lines efficiently?
You can use Eclipse yedit plugin to comment multiple lines. My previous post, explains the installation procedure of yedit plugin.

Open the yaml file in eclipse.

Select the lines that you are interested to comment.



Press Ctrl + Shift + c to comment the lines.



Previous                                                 Next                                                 Home

YAML: Install yedit plugin

Yedit is an eclipse plugin to edit YAML files.

Features of yedit
a.   Syntax highlighting
b.   Syntax checking
c.   Content outline
d.    Templates
e.    Various text editing support like auto-indenting and toggling of comments.
f.     Symfony compatibility mode.
g.    Source formatting (experimental)

How to install yedit plugin in Eclipse?
Open Eclipse.

Help -> Eclipse Marketplace

Type ‘yedit’ in Find box.

Once you click on ‘Go’ button, you can able to see yedit plugin.

Click on ‘Install’ button.

Accept the License agreement and click on Finish button.

Once installation is successful, restart the eclipse.

Open any yaml file in eclipse, you can able to see it like below.



Previous                                                 Next                                                 Home

YAML: Comments

Comments are used to document YAML file. Comments begin with # symbol and they can start anywhere in a line and continue till the end of the line.


employee.yml
# YAML file represent employee details
id: 1
firstName: "Krishna"
lastName: "Gurram"
address:
  city: "Bangalore"
  country: "India"
  street: "temple street"
  pinCode: "12345"

Below java application read the contents of employee.yml file and map them to an Employee instance.

Address.java
package com.sample.model;

public class Address {
 private String city;
 private String country;
 private String street;
 private String pinCode;

 public String getCity() {
  return city;
 }

 public void setCity(String city) {
  this.city = city;
 }

 public String getCountry() {
  return country;
 }

 public void setCountry(String country) {
  this.country = country;
 }

 public String getStreet() {
  return street;
 }

 public void setStreet(String street) {
  this.street = street;
 }

 public String getPinCode() {
  return pinCode;
 }

 public void setPinCode(String pinCode) {
  this.pinCode = pinCode;
 }

 @Override
 public String toString() {
  return "Address [city=" + city + ", country=" + country + ", street=" + street + ", pinCode=" + pinCode + "]";
 }

}

Employee.java

package com.sample.model;

public class Employee {

 private int id;
 private String firstName;
 private String lastName;
 private Address address;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public Address getAddress() {
  return address;
 }

 public void setAddress(Address address) {
  this.address = address;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", address=" + address
    + "]";
 }

}

YAMLUtil.java

package com.sample.util;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

public class YAMLUtil {

 private static ObjectMapper mapper = new ObjectMapper(new YAMLFactory());

 public static void printYAML(Object obj) throws JsonGenerationException, JsonMappingException, IOException {
  mapper.writeValue(System.out, obj);
 }

 public static <T> T getObject(String yaml, Class<T> clazz)
   throws JsonParseException, JsonMappingException, IOException {
  return mapper.readValue(yaml, clazz);

 }
}


Test.java

package com.sample.app;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.sample.model.Employee;
import com.sample.util.YAMLUtil;

public class Test {

 private static final String filePath = "C:\\Users\\krishna\\Documents\\Study\\YAML\\yaml files\\employee.yml";

 public static void main(String args[]) throws JsonGenerationException, JsonMappingException, IOException {

  String fileString = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);

  Employee emp = YAMLUtil.getObject(fileString, Employee.class);

  System.out.println(emp);
 }
}

Output

Employee [id=1, firstName=Krishna, lastName=Gurram, address=Address [city=Bangalore, country=India, street=temple street, pinCode=12345]]



Previous                                                 Next                                                 Home

YAML Tutorial

Previous                                                 Next                                                 Home

Basic data types in YAML

YAML support 3 basic data types.
a.   Scalars: Numbers, Strings, Booleans
b.   Sequences: Arrays, Lists
c.   Mappings: Hashes, Dictionaries

Scalar
Scalar represent the primitives in programming languages. For example, a scalar can be a string, integer, double, boolean.

Example
id: 1
firstName: "Krishna"
lastName: "Gurram"

Sequences
Sequences represent list (or) array of items. Here item can be an object (or) a scalar.

Example
---
- id: 1
  firstName: "Krishna"
  lastName: "Gurram"
- id: 1
  firstName: "Chamu"
  lastName: "KB"


Above example represents list of employee objects.

Mappings
Mappings are used to represent hashes, dictionaries.

Example
A map of employees (where key is the id of the employee and value is the employee object) is represented like below.
---
1:
  id: 1
  firstName: "Krishna"
  lastName: "Gurram"
2:
  id: 1
  firstName: "Chamu"
  lastName: "KB"

Above information is rendered like below in Eclipse.





Previous                                                 Next                                                 Home

Introduction to YAML

YAML is a human friendly data serialization standard for all programming languages.

YAML shows the data in very clean way, by minimizing the amount of structural characters.

For example,
a.   indentation is used for structure,
b.   colons separate key: value pairs, and
c.   dashes are used to create lists.

Don’t use tabs for indentation
Tabs have been outlawed since they are treated differently by different editors and tools, and since indentation is so critical to proper interpretation of YAML, YAML forbid tabs.

What is the file extension of yaml files?
.yaml, .yml

Is YAML a markup language?
No

Is YAML case sensitive?
Yes

Where is YAML used?
YAML was designed to work with below use cases.

a.   configuration files,
b.   log files,
c.   inter process messaging,
d.   cross-language data sharing,
e.   object persistence, and
f.    debugging of complex data structures

For example, log4j2 supports yaml configuration file.

Log4j2.yaml

Configuration:
  status: warn
  name: YAMLConfigTest
  properties:
    property:
      name: filename
      value: target/test-yaml.log
  thresholdFilter:
    level: debug
  appenders:
    Console:
      name: STDOUT
      PatternLayout:
        Pattern: "%m%n"
    File:
      name: File
      fileName: ${filename}
      PatternLayout:
        Pattern: "%d %p %C{1.} [%t] %m%n"
      Filters:
        ThresholdFilter:
          level: error
 
  Loggers:
    logger:
      -
        name: org.apache.logging.log4j.test1
        level: debug
        additivity: false
        ThreadContextMapFilter:
          KeyValuePair:
            key: test
            value: 123
        AppenderRef:
          ref: STDOUT
      -
        name: org.apache.logging.log4j.test2
        level: debug
        additivity: false
        AppenderRef:
          ref: File
    Root:
      level: error
      AppenderRef:
        ref: STDOUT


Simple yaml file in eclipse is rendered like below.

How to validate yaml data online?
You can use above website to validate your yaml data.

Can I import one YAML file into other?
No, YAML does not support any kind of "import" or "include" statement.

I am going to use below maven dependencies throughout this tutorial.

 <dependencies>
  <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-yaml -->
  <dependency>
   <groupId>com.fasterxml.jackson.dataformat</groupId>
   <artifactId>jackson-dataformat-yaml</artifactId>
   <version>2.9.5</version>
  </dependency>

  <dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.9.5</version>
  </dependency>
 </dependencies>

Reference
http://yaml.org/




Previous                                                 Next                                                 Home