001/* 002 * Copyright 2018 Anyware Services 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.ametys.web.impl.model.type.xsl; 017 018import org.apache.avalon.framework.configuration.Configuration; 019import org.apache.avalon.framework.configuration.ConfigurationException; 020import org.apache.cocoon.xml.AttributesImpl; 021import org.apache.cocoon.xml.XMLUtils; 022import org.apache.commons.lang3.StringUtils; 023import org.xml.sax.ContentHandler; 024import org.xml.sax.SAXException; 025 026import org.ametys.runtime.model.type.xml.XMLElementType; 027 028/** 029 * Interfaces for XSL parameter types 030 * @param <T> Type of the parameter value 031 */ 032public interface XSLElementType<T> extends XMLElementType<T> 033{ 034 /** 035 * XML element name. It is made public because we are in an interface and multiple extend is not possible. 036 */ 037 public static final String ELEMENT_NAME = "xsl:variable"; 038 039 public default Object read(Configuration parentConfiguration, String name) throws ConfigurationException 040 { 041 Configuration elementConfiguration = null; 042 for (Configuration configuration : parentConfiguration.getChildren(ELEMENT_NAME)) 043 { 044 if (configuration.getAttribute("name", "").equals(name)) 045 { 046 elementConfiguration = configuration; 047 break; 048 } 049 } 050 051 return readValueFromNode(elementConfiguration); 052 } 053 054 @SuppressWarnings("unchecked") 055 public default void write(ContentHandler contentHandler, String name, Object value) throws SAXException 056 { 057 AttributesImpl attrs = new AttributesImpl(); 058 attrs.addCDATAAttribute("name", name); 059 if (value == null) 060 { 061 XMLUtils.createElement(contentHandler, ELEMENT_NAME, attrs); 062 } 063 else if (getManagedClass().isInstance(value)) 064 { 065 XMLUtils.createElement(contentHandler, ELEMENT_NAME, attrs, StringUtils.defaultString(toString((T) value))); 066 } 067 else if (getManagedClassArray().isInstance(value)) 068 { 069 XMLUtils.startElement(contentHandler, ELEMENT_NAME, attrs); 070 for (T singleValue : (T[]) value) 071 { 072 XMLUtils.createElement(contentHandler, "value", StringUtils.defaultString(toString(singleValue))); 073 } 074 XMLUtils.endElement(contentHandler, ELEMENT_NAME); 075 } 076 else 077 { 078 throw new IllegalArgumentException("Try to write the non " + getManagedClass().getName() + " value '" + value + "' on element named '" + name + "'"); 079 } 080 } 081}