Cleanup: Remove passing around of DataPersistenceProvider
[controller.git] / opendaylight / md-sal / sal-rest-connector / src / test / java / org / opendaylight / controller / sal / restconf / impl / test / TestUtils.java
1 /*
2  * Copyright (c) 2014 Cisco 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 package org.opendaylight.controller.sal.restconf.impl.test;
9
10 import static org.junit.Assert.assertNotNull;
11 import static org.mockito.Matchers.any;
12 import static org.mockito.Mockito.mock;
13 import static org.mockito.Mockito.when;
14 import com.google.common.base.Preconditions;
15 import com.google.common.util.concurrent.CheckedFuture;
16 import java.io.BufferedReader;
17 import java.io.ByteArrayOutputStream;
18 import java.io.File;
19 import java.io.FileNotFoundException;
20 import java.io.FileReader;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.OutputStreamWriter;
24 import java.net.URI;
25 import java.net.URISyntaxException;
26 import java.sql.Date;
27 import java.text.ParseException;
28 import java.text.SimpleDateFormat;
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Set;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
36 import javax.xml.parsers.DocumentBuilder;
37 import javax.xml.parsers.DocumentBuilderFactory;
38 import javax.xml.parsers.ParserConfigurationException;
39 import javax.xml.transform.OutputKeys;
40 import javax.xml.transform.Transformer;
41 import javax.xml.transform.TransformerException;
42 import javax.xml.transform.TransformerFactory;
43 import javax.xml.transform.dom.DOMSource;
44 import javax.xml.transform.stream.StreamResult;
45 import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
46 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
47 import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
48 import org.opendaylight.yangtools.yang.common.QName;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
50 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
52 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
53 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
54 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
55 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.Module;
57 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
58 import org.opendaylight.yangtools.yang.model.parser.api.YangContextParser;
59 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62 import org.w3c.dom.Document;
63 import org.xml.sax.SAXException;
64
65 public final class TestUtils {
66
67     private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
68
69     private final static YangContextParser parser = new YangParserImpl();
70
71     private static Set<Module> loadModules(final String resourceDirectory) throws FileNotFoundException {
72         final File testDir = new File(resourceDirectory);
73         final String[] fileList = testDir.list();
74         final List<File> testFiles = new ArrayList<File>();
75         if (fileList == null) {
76             throw new FileNotFoundException(resourceDirectory);
77         }
78         for (int i = 0; i < fileList.length; i++) {
79             final String fileName = fileList[i];
80             if (new File(testDir, fileName).isDirectory() == false) {
81                 testFiles.add(new File(testDir, fileName));
82             }
83         }
84         return parser.parseYangModels(testFiles);
85     }
86
87     public static Set<Module> loadModulesFrom(final String yangPath) {
88         try {
89             return TestUtils.loadModules(TestUtils.class.getResource(yangPath).getPath());
90         } catch (final FileNotFoundException e) {
91             LOG.error("Yang files at path: " + yangPath + " weren't loaded.");
92         }
93
94         return null;
95     }
96
97     public static SchemaContext loadSchemaContext(final Set<Module> modules) {
98         return parser.resolveSchemaContext(modules);
99     }
100
101     public static SchemaContext loadSchemaContext(final String resourceDirectory) throws FileNotFoundException {
102         return parser.resolveSchemaContext(loadModulesFrom(resourceDirectory));
103     }
104
105     public static Module findModule(final Set<Module> modules, final String moduleName) {
106         for (final Module module : modules) {
107             if (module.getName().equals(moduleName)) {
108                 return module;
109             }
110         }
111         return null;
112     }
113
114     public static Document loadDocumentFrom(final InputStream inputStream) {
115         try {
116             final DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
117             final DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
118             return docBuilder.parse(inputStream);
119         } catch (SAXException | IOException | ParserConfigurationException e) {
120             LOG.error("Error during loading Document from XML", e);
121             return null;
122         }
123     }
124
125     public static String getDocumentInPrintableForm(final Document doc) {
126         Preconditions.checkNotNull(doc);
127         try {
128             final ByteArrayOutputStream out = new ByteArrayOutputStream();
129             final TransformerFactory tf = TransformerFactory.newInstance();
130             final Transformer transformer = tf.newTransformer();
131             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
132             transformer.setOutputProperty(OutputKeys.METHOD, "xml");
133             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
134             transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
135             transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
136
137             transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
138             final byte[] charData = out.toByteArray();
139             return new String(charData, "UTF-8");
140         } catch (IOException | TransformerException e) {
141             final String msg = "Error during transformation of Document into String";
142             LOG.error(msg, e);
143             return msg;
144         }
145
146     }
147
148     /**
149      * Searches module with name {@code searchedModuleName} in {@code modules}. If module name isn't specified and
150      * module set has only one element then this element is returned.
151      *
152      */
153     public static Module resolveModule(final String searchedModuleName, final Set<Module> modules) {
154         assertNotNull("Modules can't be null.", modules);
155         if (searchedModuleName != null) {
156             for (final Module m : modules) {
157                 if (m.getName().equals(searchedModuleName)) {
158                     return m;
159                 }
160             }
161         } else if (modules.size() == 1) {
162             return modules.iterator().next();
163         }
164         return null;
165     }
166
167     public static DataSchemaNode resolveDataSchemaNode(final String searchedDataSchemaName, final Module module) {
168         assertNotNull("Module can't be null", module);
169
170         if (searchedDataSchemaName != null) {
171             for (final DataSchemaNode dsn : module.getChildNodes()) {
172                 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
173                     return dsn;
174                 }
175             }
176         } else if (module.getChildNodes().size() == 1) {
177             return module.getChildNodes().iterator().next();
178         }
179         return null;
180     }
181
182     public static QName buildQName(final String name, final String uri, final String date, final String prefix) {
183         try {
184             final URI u = new URI(uri);
185             Date dt = null;
186             if (date != null) {
187                 dt = Date.valueOf(date);
188             }
189             return QName.create(u, dt, name);
190         } catch (final URISyntaxException e) {
191             return null;
192         }
193     }
194
195     public static QName buildQName(final String name, final String uri, final String date) {
196         return buildQName(name, uri, date, null);
197     }
198
199     public static QName buildQName(final String name) {
200         return buildQName(name, "", null);
201     }
202
203     private static void prepareMocksForRestconf(final Set<Module> modules, final RestconfImpl restconf) {
204         final ControllerContext controllerContext = ControllerContext.getInstance();
205         final BrokerFacade mockedBrokerFacade = mock(BrokerFacade.class);
206
207         controllerContext.setSchemas(TestUtils.loadSchemaContext(modules));
208
209         when(mockedBrokerFacade.commitConfigurationDataPut(any(YangInstanceIdentifier.class), any(NormalizedNode.class)))
210                 .thenReturn(mock(CheckedFuture.class));
211
212         restconf.setControllerContext(controllerContext);
213         restconf.setBroker(mockedBrokerFacade);
214     }
215
216     public static String loadTextFile(final String filePath) throws IOException {
217         final FileReader fileReader = new FileReader(filePath);
218         final BufferedReader bufReader = new BufferedReader(fileReader);
219
220         String line = null;
221         final StringBuilder result = new StringBuilder();
222         while ((line = bufReader.readLine()) != null) {
223             result.append(line);
224         }
225         bufReader.close();
226         return result.toString();
227     }
228
229     private static Pattern patternForStringsSeparatedByWhiteChars(final String... substrings) {
230         final StringBuilder pattern = new StringBuilder();
231         pattern.append(".*");
232         for (final String substring : substrings) {
233             pattern.append(substring);
234             pattern.append("\\s*");
235         }
236         pattern.append(".*");
237         return Pattern.compile(pattern.toString(), Pattern.DOTALL);
238     }
239
240     public static boolean containsStringData(final String jsonOutput, final String... substrings) {
241         final Pattern pattern = patternForStringsSeparatedByWhiteChars(substrings);
242         final Matcher matcher = pattern.matcher(jsonOutput);
243         return matcher.matches();
244     }
245
246     public static YangInstanceIdentifier.NodeIdentifier getNodeIdentifier(final String localName, final String namespace,
247             final String revision) throws ParseException {
248         return new YangInstanceIdentifier.NodeIdentifier(QName.create(namespace, revision, localName));
249     }
250
251     public static YangInstanceIdentifier.NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
252             final String namespace, final String revision, final Map<String, Object> keys) throws ParseException {
253         final Map<QName, Object> predicate = new HashMap<>();
254         for (final String key : keys.keySet()) {
255             predicate.put(QName.create(namespace, revision, key), keys.get(key));
256         }
257
258         return new YangInstanceIdentifier.NodeIdentifierWithPredicates(
259
260         QName.create(namespace, revision, localName), predicate);
261     }
262
263     public static YangInstanceIdentifier.NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
264             final String namespace, final String revision, final String... keysAndValues) throws ParseException {
265         final java.util.Date date = new SimpleDateFormat("yyyy-MM-dd").parse(revision);
266         if (keysAndValues.length % 2 != 0) {
267             new IllegalArgumentException("number of keys argument have to be divisible by 2 (map)");
268         }
269         final Map<QName, Object> predicate = new HashMap<>();
270
271         int i = 0;
272         while (i < keysAndValues.length) {
273             predicate.put(QName.create(namespace, revision, keysAndValues[i++]), keysAndValues[i++]);
274         }
275
276         return new YangInstanceIdentifier.NodeIdentifierWithPredicates(QName.create(namespace, revision, localName),
277                 predicate);
278     }
279
280     static NormalizedNode<?,?> prepareNormalizedNodeWithIetfInterfacesInterfacesData() throws ParseException {
281         final String ietfInterfacesDate = "2013-07-04";
282         final String namespace = "urn:ietf:params:xml:ns:yang:ietf-interfaces";
283         final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> mapEntryNode = ImmutableMapEntryNodeBuilder.create();
284
285         final Map<String, Object> predicates = new HashMap<>();
286         predicates.put("name", "eth0");
287
288         mapEntryNode.withNodeIdentifier(getNodeIdentifierPredicate("interface", namespace, ietfInterfacesDate,
289                 predicates));
290         mapEntryNode
291                 .withChild(new ImmutableLeafNodeBuilder<String>()
292                         .withNodeIdentifier(getNodeIdentifier("name", namespace, ietfInterfacesDate)).withValue("eth0")
293                         .build());
294         mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
295                 .withNodeIdentifier(getNodeIdentifier("type", namespace, ietfInterfacesDate))
296                 .withValue("ethernetCsmacd").build());
297         mapEntryNode.withChild(new ImmutableLeafNodeBuilder<Boolean>()
298                 .withNodeIdentifier(getNodeIdentifier("enabled", namespace, ietfInterfacesDate))
299                 .withValue(Boolean.FALSE).build());
300         mapEntryNode.withChild(new ImmutableLeafNodeBuilder<String>()
301                 .withNodeIdentifier(getNodeIdentifier("description", namespace, ietfInterfacesDate))
302                 .withValue("some interface").build());
303
304         return mapEntryNode.build();
305     }
306 }