Bug 1003: Restconf - remove whitespace on input
[controller.git] / opendaylight / md-sal / sal-rest-connector / src / main / java / org / opendaylight / controller / sal / rest / impl / RestconfDocumentedExceptionMapper.java
1 /*
2  * Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.sal.rest.impl;
10
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;
18
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;
35
36 import static org.opendaylight.controller.sal.rest.api.Draft02.RestConfModule.*;
37
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;
52
53 import com.google.common.base.Strings;
54 import com.google.common.collect.ImmutableList;
55 import com.google.gson.stream.JsonWriter;
56
57 /**
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.
61  *
62  * @author Thomas Pantelis
63  */
64 @Provider
65 public class RestconfDocumentedExceptionMapper implements ExceptionMapper<RestconfDocumentedException> {
66
67     private final static Logger LOG = LoggerFactory.getLogger( RestconfDocumentedExceptionMapper.class );
68
69     @Context
70     private HttpHeaders headers;
71
72     @Override
73     public Response toResponse( RestconfDocumentedException exception ) {
74
75         LOG.debug( "In toResponse: {}", exception.getMessage() );
76
77         // Default to the content type if there's no Accept header
78
79         MediaType mediaType = headers.getMediaType();
80
81         List<MediaType> accepts = headers.getAcceptableMediaTypes();
82
83         LOG.debug( "Accept headers: {}", accepts );
84
85         if( accepts != null && accepts.size() > 0 ) {
86             mediaType = accepts.get( 0 ); // just pick the first one
87         }
88
89         LOG.debug( "Using MediaType: {}",  mediaType );
90
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.
96
97             return Response.status( exception.getStatus() )
98                                     .type( MediaType.TEXT_PLAIN_TYPE )
99                                     .entity( " " ).build();
100         }
101
102         int status = errors.iterator().next().getErrorTag().getStatusCode();
103
104         ControllerContext context = ControllerContext.getInstance();
105         DataNodeContainer errorsSchemaNode = (DataNodeContainer)context.getRestconfModuleErrorsSchemaNode();
106
107         if( errorsSchemaNode == null ) {
108             return Response.status( status )
109                            .type( MediaType.TEXT_PLAIN_TYPE )
110                            .entity( exception.getMessage() ).build();
111         }
112
113         ImmutableList.Builder<Node<?>> errorNodes = ImmutableList.<Node<?>> builder();
114         for( RestconfError error: errors ) {
115             errorNodes.add( toDomNode( error ) );
116         }
117
118         ImmutableCompositeNode errorsNode =
119                          ImmutableCompositeNode.create( ERRORS_CONTAINER_QNAME, errorNodes.build() );
120
121         Object responseBody;
122         if( mediaType.getSubtype().endsWith( "json" ) ) {
123             responseBody = toJsonResponseBody( errorsNode, errorsSchemaNode );
124         }
125         else {
126             responseBody = toXMLResponseBody( errorsNode, errorsSchemaNode );
127         }
128
129         return Response.status( status ).type( mediaType ).entity( responseBody ).build();
130     }
131
132     private Object toJsonResponseBody( ImmutableCompositeNode errorsNode,
133                                        DataNodeContainer errorsSchemaNode ) {
134
135         JsonMapper jsonMapper = new JsonMapper();
136
137         Object responseBody = null;
138         try {
139             ByteArrayOutputStream outStream = new ByteArrayOutputStream();
140             JsonWriter writer = new JsonWriter( new OutputStreamWriter( outStream, "UTF-8" ) );
141             writer.setIndent( "    " );
142
143             jsonMapper.write( writer, errorsNode, errorsSchemaNode, null );
144             writer.flush();
145
146             responseBody = outStream.toString( "UTF-8" );
147         }
148         catch( IOException e ) {
149             LOG.error( "Error writing error response body", e );
150         }
151
152         return responseBody;
153     }
154
155     private Object toXMLResponseBody( ImmutableCompositeNode errorsNode,
156                                       DataNodeContainer errorsSchemaNode ) {
157
158         XmlMapper xmlMapper = new XmlMapper();
159
160         Object responseBody = null;
161         try {
162             Document xmlDoc = xmlMapper.write( errorsNode, errorsSchemaNode );
163
164             responseBody = documentToString( xmlDoc );
165         }
166         catch( TransformerException | UnsupportedDataTypeException | UnsupportedEncodingException e ) {
167             LOG.error( "Error writing error response body", e );
168         }
169
170         return responseBody;
171     }
172
173     private String documentToString( Document doc ) throws TransformerException, UnsupportedEncodingException {
174         Transformer transformer = createTransformer();
175         ByteArrayOutputStream outStream = new ByteArrayOutputStream();
176
177         transformer.transform( new DOMSource( doc ), new StreamResult( outStream ) );
178
179         return outStream.toString( "UTF-8" );
180     }
181
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" );
191         return transformer;
192     }
193
194     private Node<?> toDomNode( RestconfError error ) {
195
196         CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
197         builder.setQName( ERROR_LIST_QNAME );
198
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() );
203
204         Node<?> errorInfoNode = parseErrorInfo( error.getErrorInfo() );
205         if( errorInfoNode != null ) {
206             builder.add( errorInfoNode );
207         }
208
209         return builder.toInstance();
210     }
211
212     private Node<?> parseErrorInfo( String errorInfo ) {
213         if( Strings.isNullOrEmpty( errorInfo ) ) {
214             return null;
215         }
216
217         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
218         factory.setNamespaceAware( true );
219         factory.setCoalescing( true );
220         factory.setIgnoringElementContentWhitespace( true );
221         factory.setIgnoringComments( true );
222
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.
226
227         String errorInfoWithRoot =
228                 new StringBuilder( "<error-info xmlns=\"" ).append( NAMESPACE ).append( "\">" )
229                         .append( errorInfo ).append( "</error-info>" ).toString();
230
231         Document doc = null;
232         try {
233             doc = factory.newDocumentBuilder().parse(
234                                  new InputSource( new StringReader( errorInfoWithRoot ) ) );
235         }
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.
239
240             LOG.warn( "Error parsing restconf error-info, \"" + errorInfo + "\", as XML: " +
241                       e.toString() );
242             return null;
243         }
244
245         Node<?> errorInfoNode = XmlDocumentUtils.toDomNode( doc );
246
247         if( errorInfoNode instanceof CompositeNode ) {
248             CompositeNode compositeNode = (CompositeNode)XmlDocumentUtils.toDomNode( doc );
249
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.
254
255             ImmutableList.Builder<Node<?>> childNodes = ImmutableList.builder();
256             for( Entry<QName, List<Node<?>>> entry: compositeNode.entrySet() ) {
257                 childNodes.addAll( entry.getValue() );
258             }
259
260             errorInfoNode = ImmutableCompositeNode.create( ERROR_INFO_QNAME, childNodes.build() );
261         }
262
263         return errorInfoNode;
264     }
265
266     private void addLeaf( CompositeNodeBuilder<ImmutableCompositeNode> builder, QName qname,
267                           String value ) {
268         if( !Strings.isNullOrEmpty( value ) ) {
269             builder.addLeaf( qname, value );
270         }
271     }
272 }