001/* 002 * VM-Operator 003 * Copyright (C) 2023 Michael N. Lipp 004 * 005 * This program is free software: you can redistribute it and/or modify 006 * it under the terms of the GNU Affero General Public License as 007 * published by the Free Software Foundation, either version 3 of the 008 * License, or (at your option) any later version. 009 * 010 * This program is distributed in the hope that it will be useful, 011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 013 * GNU Affero General Public License for more details. 014 * 015 * You should have received a copy of the GNU Affero General Public License 016 * along with this program. If not, see <https://www.gnu.org/licenses/>. 017 */ 018 019package org.jdrupes.vmoperator.util; 020 021import freemarker.ext.util.WrapperTemplateModel; 022import freemarker.template.ObjectWrapper; 023import freemarker.template.TemplateHashModel; 024import freemarker.template.TemplateModel; 025import freemarker.template.TemplateModelException; 026import freemarker.template.WrappingTemplateModel; 027 028/** 029 * Wraps a DTO in a {@link TemplateHashModel}. 030 */ 031public class DtoTemplateModel extends WrappingTemplateModel 032 implements WrapperTemplateModel, TemplateHashModel { 033 034 private final Dto dto; 035 036 /** 037 * Instantiates a new DTO template model. 038 * 039 * @param objectWrapper the object wrapper 040 * @param dto the dto 041 */ 042 public DtoTemplateModel(ObjectWrapper objectWrapper, Dto dto) { 043 super(objectWrapper); 044 this.dto = dto; 045 } 046 047 @Override 048 @SuppressWarnings("PMD.PreserveStackTrace") 049 public TemplateModel get(String key) throws TemplateModelException { 050 try { 051 var field = dto.getClass().getDeclaredField(key); 052 return wrap(field.get(dto)); 053 } catch (NoSuchFieldException | SecurityException e) { 054 throw new TemplateModelException("No Field " + key 055 + " in class " + dto.getClass()); 056 } catch (IllegalArgumentException | IllegalAccessException e) { 057 throw new TemplateModelException("Cannot access field " + key 058 + " in class " + dto.getClass()); 059 } 060 } 061 062 @Override 063 public boolean isEmpty() throws TemplateModelException { 064 return false; 065 } 066 067 @Override 068 public Object getWrappedObject() { 069 return dto; 070 } 071 072}