001/*
002 * (C) Copyright 2006-2007 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     bstefanescu
018 *
019 * $Id$
020 */
021
022package org.nuxeo.ecm.platform.rendering.impl;
023
024import java.io.ByteArrayInputStream;
025import java.io.InputStream;
026
027import org.nuxeo.ecm.platform.rendering.RenderingResult;
028
029/**
030 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
031 */
032public abstract class DefaultRenderingResult implements RenderingResult {
033
034    private static final long serialVersionUID = 6570212240033856735L;
035
036    protected final String formatName;
037
038    /**
039     * Constructor taking a rendering result name as argument.
040     *
041     * @param formatName
042     */
043    protected DefaultRenderingResult(String formatName) {
044        this.formatName = formatName;
045    }
046
047    /**
048     * @return name of the engine that created it
049     */
050    public String getFormatName() {
051        return formatName;
052    }
053
054    public abstract Object getOutcome();
055
056    public InputStream getStream() {
057        Object outcome = getOutcome();
058        if (outcome instanceof InputStream) {
059            return (InputStream) outcome;
060        } else if (outcome instanceof byte[]) {
061            return new ByteArrayInputStream((byte[]) outcome);
062        } else if (outcome instanceof CharSequence) {
063            return new ByteArrayInputStream(outcome.toString().getBytes());
064        }
065        return getAdapter(InputStream.class);
066    }
067
068    public <E> E getAdapter(Class<E> adapter) {
069        Object outcome = getOutcome();
070        if (adapter.isAssignableFrom(outcome.getClass())) {
071            return adapter.cast(outcome);
072        }
073        return null;
074    }
075
076}