001// Copyright 2005 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
015package org.apache.tapestry.contrib.components;
016
017import java.io.BufferedOutputStream;
018import java.io.CharArrayWriter;
019import java.io.ObjectOutputStream;
020
021import org.apache.tapestry.AbstractComponent;
022import org.apache.tapestry.IMarkupWriter;
023import org.apache.tapestry.IRequestCycle;
024import org.apache.tapestry.util.io.BinaryDumpOutputStream;
025
026/**
027 * Used to dump out an object's serialized representation in a mix of hex and ascii. The output is
028 * formatted for a fixed width font, typically should be enclosed in <pre> tags.
029 * 
030 * @see org.apache.tapestry.util.io.BinaryDumpOutputStream
031 * @author Howard M. Lewis Ship
032 * @since 4.0
033 */
034
035public abstract class DumpObject extends AbstractComponent
036{
037    // Parameters:
038
039    public abstract Object getObject();
040
041    protected void renderComponent(IMarkupWriter writer, IRequestCycle cycle)
042    {
043        if (cycle.isRewinding())
044            return;
045
046        String asText = convert(getObject());
047
048        writer.print(asText);
049    }
050
051    String convert(Object object)
052    {
053        try
054        {
055            CharArrayWriter writer = new CharArrayWriter();
056            BinaryDumpOutputStream bdos = new BinaryDumpOutputStream(writer);
057            ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(bdos));
058
059            oos.writeObject(object);
060
061            oos.close();
062
063            return writer.toString();
064        }
065        catch (Exception ex)
066        {
067            return ex.toString();
068        }
069    }
070}