2 * Copyright (c) 2014 Brocade Communications Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.sal.rest.impl;
11 import java.io.ByteArrayOutputStream;
12 import java.io.IOException;
13 import java.io.OutputStreamWriter;
14 import java.io.StringReader;
15 import java.io.UnsupportedEncodingException;
16 import java.util.List;
17 import java.util.Map.Entry;
19 import javax.activation.UnsupportedDataTypeException;
20 import javax.ws.rs.core.Context;
21 import javax.ws.rs.core.HttpHeaders;
22 import javax.ws.rs.core.MediaType;
23 import javax.ws.rs.core.Response;
24 import javax.ws.rs.ext.ExceptionMapper;
25 import javax.ws.rs.ext.Provider;
26 import javax.xml.parsers.DocumentBuilderFactory;
27 import javax.xml.transform.OutputKeys;
28 import javax.xml.transform.Transformer;
29 import javax.xml.transform.TransformerConfigurationException;
30 import javax.xml.transform.TransformerException;
31 import javax.xml.transform.TransformerFactory;
32 import javax.xml.transform.TransformerFactoryConfigurationError;
33 import javax.xml.transform.dom.DOMSource;
34 import javax.xml.transform.stream.StreamResult;
36 import static org.opendaylight.controller.sal.rest.api.Draft02.RestConfModule.*;
38 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
39 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
40 import org.opendaylight.controller.sal.restconf.impl.RestconfError;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
43 import org.opendaylight.yangtools.yang.data.api.Node;
44 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
45 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
46 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
47 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.w3c.dom.Document;
51 import org.xml.sax.InputSource;
53 import com.google.common.base.Strings;
54 import com.google.common.collect.ImmutableList;
55 import com.google.gson.stream.JsonWriter;
58 * This class defines an ExceptionMapper that handles RestconfDocumentedExceptions thrown by
59 * resource implementations and translates appropriately to restconf error response as defined in
60 * the RESTCONF RFC draft.
62 * @author Thomas Pantelis
65 public class RestconfDocumentedExceptionMapper implements ExceptionMapper<RestconfDocumentedException> {
67 private final static Logger LOG = LoggerFactory.getLogger( RestconfDocumentedExceptionMapper.class );
70 private HttpHeaders headers;
73 public Response toResponse( RestconfDocumentedException exception ) {
75 LOG.debug( "In toResponse: {}", exception.getMessage() );
77 // Default to the content type if there's no Accept header
79 MediaType mediaType = headers.getMediaType();
81 List<MediaType> accepts = headers.getAcceptableMediaTypes();
83 LOG.debug( "Accept headers: {}", accepts );
85 if( accepts != null && accepts.size() > 0 ) {
86 mediaType = accepts.get( 0 ); // just pick the first one
89 LOG.debug( "Using MediaType: {}", mediaType );
91 List<RestconfError> errors = exception.getErrors();
92 if( errors.isEmpty() ) {
93 // We don't actually want to send any content but, if we don't set any content here,
94 // the tomcat front-end will send back an html error report. To prevent that, set a
95 // single space char in the entity.
97 return Response.status( exception.getStatus() )
98 .type( MediaType.TEXT_PLAIN_TYPE )
99 .entity( " " ).build();
102 int status = errors.iterator().next().getErrorTag().getStatusCode();
104 ControllerContext context = ControllerContext.getInstance();
105 DataNodeContainer errorsSchemaNode = (DataNodeContainer)context.getRestconfModuleErrorsSchemaNode();
107 if( errorsSchemaNode == null ) {
108 return Response.status( status )
109 .type( MediaType.TEXT_PLAIN_TYPE )
110 .entity( exception.getMessage() ).build();
113 ImmutableList.Builder<Node<?>> errorNodes = ImmutableList.<Node<?>> builder();
114 for( RestconfError error: errors ) {
115 errorNodes.add( toDomNode( error ) );
118 ImmutableCompositeNode errorsNode =
119 ImmutableCompositeNode.create( ERRORS_CONTAINER_QNAME, errorNodes.build() );
122 if( mediaType.getSubtype().endsWith( "json" ) ) {
123 responseBody = toJsonResponseBody( errorsNode, errorsSchemaNode );
126 responseBody = toXMLResponseBody( errorsNode, errorsSchemaNode );
129 return Response.status( status ).type( mediaType ).entity( responseBody ).build();
132 private Object toJsonResponseBody( ImmutableCompositeNode errorsNode,
133 DataNodeContainer errorsSchemaNode ) {
135 JsonMapper jsonMapper = new JsonMapper();
137 Object responseBody = null;
139 ByteArrayOutputStream outStream = new ByteArrayOutputStream();
140 JsonWriter writer = new JsonWriter( new OutputStreamWriter( outStream, "UTF-8" ) );
141 writer.setIndent( " " );
143 jsonMapper.write( writer, errorsNode, errorsSchemaNode, null );
146 responseBody = outStream.toString( "UTF-8" );
148 catch( IOException e ) {
149 LOG.error( "Error writing error response body", e );
155 private Object toXMLResponseBody( ImmutableCompositeNode errorsNode,
156 DataNodeContainer errorsSchemaNode ) {
158 XmlMapper xmlMapper = new XmlMapper();
160 Object responseBody = null;
162 Document xmlDoc = xmlMapper.write( errorsNode, errorsSchemaNode );
164 responseBody = documentToString( xmlDoc );
166 catch( TransformerException | UnsupportedDataTypeException | UnsupportedEncodingException e ) {
167 LOG.error( "Error writing error response body", e );
173 private String documentToString( Document doc ) throws TransformerException, UnsupportedEncodingException {
174 Transformer transformer = createTransformer();
175 ByteArrayOutputStream outStream = new ByteArrayOutputStream();
177 transformer.transform( new DOMSource( doc ), new StreamResult( outStream ) );
179 return outStream.toString( "UTF-8" );
182 private Transformer createTransformer() throws TransformerFactoryConfigurationError,
183 TransformerConfigurationException {
184 TransformerFactory tf = TransformerFactory.newInstance();
185 Transformer transformer = tf.newTransformer();
186 transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "no" );
187 transformer.setOutputProperty( OutputKeys.METHOD, "xml" );
188 transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
189 transformer.setOutputProperty( OutputKeys.ENCODING, "UTF-8" );
190 transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", "4" );
194 private Node<?> toDomNode( RestconfError error ) {
196 CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
197 builder.setQName( ERROR_LIST_QNAME );
199 addLeaf( builder, ERROR_TYPE_QNAME, error.getErrorType().getErrorTypeTag() );
200 addLeaf( builder, ERROR_TAG_QNAME, error.getErrorTag().getTagValue() );
201 addLeaf( builder, ERROR_MESSAGE_QNAME, error.getErrorMessage() );
202 addLeaf( builder, ERROR_APP_TAG_QNAME, error.getErrorAppTag() );
204 Node<?> errorInfoNode = parseErrorInfo( error.getErrorInfo() );
205 if( errorInfoNode != null ) {
206 builder.add( errorInfoNode );
209 return builder.toInstance();
212 private Node<?> parseErrorInfo( String errorInfo ) {
213 if( Strings.isNullOrEmpty( errorInfo ) ) {
217 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
218 factory.setNamespaceAware( true );
219 factory.setCoalescing( true );
220 factory.setIgnoringElementContentWhitespace( true );
221 factory.setIgnoringComments( true );
223 // Wrap the error info content in a root <error-info> element so it can be parsed
224 // as XML. The error info content may or may not be XML. If not then it will be
225 // parsed as text content of the <error-info> element.
227 String errorInfoWithRoot =
228 new StringBuilder( "<error-info xmlns=\"" ).append( NAMESPACE ).append( "\">" )
229 .append( errorInfo ).append( "</error-info>" ).toString();
233 doc = factory.newDocumentBuilder().parse(
234 new InputSource( new StringReader( errorInfoWithRoot ) ) );
236 catch( Exception e ) {
237 // TODO: what if the content is text that happens to contain invalid markup? Could
238 // wrap in CDATA and try again.
240 LOG.warn( "Error parsing restconf error-info, \"" + errorInfo + "\", as XML: " +
245 Node<?> errorInfoNode = XmlDocumentUtils.toDomNode( doc );
247 if( errorInfoNode instanceof CompositeNode ) {
248 CompositeNode compositeNode = (CompositeNode)XmlDocumentUtils.toDomNode( doc );
250 // At this point the QName for the "error-info" CompositeNode doesn't contain the revision
251 // as it isn't present in the XML. So we'll copy all the child nodes and create a new
252 // CompositeNode with the full QName. This is done so the XML/JSON mapping code can
253 // locate the schema.
255 ImmutableList.Builder<Node<?>> childNodes = ImmutableList.builder();
256 for( Entry<QName, List<Node<?>>> entry: compositeNode.entrySet() ) {
257 childNodes.addAll( entry.getValue() );
260 errorInfoNode = ImmutableCompositeNode.create( ERROR_INFO_QNAME, childNodes.build() );
263 return errorInfoNode;
266 private void addLeaf( CompositeNodeBuilder<ImmutableCompositeNode> builder, QName qname,
268 if( !Strings.isNullOrEmpty( value ) ) {
269 builder.addLeaf( qname, value );