Split Restconf implementations (draft02 and RFC) - base api
[netconf.git] / restconf / restconf-nb-bierman02 / src / test / java / org / opendaylight / controller / sal / restconf / impl / test / RestconfDocumentedExceptionMapperTest.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.restconf.impl.test;
10
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertFalse;
13 import static org.junit.Assert.assertNotNull;
14 import static org.junit.Assert.assertNull;
15 import static org.junit.Assert.assertTrue;
16 import static org.junit.Assert.fail;
17 import static org.mockito.Matchers.any;
18 import static org.mockito.Mockito.mock;
19 import static org.mockito.Mockito.reset;
20 import static org.mockito.Mockito.when;
21
22 import com.google.common.collect.Maps;
23 import com.google.common.io.ByteStreams;
24 import com.google.gson.JsonArray;
25 import com.google.gson.JsonElement;
26 import com.google.gson.JsonParser;
27 import java.io.ByteArrayInputStream;
28 import java.io.ByteArrayOutputStream;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.InputStreamReader;
32 import java.util.Arrays;
33 import java.util.Iterator;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Map.Entry;
37 import java.util.Set;
38 import java.util.regex.Matcher;
39 import java.util.regex.Pattern;
40 import javax.ws.rs.core.Application;
41 import javax.ws.rs.core.MediaType;
42 import javax.ws.rs.core.Response;
43 import javax.ws.rs.core.Response.Status;
44 import javax.ws.rs.core.UriInfo;
45 import javax.xml.namespace.NamespaceContext;
46 import javax.xml.xpath.XPath;
47 import javax.xml.xpath.XPathConstants;
48 import javax.xml.xpath.XPathExpression;
49 import javax.xml.xpath.XPathFactory;
50 import org.glassfish.jersey.server.ResourceConfig;
51 import org.glassfish.jersey.test.JerseyTest;
52 import org.junit.Before;
53 import org.junit.BeforeClass;
54 import org.junit.Ignore;
55 import org.junit.Test;
56 import org.opendaylight.netconf.sal.rest.api.Draft02;
57 import org.opendaylight.netconf.sal.rest.api.RestconfService;
58 import org.opendaylight.netconf.sal.rest.impl.JsonNormalizedNodeBodyReader;
59 import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeJsonBodyWriter;
60 import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeXmlBodyWriter;
61 import org.opendaylight.netconf.sal.rest.impl.RestconfDocumentedExceptionMapper;
62 import org.opendaylight.netconf.sal.rest.impl.XmlNormalizedNodeBodyReader;
63 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
64 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
65 import org.opendaylight.netconf.sal.restconf.impl.RestconfError;
66 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
67 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
68 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
69 import org.opendaylight.yangtools.util.xml.UntrustedXML;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72 import org.w3c.dom.Document;
73 import org.w3c.dom.Node;
74 import org.w3c.dom.NodeList;
75 import org.xml.sax.SAXException;
76
77 /**
78  * Unit tests for RestconfDocumentedExceptionMapper.
79  *
80  * @author Thomas Pantelis
81  */
82 public class RestconfDocumentedExceptionMapperTest extends JerseyTest {
83
84     interface ErrorInfoVerifier {
85         void verifyXML(Node errorInfoNode);
86
87         void verifyJson(JsonElement errorInfoElement);
88     }
89
90     static class SimpleErrorInfoVerifier implements ErrorInfoVerifier {
91
92         String expTextContent;
93
94         SimpleErrorInfoVerifier(final String expErrorInfo) {
95             expTextContent = expErrorInfo;
96         }
97
98         void verifyContent(final String actualContent) {
99             assertNotNull("Actual \"error-info\" text content is null", actualContent);
100             assertTrue("", actualContent.contains(expTextContent));
101         }
102
103         @Override
104         public void verifyXML(final Node errorInfoNode) {
105             verifyContent(errorInfoNode.getTextContent());
106         }
107
108         @Override
109         public void verifyJson(final JsonElement errorInfoElement) {
110             verifyContent(errorInfoElement.getAsString());
111         }
112     }
113
114     private static final Logger LOG = LoggerFactory.getLogger(RestconfDocumentedExceptionMapperTest.class);
115     static RestconfService mockRestConf = mock(RestconfService.class);
116
117     static XPath XPATH = XPathFactory.newInstance().newXPath();
118     static XPathExpression ERROR_LIST;
119     static XPathExpression ERROR_TYPE;
120     static XPathExpression ERROR_TAG;
121     static XPathExpression ERROR_MESSAGE;
122     static XPathExpression ERROR_APP_TAG;
123     static XPathExpression ERROR_INFO;
124
125     @BeforeClass
126     public static void init() throws Exception {
127         ControllerContext.getInstance().setGlobalSchema(TestUtils.loadSchemaContext("/modules"));
128
129         final NamespaceContext nsContext = new NamespaceContext() {
130             @Override
131             public Iterator<?> getPrefixes(final String namespaceURI) {
132                 return null;
133             }
134
135             @Override
136             public String getPrefix(final String namespaceURI) {
137                 return null;
138             }
139
140             @Override
141             public String getNamespaceURI(final String prefix) {
142                 return "ietf-restconf".equals(prefix) ? Draft02.RestConfModule.NAMESPACE : null;
143             }
144         };
145
146         XPATH.setNamespaceContext(nsContext);
147         ERROR_LIST = XPATH.compile("ietf-restconf:errors/ietf-restconf:error");
148         ERROR_TYPE = XPATH.compile("ietf-restconf:error-type");
149         ERROR_TAG = XPATH.compile("ietf-restconf:error-tag");
150         ERROR_MESSAGE = XPATH.compile("ietf-restconf:error-message");
151         ERROR_APP_TAG = XPATH.compile("ietf-restconf:error-app-tag");
152         ERROR_INFO = XPATH.compile("ietf-restconf:error-info");
153     }
154
155     @Override
156     @Before
157     public void setUp() throws Exception {
158         reset(mockRestConf);
159         super.setUp();
160     }
161
162     @Override
163     protected Application configure() {
164         ResourceConfig resourceConfig = new ResourceConfig();
165         resourceConfig = resourceConfig.registerInstances(mockRestConf, new XmlNormalizedNodeBodyReader(),
166             new JsonNormalizedNodeBodyReader(), new NormalizedNodeJsonBodyWriter(), new NormalizedNodeXmlBodyWriter());
167         resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
168         return resourceConfig;
169     }
170
171     void stageMockEx(final RestconfDocumentedException ex) {
172         reset(mockRestConf);
173         when(mockRestConf.readOperationalData(any(String.class), any(UriInfo.class))).thenThrow(ex);
174     }
175
176     void testJsonResponse(final RestconfDocumentedException ex, final Status expStatus, final ErrorType expErrorType,
177             final ErrorTag expErrorTag, final String expErrorMessage, final String expErrorAppTag,
178             final ErrorInfoVerifier errorInfoVerifier) throws Exception {
179
180         stageMockEx(ex);
181
182         final Response resp = target("/operational/foo").request(MediaType.APPLICATION_JSON).get();
183
184         final InputStream stream = verifyResponse(resp, MediaType.APPLICATION_JSON, expStatus);
185
186         verifyJsonResponseBody(stream, expErrorType, expErrorTag, expErrorMessage, expErrorAppTag, errorInfoVerifier);
187     }
188
189     @Test
190     public void testToJsonResponseWithMessageOnly() throws Exception {
191
192         testJsonResponse(new RestconfDocumentedException("mock error"), Status.INTERNAL_SERVER_ERROR,
193                 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null, null);
194
195
196         // To test verification code
197         // String json =
198         // "{ errors: {" +
199         // "    error: [{" +
200         // "      error-tag : \"operation-failed\"" +
201         // "      ,error-type : \"application\"" +
202         // "      ,error-message : \"An error occurred\"" +
203         // "      ,error-info : {" +
204         // "        session-id: \"123\"" +
205         // "        ,address: \"1.2.3.4\"" +
206         // "      }" +
207         // "    }]" +
208         // "  }" +
209         // "}";
210         //
211         // verifyJsonResponseBody( new java.io.StringBufferInputStream(json ),
212         // ErrorType.APPLICATION,
213         // ErrorTag.OPERATION_FAILED, "An error occurred", null,
214         // com.google.common.collect.ImmutableMap.of( "session-id", "123",
215         // "address", "1.2.3.4" ) );
216     }
217
218     @Test
219     public void testToJsonResponseWithInUseErrorTag() throws Exception {
220
221         testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.IN_USE),
222                 Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.IN_USE, "mock error", null, null);
223     }
224
225     @Test
226     public void testToJsonResponseWithInvalidValueErrorTag() throws Exception {
227
228         testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.RPC, ErrorTag.INVALID_VALUE),
229                 Status.BAD_REQUEST, ErrorType.RPC, ErrorTag.INVALID_VALUE, "mock error", null, null);
230
231     }
232
233     @Test
234     public void testToJsonResponseWithTooBigErrorTag() throws Exception {
235
236         testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.TRANSPORT, ErrorTag.TOO_BIG),
237                 Status.REQUEST_ENTITY_TOO_LARGE, ErrorType.TRANSPORT, ErrorTag.TOO_BIG, "mock error", null, null);
238
239     }
240
241     @Test
242     public void testToJsonResponseWithMissingAttributeErrorTag() throws Exception {
243
244         testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE),
245                 Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE, "mock error", null, null);
246     }
247
248     @Test
249     public void testToJsonResponseWithBadAttributeErrorTag() throws Exception {
250
251         testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE),
252                 Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE, "mock error", null, null);
253     }
254
255     @Test
256     public void testToJsonResponseWithUnknownAttributeErrorTag() throws Exception {
257
258         testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ATTRIBUTE),
259                 Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ATTRIBUTE, "mock error", null, null);
260     }
261
262     @Test
263     public void testToJsonResponseWithBadElementErrorTag() throws Exception {
264
265         testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT),
266                 Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT, "mock error", null, null);
267     }
268
269     @Test
270     public void testToJsonResponseWithUnknownElementErrorTag() throws Exception {
271
272         testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT),
273                 Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT, "mock error", null, null);
274     }
275
276     @Test
277     public void testToJsonResponseWithUnknownNamespaceErrorTag() throws Exception {
278
279         testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE),
280                 Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE, "mock error", null, null);
281     }
282
283     @Test
284     public void testToJsonResponseWithMalformedMessageErrorTag() throws Exception {
285
286         testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE),
287                 Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, "mock error", null, null);
288     }
289
290     @Test
291     public void testToJsonResponseWithAccessDeniedErrorTag() throws Exception {
292
293         testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.ACCESS_DENIED),
294                 Status.FORBIDDEN, ErrorType.PROTOCOL, ErrorTag.ACCESS_DENIED, "mock error", null, null);
295     }
296
297     @Test
298     public void testToJsonResponseWithLockDeniedErrorTag() throws Exception {
299
300         testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.LOCK_DENIED),
301                 Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.LOCK_DENIED, "mock error", null, null);
302     }
303
304     @Test
305     public void testToJsonResponseWithResourceDeniedErrorTag() throws Exception {
306
307         testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.RESOURCE_DENIED),
308                 Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.RESOURCE_DENIED, "mock error", null, null);
309     }
310
311     @Test
312     public void testToJsonResponseWithRollbackFailedErrorTag() throws Exception {
313
314         testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.ROLLBACK_FAILED),
315                 Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, ErrorTag.ROLLBACK_FAILED, "mock error", null, null);
316     }
317
318     @Test
319     public void testToJsonResponseWithDataExistsErrorTag() throws Exception {
320
321         testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS),
322                 Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS, "mock error", null, null);
323     }
324
325     @Test
326     public void testToJsonResponseWithDataMissingErrorTag() throws Exception {
327
328         testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING),
329                 Status.NOT_FOUND, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING, "mock error", null, null);
330     }
331
332     @Test
333     public void testToJsonResponseWithOperationNotSupportedErrorTag() throws Exception {
334
335         testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL,
336                 ErrorTag.OPERATION_NOT_SUPPORTED), Status.NOT_IMPLEMENTED, ErrorType.PROTOCOL,
337                 ErrorTag.OPERATION_NOT_SUPPORTED, "mock error", null, null);
338     }
339
340     @Test
341     public void testToJsonResponseWithOperationFailedErrorTag() throws Exception {
342
343         testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.OPERATION_FAILED),
344                 Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, ErrorTag.OPERATION_FAILED, "mock error", null, null);
345     }
346
347     @Test
348     public void testToJsonResponseWithPartialOperationErrorTag() throws Exception {
349
350         testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.PARTIAL_OPERATION),
351                 Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, ErrorTag.PARTIAL_OPERATION, "mock error", null, null);
352     }
353
354     @Test
355     public void testToJsonResponseWithErrorAppTag() throws Exception {
356
357         testJsonResponse(new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION,
358                 ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag")), Status.BAD_REQUEST, ErrorType.APPLICATION,
359                 ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", null);
360     }
361
362     @Test
363     @Ignore // FIXME : find why it return "error-type" RPC no expected APPLICATION
364     public void testToJsonResponseWithMultipleErrors() throws Exception {
365
366         final List<RestconfError> errorList = Arrays.asList(
367                 new RestconfError(ErrorType.APPLICATION, ErrorTag.LOCK_DENIED, "mock error1"),
368                 new RestconfError(ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, "mock error2"));
369         stageMockEx(new RestconfDocumentedException("mock", null, errorList));
370
371         final Response resp = target("/operational/foo").request(MediaType.APPLICATION_JSON).get();
372
373         final InputStream stream = verifyResponse(resp, MediaType.APPLICATION_JSON, Status.CONFLICT);
374
375         final JsonArray arrayElement = parseJsonErrorArrayElement(stream);
376
377         assertEquals("\"error\" Json array element length", 2, arrayElement.size());
378
379         verifyJsonErrorNode(
380                 arrayElement.get(0), ErrorType.APPLICATION, ErrorTag.LOCK_DENIED, "mock error1", null, null);
381
382         verifyJsonErrorNode(arrayElement.get(1), ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, "mock error2", null, null);
383     }
384
385     @Test
386     public void testToJsonResponseWithErrorInfo() throws Exception {
387
388         final String errorInfo = "<address>1.2.3.4</address> <session-id>123</session-id>";
389         testJsonResponse(new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION,
390                 ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", errorInfo)), Status.BAD_REQUEST,
391                 ErrorType.APPLICATION, ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag",
392                 new SimpleErrorInfoVerifier(errorInfo));
393     }
394
395     @Test
396     public void testToJsonResponseWithExceptionCause() throws Exception {
397
398         final Exception cause = new Exception("mock exception cause");
399         testJsonResponse(new RestconfDocumentedException("mock error", cause), Status.INTERNAL_SERVER_ERROR,
400                 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null,
401                 new SimpleErrorInfoVerifier(cause.getMessage()));
402     }
403
404     void testXMLResponse(final RestconfDocumentedException ex, final Status expStatus, final ErrorType expErrorType,
405             final ErrorTag expErrorTag, final String expErrorMessage, final String expErrorAppTag,
406             final ErrorInfoVerifier errorInfoVerifier) throws Exception {
407         stageMockEx(ex);
408
409         final Response resp = target("/operational/foo").request(MediaType.APPLICATION_XML).get();
410
411         final InputStream stream = verifyResponse(resp, MediaType.APPLICATION_XML, expStatus);
412
413         verifyXMLResponseBody(stream, expErrorType, expErrorTag, expErrorMessage, expErrorAppTag, errorInfoVerifier);
414     }
415
416     @Test
417     public void testToXMLResponseWithMessageOnly() throws Exception {
418
419         testXMLResponse(new RestconfDocumentedException("mock error"), Status.INTERNAL_SERVER_ERROR,
420                 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null, null);
421
422      // To test verification code
423         // String xml =
424         // "<errors xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\">"+
425         // "  <error>" +
426         // "    <error-type>application</error-type>"+
427         // "    <error-tag>operation-failed</error-tag>"+
428         // "    <error-message>An error occurred</error-message>"+
429         // "    <error-info>" +
430         // "      <session-id>123</session-id>" +
431         // "      <address>1.2.3.4</address>" +
432         // "    </error-info>" +
433         // "  </error>" +
434         // "</errors>";
435         //
436         // verifyXMLResponseBody( new java.io.StringBufferInputStream(xml),
437         // ErrorType.APPLICATION,
438         // ErrorTag.OPERATION_FAILED, "An error occurred", null,
439         // com.google.common.collect.ImmutableMap.of( "session-id", "123",
440         // "address", "1.2.3.4" ) );
441     }
442
443     @Test
444     public void testToXMLResponseWithInUseErrorTag() throws Exception {
445
446         testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.IN_USE),
447                 Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.IN_USE, "mock error", null, null);
448     }
449
450     @Test
451     public void testToXMLResponseWithInvalidValueErrorTag() throws Exception {
452
453         testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.RPC, ErrorTag.INVALID_VALUE),
454                 Status.BAD_REQUEST, ErrorType.RPC, ErrorTag.INVALID_VALUE, "mock error", null, null);
455     }
456
457     @Test
458     public void testToXMLResponseWithTooBigErrorTag() throws Exception {
459
460         testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.TRANSPORT, ErrorTag.TOO_BIG),
461                 Status.REQUEST_ENTITY_TOO_LARGE, ErrorType.TRANSPORT, ErrorTag.TOO_BIG, "mock error", null, null);
462     }
463
464     @Test
465     public void testToXMLResponseWithMissingAttributeErrorTag() throws Exception {
466
467         testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE),
468                 Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE, "mock error", null, null);
469     }
470
471     @Test
472     public void testToXMLResponseWithBadAttributeErrorTag() throws Exception {
473
474         testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE),
475                 Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE, "mock error", null, null);
476     }
477
478     @Test
479     public void testToXMLResponseWithUnknownAttributeErrorTag() throws Exception {
480
481         testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ATTRIBUTE),
482                 Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ATTRIBUTE, "mock error", null, null);
483     }
484
485     @Test
486     public void testToXMLResponseWithBadElementErrorTag() throws Exception {
487
488         testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT),
489                 Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT, "mock error", null, null);
490     }
491
492     @Test
493     public void testToXMLResponseWithUnknownElementErrorTag() throws Exception {
494
495         testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT),
496                 Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT, "mock error", null, null);
497     }
498
499     @Test
500     public void testToXMLResponseWithUnknownNamespaceErrorTag() throws Exception {
501
502         testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE),
503                 Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE, "mock error", null, null);
504     }
505
506     @Test
507     public void testToXMLResponseWithMalformedMessageErrorTag() throws Exception {
508
509         testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE),
510                 Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, "mock error", null, null);
511     }
512
513     @Test
514     public void testToXMLResponseWithAccessDeniedErrorTag() throws Exception {
515
516         testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.ACCESS_DENIED),
517                 Status.FORBIDDEN, ErrorType.PROTOCOL, ErrorTag.ACCESS_DENIED, "mock error", null, null);
518     }
519
520     @Test
521     public void testToXMLResponseWithLockDeniedErrorTag() throws Exception {
522
523         testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.LOCK_DENIED),
524                 Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.LOCK_DENIED, "mock error", null, null);
525     }
526
527     @Test
528     public void testToXMLResponseWithResourceDeniedErrorTag() throws Exception {
529
530         testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.RESOURCE_DENIED),
531                 Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.RESOURCE_DENIED, "mock error", null, null);
532     }
533
534     @Test
535     public void testToXMLResponseWithRollbackFailedErrorTag() throws Exception {
536
537         testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.ROLLBACK_FAILED),
538                 Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, ErrorTag.ROLLBACK_FAILED, "mock error", null, null);
539     }
540
541     @Test
542     public void testToXMLResponseWithDataExistsErrorTag() throws Exception {
543
544         testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS),
545                 Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS, "mock error", null, null);
546     }
547
548     @Test
549     public void testToXMLResponseWithDataMissingErrorTag() throws Exception {
550
551         testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING),
552                 Status.NOT_FOUND, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING, "mock error", null, null);
553     }
554
555     @Test
556     public void testToXMLResponseWithOperationNotSupportedErrorTag() throws Exception {
557
558         testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL,
559                 ErrorTag.OPERATION_NOT_SUPPORTED), Status.NOT_IMPLEMENTED, ErrorType.PROTOCOL,
560                 ErrorTag.OPERATION_NOT_SUPPORTED, "mock error", null, null);
561     }
562
563     @Test
564     public void testToXMLResponseWithOperationFailedErrorTag() throws Exception {
565
566         testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.OPERATION_FAILED),
567                 Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, ErrorTag.OPERATION_FAILED, "mock error", null, null);
568     }
569
570     @Test
571     public void testToXMLResponseWithPartialOperationErrorTag() throws Exception {
572
573         testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.PARTIAL_OPERATION),
574                 Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, ErrorTag.PARTIAL_OPERATION, "mock error", null, null);
575     }
576
577     @Test
578     public void testToXMLResponseWithErrorAppTag() throws Exception {
579
580         testXMLResponse(new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION,
581                 ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag")), Status.BAD_REQUEST, ErrorType.APPLICATION,
582                 ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", null);
583     }
584
585     @Test
586     public void testToXMLResponseWithErrorInfo() throws Exception {
587
588         final String errorInfo = "<address>1.2.3.4</address> <session-id>123</session-id>";
589         testXMLResponse(new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION,
590                 ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", errorInfo)), Status.BAD_REQUEST,
591                 ErrorType.APPLICATION, ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag",
592                 new SimpleErrorInfoVerifier(errorInfo));
593     }
594
595     @Test
596     public void testToXMLResponseWithExceptionCause() throws Exception {
597
598         final Exception cause = new Exception("mock exception cause");
599         testXMLResponse(new RestconfDocumentedException("mock error", cause), Status.INTERNAL_SERVER_ERROR,
600                 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null,
601                 new SimpleErrorInfoVerifier(cause.getMessage()));
602     }
603
604     @Test
605     @Ignore // FIXME : find why it return error-type as RPC no APPLICATION
606     public void testToXMLResponseWithMultipleErrors() throws Exception {
607
608         final List<RestconfError> errorList = Arrays.asList(
609                 new RestconfError(ErrorType.APPLICATION, ErrorTag.LOCK_DENIED, "mock error1"),
610                 new RestconfError(ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, "mock error2"));
611         stageMockEx(new RestconfDocumentedException("mock", null, errorList));
612
613         final Response resp = target("/operational/foo").request(MediaType.APPLICATION_XML).get();
614
615         final InputStream stream = verifyResponse(resp, MediaType.APPLICATION_XML, Status.CONFLICT);
616
617         final Document doc = parseXMLDocument(stream);
618
619         final NodeList children = getXMLErrorList(doc, 2);
620
621         verifyXMLErrorNode(children.item(0), ErrorType.APPLICATION, ErrorTag.LOCK_DENIED, "mock error1", null, null);
622
623         verifyXMLErrorNode(children.item(1), ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, "mock error2", null, null);
624     }
625
626     @Test
627     public void testToResponseWithAcceptHeader() throws Exception {
628
629         stageMockEx(new RestconfDocumentedException("mock error"));
630
631         final Response resp = target("/operational/foo").request().header("Accept", MediaType.APPLICATION_JSON).get();
632
633         final InputStream stream = verifyResponse(resp, MediaType.APPLICATION_JSON, Status.INTERNAL_SERVER_ERROR);
634
635         verifyJsonResponseBody(stream, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null, null);
636     }
637
638     @Test
639     @Ignore
640     public void testToResponseWithStatusOnly() throws Exception {
641
642         // The StructuredDataToJsonProvider should throw a
643         // RestconfDocumentedException with no data
644
645         when(mockRestConf.readOperationalData(any(String.class), any(UriInfo.class))).thenReturn(
646                 new NormalizedNodeContext(null, null));
647
648         final Response resp = target("/operational/foo").request(MediaType.APPLICATION_JSON).get();
649
650         verifyResponse(resp, MediaType.TEXT_PLAIN, Status.NOT_FOUND);
651     }
652
653     InputStream verifyResponse(final Response resp, final String expMediaType, final Status expStatus) {
654         assertEquals("getMediaType", MediaType.valueOf(expMediaType), resp.getMediaType());
655         assertEquals("getStatus", expStatus.getStatusCode(), resp.getStatus());
656
657         final Object entity = resp.getEntity();
658         assertEquals("Response entity", true, entity instanceof InputStream);
659         final InputStream stream = (InputStream) entity;
660         return stream;
661     }
662
663     void verifyJsonResponseBody(final InputStream stream, final ErrorType expErrorType, final ErrorTag expErrorTag,
664             final String expErrorMessage, final String expErrorAppTag, final ErrorInfoVerifier errorInfoVerifier)
665             throws Exception {
666
667         final JsonArray arrayElement = parseJsonErrorArrayElement(stream);
668
669         assertEquals("\"error\" Json array element length", 1, arrayElement.size());
670
671         verifyJsonErrorNode(arrayElement.get(0), expErrorType, expErrorTag, expErrorMessage, expErrorAppTag,
672                 errorInfoVerifier);
673     }
674
675     @SuppressWarnings("checkstyle:IllegalCatch")
676     private static JsonArray parseJsonErrorArrayElement(final InputStream stream) throws IOException {
677         final ByteArrayOutputStream bos = new ByteArrayOutputStream();
678         ByteStreams.copy(stream, bos);
679
680         LOG.info("JSON: " + bos.toString());
681
682         final JsonParser parser = new JsonParser();
683         JsonElement rootElement;
684
685         try {
686             rootElement = parser.parse(new InputStreamReader(new ByteArrayInputStream(bos.toByteArray())));
687         } catch (final Exception e) {
688             throw new IllegalArgumentException("Invalid JSON response:\n" + bos.toString(), e);
689         }
690
691         assertTrue("Root element of Json is not an Object", rootElement.isJsonObject());
692
693         final Set<Entry<String, JsonElement>> errorsEntrySet = rootElement.getAsJsonObject().entrySet();
694         assertEquals("Json Object element set count", 1, errorsEntrySet.size());
695
696         final Entry<String, JsonElement> errorsEntry = errorsEntrySet.iterator().next();
697         final JsonElement errorsElement = errorsEntry.getValue();
698         assertEquals("First Json element name", "errors", errorsEntry.getKey());
699         assertTrue("\"errors\" Json element is not an Object", errorsElement.isJsonObject());
700
701         final Set<Entry<String, JsonElement>> errorListEntrySet = errorsElement.getAsJsonObject().entrySet();
702         assertEquals("Root \"errors\" element child count", 1, errorListEntrySet.size());
703
704         final JsonElement errorListElement = errorListEntrySet.iterator().next().getValue();
705         assertEquals("\"errors\" child Json element name", "error", errorListEntrySet.iterator().next().getKey());
706         assertTrue("\"error\" Json element is not an Array", errorListElement.isJsonArray());
707
708         // As a final check, make sure there aren't multiple "error" array
709         // elements. Unfortunately,
710         // the call above to getAsJsonObject().entrySet() will out duplicate
711         // "error" elements. So
712         // we'll use regex on the json string to verify this.
713
714         final Matcher matcher = Pattern.compile("\"error\"[ ]*:[ ]*\\[", Pattern.DOTALL).matcher(bos.toString());
715         assertTrue("Expected 1 \"error\" element", matcher.find());
716         assertFalse("Found multiple \"error\" elements", matcher.find());
717
718         return errorListElement.getAsJsonArray();
719     }
720
721     void verifyJsonErrorNode(final JsonElement errorEntryElement, final ErrorType expErrorType,
722             final ErrorTag expErrorTag, final String expErrorMessage, final String expErrorAppTag,
723             final ErrorInfoVerifier errorInfoVerifier) {
724
725         JsonElement errorInfoElement = null;
726         final Map<String, String> leafMap = Maps.newHashMap();
727         for (final Entry<String, JsonElement> entry : errorEntryElement.getAsJsonObject().entrySet()) {
728             final String leafName = entry.getKey();
729             final JsonElement leafElement = entry.getValue();
730
731             if ("error-info".equals(leafName)) {
732                 assertNotNull("Found unexpected \"error-info\" element", errorInfoVerifier);
733                 errorInfoElement = leafElement;
734             } else {
735                 assertTrue("\"error\" leaf Json element " + leafName + " is not a Primitive",
736                         leafElement.isJsonPrimitive());
737
738                 leafMap.put(leafName, leafElement.getAsString());
739             }
740         }
741
742         assertEquals("error-type", expErrorType.getErrorTypeTag(), leafMap.remove("error-type"));
743         assertEquals("error-tag", expErrorTag.getTagValue(), leafMap.remove("error-tag"));
744
745         verifyOptionalJsonLeaf(leafMap.remove("error-message"), expErrorMessage, "error-message");
746         verifyOptionalJsonLeaf(leafMap.remove("error-app-tag"), expErrorAppTag, "error-app-tag");
747
748         if (!leafMap.isEmpty()) {
749             fail("Found unexpected Json leaf elements for \"error\" element: " + leafMap);
750         }
751
752         if (errorInfoVerifier != null) {
753             assertNotNull("Missing \"error-info\" element", errorInfoElement);
754             errorInfoVerifier.verifyJson(errorInfoElement);
755         }
756     }
757
758     void verifyOptionalJsonLeaf(final String actualValue, final String expValue, final String tagName) {
759         if (expValue != null) {
760             assertEquals(tagName, expValue, actualValue);
761         } else {
762             assertNull("Found unexpected \"error\" leaf entry for: " + tagName, actualValue);
763         }
764     }
765
766     void verifyXMLResponseBody(final InputStream stream, final ErrorType expErrorType, final ErrorTag expErrorTag,
767             final String expErrorMessage, final String expErrorAppTag, final ErrorInfoVerifier errorInfoVerifier)
768             throws Exception {
769
770         final Document doc = parseXMLDocument(stream);
771
772         final NodeList children = getXMLErrorList(doc, 1);
773
774         verifyXMLErrorNode(children.item(0), expErrorType, expErrorTag, expErrorMessage, expErrorAppTag,
775                 errorInfoVerifier);
776     }
777
778     private static Document parseXMLDocument(final InputStream stream) throws IOException, SAXException {
779         final ByteArrayOutputStream bos = new ByteArrayOutputStream();
780         ByteStreams.copy(stream, bos);
781
782         LOG.debug("XML: " + bos.toString());
783
784         return UntrustedXML.newDocumentBuilder().parse(new ByteArrayInputStream(bos.toByteArray()));
785     }
786
787     void verifyXMLErrorNode(final Node errorNode, final ErrorType expErrorType, final ErrorTag expErrorTag,
788             final String expErrorMessage, final String expErrorAppTag, final ErrorInfoVerifier errorInfoVerifier)
789             throws Exception {
790
791         final String errorType = (String) ERROR_TYPE.evaluate(errorNode, XPathConstants.STRING);
792         assertEquals("error-type", expErrorType.getErrorTypeTag(), errorType);
793
794         final String errorTag = (String) ERROR_TAG.evaluate(errorNode, XPathConstants.STRING);
795         assertEquals("error-tag", expErrorTag.getTagValue(), errorTag);
796
797         verifyOptionalXMLLeaf(errorNode, ERROR_MESSAGE, expErrorMessage, "error-message");
798         verifyOptionalXMLLeaf(errorNode, ERROR_APP_TAG, expErrorAppTag, "error-app-tag");
799
800         final Node errorInfoNode = (Node) ERROR_INFO.evaluate(errorNode, XPathConstants.NODE);
801         if (errorInfoVerifier != null) {
802             assertNotNull("Missing \"error-info\" node", errorInfoNode);
803
804             errorInfoVerifier.verifyXML(errorInfoNode);
805         } else {
806             assertNull("Found unexpected \"error-info\" node", errorInfoNode);
807         }
808     }
809
810     void verifyOptionalXMLLeaf(final Node fromNode, final XPathExpression xpath, final String expValue,
811             final String tagName) throws Exception {
812         if (expValue != null) {
813             final String actual = (String) xpath.evaluate(fromNode, XPathConstants.STRING);
814             assertEquals(tagName, expValue, actual);
815         } else {
816             assertNull("Found unexpected \"error\" leaf entry for: " + tagName,
817                     xpath.evaluate(fromNode, XPathConstants.NODE));
818         }
819     }
820
821     NodeList getXMLErrorList(final Node fromNode, final int count) throws Exception {
822         final NodeList errorList = (NodeList) ERROR_LIST.evaluate(fromNode, XPathConstants.NODESET);
823         assertNotNull("Root errors node is empty", errorList);
824         assertEquals("Root errors node child count", count, errorList.getLength());
825         return errorList;
826     }
827 }