001/* 002 GRANITE DATA SERVICES 003 Copyright (C) 2011 GRANITE DATA SERVICES S.A.S. 004 005 This file is part of Granite Data Services. 006 007 Granite Data Services is free software; you can redistribute it and/or modify 008 it under the terms of the GNU Library General Public License as published by 009 the Free Software Foundation; either version 2 of the License, or (at your 010 option) any later version. 011 012 Granite Data Services is distributed in the hope that it will be useful, but 013 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 014 FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License 015 for more details. 016 017 You should have received a copy of the GNU Library General Public License 018 along with this library; if not, see <http://www.gnu.org/licenses/>. 019*/ 020 021package org.granite.generator.gsp.token; 022 023import org.granite.generator.gsp.ParseException; 024 025import java.io.StringReader; 026import java.io.IOException; 027 028import java.util.Map; 029import java.util.HashMap; 030 031import org.xml.sax.Attributes; 032import org.xml.sax.SAXException; 033import org.xml.sax.InputSource; 034import org.xml.sax.helpers.DefaultHandler; 035 036import javax.xml.parsers.SAXParserFactory; 037import javax.xml.parsers.ParserConfigurationException; 038 039/** 040 * @author Franck WOLFF 041 */ 042public class Directive extends Token { 043 044 String name = null; 045 final Map<String, String> attributes = new HashMap<String, String>(); 046 047 public Directive(int index, String content) throws ParseException { 048 super(index, content); 049 try { 050 parse(content); 051 } catch (Exception e) { 052 throw new ParseException(e); 053 } 054 } 055 056 public String getName() { 057 return name; 058 } 059 060 public Map<String, String> getAttributes() { 061 return attributes; 062 } 063 064 private void parse(String content) 065 throws SAXException, ParserConfigurationException, IOException { 066 InputSource is = new InputSource(new StringReader('<' + content + "/>")); 067 SAXParserFactory.newInstance().newSAXParser().parse(is, new Handler()); 068 } 069 070 @Override 071 public String toString() { 072 return this.getClass().getName() + '[' + name + ", " + attributes + ']'; 073 } 074 075 class Handler extends DefaultHandler { 076 @Override 077 public void startElement(String namespaceURI, 078 String localName, 079 String qName, 080 Attributes atts) 081 throws SAXException { 082 if (name != null) 083 throw new SAXException("illegal nested element: " + qName); 084 name = qName; 085 for (int i = 0; i < atts.getLength(); i++) 086 attributes.put(atts.getQName(i), atts.getValue(i)); 087 } 088 } 089}