summaryrefslogtreecommitdiffstats
path: root/application/src/test/java/com/yahoo/application/container/jersey/JerseyTest.java
blob: 18e206c7add0f540a266122c078d0f0c0bf66872 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.application.container.jersey;

import com.yahoo.application.Networking;
import com.yahoo.application.container.JDisc;
import com.yahoo.application.container.ContainerTest;
import com.yahoo.application.container.jersey.resources.TestResource;
import com.yahoo.application.container.jersey.resources.nestedpackage1.NestedTestResource1;
import com.yahoo.application.container.jersey.resources.nestedpackage2.NestedTestResource2;
import com.yahoo.container.test.jars.jersey.resources.TestResourceBase;
import com.yahoo.osgi.maven.ProjectBundleClassPaths;
import com.yahoo.osgi.maven.ProjectBundleClassPaths.BundleClasspathMapping;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.Ignore;
import org.junit.Test;

import javax.ws.rs.core.UriBuilder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static java.util.Collections.emptyList;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

/**
 * @author Tony Vaagenes
 * @author ollivir
 */
@Ignore // TODO: remove test
public class JerseyTest {
    private final Path testJar = Paths.get("target/test-jars/jersey-resources.jar");
    private final String testClassesDirectory = "target/test-classes";
    private final String bundleSymbolicName = "myBundle";

    private final Set<Class<? extends TestResourceBase>> classPathResources;
    private final Set<Class<? extends TestResourceBase>> jarFileResources;

    public JerseyTest() {
        classPathResources = new HashSet<>();
        classPathResources.add(TestResource.class);
        classPathResources.add(NestedTestResource1.class);
        classPathResources.add(NestedTestResource2.class);

        jarFileResources = new HashSet<>();
        jarFileResources.add(com.yahoo.container.test.jars.jersey.resources.TestResource.class);
        jarFileResources.add(com.yahoo.container.test.jars.jersey.resources.nestedpackage1.NestedTestResource1.class);
        jarFileResources.add(com.yahoo.container.test.jars.jersey.resources.nestedpackage2.NestedTestResource2.class);
    }

    @Test
    public void jersey_resources_on_classpath_can_be_invoked_from_application() throws Exception {
        saveMainBundleClassPathMappings(testClassesDirectory);

        with_jersey_resources(emptyList(), httpGetter -> assertResourcesResponds(classPathResources, httpGetter));
    }

    @Test
    public void jersey_resources_in_provided_dependencies_can_be_invoked_from_application() throws Exception {
        BundleClasspathMapping providedDependency =
                new BundleClasspathMapping(bundleSymbolicName, List.of(testClassesDirectory));

        save(new ProjectBundleClassPaths(new BundleClasspathMapping("main", emptyList()), List.of(providedDependency)));
        with_jersey_resources(emptyList(), httpGetter -> assertResourcesResponds(classPathResources, httpGetter));
    }

    @Test
    public void jersey_resource_on_classpath_can_be_filtered_using_packages() throws Exception {
        saveMainBundleClassPathMappings(testClassesDirectory);

        with_jersey_resources(Arrays.asList("com.yahoo.application.container.jersey.resources",
                "com.yahoo.application.container.jersey.resources.nestedpackage1"), httpGetter -> {
            Class<NestedTestResource2> nestedResource2 = NestedTestResource2.class;
            assertDoesNotRespond(nestedResource2, httpGetter);
            assertResourcesResponds(copySetExcept(classPathResources, nestedResource2), httpGetter);
        });
    }

    @Test
    public void jersey_resource_in_jar_can_be_invoked_from_application() throws Exception {
        saveMainBundleJarClassPathMappings(testJar);

        with_jersey_resources(emptyList(), httpGetter -> assertResourcesResponds(jarFileResources, httpGetter));
    }

    @Test
    public void jersey_resource_in_jar_can_be_filtered_using_packages() throws Exception {
        saveMainBundleJarClassPathMappings(testJar);

        with_jersey_resources(Arrays.asList("com.yahoo.container.test.jars.jersey.resources",
                "com.yahoo.container.test.jars.jersey.resources.nestedpackage1"), httpGetter -> {
            Class<com.yahoo.container.test.jars.jersey.resources.nestedpackage2.NestedTestResource2> nestedResource2 = com.yahoo.container.test.jars.jersey.resources.nestedpackage2.NestedTestResource2.class;

            assertDoesNotRespond(nestedResource2, httpGetter);
            assertResourcesResponds(copySetExcept(jarFileResources, nestedResource2), httpGetter);
        });
    }

    private static <T> Set<T> copySetExcept(Set<T> in, T except) {
        Set<T> ret = new HashSet<>(in);
        ret.remove(except);
        return ret;
    }

    private interface ThrowingConsumer<T> {
        void accept(T arg) throws Exception;
    }

    private interface HttpGetter {
        HttpResponse get(String path) throws Exception;
    }

    @SuppressWarnings("try") // jdisc unreferenced inside try
    private void with_jersey_resources(List<String> packagesToScan, ThrowingConsumer<HttpGetter> f) throws Exception {
        StringBuilder packageElements = new StringBuilder();
        for (String p : packagesToScan) {
            packageElements.append("<package>");
            packageElements.append(p);
            packageElements.append("</package>");
        }

        try (JDisc jdisc = JDisc.fromServicesXml(
                "<services>" + //
                        "<container version=\"1.0\" id=\"default\" jetty=\"true\">" + //
                        "<rest-api path=\"rest-api\" jersey2=\"true\">" + //
                        "<components bundle=\"" + bundleSymbolicName + "\">" + //
                        packageElements + //
                        "</components>" + //
                        "</rest-api>" + //
                        "<http>" + //
                        "<server id=\"mainServer\" port=\"0\" />" + //
                        "</http>" + //
                        "<accesslog type=\"disabled\" />" +
                        "</container>" + //
                        "</services>", //
                Networking.enable)) {
            final int port = ContainerTest.getListenPort();
            f.accept(path -> {
                String p = path.startsWith("/") ? path.substring(1) : path;
                CloseableHttpClient client = HttpClientBuilder.create().build();
                return client.execute(new HttpGet("http://localhost:" + port + "/rest-api/" + p));
            });
        }
    }

    public void assertResourcesResponds(Collection<Class<? extends TestResourceBase>> resourceClasses,
                                        HttpGetter httpGetter) throws Exception {
        for (Class<? extends TestResourceBase> resource : resourceClasses) {
            HttpResponse response = httpGetter.get(path(resource));
            assertThat("Failed sending response to " + resource, response.getStatusLine().getStatusCode(), is(200));

            String content = new String(response.getEntity().getContent().readAllBytes(), StandardCharsets.UTF_8);
            assertThat(content, is(TestResourceBase.content(resource)));
        }
    }

    public void assertDoesNotRespond(Class<? extends TestResourceBase> resourceClass, HttpGetter httpGetter)
            throws Exception {
        HttpResponse response = httpGetter.get(path(resourceClass));
        assertThat(response.getStatusLine().getStatusCode(), is(404));
        EntityUtils.consume(response.getEntity());
    }

    public void saveMainBundleJarClassPathMappings(Path jarFile) throws Exception {
        assertTrue("Couldn't find file " + jarFile + ", please remember to run mvn process-test-resources first.",
                Files.isRegularFile(jarFile));
        saveMainBundleClassPathMappings(jarFile.toAbsolutePath().toString());
    }

    public void saveMainBundleClassPathMappings(String classPathElement) throws Exception {
        BundleClasspathMapping mainBundleClassPathMappings =
                new BundleClasspathMapping(bundleSymbolicName, List.of(classPathElement));
        save(new ProjectBundleClassPaths(mainBundleClassPathMappings, emptyList()));
    }

    public void save(ProjectBundleClassPaths projectBundleClassPaths) throws Exception {
        Path path = Paths.get(testClassesDirectory).resolve(ProjectBundleClassPaths.CLASSPATH_MAPPINGS_FILENAME);
        ProjectBundleClassPaths.save(path, projectBundleClassPaths);
    }

    public String path(Class<?> resourceClass) {
        return UriBuilder.fromResource(resourceClass).build().toString();
    }
}