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 2016 ForgeRock AS. 015 */ 016package org.forgerock.api.models; 017 018import static org.forgerock.json.JsonValue.array; 019import static org.forgerock.json.JsonValue.json; 020import static org.forgerock.json.JsonValue.object; 021 022import org.forgerock.json.JsonValue; 023import org.forgerock.util.Function; 024import org.forgerock.util.i18n.LocalizableString; 025import org.forgerock.util.promise.NeverThrowsException; 026 027/** 028 * Iterates over each JsonValue node in the JsonValue structure and if it's a String marked for translation, 029 * It replaces the String with a LocalizableString. 030 */ 031public class TranslateJsonSchema implements Function<JsonValue, JsonValue, NeverThrowsException> { 032 033 private final ClassLoader loader; 034 035 /** 036 * Constructor which takes a {@code ClassLoader} where the String is defined. 037 * @param loader the {@code ClassLoader} where the translation resources are defined 038 */ 039 public TranslateJsonSchema(ClassLoader loader) { 040 this.loader = loader; 041 } 042 043 /** 044 * Applies the translation to string values by converting them to {@code LocalizableString}. 045 * It traverses the JsonValue structure, iteratively applying the function to each item 046 * in a collection. 047 * @param value A JsonValue. 048 * @return a transformed copy of the JsonValue input. 049 */ 050 @Override 051 public JsonValue apply(JsonValue value) { 052 JsonValue returnValue = value; 053 if (value.isCollection()) { 054 JsonValue transformedValue = json(array()); 055 for (JsonValue item : value) { 056 transformedValue.add(item.as(this).getObject()); 057 } 058 returnValue = transformedValue; 059 } else if (value.isMap()) { 060 JsonValue transformedValue = json(object()); 061 for (String key : value.keys()) { 062 transformedValue.put(key, value.get(key).as(this).getObject()); 063 } 064 returnValue = transformedValue; 065 } else if (value.isString() && value.asString().startsWith(LocalizableString.TRANSLATION_KEY_PREFIX)) { 066 returnValue = json(new LocalizableString(value.asString(), loader)); 067 } 068 return returnValue; 069 } 070}