Fix a SpotBugs warning
[odlparent.git] / features-test-plugin / src / main / java / org / opendaylight / odlparent / features / test / plugin / PaxExamExecution.java
1 /*
2  * Copyright (c) 2024 PANTHEON.tech, s.r.o. 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.odlparent.features.test.plugin;
9
10 import static java.util.Objects.requireNonNull;
11
12 import java.io.IOException;
13 import java.io.OutputStream;
14 import java.io.PrintStream;
15 import java.nio.charset.StandardCharsets;
16 import java.util.concurrent.atomic.AtomicBoolean;
17 import org.apache.maven.plugin.MojoExecutionException;
18 import org.ops4j.pax.exam.ExamSystem;
19 import org.ops4j.pax.exam.TestContainer;
20
21 final class PaxExamExecution {
22     private final TestContainer[] containers;
23     private final ExamSystem examSystem;
24     private final String localRepository;
25
26     PaxExamExecution(final String localRepository, final ExamSystem examSystem, final TestContainer ... containers) {
27         this.localRepository = requireNonNull(localRepository);
28         this.containers = containers;
29         this.examSystem = examSystem;
30     }
31
32     @SuppressWarnings({"IllegalCatch", "RegexpSinglelineJava"})
33     void execute() throws MojoExecutionException {
34
35         // Use the same repository for Pax Exam as is used for Maven
36         System.setProperty("org.ops4j.pax.url.mvn.localRepository", localRepository);
37
38         for (var container : containers) {
39             // disable karaf stdout output to maven log
40             final var stdout = System.out;
41             System.setOut(new PrintStream(OutputStream.nullOutputStream(), true, StandardCharsets.UTF_8));
42
43             final var containerStarted = new AtomicBoolean(false);
44             try {
45                 container.start();
46                 containerStarted.set(true);
47
48                 // build probe
49                 final var probeBuilder = examSystem.createProbe();
50                 final var address = probeBuilder.addTest(TestProbe.class, "testFeature");
51                 probeBuilder.addTest(TestProbe.CheckResult.class);
52
53                 // install probe bundle
54                 container.install(probeBuilder.build().getStream());
55                 // execute probe testMethod
56                 container.call(address);
57
58             } catch (RuntimeException | IOException e) {
59                 throw new MojoExecutionException(e);
60             } finally {
61                 if (containerStarted.get()) {
62                     container.stop();
63                 }
64                 // restore stdout
65                 System.setOut(stdout);
66             }
67         }
68     }
69 }