001/* 002 * Copyright 2012 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.runtime.util; 017 018import java.util.Map; 019 020import org.xml.sax.Attributes; 021import org.xml.sax.SAXException; 022import org.xml.sax.helpers.DefaultHandler; 023 024/** 025 * This class is intended to be use as a simple helper to construct Maps from 026 * SAX events. <br> 027 * The incoming SAX document must follow this structure :<br> 028 * 029 * <root> <br> 030 * <Name1>value1</Name1> <br> 031 * <Name2>value2</Name2> <br> 032 * ... <br> 033 * </root> <br> 034 * <br> 035 * Each pair Name/Value will be put (as Strings) in the constructed Map <br> 036 */ 037public class MapHandler extends DefaultHandler 038{ 039 // The object being constructed 040 private Map<String, String> _map; 041 042 // level in the XML tree. Root is at level 1, and data at level 2 043 private int _level; 044 045 // current characters from SAX events 046 private StringBuffer _currentString; 047 048 /** 049 * Create a map handler 050 * @param map Map to fill 051 */ 052 public MapHandler(Map<String, String> map) 053 { 054 _map = map; 055 } 056 057 @Override 058 public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException 059 { 060 _level++; 061 _currentString = new StringBuffer(); 062 } 063 064 @Override 065 public void characters(char[] ch, int start, int length) throws SAXException 066 { 067 _currentString.append(ch, start, length); 068 } 069 070 @Override 071 public void endElement(String uri, String localName, String qName) throws SAXException 072 { 073 if (_level == 2) 074 { 075 // If we are at the "data" level 076 String strValue = _currentString.toString(); 077 _map.put(qName, strValue); 078 } 079 080 _level--; 081 } 082}