001/* 002 * This library is part of OpenCms - 003 * the Open Source Content Management System 004 * 005 * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com) 006 * 007 * This library 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 * This library 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 015 * Lesser General Public License for more details. 016 * 017 * For further information about Alkacon Software, please see the 018 * company website: http://www.alkacon.com 019 * 020 * For further information about OpenCms, please see the 021 * project website: http://www.opencms.org 022 * 023 * You should have received a copy of the GNU Lesser General Public 024 * License along with this library; if not, write to the Free Software 025 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 026 */ 027 028package org.opencms.jsp; 029 030import org.opencms.json.JSONException; 031import org.opencms.json.JSONObject; 032 033import javax.servlet.jsp.JspException; 034import javax.servlet.jsp.JspTagException; 035 036/** 037 * Tag for defining a JSON object. 038 * 039 * Key-value pairs created by nested JSON tags will be added to the object. 040 */ 041public class CmsJspTagJsonObject extends A_CmsJspJsonTag implements I_CmsJspJsonContext { 042 043 /** Serial version id. */ 044 private static final long serialVersionUID = -3054667197099417049L; 045 046 /** The JSON object being constructed. */ 047 private JSONObject m_jsonObject; 048 049 /** 050 * Default constructor explicitly resetting all variables. 051 */ 052 public CmsJspTagJsonObject() { 053 054 init(); 055 } 056 057 /** 058 * @see org.opencms.jsp.I_CmsJspJsonContext#addValue(java.lang.String, java.lang.Object) 059 */ 060 public void addValue(String key, Object val) throws JspException { 061 062 if (key == null) { 063 throw new JspTagException("Can not add value to JSONObject with no key (val:" + val + ")"); 064 } 065 try { 066 m_jsonObject.put(key, val); 067 } catch (JSONException e) { 068 throw new JspTagException("Could not add value to JSONObject", e); 069 } 070 } 071 072 /** 073 * @see javax.servlet.jsp.tagext.BodyTagSupport#doStartTag() 074 */ 075 @Override 076 public int doStartTag() { 077 078 m_jsonObject = new JSONObject(); 079 return EVAL_BODY_INCLUDE; 080 } 081 082 /** 083 * @see org.opencms.jsp.A_CmsJspJsonTag#getJsonValue() 084 */ 085 @Override 086 public Object getJsonValue() { 087 088 return m_jsonObject; 089 } 090 091 /** 092 * Initializes / resets the internal values.<p> 093 */ 094 @Override 095 protected void init() { 096 097 super.init(); 098 m_jsonObject = null; 099 } 100}