001 // Copyright 2006 The Apache Software Foundation
002 //
003 // Licensed under the Apache License, Version 2.0 (the "License");
004 // you may not use this file except in compliance with the License.
005 // You may obtain a copy of the License at
006 //
007 // http://www.apache.org/licenses/LICENSE-2.0
008 //
009 // Unless required by applicable law or agreed to in writing, software
010 // distributed under the License is distributed on an "AS IS" BASIS,
011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012 // See the License for the specific language governing permissions and
013 // limitations under the License.
014 package org.apache.tapestry.markup;
015
016 import java.io.PrintWriter;
017
018 import org.apache.hivemind.util.Defense;
019 import org.apache.tapestry.json.IJSONWriter;
020 import org.apache.tapestry.json.JSONArray;
021 import org.apache.tapestry.json.JSONObject;
022
023 /**
024 * Implementation of {@link IJSONWriter}.
025 *
026 * @author jkuhnert
027 */
028 public class JSONWriterImpl implements IJSONWriter
029 {
030 /** Outputstream writer. */
031 protected PrintWriter _writer;
032
033 /**
034 * Delegate object that handles object json renders.
035 */
036 private JSONObject _json;
037
038 /**
039 * Delegate array object that handles object array json renders.
040 */
041 private JSONArray _array;
042
043 /**
044 * Creates a new instance that will write all content to
045 * the specified {@link PrintWriter}.
046 *
047 * @param writer The outputstream to write to.
048 */
049 public JSONWriterImpl(PrintWriter writer)
050 {
051 Defense.notNull(writer, "writer");
052
053 _writer = writer;
054 }
055
056 /**
057 *
058 * {@inheritDoc}
059 */
060 public void close()
061 {
062 if (_json == null && _array == null)
063 _json = new JSONObject();
064
065 if (_json != null) {
066
067 _writer.write(_json.toString());
068 }
069
070 if (_array != null) {
071
072 _writer.write(_array.toString());
073 }
074
075 _writer.flush();
076 _writer.close();
077 }
078
079 /**
080 * {@inheritDoc}
081 */
082 public JSONObject object()
083 {
084 if (_json == null)
085 _json = new JSONObject();
086
087 return _json;
088 }
089
090 /**
091 * {@inheritDoc}
092 */
093 public JSONArray array()
094 {
095 if (_array == null)
096 _array = new JSONArray();
097
098 return _array;
099 }
100
101 public void flush()
102 {
103 _writer.flush();
104 }
105
106 /**
107 * The outputstream being used to write this
108 * instance's content.
109 *
110 * @return The writer being written to.
111 */
112 protected PrintWriter getWriter()
113 {
114 return _writer;
115 }
116 }