001/* 002 * SPDX-License-Identifier: Apache-2.0 003 * 004 * Copyright 2025-2026 The Enola <https://enola.dev> Authors 005 * 006 * Licensed under the Apache License, Version 2.0 (the "License"); 007 * you may not use this file except in compliance with the License. 008 * You may obtain a copy of the License at 009 * 010 * https://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package dev.enola.common.template.tool; 019 020import com.google.common.collect.ImmutableMap; 021 022import dev.enola.common.io.object.ObjectReader; 023import dev.enola.common.io.resource.ReadableResource; 024import dev.enola.common.io.resource.WritableResource; 025import dev.enola.common.template.TemplateProvider; 026 027import java.io.IOException; 028import java.util.Map; 029 030public class Temply { 031 032 private final ObjectReader objectReader; 033 private final TemplateProvider templateProvider; 034 035 public Temply(ObjectReader objectReader, TemplateProvider templateProvider) { 036 this.objectReader = objectReader; 037 this.templateProvider = templateProvider; 038 } 039 040 @SuppressWarnings("unchecked") // Due to ObjectReader API using Class<T> without TypeReference 041 public void convert( 042 Iterable<? extends ReadableResource> dataResources, 043 ReadableResource templateResource, 044 WritableResource into) 045 throws IOException { 046 047 var mapBuilder = ImmutableMap.<String, Object>builder(); 048 for (var dataResource : dataResources) { 049 mapBuilder.putAll(objectReader.read(dataResource, Map.class)); 050 } 051 052 objectReader.optional(templateResource, Map.class).ifPresent(map -> mapBuilder.putAll(map)); 053 054 var allDataMap = mapBuilder.build(); 055 var template = templateProvider.get(templateResource); 056 try (var appendable = into.charSink().openBufferedStream()) { 057 template.apply(allDataMap, appendable); 058 } 059 } 060}