001/* 002 * Copyright 2023 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.plugins.workflow.support; 017 018import java.util.Map; 019 020import org.xml.sax.Attributes; 021import org.xml.sax.SAXException; 022import org.xml.sax.helpers.DefaultHandler; 023 024import org.ametys.runtime.i18n.I18nizableText; 025 026/** 027 * This class is intended to be use as a simple helper to construct Map for i18n 028 * message from SAX events. <br> 029 * Each pair key/value will be put (as Strings) in the constructed Map 030 */ 031public class I18nMessageHandler extends DefaultHandler 032{ 033 /** The object being constructed */ 034 private Map<I18nizableText, String> _map; 035 036 /** Current characters from SAX events */ 037 private StringBuilder _currentText; 038 039 /** The catalog of the messages */ 040 private String _catalog; 041 042 /** The current key message */ 043 private String _currentKey; 044 045 /** True when saxing element with "message" qName */ 046 private boolean _message; 047 048 /** 049 * Construct a I18nMessageHandler 050 * 051 * @param i18nMessages The map representing each pair of key/value for i18n message 052 * @param catalog The catalog of the messages 053 */ 054 public I18nMessageHandler(Map<I18nizableText, String> i18nMessages, String catalog) 055 { 056 this._map = i18nMessages; 057 this._catalog = catalog; 058 } 059 060 @Override 061 public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException 062 { 063 _message = false; 064 if (qName.equals("message")) 065 { 066 _message = true; 067 _currentText = new StringBuilder(); 068 _currentKey = attributes.getValue("key"); 069 } 070 } 071 072 @Override 073 public void characters(char[] ch, int start, int length) throws SAXException 074 { 075 if (_message) 076 { 077 _currentText.append(ch, start, length); 078 } 079 } 080 081 @Override 082 public void endElement(String uri, String localName, String qName) throws SAXException 083 { 084 if (qName.equals("message")) 085 { 086 _map.put(new I18nizableText(_catalog, _currentKey), _currentText.toString()); 087 _message = false; 088 } 089 } 090}