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    protected DefaultRenderingResult(String formatName) {
042        this.formatName = formatName;
043    }
044
045    /**
046     * @return name of the engine that created it
047     */
048    @Override
049    public String getFormatName() {
050        return formatName;
051    }
052
053    @Override
054    public abstract Object getOutcome();
055
056    @Override
057    public InputStream getStream() {
058        Object outcome = getOutcome();
059        if (outcome instanceof InputStream) {
060            return (InputStream) outcome;
061        } else if (outcome instanceof byte[]) {
062            return new ByteArrayInputStream((byte[]) outcome);
063        } else if (outcome instanceof CharSequence) {
064            return new ByteArrayInputStream(outcome.toString().getBytes());
065        }
066        return getAdapter(InputStream.class);
067    }
068
069    @Override
070    public <E> E getAdapter(Class<E> adapter) {
071        Object outcome = getOutcome();
072        if (adapter.isAssignableFrom(outcome.getClass())) {
073            return adapter.cast(outcome);
074        }
075        return null;
076    }
077
078}