com.memtrip.gear2nd.parser.Deserialization.java Source code

Java tutorial

Introduction

Here is the source code for com.memtrip.gear2nd.parser.Deserialization.java

Source

/**
 * Copyright 2015-present memtrip LTD.
 *
 * 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 com.memtrip.gear2nd.parser;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
import com.memtrip.gear2nd.common.model.Schema;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * Deserialization the YAML specification
 * @author Samuel Kirton <a href="mailto:sam@memtrip.com" />
 */
public final class Deserialization {

    private Deserialization() {

    }

    protected static <T extends Schema> T go(Path path, Class<T> classDef) throws IOException {
        String fileContents = readFile(path);
        return getYAMLMapper().readValue(fileContents, classDef);
    }

    private static YAMLMapper getYAMLMapper() {
        YAMLMapper yamlMapper = new YAMLMapper();
        yamlMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        yamlMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
        return yamlMapper;
    }

    private static String readFile(Path path) {
        try {
            StringBuilder sb = new StringBuilder();

            Files.lines(path).forEach(line -> {
                sb.append(line);
                sb.append(System.lineSeparator());
            });

            return sb.toString();
        } catch (IOException e) {
            return null;
        }
    }
}