001/*
002// This software is subject to the terms of the Eclipse Public License v1.0
003// Agreement, available at the following URL:
004// http://www.eclipse.org/legal/epl-v10.html.
005// You must accept the terms of that agreement to use this software.
006//
007// Copyright (C) 2005-2010 Pentaho
008// All Rights Reserved.
009*/
010package mondrian.xmla.impl;
011
012import mondrian.olap.Util;
013import mondrian.xmla.*;
014
015import java.io.OutputStream;
016import java.io.UnsupportedEncodingException;
017
018/**
019 * Default implementation of {@link mondrian.xmla.XmlaResponse}.
020 *
021 * @author Gang Chen
022 */
023public class DefaultXmlaResponse implements XmlaResponse  {
024
025    // TODO: add a msg to MondrianResource for this.
026    private static final String MSG_ENCODING_ERROR = "Encoding unsupported: ";
027
028    private final SaxWriter writer;
029
030    public DefaultXmlaResponse(
031        OutputStream outputStream,
032        String encoding,
033        Enumeration.ResponseMimeType responseMimeType)
034    {
035        try {
036            switch (responseMimeType) {
037            case JSON:
038                writer = new JsonSaxWriter(outputStream);
039                break;
040            case SOAP:
041            default:
042                writer = new DefaultSaxWriter(outputStream, encoding);
043                break;
044            }
045        } catch (UnsupportedEncodingException uee) {
046            throw Util.newError(uee, MSG_ENCODING_ERROR + encoding);
047        }
048    }
049
050    public SaxWriter getWriter() {
051        return writer;
052    }
053
054    public void error(Throwable t) {
055        writer.completeBeforeElement("root");
056        @SuppressWarnings({"ThrowableResultOfMethodCallIgnored"})
057        Throwable throwable = XmlaUtil.rootThrowable(t);
058        writer.startElement("Messages");
059        writer.startElement(
060            "Error",
061            "ErrorCode", throwable.getClass().getName(),
062            "Description", throwable.getMessage(),
063            "Source", "Mondrian",
064            "Help", "");
065        writer.endElement(); // </Messages>
066        writer.endElement(); // </Error>
067    }
068}
069
070// End DefaultXmlaResponse.java