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