001/*
002 * The contents of this file are subject to the terms of the Common Development and
003 * Distribution License (the License). You may not use this file except in compliance with the
004 * License.
005 *
006 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
007 * specific language governing permission and limitations under the License.
008 *
009 * When distributing Covered Software, include this CDDL Header Notice in each file and include
010 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
011 * Header, with the fields enclosed by brackets [] replaced by your own identifying
012 * information: "Portions copyright [year] [name of copyright owner]".
013 *
014 * Copyright 2015-2017 ForgeRock AS.
015 */
016
017package org.forgerock.selfservice.example;
018
019import java.io.BufferedReader;
020import java.io.IOException;
021import java.io.InputStream;
022import java.io.InputStreamReader;
023import java.util.Map;
024
025import com.fasterxml.jackson.databind.ObjectMapper;
026
027import org.forgerock.json.JsonException;
028import org.forgerock.json.JsonValue;
029
030
031/**
032 * Simple utility class to parse json string into a json value.
033 *
034 * @since 0.1.0
035 */
036public final class JsonReader {
037
038    private static final ObjectMapper MAPPER = new ObjectMapper();
039
040    private JsonReader() {
041        throw new UnsupportedOperationException();
042    }
043
044    /**
045     * Given a path to a json file returns a corresponding json value.
046     *
047     * @param filename
048     *         file path to json file
049     *
050     * @return json value
051     */
052    public static JsonValue jsonFileToJsonValue(String filename) {
053        InputStream stream = JsonReader.class.getResourceAsStream(filename);
054
055        try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"))) {
056
057            StringBuilder contents = new StringBuilder();
058            String line;
059
060            while ((line = reader.readLine()) != null) {
061                contents.append(line).append('\n');
062            }
063
064            return new JsonValue(MAPPER.readValue(contents.toString(),  Map.class));
065        } catch (IOException e) {
066            throw new JsonException("Failed to parse json", e);
067        }
068    }
069
070}